Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there an alternative to compile_error based on static analysis (e.g. by optimizer)

Tags:

rust

I have a function called foo.

fn foo(val: bool) {
   if val {
      panic!("This should not ever happened");
   } else {
      // do something useful
   }
}

// somewhere else
foo(true); // this should cause compile error

What I want is stop compilation if the compiler will be sure, that function foo will be called with true value. I want to be informed as soon as possible (so compile time is better than runtime). So I want to something like compile_error! but based on static analysis. It is absolutely ok to compile it if the compiler is not sure if true branch will be called or not - program will panic at runtime.

compile_error! is sadly unusable for me because I don't want the following code failed on compile

if false {
   compile_error!("Some error");
}
like image 677
Tomas Avatar asked Oct 14 '25 03:10

Tomas


1 Answers

This is not possible with compile_error!. The macro is evaluated way before things like code optimization are happening. There are basically only two contexts in which compile_error! is useful right now:

  • Conditional compilation with #[cfg(...)]
  • Macros generating code that may contain a compile_error!

Both of these are evaluated before the compile_error! error is emitted.

There is no nice functionality to let you do what you want to achieve. However, there exists a kind of hack. It is used by the no-panic crate and causes an error at link time (something you usually see pretty rarely in Rust).

The trick works by inserting a reference to an unknown symbol at each panic location. If the optimizer (which runs very late in the compilation pipeline, but still mainly before linking) can remove the branch leading to the panic, it also removes the reference to the unknown symbol. If the optimizer cannot remove the branch, then the final code contains a reference to that unknown symbol and the linker will produce an "undefined reference to ..." error. It's not a nice error, but it stops the program from compiling.

Your goal is a bit more elaborate though: you only want an error if the compiler is sure that a panic will absolutely happen. That's more tricky, but you might be able to use this hack to solve it, too.

like image 66
Lukas Kalbertodt Avatar answered Oct 19 '25 08:10

Lukas Kalbertodt