nexcore_error_derive/lib.rs
1//! Derive macro for NexVigilant error types.
2//!
3//! Drop-in replacement for `thiserror::Error`. Provides `#[derive(Error)]`
4//! with `#[error("...")]`, `#[from]`, and `#[source]` attributes.
5//!
6//! # Usage
7//!
8//! ```
9//! use nexcore_error_derive::Error;
10//!
11//! #[derive(Debug, Error)]
12//! pub enum MyError {
13//! #[error("IO error: {0}")]
14//! Io(#[from] std::io::Error),
15//! #[error("parse error: {msg}")]
16//! Parse { msg: String },
17//! #[error("not found")]
18//! NotFound,
19//! }
20//! ```
21
22#![forbid(unsafe_code)]
23#![deny(clippy::unwrap_used)]
24#![deny(clippy::expect_used)]
25#![deny(clippy::panic)]
26#![warn(missing_docs)]
27mod attr;
28mod expand;
29
30use proc_macro::TokenStream;
31use syn::{DeriveInput, parse_macro_input};
32
33/// Derive `Display` and `std::error::Error` for an enum or struct.
34///
35/// # Attributes
36///
37/// - `#[error("format string")]` — Display format for the variant/struct
38/// - `#[error(transparent)]` — Forward Display and source to inner type
39/// - `#[from]` on a field — Generate `From<FieldType>` impl
40/// - `#[source]` on a field — Use as `Error::source()` return value
41#[proc_macro_derive(Error, attributes(error, from, source))]
42pub fn derive_error(input: TokenStream) -> TokenStream {
43 let input = parse_macro_input!(input as DeriveInput);
44 match expand::expand(&input) {
45 Ok(expanded) => expanded.into(),
46 Err(err) => err.to_compile_error().into(),
47 }
48}