Search code examples
compiler-errorsrustrust-macros

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.


Solution

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