[pre-RFC] [idea] Detecting const evaluation

I think it could be useful to add support for #[cfg(const_eval)], which would enable code only during const evaluation. Possible uses:

  • cleaning up some APIs for runtime while retaining APIs for const evaluation by annotating whole functions
  • panicking easily during const evaluation and pushing hard during runtime by annotating blocks of code
  • using faster or better algorithms on runtime, that require using non-const functions by annotating blocks of code

Would it be useful? Is it realistically possible to implement? Is it worth writing an RFC?

2 Likes

This is a great idea! This is similar to C++'s if constexpr(...) { ... }

I'm hesitant about the idea of allowing constant evaluation to run different code than runtime evaluation; one of the major advantages of const fn is running the same code in both contexts.

6 Likes

In fact, IIRC, it's actually required for soundness that const fn always behave the same given the same inputs, whether it's at compile time or at runtime.

On top of this, APIs being available at const-evaluation time but not runtime is asking for confusion. Sure, maybe there's a "better" option available for runtime, especially during the transition time until Everything Is Const and Miri Is Unleashed. But why would you ever want it to be an error to inline usages of const C = make_thing();?

1 Like

I don't think that we will ever make everything const, for example SIMD or other intrinsics that are specialized for optimizations likely won't be made const because that would bloat the compiler too much.

I don't think that it is required for soundness that they behave the same at both runtime and compile time. Just that at compile time, they must be deterministic.


I view this in the same way as trait specialization, the specialization should do the same thing, but it may do it in a different (more efficient) way. Unsafe code is not allowed to assume this, but safe code can.

Oh this is definitely being discussed elsewhere, link time!

My impression from the C++ and Rust discussions so far is that, while this should of course be a niche power user feature, it's basically inevitable that someone will need this as soon as your language offers any form of CTFE plus any target-specific optimization features (SIMD, inline asm, all the other intrinsics), simply because making CTFE emulate all of that target-specific behavior would be even worse than providing is_const_eval.


Tangential nitpick:

That's actually a very different feature. std::is_constant_evaluated is the C++20 feature for distinguishing compile-time from run-time. if constexpr is about compiling different code depending on some compile-time value. I believe you can combine them, but most of their use cases don't involve the other.

5 Likes