Rollup merge of #156403 - SpriteOvO:type-info-refactor-variant, r=oli-obk

Add `TypeId` methods `variants` `fields` `field` for `type_info`

Tracking issue rust-lang/rust#146922

- Adds `fn TypeId::variants` returns the number of variants, for struct and union and primitive types, it's always 1.
- Adds `fn TypeId::fields` returns the number of fields.
- Adds `fn TypeId::field` returns a field representing type `FieldId`.
- Adds a new type `FieldId`, which is a wrapper of `FieldRepresentingType`'s `TypeId`.

For methods `{fields,field}`, if indexing out of bounds, a compile-time error will be raised.

Regarding the removal of `Type` items, this will be done in a later PR in one go.

r? @oli-obk
This commit is contained in:
Matthias Krüger
2026-05-28 07:53:35 +02:00
committed by GitHub
9 changed files with 456 additions and 4 deletions
@@ -0,0 +1,15 @@
#![feature(type_info)]
use std::any::TypeId;
fn main() {}
const _: () = const {
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
};
@@ -0,0 +1,41 @@
error[E0080]: indexing out of bounds: the len is 2 but the index is 2
--> $DIR/variant_index_out_of_bounds.rs:8:5
|
LL | TypeId::of::<Option::<()>>().fields(2);
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ evaluation of `_::{constant#0}` failed inside this call
|
note: inside `type_info::<impl TypeId>::fields`
--> $SRC_DIR/core/src/mem/type_info.rs:LL:COL
note: erroneous constant encountered
--> $DIR/variant_index_out_of_bounds.rs:7:15
|
LL | const _: () = const {
| _______________^
LL | | TypeId::of::<Option::<()>>().fields(2);
LL | |
LL | | };
| |_^
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`.