diff --git a/compiler/rustc_const_eval/src/const_eval/valtrees.rs b/compiler/rustc_const_eval/src/const_eval/valtrees.rs index 562b5bb74b92e..a197e21ab39bc 100644 --- a/compiler/rustc_const_eval/src/const_eval/valtrees.rs +++ b/compiler/rustc_const_eval/src/const_eval/valtrees.rs @@ -1,4 +1,5 @@ use rustc_abi::{BackendRepr, FieldIdx, VariantIdx}; +use rustc_attr_ir::LangItem; use rustc_data_structures::fx::{FxHashMap, FxHashSet}; use rustc_middle::mir; use rustc_middle::mir::interpret::{EvalToValTreeResult, GlobalId, ValTreeCreationError}; @@ -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..6cbe674cbc155 100644 --- a/compiler/rustc_middle/src/ty/consts/valtree.rs +++ b/compiler/rustc_middle/src/ty/consts/valtree.rs @@ -61,6 +61,14 @@ 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 { + 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)) + } } impl<'tcx> Deref for ValTree<'tcx> { @@ -171,7 +179,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 +189,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 +197,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 +210,22 @@ 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, consts) => { + assert_eq!(consts.len(), 1); + return ty::DestructuredAdtConst::TypeId { ty, value: consts[0] }; + } + }; let (variant, fields) = match self.ty.kind() { ty::Adt(def, _) if def.variants().is_empty() => { @@ -222,7 +239,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..a032d73fbef56 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>, value: ty::Const<'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/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 6b516fb2f3972..2872f9c499cdc 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,25 @@ 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); - // 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 +169,15 @@ 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.string_compare( + self.compare_with_eq( block, success_block, fail_block, source_info, + value.ty, expected_value_operand, Operand::Copy(actual_value_ref_place), ); @@ -259,7 +258,7 @@ impl<'a, 'tcx> Builder<'a, 'tcx> { block, self.source_info(test.span), transmuted_expect, - Rvalue::Cast(CastKind::Transmute, expected_value_operand, base), + Rvalue::Cast(CastKind::Transmute, expected_value_operand.clone(), base), ); actual_value_place = transmuted_place; @@ -458,19 +457,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_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..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 @@ -220,18 +220,23 @@ 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: _, value } => { + let ty = value.to_value().ty; + s.push_str(&encode_const(tcx, value, 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..136b99f4a46c3 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: _, value } => { + self.print_const(value)?; } - 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..8b9a552055375 100644 --- a/compiler/rustc_trait_selection/src/traits/wf.rs +++ b/compiler/rustc_trait_selection/src/traits/wf.rs @@ -1226,12 +1226,14 @@ 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); + 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(adt_val.fields).map( + 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..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, Eq, PartialEq; I: Interner)] +#[derive_where(Clone, Copy, Hash, PartialEq, Eq; I: Interner)] #[derive(TypeVisitable_Generic, TypeFoldable_Generic, GenericTypeVisitable)] #[cfg_attr( feature = "nightly", @@ -249,6 +249,26 @@ pub enum ValTreeKind { /// /// ZST types are represented as an empty slice. Branch(I::Consts), + + /// `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 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 { @@ -258,7 +278,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 +288,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 +296,7 @@ impl ValTreeKind { pub fn try_to_leaf(&self) -> Option { match self { ValTreeKind::Leaf(s) => Some(*s), - ValTreeKind::Branch(_) => None, + _ => None, } } @@ -284,7 +304,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..dc26d4bf4aacc 100644 --- a/compiler/rustc_type_ir/src/flags.rs +++ b/compiler/rustc_type_ir/src/flags.rs @@ -529,7 +529,9 @@ impl FlagComputation { self.add_ty(cv.ty()); match cv.valtree().kind() { ty::ValTreeKind::Leaf(_) => (), - ty::ValTreeKind::Branch(cts) => { + 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 e87b584ebcb6b..2c4e5d1ee4d00 100644 --- a/compiler/rustc_type_ir/src/relate.rs +++ b/compiler/rustc_type_ir/src/relate.rs @@ -605,6 +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, _), 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 88364538146c2..98c31b525bd5d 100644 --- a/library/core/src/any.rs +++ b/library/core/src/any.rs @@ -87,10 +87,10 @@ #![stable(feature = "rust1", since = "1.0.0")] use crate::intrinsics::reflection::{type_id, type_id_vtable}; -use crate::intrinsics::{self}; +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 @@ -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) @@ -873,6 +876,13 @@ impl fmt::Debug for TypeId { } } +#[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 = "none")] +#[unstable_feature_bound(type_id_structural_match)] +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..4b6bdc6d4b2b5 --- /dev/null +++ b/tests/ui/const-generics/min_adt_const_params/type-id-arbitrary.rs @@ -0,0 +1,28 @@ +//@ edition:2024 +#![feature(min_adt_const_params, const_param_ty_trait, type_id_structural_match)] +#![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; + //~^ 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 new file mode 100644 index 0000000000000..ed78f3d887173 --- /dev/null +++ b/tests/ui/const-generics/min_adt_const_params/type-id.rs @@ -0,0 +1,22 @@ +//@ revisions: stock gated +//@ edition:2024 +//@[gated] run-pass +#![cfg_attr(gated, feature(min_adt_const_params, type_id_structural_match))] +#![cfg_attr(gated, allow(incomplete_features))] + +use std::any::TypeId; + +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 +} + +fn main() { + assert!(equate::<{ TypeId::of::() }, { TypeId::of::() }>()); + assert!(equate::<{ TypeId::of::() }, { TypeId::of::() }>()); + assert!(!equate::<{ TypeId::of::() }, { TypeId::of::() }>()); +} 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..49615cecacf25 --- /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:12: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:12: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 new file mode 100644 index 0000000000000..37e3d9d88ae29 --- /dev/null +++ b/tests/ui/consts/const-eval/match-type-id.rs @@ -0,0 +1,23 @@ +//@ 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; + +fn main() { + const A: TypeId = TypeId::of::(); + + let s: &[u8] = &[0; { + match TypeId::of::() { + A => 1, + //[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!(), + } + }]; + + 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..200bda25873da --- /dev/null +++ b/tests/ui/consts/const-eval/match-type-id.stock.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 +