I want to issue a warning at compile time, perhaps from a macro. It should not be silenceable by cap_lints
. My current use case is feature deprecation, but there's other possible uses for this.
Compile-time warnings can greatly improve the maintainability of your code and reduce the chance that bugs will creep into it. Compile-time warnings differ from compile-time errors; with warnings, your program will still compile and run.
Why should I enable warnings? C and C++ compilers are notoriously bad at reporting some common programmer mistakes by default, such as: forgetting to initialise a variable. forgetting to return a value from a function.
You can use the -Werror compiler flag to turn all or some warnings into errors. Show activity on this post. You can use -fdiagnostics-show-option to see the -W option that applies to a particular warning. Unfortunately, in this case there isn't any specific option that covers that warning.
The warning message for each controllable warning includes the option that controls the warning. That option can then be used with -Werror= and -Wno-error= as described above. (Printing of the option in the warning message can be disabled using the -fno-diagnostics-show-option flag.)
This currently isn't possible in stable Rust. However, there is an unstable feature, procedural macro diagnostics, which provides this functionality for procedural macros, via the Diagnostic
API.
To emit a compiler warning from inside a procedural macro, you would use it like this:
#![feature(proc_macro_diagnostic)]
use proc_macro::Diagnostic;
Diagnostic::new()
.warning("This method is deprecated")
.emit();
To associate the warning with a specific token span, you'd use spanned_warning
instead. This makes the warning output show the relevant source tokens underlined along with the message.
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