Idea
(Apologies in advance for the hand-wavy-ness)
Introduce the compile-time assertions based on supported const eval.
For example,
const BUF_SIZE: usize = 500;
const MAX_BUF_SIZE: usize = 1000;
static_assert(BUF_SIZE <= MAX_BUF_SIZE) // static assert
static_assert(10000000 < MAX_BUF_SIZE) // compile error: assertion failed...
Inside the static_assert
can be any const
expression of type bool
that is accepted by the compiler.
Motivation
Often, it can be helpful to assert the truthiness of some invariants about constants at compile time. That is, if the assertion is false, the program fails to compile. This is already a well-known and commonly-used technique in the C/C++ world, where it is often used to avoid buffer overflows on staticly-defined buffers.
This proposal suggests that static asserts may significantly improve safety and correctness of programs. Moreover, when const generics are implemented, this provides a powerful way of placing constraints on them. For example:
fn foo<const N: usize, const M: usize>(buf: [u8; N]) -> [u64; M] {
static_assert(N == M * 8);
...
}
Prior Art
-
Perhaps a bit of a stretch, but C++ concepts (http://en.cppreference.com/w/cpp/language/constraints) seem similar in usage, but I am not sure if they are compile-time enforced.
-
Languages with full dependent types can do this in the type system.
-
C/C++ libraries often have a static assert of some sort.