I want to prove that my API statically prevents an invalid usage by failing to compile.
There is tooling for assuring that code panics at run-time (#[should_panic]
), but I couldn't find anything for compilation failure. The doc tests seem most promising, because every snippet is a separate compilation unit, but panic check is all there seems to be.
Logic errors are best handled by meticulous program debugging. Compile-time errors rise at compile-time, before the execution of the program. Syntax error or missing file reference that prevents the program from successfully compiling is an example of this.
As an additional effort to measure the performance impact of the introduction of interception ability, we have measured the execution time for the Java compiler to translate the test program to Java bytecodes. The averaged execution times are presented in Table 5.
When you look at an error, the compiler or IDE shows you the line where it detects the error. But the error is not always on that line. For example, if you have omitted a semicolon on line 12 then the compiler might detect an error at line 13.
There isn't currently a way of indicating that a regular test should not compile. And by the look of related issues (#521 and #1994 ) something like #[compile_fail]
is unlikely to become available any time soon.
However, there are two other ways to write these tests.
Since Rust 1.22, you can make doc tests which are supposed to fail to compile, by labeling the code snippet with compile_fail
:
/// Foos a bar.
///
/// # Example
///
/// ```compile_fail
/// foo(3); // 3 is not a bar
/// ```
fn foo(bar: Bar) {
}
The compile-test tools used internally by the Rust project were extracted into the dedicated crate compiletest_rs
.
With the boilerplate suggested in the documentation, one can write compile-fail tests in the tests/compile-fail
folder:
fn main() {
let x: bool = 0;
}
See also:
These tests should be written with care, nevertheless. Quoting from the announcement of the compile_fail
feature:
Please note that these kinds of tests can be more fragile than others, as additions to Rust may cause code to compile when it previously would not.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With