Skip to main content

n0_error_macros/
lib.rs

1use proc_macro::TokenStream;
2use proc_macro2::Span;
3use quote::{quote, ToTokens};
4use syn::{
5    parse_macro_input, parse_quote, punctuated::Punctuated, Attribute, DeriveInput, Expr, Field,
6    Fields, FieldsNamed, Ident,
7};
8
9/// Attribute macro to expand error enums or structs.
10///
11/// This macro can be applied to enums and structs and the syntax `#[stack_error(args)]`,
12/// where `args` is a comma-seperated list of arguments.
13/// * **`add_meta`** adds a `n0_error::Meta` field to the struct or each each enum variant. The `Meta`
14///   struct contains call-site location metadata for the error.
15///   - If the item has named fields, the field will added with name `meta`
16///   - If the item is a tuple, the field will be added as the last field and marked with `#[error(meta)]`
17///   - It the item is a unit, it will be altered to named fields, and the field
18///     will be added with name `meta`
19/// * **`derive`** will add `#[derive(StackError)]`. See the docs for the [`StackError`] for details.
20/// * The item-level options of [`StackError`] derive macro (namely `from_sources` and `std_sources`)
21///   can be set `stack_error` as well. They will be expanded to an `#[error]` attribute on the item.
22///   See the documentation for [`StackError`] for details.
23///
24/// This is an attribute macro because it *modifies* its item by adding the `meta` field,
25/// which derive macros cannot.
26///
27/// ## Example
28///
29/// ```ignore
30/// #[stack_error(derive, add_meta, from_sources)]
31/// enum MyError {
32///     #[error("io failed")]
33///     Io { source: std::io::Error },
34///     #[error("remote failed with {_0}")]
35///     RemoteErrorCode(u32),
36/// }
37/// ```
38/// expands to
39/// ```ignore
40/// #[derive(n0_error::StackError)]
41/// #[error(from_sources)]
42/// enum MyError {
43///     #[error("io failed")]
44///     Io {
45///         source: std::io::Error,
46///         meta: n0_error::Meta,
47///     },
48///     #[error("remote failed with {_0}")]
49///     RemoteErrorCode(u32, #[error(meta)] n0_error::Meta),
50/// }
51/// ```
52#[proc_macro_attribute]
53pub fn stack_error(args: TokenStream, item: TokenStream) -> TokenStream {
54    match stack_error_inner(args, parse_macro_input!(item as syn::Item)) {
55        Err(err) => err.to_compile_error().into(),
56        Ok(tokens) => tokens.into(),
57    }
58}
59
60fn stack_error_inner(
61    args: TokenStream,
62    mut input: syn::Item,
63) -> Result<proc_macro2::TokenStream, syn::Error> {
64    let args: StackErrAttrArgs = syn::parse(args.clone())?;
65    match &mut input {
66        syn::Item::Enum(item) => {
67            if args.add_meta {
68                for variant in item.variants.iter_mut() {
69                    add_meta_field(&mut variant.fields);
70                }
71            }
72            modify_attrs(&args, &mut item.attrs)?;
73            Ok(quote! { #item })
74        }
75        syn::Item::Struct(item) => {
76            if args.add_meta {
77                add_meta_field(&mut item.fields);
78            }
79            modify_attrs(&args, &mut item.attrs)?;
80            Ok(quote! { #item })
81        }
82        _ => Err(err(
83            &input,
84            "#[stack_error] only supports enums and structs",
85        )),
86    }
87}
88
89fn modify_attrs(args: &StackErrAttrArgs, attrs: &mut Vec<Attribute>) -> Result<(), syn::Error> {
90    attrs.retain(|attr| !attr.path().is_ident("stackerr"));
91    if args.derive {
92        attrs.insert(0, parse_quote!(#[derive(::n0_error::StackError)]));
93    }
94    let error_args: Vec<_> = [
95        args.from_sources.then(|| quote!(from_sources)),
96        args.std_sources.then(|| quote!(std_sources)),
97    ]
98    .into_iter()
99    .flatten()
100    .collect();
101    if !error_args.is_empty() {
102        attrs.push(parse_quote!(#[error(#(#error_args),*)]))
103    }
104
105    Ok(())
106}
107
108fn add_meta_field(fields: &mut Fields) {
109    let doc = "Captured call-site metadata";
110    match fields {
111        Fields::Named(fields) => {
112            let field: syn::Field = parse_quote! { #[doc = #doc] meta: ::n0_error::Meta };
113            fields.named.push(field);
114        }
115        Fields::Unit => {
116            let mut named = FieldsNamed {
117                brace_token: Default::default(),
118                named: Default::default(),
119            };
120            let field: syn::Field = parse_quote! { #[doc = #doc] meta: ::n0_error::Meta };
121            named.named.push(field);
122            *fields = Fields::Named(named);
123        }
124        Fields::Unnamed(fields) => {
125            let field: syn::Field = parse_quote! { #[doc = #doc] #[error(meta)] ::n0_error::Meta };
126            fields.unnamed.push(field);
127        }
128    }
129}
130
131/// Derive macro that implements `StackError`, `Display`, `Debug` and `std::error::Error`
132/// and generates `From<T>` impls for fields/variants configured via `#[error(..)]`.
133/// Derive macro for stack errors.
134///
135/// This derive macro can be applied to structs and enums. Unit, tuple and named-field variants
136/// are supported equally.
137///
138/// The macro will expand to implementations of `StackError`, [`Display`], [`Debug`] and [`Error`].
139/// It will also add [`From`] impls for fields configured via the `error` attribute.
140///
141/// Items with the derive macro applied accept an `#[error(args)]` attribute, where `args` is a comma-separated
142/// list of arguments. The supported arguments vary by on the kind of item:
143///
144/// * on enums:
145///   - `#[error(from_sources)]`: Creates `From` impls for the `source` types of all variants. Will fail to compile if multiple sources have the same type.
146///   - `#[error(std_sources)]`: Defaults all sources to be std errors instead of stack errors.
147/// * on structs and enum variants:
148///   - `#[error("format {field}: {}", a + b)]`: Sets the display formatting. You can refer to named fields by their names, and to tuple fields by `_0`, `_1` etc.
149///   - `#[error(transparent)]`: Directly forwards the display implementation to the error source, and omits the outer error in the source chain when reporting errors.
150/// * on fields:
151///   - `#[error(from)]`: Creates a `From` impl for the field's type to the error type.
152///   - `#[error(source)]`: The error's `source` method returns a reference to whatever field is named `source`, or
153///     has the `source` attribute set.
154///   - `#[error(std_err)]`: *Only on on `source` fields.* Marks the error as a `std` error.
155///     Source fields not marked as `std_err` need to implement `StackError`.
156///   - `#[error(stack_error)]`: *Only on `source` fields.* Marks the error as a `StackError`. This is the default unless `std_sources` is set on the top-level item.
157///   - `#[error(meta)]: Sets a field as the `meta` field for this error or variant. Must have type [`::n0_error::Error`]
158///
159/// If the type or an enum variant has `#[deprecated]` or `#[allow(deprecated)]`,
160/// the generated impls allow deprecation warnings. Otherwise the lint is left
161/// unchanged, including in user-provided formatting expressions.
162///
163/// [`Display`]: std::fmt::Display
164/// [`Debug`]: std::fmt::Debug
165/// [`Error`]: std::error::Error.
166#[proc_macro_derive(StackError, attributes(error))]
167pub fn derive_stack_error(input: TokenStream) -> TokenStream {
168    let input = parse_macro_input!(input as syn::DeriveInput);
169    match derive_error_inner(input) {
170        Err(err) => err.to_compile_error().into(),
171        Ok(tokens) => tokens.into(),
172    }
173}
174
175fn derive_error_inner(input: DeriveInput) -> Result<proc_macro2::TokenStream, syn::Error> {
176    let allow_deprecated = allows_deprecated(&input.attrs)
177        || matches!(&input.data, syn::Data::Enum(item)
178            if item.variants.iter().any(|v| allows_deprecated(&v.attrs)));
179    let impls = match &input.data {
180        syn::Data::Enum(item) => {
181            let args = EnumAttrArgs::from_attributes(&input.attrs)?;
182            let infos = item
183                .variants
184                .iter()
185                .map(|v| {
186                    let ident = VariantIdent::Variant(&input.ident, &v.ident);
187                    VariantInfo::parse(ident, &v.fields, &v.attrs, &args)
188                })
189                .collect::<Result<Vec<_>, _>>()?;
190            Ok(generate_enum_impls(&input.ident, &input.generics, infos))
191        }
192        syn::Data::Struct(item) => {
193            let ident = VariantIdent::Struct(&input.ident);
194            let info = VariantInfo::parse(ident, &item.fields, &input.attrs, &Default::default())?;
195            Ok(generate_struct_impl(&input.ident, &input.generics, info))
196        }
197        _ => Err(err(
198            &input,
199            "#[derive(StackError)] only supports enums or structs",
200        )),
201    }?;
202    if allow_deprecated {
203        // Scope the allowance to the generated impls, not the user's item or uses.
204        Ok(quote! {
205            #[allow(deprecated)]
206            const _: () = { #impls };
207        })
208    } else {
209        Ok(impls)
210    }
211}
212
213/// Follow Serde: propagate deprecation and explicit allowances on the input.
214fn allows_deprecated(attrs: &[Attribute]) -> bool {
215    attrs.iter().any(|attr| {
216        if attr.path().is_ident("deprecated") {
217            return true;
218        }
219        if !attr.path().is_ident("allow") {
220            return false;
221        }
222        let mut found = false;
223        let _ = attr.parse_nested_meta(|meta| {
224            found |= meta.path.is_ident("deprecated");
225            Ok(())
226        });
227        found
228    })
229}
230
231struct SourceField<'a> {
232    kind: SourceKind,
233    field: FieldInfo<'a>,
234}
235
236impl<'a> SourceField<'a> {
237    fn expr_error_ref(&self, expr: proc_macro2::TokenStream) -> proc_macro2::TokenStream {
238        match self.kind {
239            SourceKind::Std => quote! { Some(::n0_error::ErrorRef::std(#expr)) },
240            SourceKind::Stack => quote! { Some(::n0_error::ErrorRef::stack(#expr)) },
241        }
242    }
243
244    fn expr_error_std(&self, expr: proc_macro2::TokenStream) -> proc_macro2::TokenStream {
245        match self.kind {
246            SourceKind::Std => quote! { Some(#expr as &dyn ::std::error::Error) },
247            SourceKind::Stack => quote! { Some(::n0_error::StackError::as_std(#expr)) },
248        }
249    }
250}
251
252enum SourceKind {
253    Stack,
254    Std,
255}
256
257#[derive(Default, Clone, Copy)]
258struct StackErrAttrArgs {
259    add_meta: bool,
260    derive: bool,
261    from_sources: bool,
262    std_sources: bool,
263}
264
265impl syn::parse::Parse for StackErrAttrArgs {
266    fn parse(input: syn::parse::ParseStream<'_>) -> syn::Result<Self> {
267        let mut out = Self::default();
268        while !input.is_empty() {
269            let ident: Ident = input.parse()?;
270            match ident.to_string().as_str() {
271                "add_meta" => out.add_meta = true,
272                "derive" => out.derive = true,
273                "from_sources" => out.from_sources = true,
274                "std_sources" => out.std_sources = true,
275                other => Err(err(
276                    ident,
277                    format!("unknown stack_error option `{}`", other),
278                ))?,
279            }
280            if input.peek(syn::Token![,]) {
281                let _ = input.parse::<syn::Token![,]>()?;
282            }
283        }
284        Ok(out)
285    }
286}
287
288#[derive(Default, Clone, Copy)]
289struct EnumAttrArgs {
290    from_sources: bool,
291    std_sources: bool,
292}
293
294impl EnumAttrArgs {
295    fn from_attributes(attrs: &[Attribute]) -> Result<Self, syn::Error> {
296        let mut out = Self::default();
297        for ident in parse_error_attr_as_idents(attrs)? {
298            match ident.to_string().as_str() {
299                "from_sources" => out.from_sources = true,
300                "std_sources" => out.std_sources = true,
301                _ => Err(err(
302                    ident,
303                    "Invalid argument for the `error` attribute on fields",
304                ))?,
305            }
306        }
307        Ok(out)
308    }
309}
310
311#[derive(Default, Clone, Copy)]
312struct FieldAttrArgs {
313    source: bool,
314    from: bool,
315    std_err: bool,
316    stack_err: bool,
317    meta: bool,
318}
319
320impl FieldAttrArgs {
321    fn from_attributes(attrs: &[Attribute]) -> Result<Self, syn::Error> {
322        let mut out = Self::default();
323        for ident in parse_error_attr_as_idents(attrs)? {
324            match ident.to_string().as_str() {
325                "source" => out.source = true,
326                "from" => out.from = true,
327                "std_err" => out.std_err = true,
328                "stack_err" => out.stack_err = true,
329                "meta" => out.meta = true,
330                _ => Err(err(
331                    ident,
332                    "Invalid argument for the `error` attribute on fields",
333                ))?,
334            }
335        }
336        Ok(out)
337    }
338}
339
340#[derive(Debug, Clone, Copy)]
341enum VariantIdent<'a> {
342    Struct(&'a Ident),
343    Variant(&'a Ident, &'a Ident),
344}
345
346impl<'a> VariantIdent<'a> {
347    fn self_ident(&self) -> proc_macro2::TokenStream {
348        match self {
349            VariantIdent::Struct(_) => quote!(Self),
350            VariantIdent::Variant(_, variant) => quote!(Self::#variant),
351        }
352    }
353    fn item_ident(&self) -> &Ident {
354        match self {
355            VariantIdent::Struct(ident) => ident,
356            VariantIdent::Variant(ident, _) => ident,
357        }
358    }
359
360    fn inner(&self) -> &Ident {
361        match self {
362            VariantIdent::Struct(ident) => ident,
363            VariantIdent::Variant(_, ident) => ident,
364        }
365    }
366}
367
368#[derive(Clone, Copy, PartialEq, Eq)]
369enum Kind {
370    Named,
371    Unit,
372    Tuple,
373}
374
375struct VariantInfo<'a> {
376    ident: VariantIdent<'a>,
377    fields: Vec<FieldInfo<'a>>,
378    kind: Kind,
379    display: DisplayArgs,
380    source: Option<SourceField<'a>>,
381    /// The field that is used for From<..> impls
382    from: Option<FieldInfo<'a>>,
383    /// The meta field if present.
384    meta: Option<FieldInfo<'a>>,
385}
386
387impl<'a> VariantInfo<'a> {
388    fn parse(
389        ident: VariantIdent<'a>,
390        fields: &'a Fields,
391        attrs: &[Attribute],
392        args: &EnumAttrArgs,
393    ) -> Result<VariantInfo<'a>, syn::Error> {
394        let display = DisplayArgs::parse(attrs)?;
395        let (kind, fields): (Kind, Vec<FieldInfo>) = match fields {
396            Fields::Named(ref fields) => (
397                Kind::Named,
398                fields
399                    .named
400                    .iter()
401                    .map(FieldInfo::from_named)
402                    .collect::<Result<_, _>>()?,
403            ),
404            Fields::Unit => (Kind::Unit, Vec::new()),
405            Fields::Unnamed(ref fields) => (
406                Kind::Tuple,
407                fields
408                    .unnamed
409                    .iter()
410                    .enumerate()
411                    .map(|(i, f)| FieldInfo::from_unnamed(i, f))
412                    .collect::<Result<_, _>>()?,
413            ),
414        };
415
416        if fields.iter().filter(|f| f.args.source).count() > 1 {
417            return Err(err(
418                ident.inner(),
419                "Only one field per variant may have #[error(source)]",
420            ));
421        }
422        let source_field = fields
423            .iter()
424            .find(|f| f.args.source)
425            .or_else(|| match kind {
426                Kind::Named => fields
427                    .iter()
428                    .find(|f| matches!(f.ident, FieldIdent::Named(name) if name == "source")),
429                Kind::Tuple if display.is_transparent() => fields.first(),
430                _ => None,
431            });
432
433        if display.is_transparent() && source_field.is_none() {
434            return Err(err(
435                ident.inner(),
436                "Variants with #[error(transparent)] require a source field",
437            ));
438        }
439
440        // Determine source kind and optional From based on field options and top-level switches
441        let source = source_field.as_ref().map(|field| {
442            let kind = if field.args.std_err || (args.std_sources && !field.args.stack_err) {
443                SourceKind::Std
444            } else {
445                SourceKind::Stack
446            };
447            SourceField {
448                kind,
449                field: (*field).clone(),
450            }
451        });
452
453        let from_field = fields
454            .iter()
455            .find(|f| f.args.from)
456            .or_else(|| args.from_sources.then_some(source_field).flatten());
457        let meta_field = fields.iter().find(|f| f.is_meta()).cloned();
458        Ok(VariantInfo {
459            ident,
460            kind,
461            display,
462            from: from_field.cloned(),
463            meta: meta_field,
464            source,
465            fields,
466        })
467    }
468
469    fn transparent(&self) -> Option<&FieldInfo<'_>> {
470        match self.display {
471            DisplayArgs::Transparent => self.source.as_ref().map(|s| &s.field),
472            _ => None,
473        }
474    }
475
476    fn spread_field(&self, field: &FieldInfo<'a>, bind: &Ident) -> proc_macro2::TokenStream {
477        let slf = self.ident.self_ident();
478        match field.ident {
479            FieldIdent::Named(ident) => {
480                quote! { #slf { #ident: #bind, .. } }
481            }
482            FieldIdent::Unnamed(_) => {
483                let pats = self.fields.iter().map(|f| {
484                    if f.ident == field.ident {
485                        quote!(#bind)
486                    } else {
487                        quote!(_)
488                    }
489                });
490                quote! { #slf ( #(#pats),* ) }
491            }
492        }
493    }
494
495    fn spread_empty(&self) -> proc_macro2::TokenStream {
496        let slf = self.ident.self_ident();
497        match self.kind {
498            Kind::Unit => quote! { #slf },
499            Kind::Named => quote! { #slf { .. } },
500            Kind::Tuple => {
501                let pats = std::iter::repeat_n(quote! { _ }, self.fields.len());
502                quote! { #slf ( #(#pats),* ) }
503            }
504        }
505    }
506
507    fn spread_all(&self) -> proc_macro2::TokenStream {
508        let binds = self.fields.iter().map(|f| f.ident.as_ident());
509        self.spread(binds.map(|i| quote!(#i)))
510    }
511
512    fn spread(
513        &self,
514        fields: impl Iterator<Item = proc_macro2::TokenStream>,
515    ) -> proc_macro2::TokenStream {
516        let slf = self.ident.self_ident();
517        match self.kind {
518            Kind::Unit => quote! { #slf },
519            Kind::Named => quote! { #slf { #(#fields),* } },
520            Kind::Tuple => quote! { #slf ( #(#fields),* ) },
521        }
522    }
523
524    fn generate_from_impl(&self) -> Option<(&syn::Type, proc_macro2::TokenStream)> {
525        self.from.as_ref().map(|from_field| {
526            let ty = &from_field.field.ty;
527            let fields = self.fields.iter().map(|field| {
528                if field.ident == from_field.ident {
529                    field.ident.init(quote!(source))
530                } else if field.is_meta() {
531                    field.ident.init(quote!(::n0_error::Meta::new()))
532                } else {
533                    field.ident.init(quote!(::std::default::Default::default()))
534                }
535            });
536            let construct = self.spread(fields);
537            (ty, construct)
538        })
539    }
540}
541
542#[derive(Clone)]
543struct FieldInfo<'a> {
544    field: &'a Field,
545    args: FieldAttrArgs,
546    ident: FieldIdent<'a>,
547}
548
549impl<'a> FieldInfo<'a> {
550    fn from_named(field: &'a Field) -> Result<Self, syn::Error> {
551        Ok(Self {
552            args: FieldAttrArgs::from_attributes(&field.attrs)?,
553            ident: FieldIdent::Named(field.ident.as_ref().unwrap()),
554            field,
555        })
556    }
557    fn from_unnamed(index: usize, field: &'a Field) -> Result<Self, syn::Error> {
558        Ok(Self {
559            args: FieldAttrArgs::from_attributes(&field.attrs)?,
560            ident: FieldIdent::Unnamed(index),
561            field,
562        })
563    }
564
565    fn is_meta(&self) -> bool {
566        self.args.meta || matches!(self.ident, FieldIdent::Named(ident) if ident == "meta")
567    }
568}
569
570#[derive(Clone, Copy, Eq, PartialEq)]
571enum FieldIdent<'a> {
572    Named(&'a Ident),
573    Unnamed(usize),
574}
575
576impl<'a> FieldIdent<'a> {
577    fn named(&self) -> Option<&'a Ident> {
578        match self {
579            FieldIdent::Named(ident) => Some(ident),
580            _ => None,
581        }
582    }
583
584    fn as_ident(&self) -> Ident {
585        match self {
586            FieldIdent::Named(ident) => (*ident).clone(),
587            FieldIdent::Unnamed(i) => syn::Ident::new(&format!("_{}", i), Span::call_site()),
588        }
589    }
590
591    fn self_expr(&self) -> proc_macro2::TokenStream {
592        match self {
593            FieldIdent::Named(ident) => quote!(&self.#ident),
594            FieldIdent::Unnamed(i) => {
595                let idx = syn::Index::from(*i);
596                quote!(&self.#idx)
597            }
598        }
599    }
600
601    fn init(&self, expr: proc_macro2::TokenStream) -> proc_macro2::TokenStream {
602        match self {
603            FieldIdent::Named(ident) => quote!(#ident: #expr),
604            FieldIdent::Unnamed(_) => quote!(#expr),
605        }
606    }
607}
608
609fn generate_enum_impls(
610    enum_ident: &Ident,
611    generics: &syn::Generics,
612    variants: Vec<VariantInfo>,
613) -> proc_macro2::TokenStream {
614    // Create an expression to match on that works for both empty and non-empty enums.
615    let this = if variants.is_empty() {
616        quote!(*self)
617    } else {
618        quote!(self)
619    };
620
621    let match_meta_arms = variants.iter().map(|vi| {
622        if let Some(meta_field) = &vi.meta {
623            let bind = syn::Ident::new("__meta", Span::call_site());
624            let pat = vi.spread_field(meta_field, &bind);
625            quote! { #pat => Some(&#bind) }
626        } else {
627            let pat = vi.spread_empty();
628            quote! { #pat => None }
629        }
630    });
631
632    let match_source_arms = variants.iter().map(|vi| match &vi.source {
633        Some(src) => {
634            let bind = syn::Ident::new("__source", Span::call_site());
635            let pat = vi.spread_field(&src.field, &bind);
636            let expr = src.expr_error_ref(quote!(#bind));
637            quote! { #pat => #expr, }
638        }
639        None => {
640            let pat = vi.spread_empty();
641            quote! { #pat => None, }
642        }
643    });
644
645    let match_std_source_arms = variants.iter().map(|vi| match &vi.source {
646        Some(src) => {
647            let bind = syn::Ident::new("__source", Span::call_site());
648            let pat = vi.spread_field(&src.field, &bind);
649            let expr = src.expr_error_std(quote!(#bind));
650            quote! { #pat => #expr, }
651        }
652        None => {
653            let pat = vi.spread_empty();
654            quote! { #pat => None, }
655        }
656    });
657
658    let match_transparent_arms = variants.iter().map(|vi| {
659        let value = vi.transparent().is_some();
660        let pat = vi.spread_empty();
661        quote! { #pat => #value }
662    });
663
664    let match_fmt_message_arms = variants.iter().map(|vi| match &vi.display {
665        DisplayArgs::Format(expr) => {
666            let pat = vi.spread_all();
667            quote! {
668                #[allow(unused)]
669                #pat => { #expr }
670            }
671        }
672        DisplayArgs::Default | DisplayArgs::Transparent => {
673            let text = format!("{}::{}", vi.ident.item_ident(), vi.ident.inner());
674            let pat = vi.spread_empty();
675            quote! { #pat => write!(f, #text) }
676        }
677    });
678
679    let match_debug_arms = variants.iter().map(|vi| {
680        let v_name = vi.ident.inner().to_string();
681        let binds = vi.fields.iter().map(|f| f.ident.as_ident());
682        let pat = vi.spread_all();
683        let labels: Vec<String> = vi
684            .fields
685            .iter()
686            .map(|f| match f.ident {
687                FieldIdent::Named(id) => id.to_string(),
688                FieldIdent::Unnamed(i) => i.to_string(),
689            })
690            .collect();
691        quote! {
692            #pat => {
693                let mut dbg = f.debug_struct(#v_name);
694                #( dbg.field(#labels, &#binds); )*; dbg.finish()?;
695            }
696        }
697    });
698
699    // From impls for variant fields marked with #[from]
700    let (impl_generics, ty_generics, where_clause) = generics.split_for_impl();
701    let from_impls = variants.iter().filter_map(|vi| vi.generate_from_impl()).map(|(ty, construct)| {
702        quote! {
703            impl #impl_generics ::core::convert::From<#ty> for #enum_ident #ty_generics #where_clause {
704                #[allow(unreachable_code)]
705                #[track_caller]
706                fn from(source: #ty) -> Self {
707                    #construct
708                }
709            }
710        }
711    });
712
713    quote! {
714        impl #impl_generics ::n0_error::StackError for #enum_ident #ty_generics #where_clause {
715            fn as_std(&self) -> &(dyn ::std::error::Error + ::std::marker::Send + ::std::marker::Sync + 'static) {
716                self
717            }
718            fn into_std(self: ::std::boxed::Box<Self>) -> ::std::boxed::Box<dyn std::error::Error + ::std::marker::Send + ::std::marker::Sync> {
719                self
720            }
721            fn as_dyn(&self) -> &(dyn ::n0_error::StackError) {
722                self
723            }
724            fn fmt_message(&self, f: &mut ::std::fmt::Formatter<'_>) -> ::std::fmt::Result {
725                match #this {
726                    #( #match_fmt_message_arms, )*
727                }
728            }
729            fn meta(&self) -> Option<&::n0_error::Meta> {
730                match #this {
731                    #( #match_meta_arms, )*
732                }
733            }
734            fn source(&self) -> Option<::n0_error::ErrorRef<'_>> {
735                match #this {
736                    #( #match_source_arms )*
737                }
738            }
739            fn is_transparent(&self) -> bool {
740                match #this {
741                    #( #match_transparent_arms, )*
742                }
743            }
744        }
745
746        impl #impl_generics ::core::convert::From<#enum_ident #ty_generics> for ::n0_error::AnyError #where_clause {
747            fn from(value: #enum_ident #ty_generics) -> ::n0_error::AnyError {
748                ::n0_error::AnyError::from_stack(value)
749            }
750        }
751
752        impl #impl_generics ::std::fmt::Display for #enum_ident #ty_generics #where_clause {
753            fn fmt(&self, f: &mut ::std::fmt::Formatter<'_>) -> ::std::fmt::Result {
754                let sources = f.alternate().then_some(::n0_error::SourceFormat::OneLine);
755                write!(f, "{}", ::n0_error::StackError::report(self).sources(sources))
756            }
757        }
758
759        impl #impl_generics ::std::fmt::Debug for #enum_ident #ty_generics #where_clause {
760            fn fmt(&self, f: &mut ::std::fmt::Formatter<'_>) -> ::std::fmt::Result {
761                if f.alternate() {
762                    match #this {
763                        #(#match_debug_arms)*
764                    }
765                } else {
766                    write!(f, "{}", ::n0_error::StackError::report(self).full())?;
767                }
768                Ok(())
769            }
770        }
771
772        impl #impl_generics ::std::error::Error for #enum_ident #ty_generics #where_clause {
773            fn source(&self) -> Option<&(dyn ::std::error::Error + 'static)> {
774                match #this {
775                    #( #match_std_source_arms )*
776                }
777            }
778        }
779        #( #from_impls )*
780    }
781}
782
783fn generate_struct_impl(
784    item_ident: &Ident,
785    generics: &syn::Generics,
786    info: VariantInfo,
787) -> proc_macro2::TokenStream {
788    let constructor = {
789        let params = info.fields.iter().filter(|f| !f.is_meta()).map(|f| {
790            let ty = &f.field.ty;
791            let ident = f.ident.as_ident();
792            quote! { #ident: #ty }
793        });
794        let fields = info.fields.iter().map(|f| {
795            if f.is_meta() {
796                f.ident.init(quote!(::n0_error::Meta::new()))
797            } else {
798                let ident = f.ident.as_ident();
799                quote!(#ident)
800            }
801        });
802        let construct = info.spread(fields);
803        let doc = format!("Creates a new [`{}`] error.", item_ident);
804        quote! {
805            #[doc = #doc]
806            #[allow(unreachable_code)]
807            #[track_caller]
808            pub fn new(#(#params),*) -> Self { #construct }
809        }
810    };
811    let get_meta = if let Some(field) = &info.meta {
812        let get_expr = field.ident.self_expr();
813        quote! { Some(&#get_expr) }
814    } else {
815        quote! { None }
816    };
817
818    let get_error_source = match &info.source {
819        Some(src) => src.expr_error_ref(src.field.ident.self_expr()),
820        None => quote! { None },
821    };
822
823    let get_std_source = match &info.source {
824        Some(src) => src.expr_error_std(src.field.ident.self_expr()),
825        None => quote! { None },
826    };
827
828    let is_transparent = info.transparent().is_some();
829
830    let get_fmt_message = {
831        match &info.display {
832            DisplayArgs::Format(expr) => {
833                let pat = info.spread_all();
834                quote! {
835                   #[allow(unused)]
836                   let #pat = self;
837                   #expr
838                }
839            }
840            DisplayArgs::Default | DisplayArgs::Transparent => {
841                let text = info.ident.item_ident().to_string();
842                quote! { write!(f, #text) }
843            }
844        }
845    };
846
847    let get_debug = {
848        let item_name = info.ident.item_ident().to_string();
849        match info.kind {
850            Kind::Unit => quote!(write!(f, #item_name)?;),
851            Kind::Named => {
852                let fields = info
853                    .fields
854                    .iter()
855                    .filter_map(|f| f.ident.named())
856                    .map(|ident| {
857                        let ident_s = ident.to_string();
858                        quote! { dbg.field(#ident_s, &self.#ident) }
859                    });
860                quote! {
861                    let mut dbg = f.debug_struct(#item_name);
862                    #(#fields);*;
863                    dbg.finish()?;
864                }
865            }
866            Kind::Tuple => {
867                let binds = (0..info.fields.len()).map(syn::Index::from);
868                quote! {
869                    let mut dbg = f.debug_tuple(#item_name);
870                    #( dbg.field(&self.#binds); )*;
871                    dbg.finish()?;
872                }
873            }
874        }
875    };
876
877    // From impls for fields marked with #[error(from)] (or inferred via from_sources)
878    let (impl_generics, ty_generics, where_clause) = generics.split_for_impl();
879    let from_impl = info.generate_from_impl().map(|(ty, construct)| {
880        quote! {
881            impl #impl_generics ::core::convert::From<#ty> for #item_ident #ty_generics #where_clause {
882                #[allow(unreachable_code)]
883                #[track_caller]
884                fn from(source: #ty) -> Self { #construct }
885            }
886        }
887    });
888
889    quote! {
890        impl #impl_generics #item_ident #ty_generics #where_clause {
891            #constructor
892        }
893
894        impl #impl_generics ::n0_error::StackError for #item_ident #ty_generics #where_clause {
895            fn as_std(&self) -> &(dyn ::std::error::Error + ::std::marker::Send + ::std::marker::Sync + 'static) {
896                self
897            }
898            fn into_std(self: ::std::boxed::Box<Self>) -> ::std::boxed::Box<dyn std::error::Error + ::std::marker::Send + ::std::marker::Sync> {
899                self
900            }
901            fn as_dyn(&self) -> &(dyn ::n0_error::StackError) {
902                self
903            }
904            fn meta(&self) -> Option<&::n0_error::Meta> {
905                #get_meta
906            }
907            fn source(&self) -> Option<::n0_error::ErrorRef<'_>> {
908                #get_error_source
909            }
910            fn is_transparent(&self) -> bool {
911                #is_transparent
912            }
913            fn fmt_message(&self, f: &mut ::std::fmt::Formatter<'_>) -> ::std::fmt::Result {
914                #get_fmt_message
915            }
916        }
917
918
919        impl #impl_generics ::core::convert::From<#item_ident #ty_generics> for ::n0_error::AnyError #where_clause {
920            fn from(value: #item_ident #ty_generics) -> ::n0_error::AnyError {
921                ::n0_error::AnyError::from_stack(value)
922            }
923        }
924
925        impl #impl_generics ::std::fmt::Display for #item_ident #ty_generics #where_clause {
926            fn fmt(&self, f: &mut ::std::fmt::Formatter<'_>) -> ::std::fmt::Result {
927                let sources = f.alternate().then_some(::n0_error::SourceFormat::OneLine);
928                write!(f, "{}", ::n0_error::StackError::report(self).sources(sources))
929            }
930        }
931
932        impl #impl_generics ::std::fmt::Debug for #item_ident #ty_generics #where_clause {
933            fn fmt(&self, f: &mut ::std::fmt::Formatter<'_>) -> ::std::fmt::Result {
934                if f.alternate() {
935                    #get_debug
936                } else {
937                    write!(f, "{}", ::n0_error::StackError::report(self).full())?;
938                }
939                Ok(())
940            }
941        }
942
943        impl #impl_generics ::std::error::Error for #item_ident #ty_generics #where_clause {
944            fn source(&self) -> Option<&(dyn ::std::error::Error + 'static)> {
945                #get_std_source
946            }
947        }
948
949        #from_impl
950    }
951}
952
953enum DisplayArgs {
954    Default,
955    Transparent,
956    Format(proc_macro2::TokenStream),
957}
958
959impl DisplayArgs {
960    fn is_transparent(&self) -> bool {
961        matches!(self, Self::Transparent)
962    }
963
964    fn parse(attrs: &[Attribute]) -> Result<DisplayArgs, syn::Error> {
965        // Only consider #[error(...)]
966        let Some(attr) = attrs.iter().find(|a| a.path().is_ident("error")) else {
967            return Ok(DisplayArgs::Default);
968        };
969
970        let args: Punctuated<Expr, syn::Token![,]> =
971            attr.parse_args_with(Punctuated::<Expr, syn::Token![,]>::parse_terminated)?;
972
973        if args.is_empty() {
974            return Err(err(
975                attr,
976                "#[error(..)] requires arguments: a format string or `transparent`",
977            ));
978        }
979
980        // #[error(transparent)]
981        if args.len() == 1 {
982            if let Expr::Path(p) = &args[0] {
983                if p.path.is_ident("transparent") {
984                    return Ok(DisplayArgs::Transparent);
985                }
986            }
987        }
988
989        // #[error("...", args...)]
990        let mut args = args.into_iter();
991        let first = args.next().unwrap();
992        let fmt_lit = match first {
993            Expr::Lit(syn::ExprLit { lit: syn::Lit::Str(s), .. }) => s,
994            other => return Err(err(
995                other,
996                "first argument to #[error(\"...\")] must be a string literal, or use #[error(transparent)]",
997            ))
998        };
999
1000        let rest: Vec<Expr> = args.collect();
1001        Ok(DisplayArgs::Format(
1002            quote! { write!(f, #fmt_lit #(, #rest)* ) },
1003        ))
1004    }
1005}
1006
1007fn err(ident: impl ToTokens, err: impl ToString) -> syn::Error {
1008    syn::Error::new_spanned(ident, err.to_string())
1009}
1010
1011fn parse_error_attr_as_idents(attrs: &[Attribute]) -> Result<Vec<Ident>, syn::Error> {
1012    let mut out = vec![];
1013    for attr in attrs.iter().filter(|a| a.path().is_ident("error")) {
1014        let idents = attr.parse_args_with(|input: syn::parse::ParseStream<'_>| {
1015            let list: Punctuated<Ident, syn::Token![,]> =
1016                Punctuated::<Ident, syn::Token![,]>::parse_terminated(input)?;
1017            Ok(list.into_iter())
1018        })?;
1019        out.extend(idents);
1020    }
1021    Ok(out)
1022}