How to achieve Compile Time reflection in next ten thousand years

I've been postponing this for a while, but wanted to write my thoughts in case a bus hit me.

Compile time is an often asked feature of Rust. But what would you need, to have this implemented by a 3rd party crate?

To get this, you first would need a Reflect trait. Ideally, this trait would define a pub const fn typeinfo() -> TypeInfo (where TypeInfo is an enum that has all the type info necessary)[1] Granted you can work around this via macros, by implementing this for primitive types yourself.

Given that you might need to instantiate an enum or a struct, you're going to need some sort of inverse of mem::discriminant. Basically a function/macro that looks like this

    fn reverse_discriminant<T: DiscriminantKind>(d: Discriminant<T>) -> T;

Finally, to either go with trait generator or the enum typeinfo, you will have to deal with complex types with N arguments or functions with N arguments (e.g. MyCoolType<N1, N2, N3, N4, N5, N6, N7....N123> or fn(A1, A2, A3, A4, A5, A6, A7, .... A451) ), to achieve that you need some sort of variadic generics. Or declaring that Rust types will never have more than thirteen type arguments.

In summary of importance:

  1. Get variadic generics - this will make it easier for any possible implementors.
  2. Get a way to read/write enum variants, or struct/union fields.
  3. Expand what is possible in const. Having an easier way to iterate, have strings rather than numbers and so on in const is a great boon. Also, maybe make it possible for a trait to declare all it has to const implemented.

  1. Why an enum and not some kind of complex trait tree that was in JeanHeyd's original proposal? Because if you want to have logic that decides whether the struct is aligned four or eight bytes aligned, you probably want to use something understandable like info.get_align() > 4 rather than a baroque set of traits. â†Šī¸Ž

1 Like

Have you heard of https://facet.rs/ ? I'm very interested in seeing where that experiment with reflection and dynamically creating objects goes.

13 Likes

There's something missing from this API, which is the payload. The problem is that each enum variant has different payload types. To properly make this API you need something like dependent types (generally considered unfeasible); or you need to receive some opaque trait object for parameters, and return Option<T> (None if the parameter doesn't match the type of that variant, checked at runtime)

2 Likes

fwiw I proposed a goal for experimenting with reflection over the next 6 months.

I am neither convinced we should to reflection nor that we shouldn't. Only that it's possible and lots of folk want it. I want to explore a design that I feel is very Rusty and see where it takes us. If we rip it all out in a year and decide it's creating more problems than it solves, that's ok, too. But there are just too many cool use cases for it not to try imo

8 Likes