4 releases

0.10.1 Jul 10, 2023
0.10.0 Mar 22, 2023
0.9.1 Nov 1, 2020
0.9.0 Oct 10, 2020

#35 in Procedural macros

Download history 208630/week @ 2025-01-28 237144/week @ 2025-02-04 228079/week @ 2025-02-11 258208/week @ 2025-02-18 274783/week @ 2025-02-25 287941/week @ 2025-03-04 279642/week @ 2025-03-11 282126/week @ 2025-03-18 273941/week @ 2025-03-25 294918/week @ 2025-04-01 300275/week @ 2025-04-08 274078/week @ 2025-04-15 275476/week @ 2025-04-22 264001/week @ 2025-04-29 289155/week @ 2025-05-06 232993/week @ 2025-05-13

1,102,298 downloads per month
Used in 1,651 crates (32 directly)

MIT/Apache

25KB
389 lines

proc-macro2-diagnostics   crates.io docs.rs

Diagnostics for stable and nightly proc-macros!

Usage

  1. Depend on the library in your proc-macro.
[dependencies]
proc_macro2_diagnostics = "0.10"
  1. Import SpanDiagnosticExt and use its methods on a proc_macro2::Span to create Diagnostics:
use syn::spanned::Spanned;
use proc_macro2::TokenStream;
use proc_macro2_diagnostics::{SpanDiagnosticExt, Diagnostic};

fn my_macro(input: TokenStream) -> Result<TokenStream, Diagnostic> {
    Err(input.span().error("there's a problem here..."))
}
  1. If there's an error, emit the diagnostic as tokens:
extern crate proc_macro;

pub fn real_macro(tokens: proc_macro::TokenStream) -> proc_macro::TokenStream {
    match my_macro(tokens.into()) {
        Ok(tokens) => tokens.into(),
        Err(diag) => diag.emit_as_expr_tokens().into()
    }
}

This does the right thing on nightly or stable.

Caveats

On stable, due to limitations, any top-level, non-error diagnostics are emitted as errors. This will abort compilation. To avoid this, you may want to cfg-gate emitting non-error diagnostics to nightly.

Colors

By default, error messages are colored on stable. To disable, disable default features:

[dependencies]
proc_macro2_diagnostics = { version = "0.10", default-features = false }

The compiler always colors diagnostics on nightly.

License

Licensed under either of the following, at your option:

Dependencies

~190–640KB
~15K SLoC