From cd8e3f113cda3c2a647f4044fe8e5fb9474d19fd Mon Sep 17 00:00:00 2001 From: soqb Date: Sat, 14 Nov 2026 19:58:49 +0000 Subject: [PATCH 1/7] feat(type_id_structural_match): baseline --- .../src/const_eval/valtrees.rs | 17 ++++- .../src/interpret/intrinsics.rs | 4 +- compiler/rustc_middle/src/thir.rs | 1 + .../rustc_middle/src/ty/consts/valtree.rs | 22 ++++-- compiler/rustc_middle/src/ty/mod.rs | 8 +- compiler/rustc_middle/src/ty/print/pretty.rs | 11 +-- .../src/builder/matches/test.rs | 53 ++++++------- .../src/thir/pattern/const_to_pat.rs | 3 + .../src/cfi/typeid/itanium_cxx_abi/encode.rs | 24 +++--- compiler/rustc_symbol_mangling/src/v0.rs | 76 ++++++++++--------- .../rustc_trait_selection/src/traits/misc.rs | 1 + .../rustc_trait_selection/src/traits/wf.rs | 13 ++-- compiler/rustc_type_ir/src/const_kind.rs | 10 ++- compiler/rustc_type_ir/src/flags.rs | 2 +- compiler/rustc_type_ir/src/relate.rs | 1 + library/core/src/any.rs | 8 +- .../min_adt_const_params/type-id-arbitrary.rs | 29 +++++++ .../min_adt_const_params/type-id.rs | 19 +++++ 18 files changed, 201 insertions(+), 101 deletions(-) create mode 100644 tests/ui/const-generics/min_adt_const_params/type-id-arbitrary.rs create mode 100644 tests/ui/const-generics/min_adt_const_params/type-id.rs diff --git a/compiler/rustc_const_eval/src/const_eval/valtrees.rs b/compiler/rustc_const_eval/src/const_eval/valtrees.rs index 562b5bb74b92e..fcd26e8d10aaa 100644 --- a/compiler/rustc_const_eval/src/const_eval/valtrees.rs +++ b/compiler/rustc_const_eval/src/const_eval/valtrees.rs @@ -1,5 +1,6 @@ use rustc_abi::{BackendRepr, FieldIdx, VariantIdx}; use rustc_data_structures::fx::{FxHashMap, FxHashSet}; +use rustc_attr_ir::LangItem; use rustc_middle::mir; use rustc_middle::mir::interpret::{EvalToValTreeResult, GlobalId, ValTreeCreationError}; use rustc_middle::traits::ObligationCause; @@ -175,6 +176,9 @@ fn const_to_valtree_inner<'tcx>( Err(ValTreeCreationError::NonSupportedType(ty)) } else if def.variants().is_empty() { bug!("uninhabited types should have errored and never gotten converted to valtree") + } else if tcx.is_lang_item(def.did(), LangItem::TypeId) { + let ty = ecx.read_type_id(place).report_err()?; + Ok(ty::ValTree::from_type_id(tcx, ty)) } else { let variant = ecx.read_discriminant(place).report_err()?; branches( @@ -336,7 +340,7 @@ pub fn valtree_to_const_value<'tcx>( } if layout.backend_repr.is_scalar() && (matches!(cv.ty.kind(), ty::Tuple(_)) - || matches!(cv.ty.kind(), ty::Adt(def, _) if def.is_struct())) + || matches!(cv.ty.kind(), ty::Adt(def, _) if def.is_struct() && !tcx.is_lang_item(def.did(), LangItem::TypeId))) { // A Scalar tuple/struct; we can avoid creating an allocation. let branches = cv.to_branch(); @@ -432,6 +436,17 @@ fn valtree_into_mplace<'tcx>( debug!(?imm); ecx.write_immediate(imm, place).unwrap(); } + ty::Adt(def, _) if ecx.tcx.is_lang_item(def.did(), LangItem::TypeId) => { + let ty::ValTreeKind::TypeId(ty) = **valtree else { + bug!("expected a TypeId valtree"); + }; + + // Need to create a place for this valtree. + ecx.write_type_id(ty, place).unwrap(); + + debug!("dump of place after writing type id:"); + dump_place(ecx, place); + } ty::Adt(_, _) | ty::Tuple(_) | ty::Array(_, _) | ty::Str | ty::Slice(_) => { let branches = valtree.to_branch(); diff --git a/compiler/rustc_const_eval/src/interpret/intrinsics.rs b/compiler/rustc_const_eval/src/interpret/intrinsics.rs index 974ea816c3b97..3dee6ebb7776d 100644 --- a/compiler/rustc_const_eval/src/interpret/intrinsics.rs +++ b/compiler/rustc_const_eval/src/interpret/intrinsics.rs @@ -141,12 +141,12 @@ impl<'tcx, M: Machine<'tcx>> InterpCx<'tcx, M> { /// Read a value of type `TypeId`, returning the type it represents. pub(crate) fn read_type_id( &self, - op: &OpTy<'tcx, M::Provenance>, + src: &impl Projectable<'tcx, M::Provenance>, ) -> InterpResult<'tcx, Ty<'tcx>> { // `TypeId` is a newtype around an array of pointers. All pointers must have the same // provenance, and that provenance represents the type. let ptr_size = self.pointer_size().bytes_usize(); - let arr = self.project_field(op, FieldIdx::ZERO)?; + let arr = self.project_field(src, FieldIdx::ZERO)?; let mut ty_and_hash = None; let mut elem_iter = self.project_array_fields(&arr)?; diff --git a/compiler/rustc_middle/src/thir.rs b/compiler/rustc_middle/src/thir.rs index b522e581b0485..6fc14585aade5 100644 --- a/compiler/rustc_middle/src/thir.rs +++ b/compiler/rustc_middle/src/thir.rs @@ -846,6 +846,7 @@ pub enum PatKind<'tcx> { /// much simpler. /// * raw pointers derived from integers, other raw pointers will have already resulted in an /// error. + /// * `TypeId`s to unify them across ctfe and runtime. Constant { value: ty::Value<'tcx>, }, diff --git a/compiler/rustc_middle/src/ty/consts/valtree.rs b/compiler/rustc_middle/src/ty/consts/valtree.rs index 2b88785a67973..eb5404a5cf520 100644 --- a/compiler/rustc_middle/src/ty/consts/valtree.rs +++ b/compiler/rustc_middle/src/ty/consts/valtree.rs @@ -61,6 +61,10 @@ impl<'tcx> ValTree<'tcx> { pub fn from_scalar_int(tcx: TyCtxt<'tcx>, i: ScalarInt) -> Self { tcx.intern_valtree(ty::ValTreeKind::Leaf(i)) } + + pub fn from_type_id(tcx: TyCtxt<'tcx>, ty: Ty<'tcx>) -> Self { + tcx.intern_valtree(ty::ValTreeKind::TypeId(ty)) + } } impl<'tcx> Deref for ValTree<'tcx> { @@ -171,7 +175,7 @@ impl<'tcx> Value<'tcx> { pub fn to_leaf(self) -> ScalarInt { match &**self.valtree { ValTreeKind::Leaf(s) => *s, - ValTreeKind::Branch(..) => bug!("expected leaf, got {:?}", self), + _ => bug!("expected leaf, got {:?}", self), } } @@ -181,7 +185,7 @@ impl<'tcx> Value<'tcx> { pub fn to_branch(self) -> &'tcx [ty::Const<'tcx>] { match &**self.valtree { ValTreeKind::Branch(branch) => &**branch, - ValTreeKind::Leaf(..) => bug!("expected branch, got {:?}", self), + _ => bug!("expected branch, got {:?}", self), } } @@ -189,7 +193,7 @@ impl<'tcx> Value<'tcx> { pub fn try_to_leaf(self) -> Option { match &**self.valtree { ValTreeKind::Leaf(s) => Some(*s), - ValTreeKind::Branch(_) => None, + _ => None, } } @@ -202,13 +206,19 @@ impl<'tcx> Value<'tcx> { pub fn try_to_branch(self) -> Option<&'tcx [ty::Const<'tcx>]> { match &**self.valtree { ValTreeKind::Branch(branch) => Some(&**branch), - ValTreeKind::Leaf(_) => None, + _ => None, } } /// Destructures ADT constants into the constants of their fields. pub fn destructure_adt_const(&self) -> ty::DestructuredAdtConst<'tcx> { - let fields = self.to_branch(); + let fields = match **self.valtree { + ValTreeKind::Leaf(_) => { + bug!("destructure_adt_const: expected branch or type id `{:?}`", self.ty) + } + ValTreeKind::Branch(branch) => &**branch, + ValTreeKind::TypeId(ty) => return ty::DestructuredAdtConst::TypeId { ty }, + }; let (variant, fields) = match self.ty.kind() { ty::Adt(def, _) if def.variants().is_empty() => { @@ -222,7 +232,7 @@ impl<'tcx> Value<'tcx> { _ => bug!("destructure_adt_const called on non-ADT type: {:?}", self.ty), }; - ty::DestructuredAdtConst { variant, fields } + ty::DestructuredAdtConst::Aggregate { variant, fields } } } diff --git a/compiler/rustc_middle/src/ty/mod.rs b/compiler/rustc_middle/src/ty/mod.rs index 53e4cf0f92e89..329a60ba7aee1 100644 --- a/compiler/rustc_middle/src/ty/mod.rs +++ b/compiler/rustc_middle/src/ty/mod.rs @@ -2589,8 +2589,8 @@ impl<'tcx> fmt::Debug for SymbolName<'tcx> { } /// The constituent parts of a type level constant of kind ADT or array. -#[derive(Copy, Clone, Debug, StableHash)] -pub struct DestructuredAdtConst<'tcx> { - pub variant: VariantIdx, - pub fields: &'tcx [ty::Const<'tcx>], +#[derive(Copy, Clone, Debug)] +pub enum DestructuredAdtConst<'tcx> { + Aggregate { variant: VariantIdx, fields: &'tcx [ty::Const<'tcx>] }, + TypeId { ty: Ty<'tcx> }, } diff --git a/compiler/rustc_middle/src/ty/print/pretty.rs b/compiler/rustc_middle/src/ty/print/pretty.rs index ea16cb64123e8..038ff5fe653c9 100644 --- a/compiler/rustc_middle/src/ty/print/pretty.rs +++ b/compiler/rustc_middle/src/ty/print/pretty.rs @@ -2000,9 +2000,11 @@ pub trait PrettyPrinter<'tcx>: Printer<'tcx> + fmt::Write { } return Ok(()); } - (ty::ValTreeKind::Branch(_), ty::Adt(def, args)) => { - let contents = cv.destructure_adt_const(); - let fields = contents.fields.iter().copied(); + (ty::ValTreeKind::Branch(_), ty::Adt(def, args)) + if let ty::DestructuredAdtConst::Aggregate { variant, fields } = + cv.destructure_adt_const() => + { + let fields = fields.iter().copied(); if def.variants().is_empty() { self.typed_value( @@ -2014,8 +2016,7 @@ pub trait PrettyPrinter<'tcx>: Printer<'tcx> + fmt::Write { ": ", )?; } else { - let variant_idx = contents.variant; - let variant_def = &def.variant(variant_idx); + let variant_def = &def.variant(variant); self.pretty_print_value_path(variant_def.def_id, args)?; match variant_def.ctor_kind() { Some(CtorKind::Const) => {} diff --git a/compiler/rustc_mir_build/src/builder/matches/test.rs b/compiler/rustc_mir_build/src/builder/matches/test.rs index 6b516fb2f3972..72cd609f797bd 100644 --- a/compiler/rustc_mir_build/src/builder/matches/test.rs +++ b/compiler/rustc_mir_build/src/builder/matches/test.rs @@ -238,33 +238,34 @@ impl<'a, 'tcx> Builder<'a, 'tcx> { let mut actual_value_place = place; + let mut transmute_to = |to: Ty<'tcx>| { + assert!(to.is_trivially_pure_clone_copy()); + + let transmuted_place = self.temp(to, test.span); + self.cfg.push_assign( + block, + self.source_info(scrutinee_span), + transmuted_place, + Rvalue::Cast(CastKind::Transmute, Operand::Copy(actual_value_place), to), + ); + + let transmuted_expect = self.temp(to, test.span); + self.cfg.push_assign( + block, + self.source_info(test.span), + transmuted_expect, + Rvalue::Cast(CastKind::Transmute, expected_value_operand.clone(), to), + ); + + actual_value_place = transmuted_place; + expected_value_operand = Operand::Copy(transmuted_expect); + expected_value_ty = to; + }; + match value.ty.kind() { - &ty::Pat(base, _) => { - assert!(base.is_trivially_pure_clone_copy()); - - let transmuted_place = self.temp(base, test.span); - self.cfg.push_assign( - block, - self.source_info(scrutinee_span), - transmuted_place, - Rvalue::Cast( - CastKind::Transmute, - Operand::Copy(actual_value_place), - base, - ), - ); - - let transmuted_expect = self.temp(base, test.span); - self.cfg.push_assign( - block, - self.source_info(test.span), - transmuted_expect, - Rvalue::Cast(CastKind::Transmute, expected_value_operand, base), - ); - - actual_value_place = transmuted_place; - expected_value_operand = Operand::Copy(transmuted_expect); - expected_value_ty = base; + &ty::Pat(base, _) => transmute_to(base), + &ty::Adt(def, _) if tcx.is_lang_item(def.did(), LangItem::TypeId) => { + transmute_to(tcx.types.u128) } _ => {} } diff --git a/compiler/rustc_mir_build/src/thir/pattern/const_to_pat.rs b/compiler/rustc_mir_build/src/thir/pattern/const_to_pat.rs index 16b3df5006c42..552d96d3424d2 100644 --- a/compiler/rustc_mir_build/src/thir/pattern/const_to_pat.rs +++ b/compiler/rustc_mir_build/src/thir/pattern/const_to_pat.rs @@ -390,6 +390,9 @@ impl<'tcx> ConstToPat<'tcx> { .lower_field_values_to_fieldpats(fields.iter().map(|ct| ct.to_value())), } } + ty::Adt(def, _) if tcx.is_lang_item(def.did(), LangItem::TypeId) => { + PatKind::Constant { value } + } ty::Adt(def, _) => { assert!(!def.is_union()); // Valtree construction would never succeed for unions. PatKind::Leaf { diff --git a/compiler/rustc_sanitizers/src/cfi/typeid/itanium_cxx_abi/encode.rs b/compiler/rustc_sanitizers/src/cfi/typeid/itanium_cxx_abi/encode.rs index a76fc401c7c60..c681097ae5c8c 100644 --- a/compiler/rustc_sanitizers/src/cfi/typeid/itanium_cxx_abi/encode.rs +++ b/compiler/rustc_sanitizers/src/cfi/typeid/itanium_cxx_abi/encode.rs @@ -220,18 +220,22 @@ fn encode_const_value<'tcx>( // User-defined types // Struct and enum values are encoded as their field values as literal arguments, preceded // by V for enum values. - ty::Adt(adt_def, ..) => { - let contents = cv.destructure_adt_const(); - if adt_def.is_enum() { - let _ = write!(s, "V{}", contents.variant.as_u32()); + ty::Adt(adt_def, ..) => match cv.destructure_adt_const() { + ty::DestructuredAdtConst::Aggregate { variant, fields } => { + if adt_def.is_enum() { + let _ = write!(s, "V{}", variant.as_u32()); + } + for field in fields { + let ty::ConstKind::Value(field_cv) = field.kind() else { + bug!("encode_const_value: unexpected kind `{:?}`", field.kind()); + }; + s.push_str(&encode_const(tcx, *field, field_cv.ty, dict, options)); + } } - for field in contents.fields { - let ty::ConstKind::Value(field_cv) = field.kind() else { - bug!("encode_const_value: unexpected kind `{:?}`", field.kind()); - }; - s.push_str(&encode_const(tcx, *field, field_cv.ty, dict, options)); + ty::DestructuredAdtConst::TypeId { ty } => { + s.push_str(&encode_ty(tcx, ty, dict, options)) } - } + }, // Pointer types // Reference values are encoded as the values of their referents (i.e., the valtree of a diff --git a/compiler/rustc_symbol_mangling/src/v0.rs b/compiler/rustc_symbol_mangling/src/v0.rs index e53c598952df9..ef64d92a472e5 100644 --- a/compiler/rustc_symbol_mangling/src/v0.rs +++ b/compiler/rustc_symbol_mangling/src/v0.rs @@ -890,46 +890,52 @@ impl<'tcx> Printer<'tcx> for V0SymbolMangler<'tcx> { } } ty::Adt(def, args) => { - let contents = cv.destructure_adt_const(); - let fields = contents.fields.iter().copied(); - - let print_field_list = |this: &mut Self| { - for field in fields.clone() { - field.print(this)?; + match cv.destructure_adt_const() { + ty::DestructuredAdtConst::TypeId { ty } => { + ty.print(self)?; } - this.push("E"); - Ok(()) - }; + ty::DestructuredAdtConst::Aggregate { variant, fields } => { + let fields = fields.iter().copied(); + let variant_def = &def.variant(variant); - let variant_idx = contents.variant; - let variant_def = &def.variant(variant_idx); + let print_field_list = |this: &mut Self| { + for field in fields.clone() { + field.print(this)?; + } + this.push("E"); + Ok(()) + }; - self.push("V"); - self.print_def_path(variant_def.def_id, *args)?; + self.push("V"); + self.print_def_path(variant_def.def_id, *args)?; - match variant_def.ctor_kind() { - Some(CtorKind::Const) => { - self.push("U"); - } - Some(CtorKind::Fn) => { - self.push("T"); - print_field_list(self)?; - } - None => { - self.push("S"); - for (field_def, field) in iter::zip(&variant_def.fields, fields) { - // HACK(eddyb) this mimics `print_path_with_simple`, - // instead of simply using `field_def.ident`, - // just to be able to handle disambiguators. - let disambiguated_field = - self.tcx.def_key(field_def.did).disambiguated_data; - let field_name = disambiguated_field.data.get_opt_name(); - self.push_disambiguator(disambiguated_field.disambiguator as u64); - self.push_ident(field_name.unwrap().as_str()); - - field.print(self)?; + match variant_def.ctor_kind() { + Some(CtorKind::Const) => { + self.push("U"); + } + Some(CtorKind::Fn) => { + self.push("T"); + print_field_list(self)?; + } + None => { + self.push("S"); + for (field_def, field) in iter::zip(&variant_def.fields, fields) { + // HACK(eddyb) this mimics `print_path_with_simple`, + // instead of simply using `field_def.ident`, + // just to be able to handle disambiguators. + let disambiguated_field = + self.tcx.def_key(field_def.did).disambiguated_data; + let field_name = disambiguated_field.data.get_opt_name(); + self.push_disambiguator( + disambiguated_field.disambiguator as u64, + ); + self.push_ident(field_name.unwrap().as_str()); + + field.print(self)?; + } + self.push("E"); + } } - self.push("E"); } } } diff --git a/compiler/rustc_trait_selection/src/traits/misc.rs b/compiler/rustc_trait_selection/src/traits/misc.rs index 76ed6a8d491c0..3e770d0f18afc 100644 --- a/compiler/rustc_trait_selection/src/traits/misc.rs +++ b/compiler/rustc_trait_selection/src/traits/misc.rs @@ -119,6 +119,7 @@ pub fn type_allowed_to_implement_const_param_ty<'tcx>( // `str` morally acts like a newtype around `[u8]` ty::Tuple(inner_tys) => inner_tys.into_iter().collect(), + ty::Adt(adt, _) if tcx.is_lang_item(adt.did(), LangItem::TypeId) => return Ok(()), ty::Adt(adt, args) if adt.is_enum() || adt.is_struct() => { if !tcx.features().adt_const_params() { for variant in adt.variants() { diff --git a/compiler/rustc_trait_selection/src/traits/wf.rs b/compiler/rustc_trait_selection/src/traits/wf.rs index 97c12d34df386..7eafcb3d73971 100644 --- a/compiler/rustc_trait_selection/src/traits/wf.rs +++ b/compiler/rustc_trait_selection/src/traits/wf.rs @@ -1226,12 +1226,13 @@ impl<'a, 'tcx> TypeVisitor> for WfPredicates<'a, 'tcx> { // FIXME(mgca): no need to feature-gate once valtree lifetimes are not erased if tcx.features().gca() { match val.ty.kind() { - ty::Adt(adt_def, args) => { - let adt_val = val.destructure_adt_const(); - let variant_def = adt_def.variant(adt_val.variant); - let cause = - self.cause(ObligationCauseCode::WellFormed(WellFormedLoc::None)); - self.out.extend(variant_def.fields.iter().zip(adt_val.fields).map( + ty::Adt(adt_def, args) + if let ty::DestructuredAdtConst::Aggregate { variant, fields } = + val.destructure_adt_const() => + { + let variant_def = adt_def.variant(variant); + let cause = self.cause(ObligationCauseCode::WellFormed(WellFormedLoc::None)); + self.out.extend(variant_def.fields.iter().zip(fields).map( |(field_def, &field_val)| { let field_ty = tcx .type_of(field_def.did) diff --git a/compiler/rustc_type_ir/src/const_kind.rs b/compiler/rustc_type_ir/src/const_kind.rs index c28121df6f3ad..c7ab899dc85a3 100644 --- a/compiler/rustc_type_ir/src/const_kind.rs +++ b/compiler/rustc_type_ir/src/const_kind.rs @@ -249,6 +249,8 @@ pub enum ValTreeKind { /// /// ZST types are represented as an empty slice. Branch(I::Consts), + + TypeId(I::Ty), } impl ValTreeKind { @@ -258,7 +260,7 @@ impl ValTreeKind { pub fn to_leaf(&self) -> I::ScalarInt { match self { ValTreeKind::Leaf(s) => *s, - ValTreeKind::Branch(..) => panic!("expected leaf, got {:?}", self), + _ => panic!("expected leaf, got {:?}", self), } } @@ -268,7 +270,7 @@ impl ValTreeKind { pub fn to_branch(&self) -> I::Consts { match self { ValTreeKind::Branch(branch) => *branch, - ValTreeKind::Leaf(..) => panic!("expected branch, got {:?}", self), + _ => panic!("expected branch, got {:?}", self), } } @@ -276,7 +278,7 @@ impl ValTreeKind { pub fn try_to_leaf(&self) -> Option { match self { ValTreeKind::Leaf(s) => Some(*s), - ValTreeKind::Branch(_) => None, + _ => None, } } @@ -284,7 +286,7 @@ impl ValTreeKind { pub fn try_to_branch(&self) -> Option { match self { ValTreeKind::Branch(branch) => Some(*branch), - ValTreeKind::Leaf(_) => None, + _ => None, } } } diff --git a/compiler/rustc_type_ir/src/flags.rs b/compiler/rustc_type_ir/src/flags.rs index 4c6ed9d44e059..07b8766637d00 100644 --- a/compiler/rustc_type_ir/src/flags.rs +++ b/compiler/rustc_type_ir/src/flags.rs @@ -528,7 +528,7 @@ impl FlagComputation { ty::ConstKind::Value(cv) => { self.add_ty(cv.ty()); match cv.valtree().kind() { - ty::ValTreeKind::Leaf(_) => (), + ty::ValTreeKind::Leaf(_) | ty::ValTreeKind::TypeId(_) => (), ty::ValTreeKind::Branch(cts) => { for ct in cts.iter() { self.add_const(ct); diff --git a/compiler/rustc_type_ir/src/relate.rs b/compiler/rustc_type_ir/src/relate.rs index e87b584ebcb6b..e287738464ae9 100644 --- a/compiler/rustc_type_ir/src/relate.rs +++ b/compiler/rustc_type_ir/src/relate.rs @@ -605,6 +605,7 @@ pub fn structurally_relate_consts>( .zip(branches_b.iter()) .all(|(a, b)| relation.relate(a, b).is_ok()) } + (ty::ValTreeKind::TypeId(a), ty::ValTreeKind::TypeId(b)) => a == b, _ => false, } } diff --git a/library/core/src/any.rs b/library/core/src/any.rs index 88364538146c2..894e567cabde8 100644 --- a/library/core/src/any.rs +++ b/library/core/src/any.rs @@ -87,7 +87,8 @@ #![stable(feature = "rust1", since = "1.0.0")] use crate::intrinsics::reflection::{type_id, type_id_vtable}; -use crate::intrinsics::{self}; +use crate::intrinsics; +use crate::marker::{ConstParamTy_, StructuralPartialEq}; use crate::mem::transmute; use crate::mem::type_info::{TraitImpl, TypeKind}; use crate::{fmt, hash, ptr}; @@ -873,6 +874,11 @@ impl fmt::Debug for TypeId { } } +#[unstable(feature = "type_id_structural_match", issue = "10000000")] +impl StructuralPartialEq for TypeId {} +#[unstable(feature = "type_id_structural_match", issue = "10000000")] +impl ConstParamTy_ for TypeId {} + /// Returns the name of a type as a string slice. /// /// # Note diff --git a/tests/ui/const-generics/min_adt_const_params/type-id-arbitrary.rs b/tests/ui/const-generics/min_adt_const_params/type-id-arbitrary.rs new file mode 100644 index 0000000000000..6c390011e13d0 --- /dev/null +++ b/tests/ui/const-generics/min_adt_const_params/type-id-arbitrary.rs @@ -0,0 +1,29 @@ +//@ edition:2024 +//@run-pass +#![feature(min_adt_const_params, const_param_ty_trait)] +#![allow(incomplete_features)] + +use std::marker::ConstParamTy; +use std::any::TypeId; + +#[derive(PartialEq, Eq, ConstParamTy)] +struct Value { + disambiguator: TypeId, +} + +macro_rules! arbitrary_const_value { + () => { + const { + enum Arbitrary {} + Value { disambiguator: TypeId::of::() } + } + } +} + +struct Wrapper; + +fn main() { + let a: Wrapper<{ arbitrary_const_value!() }> = Wrapper; + let b: Wrapper<{ arbitrary_const_value!() }> = a; +} + diff --git a/tests/ui/const-generics/min_adt_const_params/type-id.rs b/tests/ui/const-generics/min_adt_const_params/type-id.rs new file mode 100644 index 0000000000000..5784fe59fc271 --- /dev/null +++ b/tests/ui/const-generics/min_adt_const_params/type-id.rs @@ -0,0 +1,19 @@ +//@ edition:2024 +//@run-pass +#![feature(min_adt_const_params)] +#![allow(incomplete_features)] + +use std::any::TypeId; + +enum Foo {} +enum Bar {} + +fn equate() -> bool { + A == B +} + +fn main() { + assert!(equate::<{ TypeId::of::() }, { TypeId::of::() }>()); + assert!(equate::<{ TypeId::of::() }, { TypeId::of::() }>()); + assert!(!equate::<{ TypeId::of::() }, { TypeId::of::() }>()); +} From fa8b8e0a8679785c96356a80a6705f1feb63b8f5 Mon Sep 17 00:00:00 2001 From: soqb Date: Thu, 19 Nov 2026 11:51:21 +0000 Subject: [PATCH 2/7] fix(type_id_structural_match): fix consts and mangling --- .../src/const_eval/valtrees.rs | 4 +- .../rustc_middle/src/ty/consts/valtree.rs | 11 ++- compiler/rustc_middle/src/ty/mod.rs | 2 +- .../src/builder/matches/buckets.rs | 9 +- .../src/builder/matches/match_pair.rs | 5 + .../src/builder/matches/mod.rs | 8 +- .../src/builder/matches/test.rs | 91 +++++++++---------- .../src/cfi/typeid/itanium_cxx_abi/encode.rs | 5 +- compiler/rustc_symbol_mangling/src/v0.rs | 4 +- .../rustc_trait_selection/src/traits/wf.rs | 3 +- compiler/rustc_type_ir/src/const_kind.rs | 10 +- compiler/rustc_type_ir/src/flags.rs | 6 +- compiler/rustc_type_ir/src/relate.rs | 4 +- library/core/src/any.rs | 3 +- tests/ui/consts/const-eval/match-type-id.rs | 20 ++++ .../const-eval/match-type-id.stock.stderr | 26 ++++++ 16 files changed, 142 insertions(+), 69 deletions(-) create mode 100644 tests/ui/consts/const-eval/match-type-id.rs create mode 100644 tests/ui/consts/const-eval/match-type-id.stock.stderr diff --git a/compiler/rustc_const_eval/src/const_eval/valtrees.rs b/compiler/rustc_const_eval/src/const_eval/valtrees.rs index fcd26e8d10aaa..a197e21ab39bc 100644 --- a/compiler/rustc_const_eval/src/const_eval/valtrees.rs +++ b/compiler/rustc_const_eval/src/const_eval/valtrees.rs @@ -1,6 +1,6 @@ use rustc_abi::{BackendRepr, FieldIdx, VariantIdx}; -use rustc_data_structures::fx::{FxHashMap, FxHashSet}; use rustc_attr_ir::LangItem; +use rustc_data_structures::fx::{FxHashMap, FxHashSet}; use rustc_middle::mir; use rustc_middle::mir::interpret::{EvalToValTreeResult, GlobalId, ValTreeCreationError}; use rustc_middle::traits::ObligationCause; @@ -437,7 +437,7 @@ fn valtree_into_mplace<'tcx>( ecx.write_immediate(imm, place).unwrap(); } ty::Adt(def, _) if ecx.tcx.is_lang_item(def.did(), LangItem::TypeId) => { - let ty::ValTreeKind::TypeId(ty) = **valtree else { + let ty::ValTreeKind::TypeId(ty, _) = **valtree else { bug!("expected a TypeId valtree"); }; diff --git a/compiler/rustc_middle/src/ty/consts/valtree.rs b/compiler/rustc_middle/src/ty/consts/valtree.rs index eb5404a5cf520..6cbe674cbc155 100644 --- a/compiler/rustc_middle/src/ty/consts/valtree.rs +++ b/compiler/rustc_middle/src/ty/consts/valtree.rs @@ -63,7 +63,11 @@ impl<'tcx> ValTree<'tcx> { } pub fn from_type_id(tcx: TyCtxt<'tcx>, ty: Ty<'tcx>) -> Self { - tcx.intern_valtree(ty::ValTreeKind::TypeId(ty)) + let hash = tcx.type_id_hash(ty).as_u128(); + let valtree = ty::ValTree::from_scalar_int(tcx, hash.into()); + let value = ty::Const::new_value(tcx, valtree, tcx.types.u128); + let branches = tcx.mk_const_list_from_iter(Some(value).into_iter()); + tcx.intern_valtree(ty::ValTreeKind::TypeId(ty, branches)) } } @@ -217,7 +221,10 @@ impl<'tcx> Value<'tcx> { bug!("destructure_adt_const: expected branch or type id `{:?}`", self.ty) } ValTreeKind::Branch(branch) => &**branch, - ValTreeKind::TypeId(ty) => return ty::DestructuredAdtConst::TypeId { ty }, + ValTreeKind::TypeId(ty, consts) => { + assert_eq!(consts.len(), 1); + return ty::DestructuredAdtConst::TypeId { ty, value: consts[0] }; + } }; let (variant, fields) = match self.ty.kind() { diff --git a/compiler/rustc_middle/src/ty/mod.rs b/compiler/rustc_middle/src/ty/mod.rs index 329a60ba7aee1..a032d73fbef56 100644 --- a/compiler/rustc_middle/src/ty/mod.rs +++ b/compiler/rustc_middle/src/ty/mod.rs @@ -2592,5 +2592,5 @@ impl<'tcx> fmt::Debug for SymbolName<'tcx> { #[derive(Copy, Clone, Debug)] pub enum DestructuredAdtConst<'tcx> { Aggregate { variant: VariantIdx, fields: &'tcx [ty::Const<'tcx>] }, - TypeId { ty: Ty<'tcx> }, + TypeId { ty: Ty<'tcx>, value: ty::Const<'tcx> }, } diff --git a/compiler/rustc_mir_build/src/builder/matches/buckets.rs b/compiler/rustc_mir_build/src/builder/matches/buckets.rs index 4c68afb83417a..1a338dc212b1e 100644 --- a/compiler/rustc_mir_build/src/builder/matches/buckets.rs +++ b/compiler/rustc_mir_build/src/builder/matches/buckets.rs @@ -321,8 +321,11 @@ impl<'a, 'tcx> Builder<'a, 'tcx> { } ( - TestKind::StringEq { value: test_val, .. }, - TestableCase::Constant { value: case_val, kind: PatConstKind::String }, + TestKind::CallPartialEq { value: test_val, .. }, + TestableCase::Constant { + value: case_val, + kind: PatConstKind::String | PatConstKind::TypeId, + }, ) | ( TestKind::ScalarEq { value: test_val, .. }, @@ -362,7 +365,7 @@ impl<'a, 'tcx> Builder<'a, 'tcx> { | TestKind::If | TestKind::SliceLen { .. } | TestKind::Range { .. } - | TestKind::StringEq { .. } + | TestKind::CallPartialEq { .. } | TestKind::ScalarEq { .. } | TestKind::AggregateEq { .. } | TestKind::Deref { .. }, 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 e2b568e93a10a..b38c7fe209575 100644 --- a/compiler/rustc_mir_build/src/builder/matches/match_pair.rs +++ b/compiler/rustc_mir_build/src/builder/matches/match_pair.rs @@ -1,6 +1,7 @@ use std::sync::Arc; use rustc_abi::FieldIdx; +use rustc_attr_ir::LangItem; use rustc_middle::mir::{Pinnedness, Place, PlaceElem, ProjectionElem}; use rustc_middle::thir::{Ascription, DerefPatBorrowMode, FieldPat, Pat, PatKind}; use rustc_middle::ty::{self, Ty, TypeVisitableExt}; @@ -359,6 +360,10 @@ impl<'tcx> InterPat<'tcx> { PatConstKind::Float } else if pat_ty.is_str() { PatConstKind::String + } else if let ty::Adt(def, _) = pat_ty.kind() + && cx.tcx.is_lang_item(def.did(), LangItem::TypeId) + { + PatConstKind::TypeId } else { // FIXME(Zalathar): This still covers several different // categories (e.g. raw pointer, pattern-type) diff --git a/compiler/rustc_mir_build/src/builder/matches/mod.rs b/compiler/rustc_mir_build/src/builder/matches/mod.rs index 52922aa67f8dd..32c75cb456042 100644 --- a/compiler/rustc_mir_build/src/builder/matches/mod.rs +++ b/compiler/rustc_mir_build/src/builder/matches/mod.rs @@ -1230,6 +1230,8 @@ enum PatConstKind { /// from. Tested by comparing the bytes of the whole aggregate at once, /// rather than comparing element by element. Aggregate, + /// Specifically `core::any::TypeId`. + TypeId, /// Any other constant-pattern is usually tested via some kind of equality /// check. Types that might be encountered here include: /// - raw pointers derived from integer values @@ -1305,10 +1307,10 @@ enum TestKind<'tcx> { /// Test whether a `bool` is `true` or `false`. If, - /// Tests the place against a string constant using string equality. - StringEq { + /// Tests the place against a constant using `PartialEq::eq`. + CallPartialEq { /// Constant string value to test against. - /// Note that this value has type `str` (not `&str`). + /// Note that this value is not a reference, so `str`, not `&str`. value: ty::Value<'tcx>, }, diff --git a/compiler/rustc_mir_build/src/builder/matches/test.rs b/compiler/rustc_mir_build/src/builder/matches/test.rs index 72cd609f797bd..af5705df81163 100644 --- a/compiler/rustc_mir_build/src/builder/matches/test.rs +++ b/compiler/rustc_mir_build/src/builder/matches/test.rs @@ -44,8 +44,8 @@ impl<'a, 'tcx> Builder<'a, 'tcx> { TestableCase::Constant { value: _, kind: PatConstKind::IntOrChar } => { TestKind::SwitchInt } - TestableCase::Constant { value, kind: PatConstKind::String } => { - TestKind::StringEq { value } + TestableCase::Constant { value, kind: PatConstKind::String | PatConstKind::TypeId } => { + TestKind::CallPartialEq { value } } TestableCase::Constant { value, kind: PatConstKind::Aggregate } => { TestKind::AggregateEq { value } @@ -143,27 +143,26 @@ impl<'a, 'tcx> Builder<'a, 'tcx> { self.cfg.terminate(block, self.source_info(match_start_span), terminator); } - TestKind::StringEq { value } => { + TestKind::CallPartialEq { value } => { let tcx = self.tcx; let success_block = target_block(TestBranch::Success); let fail_block = target_block(TestBranch::Failure); - let ref_str_ty = Ty::new_imm_ref(tcx, tcx.lifetimes.re_erased, tcx.types.str_); - assert!(ref_str_ty.is_imm_ref_str(), "{ref_str_ty:?}"); + let ref_ty = Ty::new_imm_ref(tcx, tcx.lifetimes.re_erased, value.ty); + // assert!(ref_ty.is_imm_ref(), "{ref_ty:?}"); - // The string constant we're testing against has type `str`, but - // calling `::eq` requires `&str` operands. + // If the constant we're testing against has type `T`, + // calling `::eq` requires `&T` operands. // - // Because `str` and `&str` have the same valtree representation, + // Because `T` and `&T` have the same valtree representation, // we can "cast" to the desired type by just replacing the type. - assert!(value.ty.is_str(), "unexpected value type for StringEq test: {value:?}"); - let expected_value = ty::Value { ty: ref_str_ty, valtree: value.valtree }; + let expected_value = ty::Value { ty: ref_ty, valtree: value.valtree }; let expected_value_operand = self.literal_operand(test.span, Const::from_ty_value(tcx, expected_value)); - // Similarly, the scrutinized place has type `str`, but we need `&str`. - // Get a reference by doing `let actual_value_ref_place: &str = &place`. - let actual_value_ref_place = self.temp(ref_str_ty, test.span); + // Similarly, the scrutinized place has type `T`, but we need `&T`. + // Get a reference by doing `let actual_value_ref_place: &T = &place`. + let actual_value_ref_place = self.temp(ref_ty, test.span); self.cfg.push_assign( block, self.source_info(test.span), @@ -171,14 +170,15 @@ impl<'a, 'tcx> Builder<'a, 'tcx> { Rvalue::Ref(tcx.lifetimes.re_erased, BorrowKind::Shared, place), ); - // Compare two strings using `::eq`. + // Compare two strings using `::eq`. // (Interestingly this means that exhaustiveness analysis relies, for soundness, // on the `PartialEq` impl for `str` to be correct!) - self.string_compare( + self.compare_with_eq( block, success_block, fail_block, source_info, + value.ty, expected_value_operand, Operand::Copy(actual_value_ref_place), ); @@ -238,34 +238,33 @@ impl<'a, 'tcx> Builder<'a, 'tcx> { let mut actual_value_place = place; - let mut transmute_to = |to: Ty<'tcx>| { - assert!(to.is_trivially_pure_clone_copy()); - - let transmuted_place = self.temp(to, test.span); - self.cfg.push_assign( - block, - self.source_info(scrutinee_span), - transmuted_place, - Rvalue::Cast(CastKind::Transmute, Operand::Copy(actual_value_place), to), - ); - - let transmuted_expect = self.temp(to, test.span); - self.cfg.push_assign( - block, - self.source_info(test.span), - transmuted_expect, - Rvalue::Cast(CastKind::Transmute, expected_value_operand.clone(), to), - ); - - actual_value_place = transmuted_place; - expected_value_operand = Operand::Copy(transmuted_expect); - expected_value_ty = to; - }; - match value.ty.kind() { - &ty::Pat(base, _) => transmute_to(base), - &ty::Adt(def, _) if tcx.is_lang_item(def.did(), LangItem::TypeId) => { - transmute_to(tcx.types.u128) + &ty::Pat(base, _) => { + assert!(base.is_trivially_pure_clone_copy()); + + let transmuted_place = self.temp(base, test.span); + self.cfg.push_assign( + block, + self.source_info(scrutinee_span), + transmuted_place, + Rvalue::Cast( + CastKind::Transmute, + Operand::Copy(actual_value_place), + base, + ), + ); + + let transmuted_expect = self.temp(base, test.span); + self.cfg.push_assign( + block, + self.source_info(test.span), + transmuted_expect, + Rvalue::Cast(CastKind::Transmute, expected_value_operand.clone(), base), + ); + + actual_value_place = transmuted_place; + expected_value_operand = Operand::Copy(transmuted_expect); + expected_value_ty = base; } _ => {} } @@ -459,19 +458,19 @@ impl<'a, 'tcx> Builder<'a, 'tcx> { ); } - /// Compare two values of type `&str` using `::eq`. - fn string_compare( + /// Compare two values using `PartialEq::eq`. + fn compare_with_eq( &mut self, block: BasicBlock, success_block: BasicBlock, fail_block: BasicBlock, source_info: SourceInfo, + val_ty: Ty<'tcx>, expect: Operand<'tcx>, val: Operand<'tcx>, ) { - let str_ty = self.tcx.types.str_; let eq_def_id = self.tcx.require_lang_item(LangItem::PartialEq, source_info.span); - let method = trait_method(self.tcx, eq_def_id, sym::eq, &[str_ty.into(), str_ty.into()]); + let method = trait_method(self.tcx, eq_def_id, sym::eq, &[val_ty.into(), val_ty.into()]); let bool_ty = self.tcx.types.bool; let eq_result = self.temp(bool_ty, source_info.span); diff --git a/compiler/rustc_sanitizers/src/cfi/typeid/itanium_cxx_abi/encode.rs b/compiler/rustc_sanitizers/src/cfi/typeid/itanium_cxx_abi/encode.rs index c681097ae5c8c..f75ea16a54546 100644 --- a/compiler/rustc_sanitizers/src/cfi/typeid/itanium_cxx_abi/encode.rs +++ b/compiler/rustc_sanitizers/src/cfi/typeid/itanium_cxx_abi/encode.rs @@ -232,8 +232,9 @@ fn encode_const_value<'tcx>( s.push_str(&encode_const(tcx, *field, field_cv.ty, dict, options)); } } - ty::DestructuredAdtConst::TypeId { ty } => { - s.push_str(&encode_ty(tcx, ty, dict, options)) + ty::DestructuredAdtConst::TypeId { ty: _, value } => { + let ty = value.to_value().ty; + s.push_str(&encode_const(tcx, value, ty, dict, options)) } }, diff --git a/compiler/rustc_symbol_mangling/src/v0.rs b/compiler/rustc_symbol_mangling/src/v0.rs index ef64d92a472e5..136b99f4a46c3 100644 --- a/compiler/rustc_symbol_mangling/src/v0.rs +++ b/compiler/rustc_symbol_mangling/src/v0.rs @@ -891,8 +891,8 @@ impl<'tcx> Printer<'tcx> for V0SymbolMangler<'tcx> { } ty::Adt(def, args) => { match cv.destructure_adt_const() { - ty::DestructuredAdtConst::TypeId { ty } => { - ty.print(self)?; + ty::DestructuredAdtConst::TypeId { ty: _, value } => { + self.print_const(value)?; } ty::DestructuredAdtConst::Aggregate { variant, fields } => { let fields = fields.iter().copied(); diff --git a/compiler/rustc_trait_selection/src/traits/wf.rs b/compiler/rustc_trait_selection/src/traits/wf.rs index 7eafcb3d73971..8b9a552055375 100644 --- a/compiler/rustc_trait_selection/src/traits/wf.rs +++ b/compiler/rustc_trait_selection/src/traits/wf.rs @@ -1231,7 +1231,8 @@ impl<'a, 'tcx> TypeVisitor> for WfPredicates<'a, 'tcx> { val.destructure_adt_const() => { let variant_def = adt_def.variant(variant); - let cause = self.cause(ObligationCauseCode::WellFormed(WellFormedLoc::None)); + let cause = + self.cause(ObligationCauseCode::WellFormed(WellFormedLoc::None)); self.out.extend(variant_def.fields.iter().zip(fields).map( |(field_def, &field_val)| { let field_ty = tcx diff --git a/compiler/rustc_type_ir/src/const_kind.rs b/compiler/rustc_type_ir/src/const_kind.rs index c7ab899dc85a3..187ab8990eac6 100644 --- a/compiler/rustc_type_ir/src/const_kind.rs +++ b/compiler/rustc_type_ir/src/const_kind.rs @@ -229,7 +229,7 @@ pub enum ConstEvalErr { /// /// `ValTree` does not have this problem with representation, as it only contains integers or /// lists of (nested) `ty::Const`s (which may indirectly contain more `ValTree`s). -#[derive_where(Clone, Copy, Debug, Hash, Eq, PartialEq; I: Interner)] +#[derive_where(Clone, Copy, Debug, Hash, PartialEq, Eq; I: Interner)] #[derive(TypeVisitable_Generic, TypeFoldable_Generic, GenericTypeVisitable)] #[cfg_attr( feature = "nightly", @@ -250,7 +250,13 @@ pub enum ValTreeKind { /// ZST types are represented as an empty slice. Branch(I::Consts), - TypeId(I::Ty), + /// `core::any::TypeId` values. + /// + /// Stores the actual `I::Ty` so that valtree-to-const can annotate values with the appropriate provenance. + /// + /// Also stores an inner type which transparently contains some representation of the bits of the `TypeId`. + /// Currently, this is just `(u128,)` but this is not to be relied upon. + TypeId(I::Ty, I::Consts), } impl ValTreeKind { diff --git a/compiler/rustc_type_ir/src/flags.rs b/compiler/rustc_type_ir/src/flags.rs index 07b8766637d00..dc26d4bf4aacc 100644 --- a/compiler/rustc_type_ir/src/flags.rs +++ b/compiler/rustc_type_ir/src/flags.rs @@ -528,8 +528,10 @@ impl FlagComputation { ty::ConstKind::Value(cv) => { self.add_ty(cv.ty()); match cv.valtree().kind() { - ty::ValTreeKind::Leaf(_) | ty::ValTreeKind::TypeId(_) => (), - ty::ValTreeKind::Branch(cts) => { + ty::ValTreeKind::Leaf(_) => (), + ty::ValTreeKind::Branch(cts) | ty::ValTreeKind::TypeId(_, cts) => { + // NB: no need to add the `TypeId` type itself, + // since it is inert for flag computation. for ct in cts.iter() { self.add_const(ct); } diff --git a/compiler/rustc_type_ir/src/relate.rs b/compiler/rustc_type_ir/src/relate.rs index e287738464ae9..2c4e5d1ee4d00 100644 --- a/compiler/rustc_type_ir/src/relate.rs +++ b/compiler/rustc_type_ir/src/relate.rs @@ -605,7 +605,9 @@ pub fn structurally_relate_consts>( .zip(branches_b.iter()) .all(|(a, b)| relation.relate(a, b).is_ok()) } - (ty::ValTreeKind::TypeId(a), ty::ValTreeKind::TypeId(b)) => a == b, + (ty::ValTreeKind::TypeId(a_ty, _), ty::ValTreeKind::TypeId(b_ty, _)) => { + a_ty == b_ty + } _ => false, } } diff --git a/library/core/src/any.rs b/library/core/src/any.rs index 894e567cabde8..0076e900e308d 100644 --- a/library/core/src/any.rs +++ b/library/core/src/any.rs @@ -87,11 +87,10 @@ #![stable(feature = "rust1", since = "1.0.0")] use crate::intrinsics::reflection::{type_id, type_id_vtable}; -use crate::intrinsics; use crate::marker::{ConstParamTy_, StructuralPartialEq}; use crate::mem::transmute; use crate::mem::type_info::{TraitImpl, TypeKind}; -use crate::{fmt, hash, ptr}; +use crate::{fmt, hash, intrinsics, ptr}; /////////////////////////////////////////////////////////////////////////////// // Any trait diff --git a/tests/ui/consts/const-eval/match-type-id.rs b/tests/ui/consts/const-eval/match-type-id.rs new file mode 100644 index 0000000000000..b19a6b562d833 --- /dev/null +++ b/tests/ui/consts/const-eval/match-type-id.rs @@ -0,0 +1,20 @@ +//@ revisions: stock gated +#![cfg_attr(gated, feature(const_trait_impl, const_cmp))] +//@[gated] run-pass + +use std::any::TypeId; + +fn main() { + const A: TypeId = TypeId::of::(); + + let s: &[u8] = &[0; { + match TypeId::of::() { + A => 1, + //[stock]~^ ERROR cannot match on `TypeId` in constants + //[stock]~| ERROR `PartialEq` is not yet stable as a const trait + _ => panic!(), + } + }]; + + assert_eq!(s.len(), 1); +} diff --git a/tests/ui/consts/const-eval/match-type-id.stock.stderr b/tests/ui/consts/const-eval/match-type-id.stock.stderr new file mode 100644 index 0000000000000..894f80481a671 --- /dev/null +++ b/tests/ui/consts/const-eval/match-type-id.stock.stderr @@ -0,0 +1,26 @@ +error[E0658]: cannot match on `TypeId` in constants + --> $DIR/match-type-id.rs:12:13 + | +LL | A => 1, + | ^ + | + = note: `TypeId` cannot be compared in compile-time, and therefore cannot be used in `match`es + = note: calls in constants are limited to constant functions, tuple structs and tuple variants + = note: see issue #143874 for more information + = help: add `#![feature(const_trait_impl)]` to the crate attributes to enable + = note: this compiler was built on YYYY-MM-DD; consider upgrading it if it is out of date + +error: `PartialEq` is not yet stable as a const trait + --> $DIR/match-type-id.rs:12:13 + | +LL | A => 1, + | ^ + | +help: add `#![feature(const_cmp)]` to the crate attributes to enable + | +LL + #![feature(const_cmp)] + | + +error: aborting due to 2 previous errors + +For more information about this error, try `rustc --explain E0658`. From dd8a0d6c2a7ce579161c6a447c5577d2431ff880 Mon Sep 17 00:00:00 2001 From: soqb Date: Thu, 19 Nov 2026 12:49:36 +0000 Subject: [PATCH 3/7] fix(type_id_structural_match): fix tests --- compiler/rustc_type_ir/src/const_kind.rs | 14 ++++++++- library/core/src/any.rs | 5 ++++ .../min_adt_const_params/type-id-arbitrary.rs | 4 +-- .../type-id-arbitrary.stderr | 14 +++++++++ .../min_adt_const_params/type-id.rs | 8 +++-- .../min_adt_const_params/type-id.stock.stderr | 26 +++++++++++++++++ .../match-type-id.gated_bounds.stderr | 26 +++++++++++++++++ .../const-eval/match-type-id.gated_cmp.stderr | 15 ++++++++++ tests/ui/consts/const-eval/match-type-id.rs | 11 ++++--- .../const-eval/match-type-id.stock.stderr | 29 ++++++------------- 10 files changed, 122 insertions(+), 30 deletions(-) create mode 100644 tests/ui/const-generics/min_adt_const_params/type-id-arbitrary.stderr create mode 100644 tests/ui/const-generics/min_adt_const_params/type-id.stock.stderr create mode 100644 tests/ui/consts/const-eval/match-type-id.gated_bounds.stderr create mode 100644 tests/ui/consts/const-eval/match-type-id.gated_cmp.stderr diff --git a/compiler/rustc_type_ir/src/const_kind.rs b/compiler/rustc_type_ir/src/const_kind.rs index 187ab8990eac6..bf62fa456d03a 100644 --- a/compiler/rustc_type_ir/src/const_kind.rs +++ b/compiler/rustc_type_ir/src/const_kind.rs @@ -229,7 +229,7 @@ pub enum ConstEvalErr { /// /// `ValTree` does not have this problem with representation, as it only contains integers or /// lists of (nested) `ty::Const`s (which may indirectly contain more `ValTree`s). -#[derive_where(Clone, Copy, Debug, Hash, PartialEq, Eq; I: Interner)] +#[derive_where(Clone, Copy, Hash, PartialEq, Eq; I: Interner)] #[derive(TypeVisitable_Generic, TypeFoldable_Generic, GenericTypeVisitable)] #[cfg_attr( feature = "nightly", @@ -259,6 +259,18 @@ pub enum ValTreeKind { TypeId(I::Ty, I::Consts), } +impl fmt::Debug for ValTreeKind { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + match self { + ValTreeKind::Leaf(i) => f.debug_tuple("Leaf").field(i).finish(), + ValTreeKind::Branch(cts) => f.debug_tuple("Branch").field(cts).finish(), + ValTreeKind::TypeId(ty, _) => { + f.debug_tuple("TypeId").field(ty).field(&fmt::from_fn(|f| write!(f, "_"))).finish() + } + } + } +} + impl ValTreeKind { /// Converts to a `ValTreeKind::Leaf` value, `panic`'ing /// if this valtree is some other kind. diff --git a/library/core/src/any.rs b/library/core/src/any.rs index 0076e900e308d..9a2b8d993d7c6 100644 --- a/library/core/src/any.rs +++ b/library/core/src/any.rs @@ -741,6 +741,9 @@ unsafe impl Sync for TypeId {} #[stable(feature = "rust1", since = "1.0.0")] #[rustc_const_unstable(feature = "const_cmp", issue = "143800")] const impl PartialEq for TypeId { + // NB: `TypeId: StructuralPartialEq` and like `str`, + // the compiler uses this method to compare constants in patterns. + // Do not make nontrivial changes to this method without proper consideration of match logic. #[inline] fn eq(&self, other: &Self) -> bool { crate::intrinsics::reflection::type_id_eq(*self, *other) @@ -874,8 +877,10 @@ impl fmt::Debug for TypeId { } #[unstable(feature = "type_id_structural_match", issue = "10000000")] +#[unstable_feature_bound(type_id_structural_match)] impl StructuralPartialEq for TypeId {} #[unstable(feature = "type_id_structural_match", issue = "10000000")] +#[unstable_feature_bound(type_id_structural_match)] impl ConstParamTy_ for TypeId {} /// Returns the name of a type as a string slice. diff --git a/tests/ui/const-generics/min_adt_const_params/type-id-arbitrary.rs b/tests/ui/const-generics/min_adt_const_params/type-id-arbitrary.rs index 6c390011e13d0..c26a74f7b6cf6 100644 --- a/tests/ui/const-generics/min_adt_const_params/type-id-arbitrary.rs +++ b/tests/ui/const-generics/min_adt_const_params/type-id-arbitrary.rs @@ -1,6 +1,5 @@ //@ edition:2024 -//@run-pass -#![feature(min_adt_const_params, const_param_ty_trait)] +#![feature(min_adt_const_params, const_param_ty_trait, type_id_structural_match)] #![allow(incomplete_features)] use std::marker::ConstParamTy; @@ -25,5 +24,6 @@ struct Wrapper; fn main() { let a: Wrapper<{ arbitrary_const_value!() }> = Wrapper; let b: Wrapper<{ arbitrary_const_value!() }> = a; + //~^ ERROR mismatched types } diff --git a/tests/ui/const-generics/min_adt_const_params/type-id-arbitrary.stderr b/tests/ui/const-generics/min_adt_const_params/type-id-arbitrary.stderr new file mode 100644 index 0000000000000..62e0fe83959ac --- /dev/null +++ b/tests/ui/const-generics/min_adt_const_params/type-id-arbitrary.stderr @@ -0,0 +1,14 @@ +error[E0308]: mismatched types + --> $DIR/type-id-arbitrary.rs:26:52 + | +LL | let b: Wrapper<{ arbitrary_const_value!() }> = a; + | ------------------------------------- ^ expected `Value { disambiguator: TypeId(main::{constant#1}::{constant#0}::Arbitrary, _) }`, found `Value { disambiguator: TypeId(main::{constant#0}::{constant#0}::Arbitrary, _) }` + | | + | expected due to this + | + = note: expected struct `Wrapper` + found struct `Wrapper` + +error: aborting due to 1 previous error + +For more information about this error, try `rustc --explain E0308`. diff --git a/tests/ui/const-generics/min_adt_const_params/type-id.rs b/tests/ui/const-generics/min_adt_const_params/type-id.rs index 5784fe59fc271..7a10a071c19e0 100644 --- a/tests/ui/const-generics/min_adt_const_params/type-id.rs +++ b/tests/ui/const-generics/min_adt_const_params/type-id.rs @@ -1,7 +1,7 @@ +//@ revisions: stock gated //@ edition:2024 -//@run-pass -#![feature(min_adt_const_params)] -#![allow(incomplete_features)] +//@[gated] run-pass +#![cfg_attr(gated, feature(min_adt_const_params, type_id_structural_match), allow(incomplete_features))] use std::any::TypeId; @@ -9,6 +9,8 @@ enum Foo {} enum Bar {} fn equate() -> bool { + //[stock]~^ ERROR `TypeId` is forbidden as the type of a const generic parameter + //[stock]~| ERROR `TypeId` is forbidden as the type of a const generic parameter A == B } diff --git a/tests/ui/const-generics/min_adt_const_params/type-id.stock.stderr b/tests/ui/const-generics/min_adt_const_params/type-id.stock.stderr new file mode 100644 index 0000000000000..c346cc77418e9 --- /dev/null +++ b/tests/ui/const-generics/min_adt_const_params/type-id.stock.stderr @@ -0,0 +1,26 @@ +error: `TypeId` is forbidden as the type of a const generic parameter + --> $DIR/type-id.rs:11:20 + | +LL | fn equate() -> bool { + | ^^^^^^ + | + = note: the only supported types are integers, `bool`, and `char` +help: add `#![feature(min_adt_const_params)]` to the crate attributes to enable more complex and user defined types + | +LL + #![feature(min_adt_const_params)] + | + +error: `TypeId` is forbidden as the type of a const generic parameter + --> $DIR/type-id.rs:11:37 + | +LL | fn equate() -> bool { + | ^^^^^^ + | + = note: the only supported types are integers, `bool`, and `char` +help: add `#![feature(min_adt_const_params)]` to the crate attributes to enable more complex and user defined types + | +LL + #![feature(min_adt_const_params)] + | + +error: aborting due to 2 previous errors + diff --git a/tests/ui/consts/const-eval/match-type-id.gated_bounds.stderr b/tests/ui/consts/const-eval/match-type-id.gated_bounds.stderr new file mode 100644 index 0000000000000..d7c5851b1a8f8 --- /dev/null +++ b/tests/ui/consts/const-eval/match-type-id.gated_bounds.stderr @@ -0,0 +1,26 @@ +error[E0658]: cannot match on `TypeId` in constants + --> $DIR/match-type-id.rs:14:13 + | +LL | A => 1, + | ^ + | + = note: `TypeId` cannot be compared in compile-time, and therefore cannot be used in `match`es + = note: calls in constants are limited to constant functions, tuple structs and tuple variants + = note: see issue #143874 for more information + = help: add `#![feature(const_trait_impl)]` to the crate attributes to enable + = note: this compiler was built on YYYY-MM-DD; consider upgrading it if it is out of date + +error: `PartialEq` is not yet stable as a const trait + --> $DIR/match-type-id.rs:14:13 + | +LL | A => 1, + | ^ + | +help: add `#![feature(const_cmp)]` to the crate attributes to enable + | +LL + #![feature(const_cmp)] + | + +error: aborting due to 2 previous errors + +For more information about this error, try `rustc --explain E0658`. diff --git a/tests/ui/consts/const-eval/match-type-id.gated_cmp.stderr b/tests/ui/consts/const-eval/match-type-id.gated_cmp.stderr new file mode 100644 index 0000000000000..200bda25873da --- /dev/null +++ b/tests/ui/consts/const-eval/match-type-id.gated_cmp.stderr @@ -0,0 +1,15 @@ +error: constant of non-structural type `TypeId` in a pattern + --> $DIR/match-type-id.rs:14:13 + | +LL | const A: TypeId = TypeId::of::(); + | --------------- constant defined here +... +LL | A => 1, + | ^ constant of non-structural type + | + --> $SRC_DIR/core/src/any.rs:LL:COL + | + = note: `TypeId` is not usable in patterns + +error: aborting due to 1 previous error + diff --git a/tests/ui/consts/const-eval/match-type-id.rs b/tests/ui/consts/const-eval/match-type-id.rs index b19a6b562d833..37e3d9d88ae29 100644 --- a/tests/ui/consts/const-eval/match-type-id.rs +++ b/tests/ui/consts/const-eval/match-type-id.rs @@ -1,5 +1,7 @@ -//@ revisions: stock gated -#![cfg_attr(gated, feature(const_trait_impl, const_cmp))] +//@ revisions: stock gated_cmp gated_bounds gated +//@ edition:2024 +#![cfg_attr(any(gated, gated_bounds), feature(type_id_structural_match))] +#![cfg_attr(any(gated, gated_cmp), feature(const_trait_impl, const_cmp))] //@[gated] run-pass use std::any::TypeId; @@ -10,8 +12,9 @@ fn main() { let s: &[u8] = &[0; { match TypeId::of::() { A => 1, - //[stock]~^ ERROR cannot match on `TypeId` in constants - //[stock]~| ERROR `PartialEq` is not yet stable as a const trait + //[stock,gated_cmp]~^ ERROR constant of non-structural type `TypeId` in a pattern + //[gated_bounds]~^^ ERROR cannot match on `TypeId` in constants + //[gated_bounds]~| ERROR `PartialEq` is not yet stable as a const trait _ => panic!(), } }]; diff --git a/tests/ui/consts/const-eval/match-type-id.stock.stderr b/tests/ui/consts/const-eval/match-type-id.stock.stderr index 894f80481a671..200bda25873da 100644 --- a/tests/ui/consts/const-eval/match-type-id.stock.stderr +++ b/tests/ui/consts/const-eval/match-type-id.stock.stderr @@ -1,26 +1,15 @@ -error[E0658]: cannot match on `TypeId` in constants - --> $DIR/match-type-id.rs:12:13 +error: constant of non-structural type `TypeId` in a pattern + --> $DIR/match-type-id.rs:14:13 | +LL | const A: TypeId = TypeId::of::(); + | --------------- constant defined here +... LL | A => 1, - | ^ + | ^ constant of non-structural type | - = note: `TypeId` cannot be compared in compile-time, and therefore cannot be used in `match`es - = note: calls in constants are limited to constant functions, tuple structs and tuple variants - = note: see issue #143874 for more information - = help: add `#![feature(const_trait_impl)]` to the crate attributes to enable - = note: this compiler was built on YYYY-MM-DD; consider upgrading it if it is out of date - -error: `PartialEq` is not yet stable as a const trait - --> $DIR/match-type-id.rs:12:13 - | -LL | A => 1, - | ^ - | -help: add `#![feature(const_cmp)]` to the crate attributes to enable - | -LL + #![feature(const_cmp)] + --> $SRC_DIR/core/src/any.rs:LL:COL | + = note: `TypeId` is not usable in patterns -error: aborting due to 2 previous errors +error: aborting due to 1 previous error -For more information about this error, try `rustc --explain E0658`. From 27adbdaa65c4ef785a2961022890e4094891425c Mon Sep 17 00:00:00 2001 From: soqb Date: Thu, 19 Nov 2026 13:04:05 +0000 Subject: [PATCH 4/7] fix: issue 1 million -> issue none --- library/core/src/any.rs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/library/core/src/any.rs b/library/core/src/any.rs index 9a2b8d993d7c6..98c31b525bd5d 100644 --- a/library/core/src/any.rs +++ b/library/core/src/any.rs @@ -876,10 +876,10 @@ impl fmt::Debug for TypeId { } } -#[unstable(feature = "type_id_structural_match", issue = "10000000")] +#[unstable(feature = "type_id_structural_match", issue = "none")] #[unstable_feature_bound(type_id_structural_match)] impl StructuralPartialEq for TypeId {} -#[unstable(feature = "type_id_structural_match", issue = "10000000")] +#[unstable(feature = "type_id_structural_match", issue = "none")] #[unstable_feature_bound(type_id_structural_match)] impl ConstParamTy_ for TypeId {} From b7e83e335a1806ac5b67e3b9ea6b2fd29005e35f Mon Sep 17 00:00:00 2001 From: soqb Date: Thu, 19 Nov 2026 13:09:57 +0000 Subject: [PATCH 5/7] tidy --- .../const-generics/min_adt_const_params/type-id-arbitrary.rs | 1 - tests/ui/const-generics/min_adt_const_params/type-id.rs | 3 ++- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/tests/ui/const-generics/min_adt_const_params/type-id-arbitrary.rs b/tests/ui/const-generics/min_adt_const_params/type-id-arbitrary.rs index c26a74f7b6cf6..4b6bdc6d4b2b5 100644 --- a/tests/ui/const-generics/min_adt_const_params/type-id-arbitrary.rs +++ b/tests/ui/const-generics/min_adt_const_params/type-id-arbitrary.rs @@ -26,4 +26,3 @@ fn main() { let b: Wrapper<{ arbitrary_const_value!() }> = a; //~^ ERROR mismatched types } - diff --git a/tests/ui/const-generics/min_adt_const_params/type-id.rs b/tests/ui/const-generics/min_adt_const_params/type-id.rs index 7a10a071c19e0..ed78f3d887173 100644 --- a/tests/ui/const-generics/min_adt_const_params/type-id.rs +++ b/tests/ui/const-generics/min_adt_const_params/type-id.rs @@ -1,7 +1,8 @@ //@ revisions: stock gated //@ edition:2024 //@[gated] run-pass -#![cfg_attr(gated, feature(min_adt_const_params, type_id_structural_match), allow(incomplete_features))] +#![cfg_attr(gated, feature(min_adt_const_params, type_id_structural_match))] +#![cfg_attr(gated, allow(incomplete_features))] use std::any::TypeId; From 44821dc2c4b14892ca869af0caec5d58b0b81e2d Mon Sep 17 00:00:00 2001 From: soqb Date: Thu, 19 Nov 2026 13:14:11 +0000 Subject: [PATCH 6/7] fix: comments in mir patterns --- compiler/rustc_mir_build/src/builder/matches/test.rs | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/compiler/rustc_mir_build/src/builder/matches/test.rs b/compiler/rustc_mir_build/src/builder/matches/test.rs index af5705df81163..2872f9c499cdc 100644 --- a/compiler/rustc_mir_build/src/builder/matches/test.rs +++ b/compiler/rustc_mir_build/src/builder/matches/test.rs @@ -149,7 +149,6 @@ impl<'a, 'tcx> Builder<'a, 'tcx> { let fail_block = target_block(TestBranch::Failure); let ref_ty = Ty::new_imm_ref(tcx, tcx.lifetimes.re_erased, value.ty); - // assert!(ref_ty.is_imm_ref(), "{ref_ty:?}"); // If the constant we're testing against has type `T`, // calling `::eq` requires `&T` operands. @@ -170,7 +169,7 @@ impl<'a, 'tcx> Builder<'a, 'tcx> { Rvalue::Ref(tcx.lifetimes.re_erased, BorrowKind::Shared, place), ); - // Compare two strings using `::eq`. + // Compare two consts using `::eq`. // (Interestingly this means that exhaustiveness analysis relies, for soundness, // on the `PartialEq` impl for `str` to be correct!) self.compare_with_eq( From 46dfb64aa2da869d7e03769c567c4ece380c8a19 Mon Sep 17 00:00:00 2001 From: soqb Date: Thu, 19 Nov 2026 14:41:55 +0000 Subject: [PATCH 7/7] fix: bless tests --- .../const-generics/min_adt_const_params/type-id.stock.stderr | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/tests/ui/const-generics/min_adt_const_params/type-id.stock.stderr b/tests/ui/const-generics/min_adt_const_params/type-id.stock.stderr index c346cc77418e9..49615cecacf25 100644 --- a/tests/ui/const-generics/min_adt_const_params/type-id.stock.stderr +++ b/tests/ui/const-generics/min_adt_const_params/type-id.stock.stderr @@ -1,5 +1,5 @@ error: `TypeId` is forbidden as the type of a const generic parameter - --> $DIR/type-id.rs:11:20 + --> $DIR/type-id.rs:12:20 | LL | fn equate() -> bool { | ^^^^^^ @@ -11,7 +11,7 @@ LL + #![feature(min_adt_const_params)] | error: `TypeId` is forbidden as the type of a const generic parameter - --> $DIR/type-id.rs:11:37 + --> $DIR/type-id.rs:12:37 | LL | fn equate() -> bool { | ^^^^^^