I'd like to emit a compilation error from a macro if the number of items provided exceed a given length. The problem is that the length can be a const expression so I can't check it within the macro code.
I'm wondering if there are any existing open RFCs that cover what I need.
A very simplified version of my macro, which shows the use-case:
const N: usize = 3; let a = arr![1, 2, 3, 4; N]; // should be a compile error let a = arr![1, 2, 3; N]; // Ok, same length let a = arr![1, 2; N]; // Ok, fewer items than length
There are 4 values here, but the given length is 3. I want to emit a compilation error, rather than panic in this case.
There are two "obvious" ways this could work:
- Have a means to evaluate the
3(which could also be any const expression) inside the macro and compare it with the number of elements. With my limited knowledge of compiler internals, implementing this in the compiler seems unlikely.
- Have a macro similar to
compile_error, which conditionally produces a compilation error based on a const expression. e.g.
This works like
compile_error_when!(condition, "oh no, an error");
compile_errorexcept the compiler will not emit an error if the condition - which must be a const expression - resolves to false.
Has anything like this been discussed anywhere before?