Skip to content

Commit 6fd4c3f

Browse files
committed
Auto merge of #72488 - KodrAus:stabilize/const_type_id, r=nikomatsakis
Stabilize const_type_id feature The tracking issue for `const_type_id` points to the ill-fated #41875. So I'm re-energizing `TypeId` shenanigans by opening this one up to see if there's anything blocking us from stabilizing the constification of type ids. Will wait for CI before pinging teams/groups. ----- This PR stabilizes the `const_type_id` feature, which allows `TypeId::of` (and the underlying unstable intrinsic) to be called in constant contexts. There are some [sanity tests](https://github.com/rust-lang/rust/blob/master/src/test/ui/consts/const-typeid-of-rpass.rs) that demonstrate its usage, but I’ve included some more below. As a simple example, you could create a constant item that contains some type ids: ```rust use std::any::TypeId; const TYPE_IDS: [TypeId; 2] = [ TypeId::of::<u32>(), TypeId::of::<i32>(), ]; assert_eq!(TypeId::of::<u32>(), TYPE_IDS[0]); ``` Type ids can also now appear in associated constants. You could create a trait that associates each type with its constant type id: ```rust trait Any where Self: 'static { const TYPE_ID: TypeId = TypeId::of::<Self>(); } impl<T: 'static> Any for T { } assert_eq!(TypeId::of::<usize>(), usize::TYPE_ID); ``` `TypeId::of` is generic, which we saw above in the way the generic `Self` argument was used. This has some implications for const evaluation. It means we can make trait impls evaluate differently depending on information that wasn't directly passed through the trait system. This violates the _parametricity_ property, which requires all instances of a generic function to behave the same way with respect to its generic parameters. That's not unique to `TypeId::of`, other generic const functions based on compiler intrinsics like `mem::align_of` can also violate parametricity. In practice Rust doesn't really have type parametricity anyway since it monomorphizes generics into concrete functions, so violating it using type ids isn’t new. As an example of how impls can behave differently, you could combine constant type ids with the `const_if_match` feature to dispatch calls based on the type id of the generic `Self`, rather than based on information about `Self` that was threaded through trait bounds. It's like a rough-and-ready form of specialization: ```rust #![feature(const_if_match)] trait Specialized where Self: 'static { // An associated constant that determines the function to call // at compile-time based on `TypeId::of::<Self>`. const CALL: fn(&Self) = { const USIZE: TypeId = TypeId::of::<usize>(); match TypeId::of::<Self>() { // Use a closure for `usize` that transmutes the generic `Self` to // a concrete `usize` and dispatches to `Self::usize`. USIZE => |x| Self::usize(unsafe { &*(x as *const Self as *const usize) }), // For other types, dispatch to the generic `Self::default`. _ => Self::default, } }; fn call(&self) { // Call the function we determined at compile-time (Self::CALL)(self) } fn default(x: &Self); fn usize(x: &usize); } // Implement our `Specialized` trait for any `Debug` type. impl<T: fmt::Debug + 'static> Specialized for T { fn default(x: &Self) { println!("default: {:?}", x); } fn usize(x: &usize) { println!("usize: {:?}", x); } } // Will print "usize: 42" Specialized::call(&42usize); // Will print "default: ()" Specialized::call(&()); ``` Type ids have some edges that this stabilization exposes to more contexts. It's possible for type ids to collide (but this is a bug). Since they can change between compiler versions, it's never valid to cast a type id to its underlying value.
2 parents 584e83d + 9d4818c commit 6fd4c3f

9 files changed

+6
-28
lines changed

library/core/src/any.rs

+1-1
Original file line numberDiff line numberDiff line change
@@ -435,7 +435,7 @@ impl TypeId {
435435
/// assert_eq!(is_string(&"cookie monster".to_string()), true);
436436
/// ```
437437
#[stable(feature = "rust1", since = "1.0.0")]
438-
#[rustc_const_unstable(feature = "const_type_id", issue = "41875")]
438+
#[rustc_const_stable(feature = "const_type_id", since = "1.46.0")]
439439
pub const fn of<T: ?Sized + 'static>() -> TypeId {
440440
TypeId { t: intrinsics::type_id::<T>() }
441441
}

library/core/src/intrinsics.rs

+1-1
Original file line numberDiff line numberDiff line change
@@ -1024,7 +1024,7 @@ extern "rust-intrinsic" {
10241024
///
10251025
/// The stabilized version of this intrinsic is
10261026
/// [`std::any::TypeId::of`](../../std/any/struct.TypeId.html#method.of)
1027-
#[rustc_const_unstable(feature = "const_type_id", issue = "41875")]
1027+
#[rustc_const_stable(feature = "const_type_id", since = "1.46.0")]
10281028
pub fn type_id<T: ?Sized + 'static>() -> u64;
10291029

10301030
/// A guard for unsafe functions that cannot ever be executed if `T` is uninhabited:

library/core/src/lib.rs

-1
Original file line numberDiff line numberDiff line change
@@ -145,7 +145,6 @@
145145
#![feature(maybe_uninit_slice)]
146146
#![feature(external_doc)]
147147
#![feature(associated_type_bounds)]
148-
#![feature(const_type_id)]
149148
#![feature(const_caller_location)]
150149
#![feature(slice_ptr_get)]
151150
#![feature(no_niche)] // rust-lang/rust#68303

src/test/ui/consts/const-typeid-of-rpass.rs

-1
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,5 @@
11
// run-pass
22
#![feature(core_intrinsics)]
3-
#![feature(const_type_id)]
43

54
use std::any::TypeId;
65

src/test/ui/consts/const-typeid-of.rs

-8
This file was deleted.

src/test/ui/consts/const-typeid-of.stderr

-10
This file was deleted.

src/test/ui/consts/issue-73976-monomorphic.rs

-1
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,6 @@
55
// will be properly rejected. This test will ensure that monomorphic use of these
66
// would not be wrongly rejected in patterns.
77

8-
#![feature(const_type_id)]
98
#![feature(const_type_name)]
109

1110
use std::any::{self, TypeId};

src/test/ui/consts/issue-73976-polymorphic.rs

-1
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,6 @@
55
// This test case should either run-pass or be rejected at compile time.
66
// Currently we just disallow this usage and require pattern is monomorphic.
77

8-
#![feature(const_type_id)]
98
#![feature(const_type_name)]
109

1110
use std::any::{self, TypeId};

src/test/ui/consts/issue-73976-polymorphic.stderr

+4-4
Original file line numberDiff line numberDiff line change
@@ -1,23 +1,23 @@
11
error: could not evaluate constant pattern
2-
--> $DIR/issue-73976-polymorphic.rs:20:37
2+
--> $DIR/issue-73976-polymorphic.rs:19:37
33
|
44
LL | matches!(GetTypeId::<T>::VALUE, GetTypeId::<T>::VALUE)
55
| ^^^^^^^^^^^^^^^^^^^^^
66

77
error: could not evaluate constant pattern
8-
--> $DIR/issue-73976-polymorphic.rs:32:42
8+
--> $DIR/issue-73976-polymorphic.rs:31:42
99
|
1010
LL | matches!(GetTypeNameLen::<T>::VALUE, GetTypeNameLen::<T>::VALUE)
1111
| ^^^^^^^^^^^^^^^^^^^^^^^^^^
1212

1313
error: could not evaluate constant pattern
14-
--> $DIR/issue-73976-polymorphic.rs:20:37
14+
--> $DIR/issue-73976-polymorphic.rs:19:37
1515
|
1616
LL | matches!(GetTypeId::<T>::VALUE, GetTypeId::<T>::VALUE)
1717
| ^^^^^^^^^^^^^^^^^^^^^
1818

1919
error: could not evaluate constant pattern
20-
--> $DIR/issue-73976-polymorphic.rs:32:42
20+
--> $DIR/issue-73976-polymorphic.rs:31:42
2121
|
2222
LL | matches!(GetTypeNameLen::<T>::VALUE, GetTypeNameLen::<T>::VALUE)
2323
| ^^^^^^^^^^^^^^^^^^^^^^^^^^

0 commit comments

Comments
 (0)