Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Issuing a warning at compile time?

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.

like image 902
llogiq Avatar asked Jul 14 '19 08:07

llogiq


People also ask

What is compile time warning?

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 is it a good idea to always enable compiler warnings in C?

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.

How does GCC treat warning errors?

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.

Which option can be used to display compiler warnings?

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.)


1 Answers

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.

like image 128
Peter Hall Avatar answered Oct 30 '22 21:10

Peter Hall