mirror of
https://github.com/rust-lang/rust.git
synced 2026-05-30 13:06:28 +03:00
Add TypeId::field method to get a field representing type for type_info
This commit is contained in:
@@ -647,6 +647,53 @@ fn call_intrinsic(
|
||||
ecx.write_scalar(Scalar::from_target_usize(fields_num as u64, ecx), dest)?;
|
||||
}
|
||||
|
||||
sym::type_id_field => {
|
||||
let ty = ecx.read_type_id(&args[0])?;
|
||||
let variant_idx = ecx.read_target_usize(&args[1])? as usize;
|
||||
let field_idx = ecx.read_target_usize(&args[2])? as usize;
|
||||
|
||||
let variants_num =
|
||||
ty.ty_adt_def().map(|adt_def| adt_def.variants().len()).unwrap_or(1);
|
||||
if variant_idx >= variants_num {
|
||||
throw_ub!(BoundsCheckFailed {
|
||||
len: variants_num as u64,
|
||||
index: variant_idx as u64
|
||||
});
|
||||
}
|
||||
|
||||
let field_ty = match ty.kind() {
|
||||
ty::Adt(adt_def, generics) => {
|
||||
let variant_def = &adt_def.variants()[VariantIdx::from_usize(variant_idx)];
|
||||
let fields_num = variant_def.fields.len();
|
||||
if field_idx >= fields_num {
|
||||
throw_ub!(BoundsCheckFailed {
|
||||
len: fields_num as u64,
|
||||
index: field_idx as u64
|
||||
});
|
||||
}
|
||||
let field_def = &variant_def.fields[FieldIdx::from_usize(field_idx)];
|
||||
field_def.ty(ecx.tcx.tcx, generics).skip_norm_wip()
|
||||
}
|
||||
ty::Tuple(fields) => {
|
||||
let fields_num = fields.len();
|
||||
if field_idx >= fields_num {
|
||||
throw_ub!(BoundsCheckFailed {
|
||||
len: fields_num as u64,
|
||||
index: field_idx as u64
|
||||
});
|
||||
}
|
||||
fields[field_idx]
|
||||
}
|
||||
_ => {
|
||||
// Other types have no fields, so any field index is out of bounds.
|
||||
throw_ub!(BoundsCheckFailed { len: 0, index: field_idx as u64 });
|
||||
}
|
||||
};
|
||||
|
||||
let field_ty = ecx.tcx.erase_and_anonymize_regions(field_ty);
|
||||
ecx.write_type_id(field_ty, dest)?;
|
||||
}
|
||||
|
||||
sym::type_id_variants => {
|
||||
let ty = ecx.read_type_id(&args[0])?;
|
||||
let variants_num = ty.ty_adt_def().map(|def| def.variants().len()).unwrap_or(1);
|
||||
|
||||
@@ -213,6 +213,7 @@ fn intrinsic_operation_unsafety(tcx: TyCtxt<'_>, intrinsic_id: LocalDefId) -> hi
|
||||
| sym::truncf128
|
||||
| sym::type_id
|
||||
| sym::type_id_eq
|
||||
| sym::type_id_field
|
||||
| sym::type_id_fields
|
||||
| sym::type_id_variants
|
||||
| sym::type_id_vtable
|
||||
@@ -321,6 +322,9 @@ pub(crate) fn check_intrinsic_type(
|
||||
sym::type_name => (1, 0, vec![], Ty::new_static_str(tcx)),
|
||||
sym::type_id => (1, 0, vec![], type_id_ty()),
|
||||
sym::type_id_eq => (0, 0, vec![type_id_ty(), type_id_ty()], tcx.types.bool),
|
||||
sym::type_id_field => {
|
||||
(0, 0, vec![type_id_ty(), tcx.types.usize, tcx.types.usize], type_id_ty())
|
||||
}
|
||||
sym::type_id_fields => (0, 0, vec![type_id_ty(), tcx.types.usize], tcx.types.usize),
|
||||
sym::type_id_variants => (0, 0, vec![type_id_ty()], tcx.types.usize),
|
||||
sym::type_id_vtable => {
|
||||
|
||||
@@ -2098,6 +2098,7 @@
|
||||
type_changing_struct_update,
|
||||
type_id,
|
||||
type_id_eq,
|
||||
type_id_field,
|
||||
type_id_fields,
|
||||
type_id_variants,
|
||||
type_id_vtable,
|
||||
|
||||
@@ -852,7 +852,7 @@ pub const fn trait_info_of_trait_type_id(
|
||||
}
|
||||
}
|
||||
|
||||
fn as_u128(self) -> u128 {
|
||||
pub(crate) fn as_u128(self) -> u128 {
|
||||
let mut bytes = [0; 16];
|
||||
|
||||
// This is a provenance-stripping memcpy.
|
||||
|
||||
@@ -2964,6 +2964,19 @@ pub const fn type_id_fields(_id: crate::any::TypeId, _variant_index: usize) -> u
|
||||
panic!("`TypeId::fields` can only be called at compile-time")
|
||||
}
|
||||
|
||||
/// Gets the `TypeId` of the field at the given index of the type represented by this `TypeId`.
|
||||
///
|
||||
/// The more user-friendly version of this intrinsic is [`core::any::TypeId::field`].
|
||||
#[rustc_intrinsic]
|
||||
#[unstable(feature = "core_intrinsics", issue = "none")]
|
||||
pub const fn type_id_field(
|
||||
_id: crate::any::TypeId,
|
||||
_variant_index: usize,
|
||||
_field_index: usize,
|
||||
) -> crate::any::TypeId {
|
||||
panic!("`TypeId::field` can only be called at compile-time")
|
||||
}
|
||||
|
||||
/// Lowers in MIR to `Rvalue::Aggregate` with `AggregateKind::RawPtr`.
|
||||
///
|
||||
/// This is used to implement functions like `slice::from_raw_parts_mut` and
|
||||
|
||||
@@ -2,6 +2,7 @@
|
||||
//! runtime or const-eval processable way.
|
||||
|
||||
use crate::any::TypeId;
|
||||
use crate::fmt;
|
||||
use crate::intrinsics::{self, type_id, type_of};
|
||||
use crate::marker::PointeeSized;
|
||||
use crate::ptr::DynMetadata;
|
||||
@@ -463,4 +464,94 @@ pub const fn variants(self) -> usize {
|
||||
pub const fn fields(self, variant_index: usize) -> usize {
|
||||
intrinsics::type_id_fields(self, variant_index)
|
||||
}
|
||||
|
||||
/// Returns the field representing type at the given index of the type represented by this `TypeId`.
|
||||
///
|
||||
/// ```
|
||||
/// #![feature(type_info)]
|
||||
/// use std::any::TypeId;
|
||||
///
|
||||
/// struct Point {
|
||||
/// x: u32,
|
||||
/// y: u32,
|
||||
/// }
|
||||
/// assert_eq!(const { TypeId::of::<Point>().field(0, 0).type_id() }, TypeId::of::<u32>());
|
||||
/// assert_eq!(const { TypeId::of::<Point>().field(0, 1).type_id() }, TypeId::of::<u32>());
|
||||
///
|
||||
/// enum Enum {
|
||||
/// Unit,
|
||||
/// Tuple(u32, u64),
|
||||
/// Struct { x: u32, y: u32, z: String },
|
||||
/// }
|
||||
/// assert_eq!(const { TypeId::of::<Enum>().field(1, 0).type_id() }, TypeId::of::<u32>());
|
||||
/// assert_eq!(const { TypeId::of::<Enum>().field(2, 2).type_id() }, TypeId::of::<String>());
|
||||
/// ```
|
||||
///
|
||||
/// The variant index and field index refer to the source order index of a variant in a type and
|
||||
/// the source order index of a field in a variant, respectively.
|
||||
///
|
||||
/// For enums, variant indexes are always `0..variant_count`, regardless of any custom discriminants that may have been defined.
|
||||
/// `struct`s, `tuples`, and `unions`s are considered to have a single variant with variant index zero.
|
||||
///
|
||||
/// As for field indexes, they may not be the same as the layout order for `repr(Rust)` types, but they are for `repr(C)` types.
|
||||
///
|
||||
/// ```
|
||||
/// enum Enum {
|
||||
/// Foo, // variant index == 0
|
||||
/// Bar { // variant index == 1
|
||||
/// a: (), // field index == 0 in `Bar`
|
||||
/// b: (), // field index == 1 in `Bar`
|
||||
/// }
|
||||
/// }
|
||||
/// ```
|
||||
///
|
||||
/// Out-of-bounds indexing will be treated as a compile-time error.
|
||||
///
|
||||
/// ```compile_fail,E0080
|
||||
/// # #![feature(type_info)]
|
||||
/// # use std::any::TypeId;
|
||||
/// #
|
||||
/// # struct Point {
|
||||
/// # x: u32,
|
||||
/// # y: u32,
|
||||
/// # }
|
||||
/// # enum Enum {
|
||||
/// # Unit,
|
||||
/// # Tuple(u32, u64),
|
||||
/// # Struct { x: u32, y: u32, z: String },
|
||||
/// # }
|
||||
/// const {
|
||||
/// _ = TypeId::of::<Point>().field(0, 10); // error: indexing out of bounds: the len is 2 but the index is 10
|
||||
/// _ = TypeId::of::<Enum>().field(2, 10); // error: indexing out of bounds: the len is 3 but the index is 10
|
||||
/// }
|
||||
/// ```
|
||||
#[unstable(feature = "type_info", issue = "146922")]
|
||||
#[rustc_const_unstable(feature = "type_info", issue = "146922")]
|
||||
pub const fn field(self, variant_index: usize, field_index: usize) -> FieldId {
|
||||
FieldId { type_id: intrinsics::type_id_field(self, variant_index, field_index) }
|
||||
}
|
||||
}
|
||||
|
||||
/// `FieldId` is a wrapper of `TypeId`, representing a field of a struct, tuple or enum variant.
|
||||
#[derive(Copy, PartialOrd, Ord, Hash)]
|
||||
#[derive_const(Clone, PartialEq, Eq)]
|
||||
#[unstable(feature = "type_info", issue = "146922")]
|
||||
pub struct FieldId {
|
||||
type_id: TypeId,
|
||||
}
|
||||
|
||||
#[unstable(feature = "type_info", issue = "146922")]
|
||||
impl fmt::Debug for FieldId {
|
||||
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||
write!(f, "FieldId({:#034x})", self.type_id.as_u128())
|
||||
}
|
||||
}
|
||||
|
||||
impl FieldId {
|
||||
/// Returns the `TypeId` of this field.
|
||||
#[unstable(feature = "type_info", issue = "146922")]
|
||||
#[rustc_const_unstable(feature = "type_info", issue = "146922")]
|
||||
pub const fn type_id(self) -> TypeId {
|
||||
self.type_id
|
||||
}
|
||||
}
|
||||
|
||||
@@ -78,11 +78,14 @@ fn assert_tuple_arity<T: 'static, const N: usize>() {
|
||||
assert!(ty_id.size() == Some(size_of::<(u8,)>()));
|
||||
assert!(ty_id.variants() == 1);
|
||||
assert!(ty_id.fields(0) == 1);
|
||||
assert!(ty_id.field(0, 0).type_id() == TypeId::of::<u8>());
|
||||
|
||||
let ty_id = TypeId::of::<(u8, u8)>();
|
||||
assert!(ty_id.size() == Some(size_of::<(u8, u8)>()));
|
||||
let ty_id = TypeId::of::<(u8, u16)>();
|
||||
assert!(ty_id.size() == Some(size_of::<(u8, u16)>()));
|
||||
assert!(ty_id.variants() == 1);
|
||||
assert!(ty_id.fields(0) == 2);
|
||||
assert!(ty_id.field(0, 0).type_id() == TypeId::of::<u8>());
|
||||
assert!(ty_id.field(0, 1).type_id() == TypeId::of::<u16>());
|
||||
}
|
||||
}
|
||||
|
||||
@@ -114,6 +117,9 @@ struct TestStruct {
|
||||
assert!(ty_id.size() == Some(size_of::<TestStruct>()));
|
||||
assert!(ty_id.variants() == 1);
|
||||
assert!(ty_id.fields(0) == 3);
|
||||
assert!(ty_id.field(0, 0).type_id() == TypeId::of::<u8>());
|
||||
assert!(ty_id.field(0, 1).type_id() == TypeId::of::<u16>());
|
||||
assert!(ty_id.field(0, 2).type_id() == TypeId::of::<&u16>());
|
||||
}
|
||||
|
||||
const {
|
||||
@@ -135,6 +141,13 @@ struct NonExhaustive {
|
||||
assert!(ty.fields[0].ty == TypeId::of::<u8>());
|
||||
assert!(ty.fields[1].name == "1");
|
||||
assert!(ty.fields[1].ty == TypeId::of::<u16>());
|
||||
|
||||
let ty_id = TypeId::of::<TupleStruct>();
|
||||
assert!(ty_id.size() == Some(size_of::<TupleStruct>()));
|
||||
assert!(ty_id.variants() == 1);
|
||||
assert!(ty_id.fields(0) == 2);
|
||||
assert!(ty_id.field(0, 0).type_id() == TypeId::of::<u8>());
|
||||
assert!(ty_id.field(0, 1).type_id() == TypeId::of::<u16>());
|
||||
}
|
||||
|
||||
const {
|
||||
@@ -177,6 +190,8 @@ union TestUnion {
|
||||
assert!(ty_id.size() == Some(size_of::<TestUnion>()));
|
||||
assert!(ty_id.variants() == 1);
|
||||
assert!(ty_id.fields(0) == 2);
|
||||
assert!(ty_id.field(0, 0).type_id() == TypeId::of::<i16>());
|
||||
assert!(ty_id.field(0, 1).type_id() == TypeId::of::<u16>());
|
||||
}
|
||||
|
||||
const {
|
||||
@@ -237,6 +252,9 @@ enum E {
|
||||
assert!(ty_id.fields(0) == 1);
|
||||
assert!(ty_id.fields(1) == 0);
|
||||
assert!(ty_id.fields(2) == 2);
|
||||
assert!(ty_id.field(0, 0).type_id() == TypeId::of::<u32>());
|
||||
assert!(ty_id.field(2, 0).type_id() == TypeId::of::<()>());
|
||||
assert!(ty_id.field(2, 1).type_id() == TypeId::of::<&str>());
|
||||
}
|
||||
|
||||
const {
|
||||
@@ -251,6 +269,7 @@ enum E {
|
||||
assert!(ty_id.variants() == 2);
|
||||
assert!(ty_id.fields(0) == 0);
|
||||
assert!(ty_id.fields(1) == 1);
|
||||
assert!(ty_id.field(1, 0).type_id() == TypeId::of::<i32>());
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -8,3 +8,8 @@ fn main() {}
|
||||
TypeId::of::<Option::<()>>().fields(2);
|
||||
//~^ ERROR indexing out of bounds: the len is 2 but the index is 2
|
||||
};
|
||||
|
||||
const _: () = const {
|
||||
TypeId::of::<Option::<()>>().field(0, 1);
|
||||
//~^ ERROR indexing out of bounds: the len is 0 but the index is 1
|
||||
};
|
||||
|
||||
@@ -17,6 +17,25 @@ LL | |
|
||||
LL | | };
|
||||
| |_^
|
||||
|
||||
error: aborting due to 1 previous error
|
||||
error[E0080]: indexing out of bounds: the len is 0 but the index is 1
|
||||
--> $DIR/variant_index_out_of_bounds.rs:13:5
|
||||
|
|
||||
LL | TypeId::of::<Option::<()>>().field(0, 1);
|
||||
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ evaluation of `_::{constant#0}` failed inside this call
|
||||
|
|
||||
note: inside `type_info::<impl TypeId>::field`
|
||||
--> $SRC_DIR/core/src/mem/type_info.rs:LL:COL
|
||||
|
||||
note: erroneous constant encountered
|
||||
--> $DIR/variant_index_out_of_bounds.rs:12:15
|
||||
|
|
||||
LL | const _: () = const {
|
||||
| _______________^
|
||||
LL | | TypeId::of::<Option::<()>>().field(0, 1);
|
||||
LL | |
|
||||
LL | | };
|
||||
| |_^
|
||||
|
||||
error: aborting due to 2 previous errors
|
||||
|
||||
For more information about this error, try `rustc --explain E0080`.
|
||||
|
||||
Reference in New Issue
Block a user