Will rust implement compile time function evaluation?

This raises a question for me: when I run miri manually, it can take quite a while to run depending on the project. So how is it possible to at the same time:

  1. Run miri to do CTFE
  2. keep compile times reasonable for some definition of reasonable
  • const fns are quite limited right now (e.g. no traits = no for loops) so there's not a lot of people writing runtime-expensive const fns right now
  • running MIRI might do things (tagging pointers for instance) which have expensive safety checks but are disabled for the const fn evaluator; although I don't know if this is actually how it works.
  • remember the interpreter is only used when a const fn is used to generate a const value, otherwise they're just treated as regular functions, and inlining/folding is up to the backend (llvm).
1 Like

Sorry for the late reply, I've been unusually busy.

So, if I have understood correctly, converting heap-allocated objects into immutable stack ones would require writing a procedure for doing so for every other standard object, so I should not count on it being implemented anytime soon.

Also, I'm guessing build.rs can't be used for this purpose because it might have compatibility issues between platforms.

I still don't have any experience with rust objects like cells, pins and mutexes in general, but for what I've read in the meantime it seems the general consensus is to use the lazy_static strategy and use a singleton that's only computed on the first request and referenced for the following ones

This is probably a perfectly adequate solution, the purpose of this thread was to explore the possibility of compile-time approaches to also enjoy the error detection of the compiler

Yep, that summary is basically correct.

If you really want to precompute values that can't be done const, databake offers the pattern of building the object and serializing it to Rust code to reconstruct the value. Databake only (intends to) supports generating const supporting data structures (e.g. Cow<'static, [_]> based and not Vec<[_]> based) that can be fully baked into the executable's static data section, but the pattern can be trivially extended to generate a const serialization which is loaded into a normal structure on first use (e.g. by lazy!).

2 Likes

You might also want to look at uneval for the alternative (Serde-based) approach. I might borrow some ideas from databake for the future, though - their idea looks really interesting.

3 Likes