errlanes-derive 0.16.1

Derive macros for errlanes (Rejection, Lift, Failure)
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
//! `#[derive(errlanes::Classify)]`.
//!
//! **Pure mode**: no variant and no type-level `#[classify(..)]` item names a
//! lane (`fatal`/`transient`/`denied`), `delegate`, or `with` — the type
//! emits exactly what `#[derive(errlanes::Rejection)]` emits today (that
//! derive's own `impl<R: Rejection> Classify for R` blanket then supplies
//! `Classify`). Implemented by renaming every `#[classify(..)]` attribute to
//! `#[rejection(..)]` and handing the whole, unexamined `DeriveInput` to
//! [`crate::rejection::derive`] — identical grammar, same engine.
//!
//! **Laned mode**: otherwise. Emits `impl Classify` and nothing else.

use proc_macro2::TokenStream;
use quote::quote;
use syn::{Fields, Ident, Path, Token, punctuated::Punctuated};

use crate::std_error::{self, DisplayDefault, Unit};

#[derive(Default)]
struct ClassifyMeta {
    lane: Option<Lane>,
    delegate: bool,
    narrow: Option<Narrow>,
    from: bool,
    with: Option<Path>,
    lanes: Vec<Ident>,
    saw_pure_marker: bool,
    error_manual: bool,
}

enum Lane {
    Fatal(Ident),
    Transient(Ident),
    Denied,
}

#[derive(PartialEq, Eq)]
enum Narrow {
    Denied,
    Rejected,
}

impl ClassifyMeta {
    fn is_laned(&self) -> bool {
        self.lane.is_some() || self.delegate || self.with.is_some()
    }
}

fn parse_classify_meta(attrs: &[syn::Attribute], is_type: bool) -> syn::Result<ClassifyMeta> {
    let mut meta = ClassifyMeta::default();
    for attr in attrs {
        if !attr.path().is_ident("classify") {
            continue;
        }
        attr.parse_nested_meta(|nested| {
            let key = nested
                .path
                .get_ident()
                .map(|i| i.to_string())
                .unwrap_or_default();
            match key.as_str() {
                "fatal" => {
                    let content;
                    syn::parenthesized!(content in nested.input);
                    meta.lane = Some(Lane::Fatal(content.parse()?));
                }
                "transient" => {
                    let content;
                    syn::parenthesized!(content in nested.input);
                    meta.lane = Some(Lane::Transient(content.parse()?));
                }
                "denied" => meta.lane = Some(Lane::Denied),
                "delegate" => meta.delegate = true,
                "narrow" => {
                    let content;
                    syn::parenthesized!(content in nested.input);
                    let which: Ident = content.parse()?;
                    meta.narrow = Some(match which.to_string().as_str() {
                        "Denied" => Narrow::Denied,
                        "Rejected" => Narrow::Rejected,
                        "Transient" => {
                            return Err(nested.error(
                                "narrow(Transient) needs an attempt count; narrow it in the \
                                 retry loop with `Fail::narrow_transient`/`Fault::narrow_transient`, \
                                 not in `derive(Classify)`",
                            ));
                        }
                        other => {
                            return Err(nested.error(format!(
                                "unknown narrow target `{other}`, expected `Denied` or `Rejected`"
                            )));
                        }
                    });
                }
                "from" => meta.from = true,
                "error" => {
                    if !is_type {
                        return Err(nested.error(
                            "`error = manual` is type-level only; put it on the enum/struct, \
                             not a variant",
                        ));
                    }
                    nested.input.parse::<Token![=]>()?;
                    let which: Ident = nested.input.parse()?;
                    if which != "manual" {
                        return Err(nested
                            .error("unknown `error` value, expected `error = manual`"));
                    }
                    meta.error_manual = true;
                }
                "with" => {
                    nested.input.parse::<Token![=]>()?;
                    meta.with = Some(nested.input.parse()?);
                }
                "lanes" => {
                    let content;
                    syn::parenthesized!(content in nested.input);
                    let list = Punctuated::<Ident, Token![,]>::parse_terminated(&content)?;
                    meta.lanes = list.into_iter().collect();
                }
                // Pure-mode items: meaningless here (laned mode never reaches
                // this type's attrs again — pure mode forwards the raw
                // tokens to `rejection::derive` instead), so just consume
                // them so `parse_nested_meta` does not choke on `= value` or
                // `(..)` it does not otherwise recognise.
                "code" | "level" | "code_prefix" | "forward" | "origin" => {
                    meta.saw_pure_marker = true;
                    if nested.input.peek(Token![=]) {
                        nested.input.parse::<Token![=]>()?;
                        let _: syn::Expr = nested.input.parse()?;
                    } else if nested.input.peek(syn::token::Paren) {
                        let content;
                        syn::parenthesized!(content in nested.input);
                        let _: proc_macro2::TokenStream = content.parse()?;
                    }
                }
                other => {
                    return Err(nested.error(format!("unknown `classify` item `{other}`")));
                }
            }
            Ok(())
        })?;
    }
    Ok(meta)
}

/// Renames every `#[classify(..)]` on the type (and, for an enum, every
/// variant) to `#[rejection(..)]`, leaving every other attribute — including
/// `#[lift(..)]`, `#[error(..)]`, `#[derive(..)]` — untouched, then hands the
/// result to [`crate::rejection::derive`]. Pure mode's grammar is, by
/// design, identical to `derive(Rejection)`'s; this is that identity made
/// literal instead of re-implemented.
fn derive_pure(ast: &syn::DeriveInput) -> darling::Result<TokenStream> {
    let mut ast = ast.clone();
    rename_classify_attrs(&mut ast.attrs);
    match &mut ast.data {
        syn::Data::Enum(data) => {
            for variant in &mut data.variants {
                rename_classify_attrs(&mut variant.attrs);
            }
        }
        syn::Data::Struct(data) => {
            for field in data.fields.iter_mut() {
                rename_classify_attrs(&mut field.attrs);
            }
        }
        syn::Data::Union(_) => {}
    }
    crate::rejection::derive(&ast)
}

fn rename_classify_attrs(attrs: &mut [syn::Attribute]) {
    for attr in attrs.iter_mut() {
        if let syn::Meta::List(list) = &mut attr.meta
            && list.path.is_ident("classify")
        {
            list.path = syn::parse_quote!(rejection);
        }
    }
}

/// The lane-profile *type* a single variant/struct contributes to the
/// enclosing `Lanes` union — `errlanes::lanes!(..)` for a static lane, or
/// `<FieldTy as errlanes::Classify>::Lanes` (optionally projected through
/// `WithoutDenied`) for a `delegate`.
fn lane_profile_ty(meta: &ClassifyMeta, field_ty: Option<&syn::Type>) -> syn::Result<TokenStream> {
    if let Some(lane) = &meta.lane {
        return Ok(match lane {
            Lane::Fatal(_) => quote! { errlanes::lanes!(Fatal) },
            Lane::Transient(_) => quote! { errlanes::lanes!(Transient) },
            Lane::Denied => quote! { errlanes::lanes!(Denied) },
        });
    }
    if meta.delegate {
        let field_ty = field_ty.expect("delegate requires a field");
        return Ok(match meta.narrow {
            Some(Narrow::Denied) => quote! {
                <<#field_ty as errlanes::Classify>::Lanes as errlanes::LaneProfile>::WithoutDenied
            },
            _ => quote! { <#field_ty as errlanes::Classify>::Lanes },
        });
    }
    unreachable!("lane_profile_ty called on a variant with neither a lane nor delegate")
}

/// `self`/`v` (already bound to the whole value, so a handler or test can
/// `downcast_ref` the wrapper itself out of the chain) constructed as the
/// static lane's payload.
fn static_lane_expr(lane: &Lane, value: TokenStream) -> TokenStream {
    match lane {
        Lane::Fatal(kind) => quote! {
            errlanes::Fail::Fatal(errlanes::Fatal::from_error(errlanes::FatalKind::#kind, #value))
        },
        Lane::Transient(kind) => quote! {
            errlanes::Fail::Transient(errlanes::Transient::from_error(errlanes::TransientKind::#kind, #value))
        },
        // `Denied` carries no source today (see `errlanes::Denied`'s docs) —
        // the value is still consumed by the match arm, just not kept.
        Lane::Denied => quote! { errlanes::Fail::Denied(errlanes::Denied::default()) },
    }
}

/// The field a `delegate`/`from` acts on, and how to spell it.
pub(crate) struct Payload<'a> {
    pub(crate) ty: &'a syn::Type,
    /// This field's index among its siblings — the same index
    /// [`crate::std_error::field_binding`] uses to name it.
    pub(crate) index: usize,
    /// Binds the payload to `p`: `(p)`, `{ name: p }` or `{ name: p, .. }`.
    pattern: TokenStream,
    /// Wraps `value`: `(value)` or `{ name: value }`. `None` when sibling
    /// fields exist — `delegate` can ignore them, `from` cannot invent them.
    constructor: Option<TokenStream>,
}

/// The only field, or — among several named fields — the one errlanes (like
/// `thiserror`) treats as the cause: marked `#[source]`, or named `source`.
/// Tuple fields cannot be singled out among siblings.
pub(crate) fn payload_field<'a>(
    fields: &'a Fields,
    span: &Ident,
    what: &str,
) -> syn::Result<Payload<'a>> {
    match fields {
        Fields::Unnamed(f) if f.unnamed.len() == 1 => Ok(Payload {
            ty: &f.unnamed[0].ty,
            index: 0,
            pattern: quote! { (p) },
            constructor: Some(quote! { (value) }),
        }),
        Fields::Named(f) if f.named.len() == 1 => {
            let name = f.named[0].ident.as_ref().expect("named field");
            Ok(Payload {
                ty: &f.named[0].ty,
                index: 0,
                pattern: quote! { { #name: p } },
                constructor: Some(quote! { { #name: value } }),
            })
        }
        Fields::Named(f) => {
            let is_cause = |field: &syn::Field| {
                field.attrs.iter().any(|a| a.path().is_ident("source"))
                    || field.ident.as_ref().is_some_and(|i| i == "source")
            };
            let mut causes = f
                .named
                .iter()
                .enumerate()
                .filter(|(_, field)| is_cause(field));
            match (causes.next(), causes.next()) {
                (Some((index, field)), None) => {
                    let name = field.ident.as_ref().expect("named field");
                    Ok(Payload {
                        ty: &field.ty,
                        index,
                        pattern: quote! { { #name: p, .. } },
                        constructor: None,
                    })
                }
                (None, _) => Err(syn::Error::new_spanned(
                    span,
                    format!(
                        "{what} with several fields needs the payload singled out: mark it \
                         `#[source]` or name it `source`"
                    ),
                )),
                (Some(_), Some(_)) => Err(syn::Error::new_spanned(
                    span,
                    format!("{what} found more than one `#[source]`/`source` field"),
                )),
            }
        }
        _ => Err(syn::Error::new_spanned(
            span,
            format!(
                "{what} needs a field to hold the payload, e.g. `Variant(Inner)` or \
                 `Variant {{ source: Inner }}`"
            ),
        )),
    }
}

pub(crate) fn from_impl(
    target: &Ident,
    generics: &syn::Generics,
    variant: Option<&Ident>,
    payload: &Payload<'_>,
    span: &Ident,
) -> syn::Result<TokenStream> {
    let Some(constructor) = &payload.constructor else {
        return Err(syn::Error::new_spanned(
            span,
            "`#[classify(from)]` needs the payload to be the only field: `From` has nothing to \
             fill its siblings with",
        ));
    };
    let field_ty = payload.ty;
    let (impl_generics, ty_generics, where_clause) = generics.split_for_impl();
    let build = match variant {
        Some(v) => quote! { Self::#v #constructor },
        None => quote! { Self #constructor },
    };
    Ok(quote! {
        impl #impl_generics From<#field_ty> for #target #ty_generics #where_clause {
            fn from(value: #field_ty) -> Self {
                #build
            }
        }
    })
}

fn with_impl(
    ident: &Ident,
    generics: &syn::Generics,
    with: &Path,
    lanes: &[Ident],
    error_manual: bool,
    attrs: &[syn::Attribute],
) -> syn::Result<TokenStream> {
    if lanes.is_empty() {
        return Err(syn::Error::new_spanned(
            with,
            "`with = ..` requires `lanes(..)` naming at least one lane",
        ));
    }
    let (impl_generics, ty_generics, where_clause) = generics.split_for_impl();
    let mut out = quote! {
        impl #impl_generics errlanes::Classify for #ident #ty_generics #where_clause {
            type Rejected = core::convert::Infallible;
            type Lanes = errlanes::lanes!(#(#lanes),*);

            fn classify(self) -> errlanes::Fail<Self::Rejected, Self::Lanes> {
                (#with(self)).into()
            }
        }
    };
    if !error_manual {
        let fields = Fields::Unit;
        let error = std_error::take_error_lit(attrs)?;
        out.extend(std_error::emit(
            ident,
            generics,
            DisplayDefault::Name,
            &[Unit {
                pat: quote! { _ },
                fields: &fields,
                error,
                name: ident.clone(),
                source: None,
            }],
        )?);
    }
    Ok(out)
}

fn derive_laned_struct(ast: &syn::DeriveInput, data: &syn::DataStruct) -> syn::Result<TokenStream> {
    let ident = &ast.ident;
    let meta = parse_classify_meta(&ast.attrs, true)?;
    let mut out = TokenStream::new();

    let from_payload = if meta.from {
        let payload = payload_field(&data.fields, ident, "`#[classify(from)]` on a struct")?;
        out.extend(from_impl(ident, &ast.generics, None, &payload, ident)?);
        Some(payload)
    } else {
        None
    };

    if let Some(with) = &meta.with {
        out.extend(with_impl(
            ident,
            &ast.generics,
            with,
            &meta.lanes,
            meta.error_manual,
            &ast.attrs,
        )?);
        return Ok(out);
    }

    if !meta.error_manual {
        std_error::reject_from_field_attr(&data.fields)?;
        let source = match &from_payload {
            Some(p) => Some({
                let name = std_error::field_binding(&data.fields, p.index);
                quote! { #name }
            }),
            None => std_error::marked_source(&data.fields, ident)?,
        };
        let pat = std_error::bind_pattern(quote! { Self }, &data.fields);
        let error = std_error::take_error_lit(&ast.attrs)?;
        out.extend(std_error::emit(
            ident,
            &ast.generics,
            DisplayDefault::Name,
            &[Unit {
                pat,
                fields: &data.fields,
                error,
                name: ident.clone(),
                source,
            }],
        )?);
    }

    let Some(lane) = &meta.lane else {
        return Err(syn::Error::new_spanned(
            ident,
            "a laned struct needs a lane (`#[classify(fatal(Kind))]`, `transient(Kind)`, or \
             `denied`) or `with = ..`; a struct naming neither a lane, `delegate`, nor `with` is \
             pure — derive `errlanes::Rejection` instead",
        ));
    };
    let lanes_ty = lane_profile_ty(&meta, None)?;
    let body = static_lane_expr(lane, quote! { self });
    let (impl_generics, ty_generics, where_clause) = ast.generics.split_for_impl();
    out.extend(quote! {
        impl #impl_generics errlanes::Classify for #ident #ty_generics #where_clause {
            type Rejected = core::convert::Infallible;
            type Lanes = #lanes_ty;

            fn classify(self) -> errlanes::Fail<Self::Rejected, Self::Lanes> {
                #body
            }
        }
    });
    Ok(out)
}

fn derive_laned_enum(ast: &syn::DeriveInput, data: &syn::DataEnum) -> syn::Result<TokenStream> {
    let ident = &ast.ident;
    let type_meta = parse_classify_meta(&ast.attrs, true)?;

    if let Some(with) = &type_meta.with {
        return with_impl(
            ident,
            &ast.generics,
            with,
            &type_meta.lanes,
            type_meta.error_manual,
            &ast.attrs,
        );
    }

    // A type-level lane applies uniformly to every variant: the whole enum
    // value is the payload's source, so no per-variant attribute (or even a
    // per-variant match) is needed at all.
    if let Some(lane) = &type_meta.lane {
        let lanes_ty = lane_profile_ty(&type_meta, None)?;
        let body = static_lane_expr(lane, quote! { self });
        let (impl_generics, ty_generics, where_clause) = ast.generics.split_for_impl();
        let mut out = quote! {
            impl #impl_generics errlanes::Classify for #ident #ty_generics #where_clause {
                type Rejected = core::convert::Infallible;
                type Lanes = #lanes_ty;

                fn classify(self) -> errlanes::Fail<Self::Rejected, Self::Lanes> {
                    #body
                }
            }
        };
        if !type_meta.error_manual {
            let fields = Fields::Unit;
            let error = std_error::take_error_lit(&ast.attrs)?;
            out.extend(std_error::emit(
                ident,
                &ast.generics,
                DisplayDefault::Name,
                &[Unit {
                    pat: quote! { _ },
                    fields: &fields,
                    error,
                    name: ident.clone(),
                    source: None,
                }],
            )?);
        }
        return Ok(out);
    }

    // Otherwise every variant declares its own lane or `delegate`.
    struct Resolved<'a> {
        variant: &'a syn::Variant,
        meta: ClassifyMeta,
        payload: Option<Payload<'a>>,
    }
    let mut resolved = Vec::new();
    for variant in &data.variants {
        let meta = parse_classify_meta(&variant.attrs, false)?;
        if !meta.is_laned() {
            return Err(syn::Error::new_spanned(
                &variant.ident,
                "every variant needs a lane (`fatal(Kind)`/`transient(Kind)`/`denied`) or \
                 `delegate`, or put one lane on the enum itself",
            ));
        }
        let payload = if meta.delegate || meta.from {
            Some(payload_field(
                &variant.fields,
                &variant.ident,
                if meta.delegate {
                    "`delegate`"
                } else {
                    "`#[classify(from)]` on a variant"
                },
            )?)
        } else {
            None
        };
        if meta.narrow.is_some() && !meta.delegate {
            return Err(syn::Error::new_spanned(
                &variant.ident,
                "`narrow(..)` only applies to a `delegate` variant",
            ));
        }
        resolved.push(Resolved {
            variant,
            meta,
            payload,
        });
    }

    let mut lanes_ty = quote! { errlanes::profile::NoLanes };
    for r in &resolved {
        let contribution = lane_profile_ty(&r.meta, r.payload.as_ref().map(|p| p.ty))?;
        lanes_ty = quote! { <#lanes_ty as errlanes::profile::Union<#contribution>>::Out };
    }

    // Folded via `RejectedUnion`, not "the first delegate": at most one
    // delegate may carry a genuine rejection, but which one is first is an
    // accident of declaration order, and a never-rejecting source (a
    // `classify-sqlx`-blessed `sqlx::Error`, say) is just as likely to lead.
    // Folding order-independently means whichever delegate turns out to
    // reject, `Self::Rejected` resolves to its type — and two delegates
    // that both genuinely (and differently) reject become a compile error
    // from `RejectedUnion` itself, not a silent wrong answer.
    let mut rejected_ty = quote! { core::convert::Infallible };
    for r in &resolved {
        if r.meta.delegate && r.meta.narrow != Some(Narrow::Rejected) {
            let field_ty = r.payload.as_ref().unwrap().ty;
            let contribution = quote! { <#field_ty as errlanes::Classify>::Rejected };
            rejected_ty = quote! { <#rejected_ty as errlanes::RejectedUnion<#contribution>>::Out };
        }
    }

    let mut arms = Vec::new();
    let mut from_impls = TokenStream::new();
    for r in &resolved {
        let variant_ident = &r.variant.ident;
        if let Some(lane) = &r.meta.lane {
            let pat = match &r.variant.fields {
                Fields::Unit => quote! { Self::#variant_ident },
                Fields::Unnamed(_) => quote! { Self::#variant_ident(..) },
                Fields::Named(_) => quote! { Self::#variant_ident { .. } },
            };
            let value = quote! { v };
            let expr = static_lane_expr(lane, value);
            arms.push(quote! { v @ #pat => #expr });
        } else if r.meta.delegate {
            let payload = r.payload.as_ref().unwrap();
            let field_ty = payload.ty;
            let pattern = &payload.pattern;
            let classify_call = quote! {
                <#field_ty as errlanes::Classify>::classify(p)
            };
            let narrowed = match r.meta.narrow {
                Some(Narrow::Denied) => quote! { #classify_call.narrow_denied() },
                Some(Narrow::Rejected) => quote! { #classify_call.narrow_rejected() },
                None => classify_call,
            };
            let expr = match r.meta.narrow {
                Some(Narrow::Rejected) => quote! { errlanes::Fail::from(#narrowed) },
                _ => quote! { errlanes::Fail::widen(#narrowed) },
            };
            arms.push(quote! { Self::#variant_ident #pattern => #expr });
        }
        if r.meta.from {
            from_impls.extend(from_impl(
                ident,
                &ast.generics,
                Some(variant_ident),
                r.payload.as_ref().unwrap(),
                variant_ident,
            )?);
        }
    }

    let (impl_generics, ty_generics, where_clause) = ast.generics.split_for_impl();
    let mut out = quote! {
        impl #impl_generics errlanes::Classify for #ident #ty_generics #where_clause {
            type Rejected = #rejected_ty;
            type Lanes = #lanes_ty;

            fn classify(self) -> errlanes::Fail<Self::Rejected, Self::Lanes> {
                match self {
                    #(#arms,)*
                }
            }
        }
    };
    out.extend(from_impls);

    if !type_meta.error_manual {
        let mut display_units = Vec::with_capacity(resolved.len());
        for r in &resolved {
            std_error::reject_from_field_attr(&r.variant.fields)?;
            let variant_ident = &r.variant.ident;
            let source = match &r.payload {
                Some(p) => {
                    let name = std_error::field_binding(&r.variant.fields, p.index);
                    Some(quote! { #name })
                }
                None => std_error::marked_source(&r.variant.fields, variant_ident)?,
            };
            let pat = std_error::bind_pattern(quote! { Self::#variant_ident }, &r.variant.fields);
            let error = std_error::take_error_lit(&r.variant.attrs)?;
            display_units.push(Unit {
                pat,
                fields: &r.variant.fields,
                error,
                name: variant_ident.clone(),
                source,
            });
        }
        out.extend(std_error::emit(
            ident,
            &ast.generics,
            DisplayDefault::Name,
            &display_units,
        )?);
    }

    Ok(out)
}

pub fn derive(ast: &syn::DeriveInput) -> darling::Result<TokenStream> {
    let type_meta = parse_classify_meta(&ast.attrs, true).map_err(darling::Error::from)?;
    let any_variant_laned = match &ast.data {
        syn::Data::Enum(data) => data
            .variants
            .iter()
            .map(|v| parse_classify_meta(&v.attrs, false))
            .collect::<syn::Result<Vec<_>>>()
            .map_err(darling::Error::from)?
            .iter()
            .any(ClassifyMeta::is_laned),
        _ => false,
    };

    if !type_meta.is_laned() && !any_variant_laned {
        return derive_pure(ast);
    }

    match &ast.data {
        syn::Data::Struct(data) => derive_laned_struct(ast, data).map_err(darling::Error::from),
        syn::Data::Enum(data) => derive_laned_enum(ast, data).map_err(darling::Error::from),
        syn::Data::Union(_) => Err(darling::Error::custom(
            "Classify cannot be derived for a union",
        )
        .with_span(&ast.ident)),
    }
}