fack_macro/lib.rs
1use proc_macro::TokenStream;
2
3use fack_codegen::generate;
4
5/// Derive `Display` and `Error` implementations from `#[error(...)]`
6/// declarations.
7///
8/// A format string defines ordinary display behavior.
9///
10/// ```rust
11/// # use fack_macro::Error;
12/// #[derive(Error, Debug)]
13/// #[error("failed to read {path}")]
14/// struct ReadError {
15/// path: String,
16/// }
17/// ```
18///
19/// `source(field)` selects the ordinary error source.
20///
21/// ```rust
22/// # use fack_macro::Error;
23/// #[derive(Error, Debug)]
24/// #[error("network request failed")]
25/// #[error(source(io))]
26/// struct NetworkError {
27/// io: std::io::Error,
28/// }
29/// ```
30///
31/// `transparent(field)` requires exactly one non-optional field. Display
32/// forwards to that field and source chaining forwards through the field's own
33/// `Error::source` implementation.
34///
35/// ```rust
36/// # use fack_macro::Error;
37/// #[derive(Error, Debug)]
38/// #[error(transparent(0))]
39/// struct Wrapper(std::io::Error);
40/// ```
41///
42/// `from` requires exactly one field. It generates `From<T>` and selects that
43/// field as the ordinary source.
44///
45/// ```rust
46/// # use fack_macro::Error;
47/// #[derive(Error, Debug)]
48/// #[error("parse failed")]
49/// #[error(from)]
50/// struct ParseError(std::num::ParseIntError);
51/// ```
52///
53/// `display(path)` selects a custom formatter function.
54///
55/// ```rust
56/// # use fack_macro::Error;
57/// fn render(error: &Rendered, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
58/// let Rendered { code } = error;
59/// write!(f, "rendered {code}")
60/// }
61///
62/// #[derive(Error, Debug)]
63/// #[error(display(render))]
64/// struct Rendered {
65/// code: u8,
66/// }
67/// ```
68///
69/// Inline control is optional. Omitting it emits no explicit inline attribute.
70/// `inline` and `inline(neutral)` emit ordinary `#[inline]`. The `always` and
71/// `never` strategies emit the corresponding Rust attributes.
72///
73/// ```rust
74/// # use fack_macro::Error;
75/// #[derive(Error, Debug)]
76/// #[error(inline(never))]
77/// #[error("rare error")]
78/// struct RareError;
79/// ```
80///
81/// Generated paths use `::core` by default. `import(path)` selects a different
82/// root.
83///
84/// ```rust
85/// # use fack_macro::Error;
86/// #[derive(Error, Debug)]
87/// #[error(import(::std))]
88/// #[error("standard error")]
89/// struct StdError;
90/// ```
91#[proc_macro_derive(Error, attributes(error))]
92pub fn error(input: TokenStream) -> TokenStream {
93 let input = syn::parse_macro_input!(input as syn::DeriveInput);
94
95 match generate(&input) {
96 Ok(tokens) => TokenStream::from(tokens),
97 Err(error) => error.to_compile_error().into(),
98 }
99}