Skip to main content

error_forge/
macros.rs

1/// Error severity level passed to a registered hook callback.
2///
3/// Marked `#[non_exhaustive]` so future minor releases can add new
4/// severity variants (e.g. `Notice`, `Trace`) without breaking
5/// existing `match` statements.
6#[derive(Clone, Copy, PartialEq, Eq, Debug)]
7#[non_exhaustive]
8pub enum ErrorLevel {
9    /// Debug-level errors (for detailed debugging)
10    Debug,
11    /// Information-level errors (least severe)
12    Info,
13    /// Warning-level errors (moderate severity)
14    Warning,
15    /// Error-level errors (high severity)
16    Error,
17    /// Critical-level errors (most severe)
18    Critical,
19}
20
21/// Error context passed to registered hooks.
22///
23/// Marked `#[non_exhaustive]` so future minor releases can add new
24/// fields without breaking callers that destructure the struct.
25/// Construct via [`ErrorContext::new`] (rather than struct-literal
26/// syntax) from outside the crate.
27#[non_exhaustive]
28pub struct ErrorContext<'a> {
29    /// The error caption
30    pub caption: &'a str,
31    /// The error kind
32    pub kind: &'a str,
33    /// The error level
34    pub level: ErrorLevel,
35    /// Whether the error is fatal
36    pub is_fatal: bool,
37    /// Whether the error can be retried
38    pub is_retryable: bool,
39}
40
41impl<'a> ErrorContext<'a> {
42    /// Construct an [`ErrorContext`] from its components.
43    ///
44    /// Provided so external callers (tests, custom hook wiring) can
45    /// build the struct without depending on its field list, which
46    /// may grow over the `1.x` line.
47    pub fn new(
48        caption: &'a str,
49        kind: &'a str,
50        level: ErrorLevel,
51        is_fatal: bool,
52        is_retryable: bool,
53    ) -> Self {
54        Self {
55            caption,
56            kind,
57            level,
58            is_fatal,
59            is_retryable,
60        }
61    }
62}
63
64use std::sync::OnceLock;
65
66/// Hook callback type.
67///
68/// Stored as a boxed `Fn` so callers can capture environment in a
69/// closure (a `Write`-implementing buffer, a thread-safe logger
70/// handle, an `Arc<Config>`, etc.). The `Send + Sync` bounds let
71/// the hook fire from any thread.
72type ErrorHookFn = Box<dyn Fn(ErrorContext<'_>) + Send + Sync + 'static>;
73
74/// Global error hook for centralized error handling.
75static ERROR_HOOK: OnceLock<ErrorHookFn> = OnceLock::new();
76
77#[doc(hidden)]
78pub trait ErrorSource {
79    fn as_source(&self) -> Option<&(dyn std::error::Error + 'static)>;
80}
81
82impl ErrorSource for std::io::Error {
83    fn as_source(&self) -> Option<&(dyn std::error::Error + 'static)> {
84        Some(self)
85    }
86}
87
88impl ErrorSource for Box<dyn std::error::Error + Send + Sync> {
89    fn as_source(&self) -> Option<&(dyn std::error::Error + 'static)> {
90        Some(self.as_ref())
91    }
92}
93
94impl ErrorSource for Box<dyn std::error::Error> {
95    fn as_source(&self) -> Option<&(dyn std::error::Error + 'static)> {
96        Some(self.as_ref())
97    }
98}
99
100impl ErrorSource for Option<std::io::Error> {
101    fn as_source(&self) -> Option<&(dyn std::error::Error + 'static)> {
102        self.as_ref()
103            .map(|error| error as &(dyn std::error::Error + 'static))
104    }
105}
106
107impl ErrorSource for Option<Box<dyn std::error::Error + Send + Sync>> {
108    fn as_source(&self) -> Option<&(dyn std::error::Error + 'static)> {
109        self.as_deref()
110            .map(|error| error as &(dyn std::error::Error + 'static))
111    }
112}
113
114impl ErrorSource for Option<Box<dyn std::error::Error>> {
115    fn as_source(&self) -> Option<&(dyn std::error::Error + 'static)> {
116        self.as_deref()
117            .map(|error| error as &(dyn std::error::Error + 'static))
118    }
119}
120
121/// Register a callback to be called when errors are created.
122///
123/// **Deprecated since `1.0.0`.** This variant silently discards
124/// the registration failure when a hook is already installed.
125/// Use [`try_register_error_hook`] instead — it returns the
126/// failure explicitly so callers can decide how to handle the
127/// double-registration case.
128///
129/// # Example
130///
131/// ```
132/// use error_forge::macros::{try_register_error_hook, ErrorLevel};
133///
134/// let _ = try_register_error_hook(|ctx| {
135///     match ctx.level {
136///         ErrorLevel::Debug => println!("DEBUG: {} ({})", ctx.caption, ctx.kind),
137///         ErrorLevel::Info => println!("INFO: {} ({})", ctx.caption, ctx.kind),
138///         ErrorLevel::Warning => println!("WARNING: {} ({})", ctx.caption, ctx.kind),
139///         ErrorLevel::Error => println!("ERROR: {} ({})", ctx.caption, ctx.kind),
140///         ErrorLevel::Critical => println!("CRITICAL: {} ({})", ctx.caption, ctx.kind),
141///         // `ErrorLevel` is `#[non_exhaustive]` — minor releases
142///         // may add new severity levels.
143///         _ => println!("OTHER: {} ({})", ctx.caption, ctx.kind),
144///     }
145/// });
146/// ```
147#[deprecated(
148    since = "1.0.0",
149    note = "register_error_hook silently drops registration failures; use \
150            try_register_error_hook instead"
151)]
152pub fn register_error_hook<F>(callback: F)
153where
154    F: Fn(ErrorContext<'_>) + Send + Sync + 'static,
155{
156    let _ = try_register_error_hook(callback);
157}
158
159/// Attempt to register a callback to be called when errors are
160/// created.
161///
162/// The callback may be a function pointer or a closure capturing
163/// thread-safe state. Only one hook can be registered per process;
164/// subsequent calls return `Err("Error hook already registered")`.
165///
166/// # Example
167///
168/// ```
169/// use error_forge::macros::try_register_error_hook;
170/// use std::sync::{Arc, Mutex};
171///
172/// // Closures that capture state work too — not just function pointers.
173/// let log: Arc<Mutex<Vec<String>>> = Arc::new(Mutex::new(Vec::new()));
174/// let log_for_hook = Arc::clone(&log);
175/// let _ = try_register_error_hook(move |ctx| {
176///     log_for_hook
177///         .lock()
178///         .unwrap()
179///         .push(format!("{}: {}", ctx.kind, ctx.caption));
180/// });
181/// ```
182pub fn try_register_error_hook<F>(callback: F) -> Result<(), &'static str>
183where
184    F: Fn(ErrorContext<'_>) + Send + Sync + 'static,
185{
186    ERROR_HOOK
187        .set(Box::new(callback))
188        .map_err(|_| "Error hook already registered")
189}
190
191thread_local! {
192    /// Set while the registered hook runs on this thread. An error
193    /// created from inside the hook would otherwise call the hook
194    /// again and recurse until the stack overflows.
195    static IN_HOOK: std::cell::Cell<bool> = const { std::cell::Cell::new(false) };
196}
197
198/// Clears [`IN_HOOK`] when the hook call ends, including by unwinding.
199struct InHookGuard;
200
201impl Drop for InHookGuard {
202    fn drop(&mut self) {
203        IN_HOOK.with(|flag| flag.set(false));
204    }
205}
206
207/// Call the registered error hook with error context if one is registered.
208///
209/// The hook is not re-entered: errors created while the hook runs on the
210/// same thread (for example by a logging sink that fails) do not call it
211/// again. A panic inside the hook is caught here so it does not unwind
212/// through the error constructor that fired it; the process panic hook
213/// still reports it.
214#[doc(hidden)]
215pub fn call_error_hook(caption: &str, kind: &str, is_fatal: bool, is_retryable: bool) {
216    let Some(hook) = ERROR_HOOK.get() else {
217        return;
218    };
219    if IN_HOOK.with(|flag| flag.replace(true)) {
220        return;
221    }
222    let _guard = InHookGuard;
223
224    // Determine error level based on error properties
225    let level = if is_fatal {
226        ErrorLevel::Critical
227    } else if !is_retryable {
228        ErrorLevel::Error
229    } else if kind == "Warning" {
230        ErrorLevel::Warning
231    } else if kind == "Debug" {
232        ErrorLevel::Debug
233    } else {
234        ErrorLevel::Info
235    };
236
237    let context = ErrorContext {
238        caption,
239        kind,
240        level,
241        is_fatal,
242        is_retryable,
243    };
244
245    // `AssertUnwindSafe`: the closure only borrows the shared hook and
246    // `&str`s. Nothing this function owns is left half-updated by an
247    // unwind (the re-entrancy flag is reset by `_guard` either way), and
248    // any state the hook keeps for itself is the hook's own concern, as
249    // it would be if the panic had reached the caller.
250    let outcome = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| hook(context)));
251    if let Err(payload) = outcome {
252        // Dropping a payload can itself panic; never let that escape.
253        let _ = std::panic::catch_unwind(std::panic::AssertUnwindSafe(move || drop(payload)));
254    }
255}
256
257/// Declare an error enum with constructors, metadata methods,
258/// `Display` and `std::error::Error`.
259///
260/// Each variant needs a `#[kind(Name, tag = value, ...)]` attribute and
261/// may carry one `#[error(display = "...", field, ...)]` attribute. The
262/// two may appear in either order, and doc comments or other attributes
263/// (`#[allow(...)]`, `#[serde(...)]`, ...) are passed through to the
264/// variant. The trailing comma after the last variant is optional.
265///
266/// Recognised `#[kind]` tags are `caption`, `retryable`, `fatal`,
267/// `status` and `exit`; any other tag is a compile error.
268///
269/// The macro generates, for each enum:
270///
271/// - the enum itself with `#[derive(Debug)]`;
272/// - a constructor per variant named after the lowercased variant
273///   (`Config` becomes `config(...)`), which fires the registered
274///   error hook;
275/// - inherent `kind`, `caption`, `is_retryable`, `is_fatal`,
276///   `status_code` and `exit_code` methods (it does **not** implement
277///   [`ForgeError`](crate::ForgeError); see the [`group!`](crate::group)
278///   docs for the delegating impl);
279/// - `Display`, using the `display` string when one is given, or
280///   `"<caption>: <Variant> | field = value ..."` otherwise. Only the
281///   default format needs the fields to implement `Debug` (and
282///   `Display` for a field named `source`); a custom display string
283///   only needs what it formats;
284/// - `std::error::Error`, whose `source()` returns a field named
285///   `source` through [`ErrorSource`].
286///
287/// The display string is a `format!` string. Fields listed after it are
288/// passed as named arguments, and fields it names inline (`{path:?}`)
289/// are captured directly, so `{{` and `}}` produce literal braces.
290///
291/// # Example
292///
293/// ```
294/// use error_forge::define_errors;
295/// use std::path::PathBuf;
296///
297/// define_errors! {
298///     pub enum StoreError {
299///         /// The store file could not be read.
300///         #[error(display = "cannot read {path:?}")]
301///         #[kind(Io, retryable = true, status = 503)]
302///         Read { path: PathBuf },
303///
304///         #[kind(Corrupt, fatal = true, exit = 3)]
305///         Corrupt
306///     }
307/// }
308///
309/// let err = StoreError::read(PathBuf::from("db.bin"));
310/// assert_eq!(err.to_string(), "cannot read \"db.bin\"");
311/// assert!(err.is_retryable());
312/// assert_eq!(StoreError::corrupt().exit_code(), 3);
313/// assert_eq!(StoreError::corrupt().to_string(), "Corrupt: Corrupt");
314/// ```
315#[macro_export]
316macro_rules! define_errors {
317    // ------------------------------------------------------------------
318    // Code generation from the normalised variant list.
319    //
320    // Each variant arrives as
321    // `{ [attrs] [display] [kind, tags] Variant {fields}? }`.
322    // ------------------------------------------------------------------
323    (@emit [[$(#[$meta:meta])*] [$vis:vis] $name:ident]
324        $({
325            [$($vattr:tt)*]
326            [$($disp:tt)*]
327            [$kind:ident $(, $tag:ident = $val:expr)*]
328            $variant:ident $({ $($field:ident : $ftype:ty),* })?
329        })*
330    ) => {
331        $(#[$meta])* #[derive(::core::fmt::Debug)]
332        #[cfg_attr(feature = "serde", derive(::serde::Serialize))]
333        $vis enum $name {
334            $( $($vattr)* $variant $( { $($field : $ftype),* } )?, )*
335        }
336
337        // Rejects misspelled `#[kind]` tags, which would otherwise be
338        // ignored silently.
339        const _: () = {
340            $( $( $crate::define_errors!(@check_tag $tag); )* )*
341        };
342
343        impl $name {
344            $(
345                $crate::__private::pastey::paste! {
346                    pub fn [<$variant:lower>]($($($field : $ftype),*)?) -> Self {
347                        let instance = Self::$variant $( { $($field),* } )?;
348                        $crate::macros::call_error_hook(
349                            instance.caption(),
350                            instance.kind(),
351                            instance.is_fatal(),
352                            instance.is_retryable()
353                        );
354                        instance
355                    }
356                }
357            )*
358
359            pub fn caption(&self) -> &'static str {
360                match self {
361                    $( Self::$variant { .. } => {
362                        $crate::define_errors!(@get_caption $kind $(, $tag = $val)*)
363                    } ),*
364                }
365            }
366
367            pub fn kind(&self) -> &'static str {
368                match self {
369                    $( Self::$variant { .. } => {
370                        ::core::stringify!($kind)
371                    } ),*
372                }
373            }
374
375            pub fn is_retryable(&self) -> bool {
376                match self {
377                    $( Self::$variant { .. } => {
378                        $crate::define_errors!(@get_tag retryable, false $(, $tag = $val)*)
379                    } ),*
380                }
381            }
382
383            pub fn is_fatal(&self) -> bool {
384                match self {
385                    $( Self::$variant { .. } => {
386                        $crate::define_errors!(@get_tag fatal, false $(, $tag = $val)*)
387                    } ),*
388                }
389            }
390
391            pub fn status_code(&self) -> u16 {
392                match self {
393                    $( Self::$variant { .. } => {
394                        $crate::define_errors!(@get_tag status, 500 $(, $tag = $val)*)
395                    } ),*
396                }
397            }
398
399            pub fn exit_code(&self) -> i32 {
400                match self {
401                    $( Self::$variant { .. } => {
402                        $crate::define_errors!(@get_tag exit, 1 $(, $tag = $val)*)
403                    } ),*
404                }
405            }
406        }
407
408        impl ::core::fmt::Display for $name {
409            #[allow(unused_variables)]
410            fn fmt(&self, f: &mut ::core::fmt::Formatter<'_>) -> ::core::fmt::Result {
411                match self {
412                    $( Self::$variant $( { $($field),* } )? => {
413                        $crate::define_errors!(
414                            @display f [$($disp)*] self.caption(); $variant $($($field)*)?
415                        )
416                    } ),*
417                }
418            }
419        }
420
421        impl ::std::error::Error for $name {
422            #[allow(unused_variables)]
423            fn source(&self) -> ::core::option::Option<&(dyn ::std::error::Error + 'static)> {
424                match self {
425                    $( Self::$variant $( { $($field),* } )? => {
426                        $crate::define_errors!(@find_source $( $($field),* )? )
427                    } ),*
428                }
429            }
430        }
431    };
432
433    // `Display` body for one variant: the custom string when given ...
434    (@display $f:ident [$display:literal $(, $param:ident)*] $caption:expr; $variant:ident $($field:ident)*) => {
435        ::core::write!($f, $display $(, $param = $param)*)
436    };
437    // ... otherwise `<caption>: <Variant> | field = value ...`. The
438    // default format is only generated for variants without a custom
439    // string, so it is the only place the fields need `Debug`.
440    (@display $f:ident [] $caption:expr; $variant:ident $($field:ident)*) => {{
441        ::core::write!($f, "{}: ", $caption)?;
442        $f.write_str(::core::stringify!($variant))?;
443        $(
444            ::core::write!($f, " | {} = ", ::core::stringify!($field))?;
445            $crate::define_errors!(@fmt_field $f, $field, $field)?;
446        )*
447        ::core::result::Result::Ok(())
448    }};
449    (@display $($rest:tt)*) => {
450        ::core::compile_error!(
451            "define_errors!: a variant may carry only one #[error(display = \"...\")] attribute"
452        )
453    };
454
455    // A field named `source` is shown with `Display`, every other field
456    // with `Debug`. Matching the name here (rather than a runtime `match`
457    // on `stringify!`) keeps the unused branch out of the generated code.
458    (@fmt_field $f:ident, source, $field:ident) => {
459        ::core::write!($f, "{}", $field)
460    };
461    (@fmt_field $f:ident, $name:ident, $field:ident) => {
462        ::core::write!($f, "{:?}", $field)
463    };
464
465    (@check_tag caption) => {};
466    (@check_tag retryable) => {};
467    (@check_tag fatal) => {};
468    (@check_tag status) => {};
469    (@check_tag exit) => {};
470    (@check_tag $other:ident) => {
471        ::core::compile_error!(::core::concat!(
472            "define_errors!: unknown #[kind] tag `",
473            ::core::stringify!($other),
474            "`; expected one of `caption`, `retryable`, `fatal`, `status`, `exit`"
475        ));
476    };
477
478    // ------------------------------------------------------------------
479    // General variant parser, used when the fast form below does not
480    // match (attributes other than doc comments, doc comments placed
481    // between `#[error]` and `#[kind]`, or malformed input that deserves
482    // a precise error). It walks one attribute or variant per step, so
483    // very large enums written this way may need a higher
484    // `#![recursion_limit]`.
485    //
486    // State: `$hdr [done variants] [pending attrs] [display] [kind]`.
487    // ------------------------------------------------------------------
488    (@munch $hdr:tt [$($done:tt)*] [] [] []) => {
489        $crate::define_errors!(@emit $hdr $($done)*);
490    };
491    (@munch $hdr:tt $done:tt [$($attrs:tt)*] [] $kind:tt
492        #[error(display = $display:literal $(, $param:ident)* $(,)?)] $($rest:tt)*
493    ) => {
494        $crate::define_errors!(@munch $hdr $done [$($attrs)*] [$display $(, $param)*] $kind $($rest)*);
495    };
496    (@munch $hdr:tt $done:tt $attrs:tt $disp:tt $kind:tt #[error $($bad:tt)*] $($rest:tt)*) => {
497        ::core::compile_error!(::core::concat!(
498            "define_errors!: expected a single `#[error(display = \"...\", field, ...)]` per variant, found `#[error",
499            ::core::stringify!($($bad)*),
500            "]`"
501        ));
502    };
503    (@munch $hdr:tt $done:tt [$($attrs:tt)*] $disp:tt []
504        #[kind($kind:ident $(, $tag:ident = $val:expr)* $(,)?)] $($rest:tt)*
505    ) => {
506        $crate::define_errors!(@munch $hdr $done [$($attrs)*] $disp [$kind $(, $tag = $val)*] $($rest)*);
507    };
508    (@munch $hdr:tt $done:tt $attrs:tt $disp:tt $kind:tt #[kind $($bad:tt)*] $($rest:tt)*) => {
509        ::core::compile_error!(::core::concat!(
510            "define_errors!: expected a single `#[kind(Name, tag = value, ...)]` per variant, found `#[kind",
511            ::core::stringify!($($bad)*),
512            "]`"
513        ));
514    };
515    (@munch $hdr:tt $done:tt [$($attrs:tt)*] $disp:tt $kind:tt #[$($attr:tt)*] $($rest:tt)*) => {
516        $crate::define_errors!(@munch $hdr $done [$($attrs)* #[$($attr)*]] $disp $kind $($rest)*);
517    };
518    (@munch $hdr:tt [$($done:tt)*] [$($attrs:tt)*] [$($disp:tt)*] [$($kind:tt)+]
519        $variant:ident { $($field:ident : $ftype:ty),* $(,)? } $(, $($rest:tt)*)?
520    ) => {
521        $crate::define_errors!(@munch $hdr
522            [$($done)* { [$($attrs)*] [$($disp)*] [$($kind)+] $variant { $($field : $ftype),* } }]
523            [] [] [] $($($rest)*)?);
524    };
525    (@munch $hdr:tt [$($done:tt)*] [$($attrs:tt)*] [$($disp:tt)*] [$($kind:tt)+]
526        $variant:ident $(, $($rest:tt)*)?
527    ) => {
528        $crate::define_errors!(@munch $hdr
529            [$($done)* { [$($attrs)*] [$($disp)*] [$($kind)+] $variant }]
530            [] [] [] $($($rest)*)?);
531    };
532    (@munch $hdr:tt $done:tt $attrs:tt $disp:tt [] $variant:ident $($rest:tt)*) => {
533        ::core::compile_error!(::core::concat!(
534            "define_errors!: variant `",
535            ::core::stringify!($variant),
536            "` needs a `#[kind(Name, ...)]` attribute"
537        ));
538    };
539    (@munch $hdr:tt $done:tt $attrs:tt $disp:tt $kind:tt) => {
540        ::core::compile_error!("define_errors!: attributes must be followed by a variant");
541    };
542    (@munch $hdr:tt $done:tt $attrs:tt $disp:tt $kind:tt $($rest:tt)+) => {
543        ::core::compile_error!(::core::concat!(
544            "define_errors!: expected a unit or struct-like variant (`Name` or `Name { field: Type }`), found `",
545            ::core::stringify!($($rest)+),
546            "`"
547        ));
548    };
549
550    // ------------------------------------------------------------------
551    // Helpers kept from 1.0.x.
552    // ------------------------------------------------------------------
553    (@find_source) => {
554        ::core::option::Option::None
555    };
556
557    (@find_source $field:ident $(, $rest:ident)*) => {
558        $crate::define_errors!(@find_source_match $field, $field $(, $rest)*)
559    };
560
561    (@find_source_match source, $source_field:ident $(, $rest:ident)*) => {
562        $crate::macros::ErrorSource::as_source($source_field)
563    };
564
565    (@find_source_match $field_name:ident, $field:ident $(, $rest:ident)*) => {
566        $crate::define_errors!(@find_source $($rest),*)
567    };
568
569    (@get_caption $kind:ident) => {
570        ::core::stringify!($kind)
571    };
572
573    (@get_caption $kind:ident, caption = $caption:expr $(, $($rest:tt)*)?) => {
574        $caption
575    };
576
577    (@get_caption $kind:ident, $tag:ident = $val:expr $(, $($rest:tt)*)?) => {
578        $crate::define_errors!(@get_caption $kind $(, $($rest)*)?)
579    };
580
581    (@get_tag $target:ident, $default:expr) => {
582        $default
583    };
584
585    (@get_tag retryable, $default:expr, retryable = $val:expr $(, $($rest:tt)*)?) => {
586        $val
587    };
588
589    (@get_tag fatal, $default:expr, fatal = $val:expr $(, $($rest:tt)*)?) => {
590        $val
591    };
592
593    (@get_tag status, $default:expr, status = $val:expr $(, $($rest:tt)*)?) => {
594        $val
595    };
596
597    (@get_tag exit, $default:expr, exit = $val:expr $(, $($rest:tt)*)?) => {
598        $val
599    };
600
601    (@get_tag $target:ident, $default:expr, $tag:ident = $val:expr $(, $($rest:tt)*)?) => {
602        $crate::define_errors!(@get_tag $target, $default $(, $($rest)*)?)
603    };
604
605    (@format_display $display:literal) => {
606        ::core::option::Option::Some(::std::format!($display))
607    };
608
609    (@format_display $display:literal, $($param:ident),+) => {
610        ::core::option::Option::Some(::std::format!($display, $($param = $param),+))
611    };
612
613    (@format_display_field $field:ident) => {
614        $field
615    };
616
617    (@format_display_field $field:ident . $($rest:ident).+) => {
618        $field$(.$rest)+
619    };
620
621    // ------------------------------------------------------------------
622    // Entry points.
623    // ------------------------------------------------------------------
624
625    // Fast form: optional doc comments, then `#[kind]` with an optional
626    // `#[error]` before or after it. Matched without recursion, so enums
627    // of any size work. Every input accepted by 1.0.1 takes this path.
628    (
629        $(
630            $(#[$meta:meta])* $vis:vis enum $name:ident {
631                $(
632                    $(#[doc = $vdoc:expr])*
633                    $(#[error(display = $display_a:literal $(, $param_a:ident)* $(,)?)])?
634                    #[kind($kind:ident $(, $tag:ident = $val:expr)* $(,)?)]
635                    $(#[error(display = $display_b:literal $(, $param_b:ident)* $(,)?)])?
636                    $variant:ident $( { $($field:ident : $ftype:ty),* $(,)? } )?
637                ),* $(,)?
638            }
639        )*
640    ) => {
641        $(
642            $crate::define_errors!(@emit [[$(#[$meta])*] [$vis] $name]
643                $({
644                    [$(#[doc = $vdoc])*]
645                    [
646                        $($display_a $(, $param_a)*)?
647                        $($display_b $(, $param_b)*)?
648                    ]
649                    [$kind $(, $tag = $val)*]
650                    $variant $( { $($field : $ftype),* } )?
651                })*
652            );
653        )*
654    };
655
656    // General form: any attributes in any order.
657    (
658        $(
659            $(#[$meta:meta])* $vis:vis enum $name:ident { $($body:tt)* }
660        )*
661    ) => {
662        $(
663            $crate::define_errors!(@munch [[$(#[$meta])*] [$vis] $name] [] [] [] [] $($body)*);
664        )*
665    };
666}