vespera_macro 0.1.43

Procedural macros for Vespera - automatic route discovery and OpenAPI generation
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
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
//! Vespera's `Multipart` derive macro implementation.
//!
//! This is a re-implementation of `axum_typed_multipart`'s derive macro that
//! natively supports `#[serde(rename_all)]` and `#[serde(rename)]` attributes
//! for field name resolution in multipart form data.
//!
//! ## Why?
//!
//! `axum_typed_multipart`'s derive macro only reads `#[try_from_multipart(rename_all)]`
//! and ignores `#[serde(rename_all)]`. This causes a mismatch: the OpenAPI spec
//! (generated by `Schema` derive) shows camelCase field names, but the runtime
//! multipart parser expects snake_case Rust field names.
//!
//! ## Field Name Resolution Priority
//!
//! 1. `#[form_data(field_name = "...")]` — explicit override (highest priority)
//! 2. `#[serde(rename = "...")]` — serde field rename
//! 3. `#[serde(rename_all = "...")]` or `#[try_from_multipart(rename_all = "...")]` applied to Rust name
//! 4. Rust field name as-is (lowest priority)

use proc_macro2::TokenStream;
use quote::quote;
use syn::{DeriveInput, Fields, Type};

use crate::parser::{extract_default, extract_field_rename, extract_rename_all, rename_field};

/// Collected codegen fragments for each struct field.
struct FieldCodegen<'a> {
    declarations: Vec<TokenStream>,
    assignments: Vec<TokenStream>,
    post_loop: Vec<TokenStream>,
    idents: Vec<&'a syn::Ident>,
}

/// How a missing field should be handled.
enum DefaultKind {
    /// No default — field is required; emit `MissingField` error.
    None,
    /// Use `Default::default()` — from `#[serde(default)]` or `#[form_data(default)]`.
    Trait,
    /// Call a custom function — from `#[serde(default = "path::to::fn")]`.
    Function(String),
}

/// Process all named fields into codegen fragments.
fn process_fields<'a>(
    fields: impl Iterator<Item = &'a syn::Field>,
    rename_all: Option<&str>,
    strict: bool,
    struct_default: bool,
) -> FieldCodegen<'a> {
    let mut cg = FieldCodegen {
        declarations: Vec::new(),
        assignments: Vec::new(),
        post_loop: Vec::new(),
        idents: Vec::new(),
    };

    for field in fields {
        let ident = field.ident.as_ref().unwrap();
        let ty = &field.ty;
        let is_vec = is_vec_type(ty);
        let is_option = is_option_type(ty);
        let field_name = resolve_field_name(ident, &field.attrs, rename_all);
        let limit_tokens = extract_limit_tokens(&field.attrs);
        let default_kind = resolve_default_kind(&field.attrs, struct_default);

        // The concrete type for TryFromFieldWithState turbofish. For Option<T>
        // and Vec<T> the derive wraps the parsed value, so the trait Self is T.
        let parse_ty = if is_option || is_vec {
            extract_inner_generic(ty).unwrap_or_else(|| ty.clone())
        } else {
            ty.clone()
        };

        // Variable declaration
        if is_vec {
            cg.declarations
                .push(quote! { let mut #ident: #ty = std::vec::Vec::new(); });
        } else if is_option {
            cg.declarations
                .push(quote! { let mut #ident: #ty = std::option::Option::None; });
        } else {
            cg.declarations.push(
                quote! { let mut #ident: std::option::Option<#ty> = std::option::Option::None; },
            );
        }

        // Field value parsing — explicit turbofish types are required because
        // RPITIT opaque return types prevent the compiler from inferring
        // `TryFromFieldWithState::Self` through `.await`.
        let try_from_call = quote! { <#parse_ty as vespera::multipart::TryFromFieldWithState<__VesperaS__>>::try_from_field_with_state };
        let parse_value = quote! { #try_from_call(__field__, #limit_tokens, __state__).await? };

        let assignment = if is_vec {
            quote! { #ident.push(#parse_value); }
        } else if strict {
            let set_value = quote! { #ident = std::option::Option::Some(#parse_value) };
            let dup_err = quote! { return std::result::Result::Err(vespera::multipart::TypedMultipartError::DuplicateField { field_name: std::string::String::from(#field_name) }) };
            quote! { if #ident.is_none() { #set_value ; } else { #dup_err ; } }
        } else {
            quote! { #ident = std::option::Option::Some(#parse_value); }
        };

        let field_match = quote! { if __field_name__ == #field_name { #assignment } };
        cg.assignments.push(field_match);

        // Post-loop: required field checks / defaults
        if !is_option && !is_vec {
            match &default_kind {
                DefaultKind::Trait => {
                    cg.post_loop.push(quote! {
                        let #ident: #ty = #ident.unwrap_or_default();
                    });
                }
                DefaultKind::Function(fn_path) => {
                    let path: syn::ExprPath =
                        syn::parse_str(fn_path).expect("invalid default function path");
                    cg.post_loop.push(quote! {
                        let #ident: #ty = #ident.unwrap_or_else(#path);
                    });
                }
                DefaultKind::None => {
                    cg.post_loop.push(quote! {
                        let #ident = #ident.ok_or(
                            vespera::multipart::TypedMultipartError::MissingField {
                                field_name: std::string::String::from(#field_name)
                            }
                        )?;
                    });
                }
            }
        }

        cg.idents.push(ident);
    }

    cg
}

/// Process the `#[derive(TryFromMultipart)]` macro input.
pub fn process_derive(input: &DeriveInput) -> TokenStream {
    let struct_name = &input.ident;
    let rename_all = extract_rename_all(&input.attrs);
    let strict = extract_strict(&input.attrs);
    let struct_default = extract_struct_default(&input.attrs);

    let fields = match &input.data {
        syn::Data::Struct(data) => match &data.fields {
            Fields::Named(named) => &named.named,
            _ => {
                return syn::Error::new_spanned(
                    &input.ident,
                    "Multipart only supports structs with named fields",
                )
                .to_compile_error();
            }
        },
        _ => {
            return syn::Error::new_spanned(
                &input.ident,
                "Multipart can only be derived for structs",
            )
            .to_compile_error();
        }
    };

    let mut cg = process_fields(fields.iter(), rename_all.as_deref(), strict, struct_default);

    if strict {
        cg.assignments.push(quote! {
            {
                return std::result::Result::Err(
                    vespera::multipart::TypedMultipartError::UnknownField {
                        field_name: __field_name__
                    }
                );
            }
        });
    }

    let missing_name_fallback = if strict {
        quote! {
            return std::result::Result::Err(
                vespera::multipart::TypedMultipartError::NamelessField
            )
        }
    } else {
        quote! { continue }
    };

    let FieldCodegen {
        declarations,
        assignments,
        post_loop,
        idents,
        ..
    } = &cg;

    quote! {
        impl<__VesperaS__: Send + Sync> vespera::multipart::TryFromMultipartWithState<__VesperaS__> for #struct_name {
            async fn try_from_multipart_with_state(
                __multipart__: &mut vespera::axum::extract::Multipart,
                __state__: &__VesperaS__,
            ) -> std::result::Result<Self, vespera::multipart::TypedMultipartError> {
                #(#declarations)*

                while let std::option::Option::Some(__field__) = __multipart__
                    .next_field().await
                    .map_err(vespera::multipart::TypedMultipartError::from)? {
                    let __field_name__ = match __field__.name() {
                        | std::option::Option::Some("")
                        | std::option::Option::None => #missing_name_fallback,
                        | std::option::Option::Some(__name__) => __name__.to_string(),
                    };

                    #(#assignments) else *
                }

                #(#post_loop)*

                std::result::Result::Ok(Self { #(#idents),* })
            }
        }
    }
}

// ─── Field Name Resolution ──────────────────────────────────────────────────

/// Resolve the multipart field name using serde + form_data attributes.
///
/// Priority:
/// 1. `#[form_data(field_name = "...")]`
/// 2. `#[serde(rename = "...")]`
/// 3. struct-level `rename_all` applied to Rust field name
/// 4. Rust field name as-is
fn resolve_field_name(
    ident: &syn::Ident,
    attrs: &[syn::Attribute],
    rename_all: Option<&str>,
) -> String {
    // 1. Explicit form_data override
    if let Some(name) = extract_form_data_field_name(attrs) {
        return name;
    }

    // 2. Serde field rename
    if let Some(name) = extract_field_rename(attrs) {
        return name;
    }

    // 3. Apply rename_all to Rust field name
    let rust_name = strip_raw_prefix(&ident.to_string());
    rename_field(&rust_name, rename_all)
}

// ─── Attribute Extraction ───────────────────────────────────────────────────

/// Extract `field_name` from `#[form_data(field_name = "...")]`.
fn extract_form_data_field_name(attrs: &[syn::Attribute]) -> Option<String> {
    for attr in attrs {
        if attr.path().is_ident("form_data") {
            let mut found = None;
            let _ = attr.parse_nested_meta(|meta| {
                if meta.path.is_ident("field_name")
                    && let Ok(value) = meta.value()
                    && let Ok(lit) = value.parse::<syn::LitStr>()
                {
                    found = Some(lit.value());
                }
                Ok(())
            });
            if found.is_some() {
                return found;
            }
        }
    }
    None
}

/// Extract `strict` flag from `#[try_from_multipart(strict)]`.
fn extract_strict(attrs: &[syn::Attribute]) -> bool {
    for attr in attrs {
        if attr.path().is_ident("try_from_multipart") {
            let mut strict = false;
            let _ = attr.parse_nested_meta(|meta| {
                if meta.path.is_ident("strict") {
                    strict = true;
                }
                Ok(())
            });
            if strict {
                return true;
            }
        }
    }
    false
}

/// Extract `limit` from `#[form_data(limit = "10MiB")]` and emit as `Option<usize>` tokens.
fn extract_limit_tokens(attrs: &[syn::Attribute]) -> TokenStream {
    for attr in attrs {
        if attr.path().is_ident("form_data") {
            let mut limit_str = None;
            let _ = attr.parse_nested_meta(|meta| {
                if meta.path.is_ident("limit")
                    && let Ok(value) = meta.value()
                    && let Ok(lit) = value.parse::<syn::LitStr>()
                {
                    limit_str = Some(lit.value());
                }
                Ok(())
            });
            if let Some(s) = limit_str {
                if s == "unlimited" {
                    return quote! { std::option::Option::None };
                }
                if let Some(bytes) = parse_byte_unit(&s) {
                    return quote! { std::option::Option::Some(#bytes) };
                }
            }
        }
    }
    // Default: no limit (None)
    quote! { std::option::Option::None }
}

/// Resolve the default behavior for a field.
///
/// Priority:
/// 1. `#[form_data(default)]` — explicit form_data override (bare default)
/// 2. `#[serde(default)]` — bare default via `Default::default()`
/// 3. `#[serde(default = "fn_path")]` — custom default function
/// 4. Struct-level `#[serde(default)]` — all fields get `Default::default()`
/// 5. No default — field is required
fn resolve_default_kind(attrs: &[syn::Attribute], struct_default: bool) -> DefaultKind {
    // 1. Check #[form_data(default)]
    if extract_form_data_default(attrs) {
        return DefaultKind::Trait;
    }

    // 2-3. Check #[serde(default)] or #[serde(default = "fn")]
    if let Some(serde_default) = extract_default(attrs) {
        return serde_default.map_or(DefaultKind::Trait, DefaultKind::Function);
    }

    // 4. Struct-level #[serde(default)]
    if struct_default {
        return DefaultKind::Trait;
    }

    DefaultKind::None
}

/// Extract `default` flag from `#[form_data(default)]`.
fn extract_form_data_default(attrs: &[syn::Attribute]) -> bool {
    for attr in attrs {
        if attr.path().is_ident("form_data") {
            let mut has_default = false;
            let _ = attr.parse_nested_meta(|meta| {
                if meta.path.is_ident("default") {
                    has_default = true;
                }
                Ok(())
            });
            if has_default {
                return true;
            }
        }
    }
    false
}

/// Check if the struct has `#[serde(default)]` at the struct level.
fn extract_struct_default(attrs: &[syn::Attribute]) -> bool {
    // Reuse extract_default — if it returns Some(None), it's bare #[serde(default)]
    // For struct-level, we only support bare default (no custom function)
    extract_default(attrs).is_some()
}

// ─── Type Utilities ─────────────────────────────────────────────────────────

/// Extract the first generic type argument from a type like `Option<T>` or `Vec<T>`.
fn extract_inner_generic(ty: &Type) -> Option<Type> {
    let Type::Path(type_path) = ty else {
        return None;
    };
    let segment = type_path.path.segments.last()?;
    if let syn::PathArguments::AngleBracketed(args) = &segment.arguments
        && let Some(syn::GenericArgument::Type(inner)) = args.args.first()
    {
        return Some(inner.clone());
    }
    None
}

/// Check if a type matches `Option<T>`.
fn is_option_type(ty: &Type) -> bool {
    matches_type_name(
        ty,
        &["Option", "std::option::Option", "core::option::Option"],
    )
}

/// Check if a type matches `Vec<T>`.
fn is_vec_type(ty: &Type) -> bool {
    matches_type_name(ty, &["Vec", "std::vec::Vec"])
}

/// Check if a type's path matches any of the given names.
fn matches_type_name(ty: &Type, names: &[&str]) -> bool {
    let path = match ty {
        Type::Path(type_path) if type_path.qself.is_none() => &type_path.path,
        _ => return false,
    };
    let sig = path
        .segments
        .iter()
        .map(|s| s.ident.to_string())
        .collect::<Vec<_>>()
        .join("::");
    names.contains(&sig.as_str())
}

/// Strip leading `r#` from raw identifiers.
fn strip_raw_prefix(s: &str) -> String {
    s.strip_prefix("r#").unwrap_or(s).to_string()
}

// ─── Byte Unit Parser ───────────────────────────────────────────────────────

/// Parse a human-readable byte unit string into bytes.
///
/// Supports: `"10MiB"`, `"1GB"`, `"500KB"`, `"1024"`, `"unlimited"`.
fn parse_byte_unit(s: &str) -> Option<usize> {
    let s = s.trim();

    // Binary and decimal suffixes, longest first to avoid prefix collisions
    let suffixes: &[(&str, usize)] = &[
        ("GiB", 1024 * 1024 * 1024),
        ("MiB", 1024 * 1024),
        ("KiB", 1024),
        ("GB", 1_000_000_000),
        ("MB", 1_000_000),
        ("KB", 1_000),
        ("B", 1),
    ];

    for (suffix, multiplier) in suffixes {
        if let Some(num_str) = s.strip_suffix(suffix) {
            return num_str.trim().parse::<usize>().ok().map(|n| n * multiplier);
        }
    }

    // Plain number (bytes)
    s.parse::<usize>().ok()
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_parse_byte_unit() {
        assert_eq!(parse_byte_unit("10MiB"), Some(10 * 1024 * 1024));
        assert_eq!(parse_byte_unit("50MiB"), Some(50 * 1024 * 1024));
        assert_eq!(parse_byte_unit("1GB"), Some(1_000_000_000));
        assert_eq!(parse_byte_unit("500KB"), Some(500_000));
        assert_eq!(parse_byte_unit("1024"), Some(1024));
        assert_eq!(parse_byte_unit("0"), Some(0));
        assert_eq!(parse_byte_unit("invalid"), None);
    }

    #[test]
    fn test_parse_byte_unit_all_suffixes() {
        assert_eq!(parse_byte_unit("1GiB"), Some(1024 * 1024 * 1024));
        assert_eq!(parse_byte_unit("2KiB"), Some(2 * 1024));
        assert_eq!(parse_byte_unit("3MB"), Some(3_000_000));
        assert_eq!(parse_byte_unit("4B"), Some(4));
        assert_eq!(parse_byte_unit("  5MiB  "), Some(5 * 1024 * 1024));
    }

    #[test]
    fn test_strip_raw_prefix() {
        assert_eq!(strip_raw_prefix("r#type"), "type");
        assert_eq!(strip_raw_prefix("normal"), "normal");
    }

    // ─── extract_inner_generic ──────────────────────────────────────────

    #[test]
    fn test_extract_inner_generic_option() {
        let ty: syn::Type = syn::parse_str("Option<String>").unwrap();
        let inner = extract_inner_generic(&ty).unwrap();
        assert_eq!(quote!(#inner).to_string(), "String");
    }

    #[test]
    fn test_extract_inner_generic_vec() {
        let ty: syn::Type = syn::parse_str("Vec<i32>").unwrap();
        let inner = extract_inner_generic(&ty).unwrap();
        assert_eq!(quote!(#inner).to_string(), "i32");
    }

    #[test]
    fn test_extract_inner_generic_no_generics() {
        let ty: syn::Type = syn::parse_str("String").unwrap();
        assert!(extract_inner_generic(&ty).is_none());
    }

    #[test]
    fn test_extract_inner_generic_non_path() {
        let ty: syn::Type = syn::parse_str("(i32, String)").unwrap();
        assert!(extract_inner_generic(&ty).is_none());
    }

    // ─── is_option_type / is_vec_type ───────────────────────────────────

    #[test]
    fn test_is_option_type() {
        let ty: syn::Type = syn::parse_str("Option<String>").unwrap();
        assert!(is_option_type(&ty));

        let ty: syn::Type = syn::parse_str("std::option::Option<i32>").unwrap();
        assert!(is_option_type(&ty));

        let ty: syn::Type = syn::parse_str("Vec<String>").unwrap();
        assert!(!is_option_type(&ty));

        let ty: syn::Type = syn::parse_str("String").unwrap();
        assert!(!is_option_type(&ty));
    }

    #[test]
    fn test_is_vec_type() {
        let ty: syn::Type = syn::parse_str("Vec<String>").unwrap();
        assert!(is_vec_type(&ty));

        let ty: syn::Type = syn::parse_str("std::vec::Vec<i32>").unwrap();
        assert!(is_vec_type(&ty));

        let ty: syn::Type = syn::parse_str("Option<String>").unwrap();
        assert!(!is_vec_type(&ty));

        let ty: syn::Type = syn::parse_str("String").unwrap();
        assert!(!is_vec_type(&ty));
    }

    // ─── matches_type_name ──────────────────────────────────────────────

    #[test]
    fn test_matches_type_name_simple() {
        let ty: syn::Type = syn::parse_str("Option<i32>").unwrap();
        assert!(matches_type_name(&ty, &["Option"]));
        assert!(!matches_type_name(&ty, &["Vec"]));
    }

    #[test]
    fn test_matches_type_name_qualified() {
        let ty: syn::Type = syn::parse_str("std::option::Option<i32>").unwrap();
        assert!(matches_type_name(&ty, &["std::option::Option"]));
        assert!(!matches_type_name(&ty, &["Option"])); // qualified doesn't match simple
    }

    #[test]
    fn test_matches_type_name_non_path() {
        let ty: syn::Type = syn::parse_str("(i32, String)").unwrap();
        assert!(!matches_type_name(&ty, &["Option", "Vec"]));
    }

    // ─── extract_form_data_field_name ───────────────────────────────────

    fn parse_field(code: &str) -> syn::Field {
        let input: syn::DeriveInput = syn::parse_str(&format!("struct T {{ {code} }}")).unwrap();
        match &input.data {
            syn::Data::Struct(s) => match &s.fields {
                Fields::Named(n) => n.named.first().unwrap().clone(),
                _ => unreachable!(),
            },
            _ => unreachable!(),
        }
    }

    fn parse_attrs(code: &str) -> Vec<syn::Attribute> {
        parse_field(code).attrs
    }

    #[test]
    fn test_extract_form_data_field_name_present() {
        let attrs = parse_attrs(r#"#[form_data(field_name = "custom")] pub x: String"#);
        assert_eq!(
            extract_form_data_field_name(&attrs),
            Some("custom".to_string())
        );
    }

    #[test]
    fn test_extract_form_data_field_name_absent() {
        let attrs = parse_attrs("pub x: String");
        assert_eq!(extract_form_data_field_name(&attrs), None);
    }

    #[test]
    fn test_extract_form_data_field_name_other_form_data_attr() {
        let attrs = parse_attrs(r#"#[form_data(limit = "100")] pub x: String"#);
        assert_eq!(extract_form_data_field_name(&attrs), None);
    }

    // ─── extract_strict ─────────────────────────────────────────────────

    fn parse_struct_attrs(code: &str) -> Vec<syn::Attribute> {
        let input: syn::DeriveInput = syn::parse_str(code).unwrap();
        input.attrs
    }

    #[test]
    fn test_extract_strict_present() {
        let attrs = parse_struct_attrs("#[try_from_multipart(strict)] struct T { }");
        assert!(extract_strict(&attrs));
    }

    #[test]
    fn test_extract_strict_absent() {
        let attrs = parse_struct_attrs("struct T { }");
        assert!(!extract_strict(&attrs));
    }

    #[test]
    fn test_extract_strict_other_attr() {
        let attrs =
            parse_struct_attrs("#[try_from_multipart(rename_all = \"camelCase\")] struct T { }");
        assert!(!extract_strict(&attrs));
    }

    // ─── extract_form_data_default ──────────────────────────────────────

    #[test]
    fn test_extract_form_data_default_present() {
        let attrs = parse_attrs("#[form_data(default)] pub x: i32");
        assert!(extract_form_data_default(&attrs));
    }

    #[test]
    fn test_extract_form_data_default_absent() {
        let attrs = parse_attrs("pub x: i32");
        assert!(!extract_form_data_default(&attrs));
    }

    #[test]
    fn test_extract_form_data_default_other_form_data() {
        let attrs = parse_attrs(r#"#[form_data(limit = "100")] pub x: i32"#);
        assert!(!extract_form_data_default(&attrs));
    }

    // ─── extract_struct_default ─────────────────────────────────────────

    #[test]
    fn test_extract_struct_default_present() {
        let attrs = parse_struct_attrs("#[serde(default)] struct T { }");
        assert!(extract_struct_default(&attrs));
    }

    #[test]
    fn test_extract_struct_default_absent() {
        let attrs = parse_struct_attrs("struct T { }");
        assert!(!extract_struct_default(&attrs));
    }

    // ─── resolve_default_kind ───────────────────────────────────────────

    #[test]
    fn test_resolve_default_kind_none() {
        let attrs = parse_attrs("pub x: i32");
        assert!(matches!(
            resolve_default_kind(&attrs, false),
            DefaultKind::None
        ));
    }

    #[test]
    fn test_resolve_default_kind_serde_default() {
        let attrs = parse_attrs("#[serde(default)] pub x: i32");
        assert!(matches!(
            resolve_default_kind(&attrs, false),
            DefaultKind::Trait
        ));
    }

    #[test]
    fn test_resolve_default_kind_serde_default_fn() {
        let attrs = parse_attrs(r#"#[serde(default = "my_fn")] pub x: i32"#);
        assert!(
            matches!(resolve_default_kind(&attrs, false), DefaultKind::Function(ref f) if f == "my_fn")
        );
    }

    #[test]
    fn test_resolve_default_kind_form_data_default() {
        let attrs = parse_attrs("#[form_data(default)] pub x: i32");
        assert!(matches!(
            resolve_default_kind(&attrs, false),
            DefaultKind::Trait
        ));
    }

    #[test]
    fn test_resolve_default_kind_struct_level() {
        let attrs = parse_attrs("pub x: i32");
        assert!(matches!(
            resolve_default_kind(&attrs, true),
            DefaultKind::Trait
        ));
    }

    #[test]
    fn test_resolve_default_kind_form_data_overrides_struct_default() {
        // form_data(default) takes priority, but result is the same (Trait)
        let attrs = parse_attrs("#[form_data(default)] pub x: i32");
        assert!(matches!(
            resolve_default_kind(&attrs, true),
            DefaultKind::Trait
        ));
    }

    // ─── resolve_field_name ─────────────────────────────────────────────

    #[test]
    fn test_resolve_field_name_plain() {
        let field = parse_field("pub my_field: String");
        let name = resolve_field_name(field.ident.as_ref().unwrap(), &field.attrs, None);
        assert_eq!(name, "my_field");
    }

    #[test]
    fn test_resolve_field_name_rename_all() {
        let field = parse_field("pub my_field: String");
        let name = resolve_field_name(
            field.ident.as_ref().unwrap(),
            &field.attrs,
            Some("camelCase"),
        );
        assert_eq!(name, "myField");
    }

    #[test]
    fn test_resolve_field_name_serde_rename() {
        let field = parse_field(r#"#[serde(rename = "custom")] pub my_field: String"#);
        let name = resolve_field_name(
            field.ident.as_ref().unwrap(),
            &field.attrs,
            Some("camelCase"),
        );
        assert_eq!(name, "custom"); // explicit rename beats rename_all
    }

    #[test]
    fn test_resolve_field_name_form_data_field_name() {
        let field = parse_field(
            r#"#[form_data(field_name = "override")] #[serde(rename = "serde_name")] pub my_field: String"#,
        );
        let name = resolve_field_name(
            field.ident.as_ref().unwrap(),
            &field.attrs,
            Some("camelCase"),
        );
        assert_eq!(name, "override"); // form_data field_name beats everything
    }

    // ─── extract_limit_tokens ───────────────────────────────────────────

    #[test]
    fn test_extract_limit_tokens_none() {
        let attrs = parse_attrs("pub x: String");
        let tokens = extract_limit_tokens(&attrs);
        assert_eq!(tokens.to_string(), "std :: option :: Option :: None");
    }

    #[test]
    fn test_extract_limit_tokens_with_value() {
        let attrs = parse_attrs(r#"#[form_data(limit = "100")] pub x: String"#);
        let tokens = extract_limit_tokens(&attrs);
        assert_eq!(
            tokens.to_string(),
            "std :: option :: Option :: Some (100usize)"
        );
    }

    #[test]
    fn test_extract_limit_tokens_unlimited() {
        let attrs = parse_attrs(r#"#[form_data(limit = "unlimited")] pub x: String"#);
        let tokens = extract_limit_tokens(&attrs);
        assert_eq!(tokens.to_string(), "std :: option :: Option :: None");
    }

    #[test]
    fn test_extract_limit_tokens_mib() {
        let attrs = parse_attrs(r#"#[form_data(limit = "10MiB")] pub x: String"#);
        let tokens = extract_limit_tokens(&attrs);
        let expected = 10 * 1024 * 1024;
        assert_eq!(
            tokens.to_string(),
            format!("std :: option :: Option :: Some ({expected}usize)")
        );
    }

    // ─── process_derive ─────────────────────────────────────────────────

    #[test]
    fn test_process_derive_basic_struct() {
        let input: syn::DeriveInput =
            syn::parse_str("struct MyForm { pub name: String, pub age: i32 }").unwrap();
        let tokens = process_derive(&input);
        let code = tokens.to_string();
        assert!(
            code.contains("TryFromMultipartWithState"),
            "should generate trait impl"
        );
        assert!(code.contains("MyForm"), "should reference the struct name");
        assert!(code.contains("\"name\""), "should reference field name");
        assert!(code.contains("\"age\""), "should reference field name");
    }

    #[test]
    fn test_process_derive_with_option_field() {
        let input: syn::DeriveInput =
            syn::parse_str("struct MyForm { pub name: String, pub bio: Option<String> }").unwrap();
        let tokens = process_derive(&input);
        let code = tokens.to_string();
        assert!(code.contains("TryFromMultipartWithState"));
        // Option fields get initialized to None, no MissingField check
        assert!(code.contains("Option :: None"));
    }

    #[test]
    fn test_process_derive_with_vec_field() {
        let input: syn::DeriveInput =
            syn::parse_str("struct MyForm { pub name: String, pub tags: Vec<String> }").unwrap();
        let tokens = process_derive(&input);
        let code = tokens.to_string();
        assert!(
            code.contains("Vec :: new"),
            "Vec fields should be initialized with Vec::new()"
        );
        assert!(code.contains("push"), "Vec fields should use push()");
    }

    #[test]
    fn test_process_derive_strict_mode() {
        let input: syn::DeriveInput =
            syn::parse_str("#[try_from_multipart(strict)] struct MyForm { pub name: String }")
                .unwrap();
        let tokens = process_derive(&input);
        let code = tokens.to_string();
        assert!(
            code.contains("DuplicateField"),
            "strict mode should check for duplicates"
        );
        assert!(
            code.contains("UnknownField"),
            "strict mode should reject unknown fields"
        );
        assert!(
            code.contains("NamelessField"),
            "strict mode should reject nameless fields"
        );
    }

    #[test]
    fn test_process_derive_with_rename_all() {
        let input: syn::DeriveInput = syn::parse_str(
            r#"#[serde(rename_all = "camelCase")] struct MyForm { pub user_name: String }"#,
        )
        .unwrap();
        let tokens = process_derive(&input);
        let code = tokens.to_string();
        assert!(
            code.contains("\"userName\""),
            "rename_all should convert to camelCase"
        );
    }

    #[test]
    fn test_process_derive_with_serde_default() {
        let input: syn::DeriveInput =
            syn::parse_str("#[serde(default)] struct MyForm { pub count: i32 }").unwrap();
        let tokens = process_derive(&input);
        let code = tokens.to_string();
        assert!(
            code.contains("unwrap_or_default"),
            "struct-level default should use unwrap_or_default"
        );
    }

    #[test]
    fn test_process_derive_with_field_default_fn() {
        let input: syn::DeriveInput =
            syn::parse_str(r#"struct MyForm { #[serde(default = "my_default")] pub val: String }"#)
                .unwrap();
        let tokens = process_derive(&input);
        let code = tokens.to_string();
        assert!(
            code.contains("unwrap_or_else"),
            "field default fn should use unwrap_or_else"
        );
        assert!(
            code.contains("my_default"),
            "should reference the default function"
        );
    }

    #[test]
    fn test_process_derive_non_struct_errors() {
        let input: syn::DeriveInput = syn::parse_str("enum Foo { A, B }").unwrap();
        let tokens = process_derive(&input);
        let code = tokens.to_string();
        assert!(
            code.contains("compile_error"),
            "enums should produce compile error"
        );
    }

    #[test]
    fn test_process_derive_tuple_struct_errors() {
        let input: syn::DeriveInput = syn::parse_str("struct Foo(String, i32);").unwrap();
        let tokens = process_derive(&input);
        let code = tokens.to_string();
        assert!(
            code.contains("compile_error"),
            "tuple structs should produce compile error"
        );
    }

    #[test]
    fn test_process_derive_form_data_field_name() {
        let input: syn::DeriveInput = syn::parse_str(
            r#"struct MyForm { #[form_data(field_name = "custom")] pub data: String }"#,
        )
        .unwrap();
        let tokens = process_derive(&input);
        let code = tokens.to_string();
        assert!(
            code.contains("\"custom\""),
            "form_data field_name should be used"
        );
    }

    #[test]
    fn test_process_derive_form_data_default() {
        let input: syn::DeriveInput =
            syn::parse_str("struct MyForm { #[form_data(default)] pub count: i32 }").unwrap();
        let tokens = process_derive(&input);
        let code = tokens.to_string();
        assert!(
            code.contains("unwrap_or_default"),
            "form_data(default) should use unwrap_or_default"
        );
    }

    #[test]
    fn test_process_derive_non_strict_no_duplicate_check() {
        let input: syn::DeriveInput = syn::parse_str("struct MyForm { pub name: String }").unwrap();
        let tokens = process_derive(&input);
        let code = tokens.to_string();
        assert!(
            !code.contains("DuplicateField"),
            "non-strict should not check for duplicates"
        );
        assert!(
            !code.contains("UnknownField"),
            "non-strict should not check for unknown fields"
        );
    }

    // ─── process_fields direct tests ────────────────────────────────────
    //
    // Exercise process_fields directly to ensure quote! token construction
    // for each branch (parse_value, strict assignment, field matching) is
    // fully traced by the coverage tool.

    fn parse_fields_from(code: &str) -> syn::DeriveInput {
        syn::parse_str(code).unwrap()
    }

    fn get_named_fields(
        input: &syn::DeriveInput,
    ) -> &syn::punctuated::Punctuated<syn::Field, syn::token::Comma> {
        match &input.data {
            syn::Data::Struct(s) => match &s.fields {
                Fields::Named(n) => &n.named,
                _ => panic!("expected named fields"),
            },
            _ => panic!("expected struct"),
        }
    }

    #[test]
    fn test_process_fields_required_field_generates_parse_value() {
        let input = parse_fields_from("struct T { pub name: String }");
        let fields = get_named_fields(&input);
        let cg = process_fields(fields.iter(), None, false, false);

        // parse_value is interpolated into each assignment
        let assignment_code = cg
            .assignments
            .iter()
            .map(ToString::to_string)
            .collect::<Vec<_>>()
            .join(" ");
        assert!(
            assignment_code.contains("TryFromFieldWithState"),
            "parse_value should contain turbofish call"
        );
        assert!(
            assignment_code.contains("try_from_field_with_state"),
            "should call try_from_field_with_state"
        );
        assert!(
            assignment_code.contains("\"name\""),
            "should match on field name"
        );

        // post_loop should have MissingField check for required fields
        let post_code = cg
            .post_loop
            .iter()
            .map(ToString::to_string)
            .collect::<Vec<_>>()
            .join(" ");
        assert!(
            post_code.contains("MissingField"),
            "required field should have MissingField check"
        );
    }

    #[test]
    fn test_process_fields_strict_required_field_generates_duplicate_check() {
        let input = parse_fields_from("struct T { pub name: String, pub age: i32 }");
        let fields = get_named_fields(&input);
        let cg = process_fields(fields.iter(), None, true, false);

        // strict mode: assignments should contain is_none + DuplicateField check
        let assignment_code = cg
            .assignments
            .iter()
            .map(ToString::to_string)
            .collect::<Vec<_>>()
            .join(" ");
        assert!(
            assignment_code.contains("is_none"),
            "strict assignment should check is_none"
        );
        assert!(
            assignment_code.contains("DuplicateField"),
            "strict assignment should have DuplicateField"
        );
        assert!(
            assignment_code.contains("\"name\""),
            "should match name field"
        );
        assert!(
            assignment_code.contains("\"age\""),
            "should match age field"
        );

        // Both fields should have parse_value with turbofish
        assert!(
            assignment_code.contains("TryFromFieldWithState"),
            "should contain turbofish"
        );
    }

    #[test]
    fn test_process_fields_vec_field_generates_push() {
        let input = parse_fields_from("struct T { pub tags: Vec<String> }");
        let fields = get_named_fields(&input);
        let cg = process_fields(fields.iter(), None, false, false);

        let decl_code = cg
            .declarations
            .iter()
            .map(ToString::to_string)
            .collect::<Vec<_>>()
            .join(" ");
        assert!(
            decl_code.contains("Vec :: new"),
            "Vec field should initialize with Vec::new()"
        );

        let assignment_code = cg
            .assignments
            .iter()
            .map(ToString::to_string)
            .collect::<Vec<_>>()
            .join(" ");
        assert!(
            assignment_code.contains("push"),
            "Vec field assignment should use push"
        );

        // Vec fields should NOT have post_loop (no MissingField check)
        assert!(
            cg.post_loop.is_empty(),
            "Vec fields should not have post-loop checks"
        );
    }

    #[test]
    fn test_process_fields_option_field_no_missing_check() {
        let input = parse_fields_from("struct T { pub bio: Option<String> }");
        let fields = get_named_fields(&input);
        let cg = process_fields(fields.iter(), None, false, false);

        let decl_code = cg
            .declarations
            .iter()
            .map(ToString::to_string)
            .collect::<Vec<_>>()
            .join(" ");
        assert!(
            decl_code.contains("Option :: None"),
            "Option field should initialize to None"
        );

        // Option fields should NOT have post_loop
        assert!(
            cg.post_loop.is_empty(),
            "Option fields should not have post-loop checks"
        );
    }

    #[test]
    fn test_process_fields_strict_vec_field_uses_push_not_duplicate() {
        let input = parse_fields_from("struct T { pub tags: Vec<String> }");
        let fields = get_named_fields(&input);
        let cg = process_fields(fields.iter(), None, true, false);

        // Even in strict mode, Vec fields use push (not duplicate check)
        let assignment_code = cg
            .assignments
            .iter()
            .map(ToString::to_string)
            .collect::<Vec<_>>()
            .join(" ");
        assert!(
            assignment_code.contains("push"),
            "Vec in strict mode should still use push"
        );
        assert!(
            !assignment_code.contains("DuplicateField"),
            "Vec should not have duplicate check"
        );
    }

    #[test]
    fn test_process_fields_mixed_types() {
        let input = parse_fields_from(
            "struct T { pub name: String, pub tags: Vec<String>, pub bio: Option<String> }",
        );
        let fields = get_named_fields(&input);
        let cg = process_fields(fields.iter(), None, false, false);

        assert_eq!(cg.idents.len(), 3, "should have 3 fields");
        assert_eq!(cg.declarations.len(), 3, "should have 3 declarations");
        assert_eq!(cg.assignments.len(), 3, "should have 3 assignments");
        // Only 'name' is required (not Option, not Vec), so 1 post_loop
        assert_eq!(
            cg.post_loop.len(),
            1,
            "only required field should have post-loop"
        );
    }
}