ontogen-ts 0.1.4

Rust AST → TypeScript emitter for ontogen's long-tail type bindings
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
//! Serde-attribute extraction on `syn::Attribute` lists.
//!
//! Phase-1 supports the rename family (`rename`, `rename_all`,
//! `rename_all_fields`, `skip`) plus `default` at either scope (which maps
//! to a TS-optional `?` — on a field for that field, on a struct for every
//! field) and field-level
//! `flatten` (which maps to a TS intersection member — see
//! [`crate::emit::emit_struct_named`]), and rejects the remaining
//! shape-changing attrs (`tag`, `content`, `untagged`) plus split-rename
//! (`rename(serialize = "...", deserialize = "...")`) with an
//! [`EmitError::UnsupportedSerdeAttr`] carrying a hint at the symmetric form
//! or `#[ontogen::ts_opaque]`. Other serde attrs that don't change TS shape
//! (`borrow`, `bound`, `with`, `serialize_with`, etc.) are silently ignored.
//!
//! Each extractor handles an attribute at the level where serde itself
//! gives it meaning, and rejects it elsewhere. `tag`/`content`/`untagged`
//! are container attrs, so the field extractor rejects them; `flatten` is a
//! field attr, so the container and variant extractors reject it. (An
//! earlier revision listed `flatten` alongside the container attrs and
//! consulted the list only at container level, where serde forbids
//! `flatten` outright — so field-level `flatten` was silently ignored and
//! emitted TS that disagreed with the wire.)
//!
//! The same care applies to the rename family, where serde overloads one
//! spelling across two axes. On an enum, `rename_all` renames the
//! *variants*; `rename_all_fields` renames the fields inside every struct
//! variant; and `rename_all` on an individual *variant* renames that
//! variant's fields. They are kept in three separate slots
//! ([`ContainerAttrs::rename_all`], [`ContainerAttrs::rename_all_fields`],
//! [`VariantAttrs::rename_all`]) precisely so the emitter cannot apply one
//! where serde applies another.
//!
//! Parsing uses [`syn::Attribute::parse_nested_meta`] — the same primitive
//! `serde_derive`'s own parser uses — so the exact syntax we accept matches
//! what serde itself accepts.

use crate::types::{EmitError, RenameAll, TypePath};

/// Attributes on a container (struct or enum).
#[derive(Debug, Clone, Default)]
pub(crate) struct ContainerAttrs {
    /// `#[serde(rename_all = "...")]`.
    pub rename_all: Option<RenameAll>,
    /// `#[serde(rename = "...")]` on the container itself — overrides the
    /// container's TS name. Phase-1 emits structs/enums under their Rust
    /// ident; this field is parsed so future PRs can act on it.
    pub rename: Option<String>,
    /// `#[serde(rename_all_fields = "...")]` (serde 1.0.181+). Enums only:
    /// it renames the *fields of every struct variant*, which is a
    /// different axis from [`Self::rename_all`] (which on an enum renames
    /// the variants themselves). Kept separate so the emitter can't confuse
    /// the two.
    pub rename_all_fields: Option<RenameAll>,
    /// `#[serde(default)]` (or `default = "path::to::fn"`) on a struct. Any
    /// field absent from the input is taken from the struct's `Default`, so
    /// *every* field is optional on the wire and the emitter renders them
    /// all as `field?: T`.
    ///
    /// Serde only accepts this on a struct with named fields; on an enum it
    /// is a compile error, so [`crate::emit::emit_enum_named`] ignores it.
    pub default: bool,
}

/// Attributes on a struct field.
#[derive(Debug, Clone, Default)]
pub(crate) struct FieldAttrs {
    /// `#[serde(rename = "...")]` on the field.
    pub rename: Option<String>,
    /// `#[serde(skip)]` (or `skip_serializing` / `skip_deserializing` — any of
    /// the three drops the field from TS emission since we can't represent a
    /// field that's serialized but not deserialized as a single TS type).
    pub skip: bool,
    /// `#[serde(default)]` or `#[serde(default = "path::to::fn")]`. The
    /// deserializer substitutes a default when the field is absent, so the
    /// wire contract treats the field as optional — the emitter renders it as
    /// a TS-optional `field?: T`.
    pub default: bool,
    /// `#[serde(flatten)]`. The field's own name never reaches the wire —
    /// its type's keys are spliced into the parent object — so the emitter
    /// renders it as a TS intersection member rather than a property.
    pub flatten: bool,
}

/// Attributes on an enum variant.
#[derive(Debug, Clone, Default)]
pub(crate) struct VariantAttrs {
    /// `#[serde(rename = "...")]` on the variant.
    pub rename: Option<String>,
    /// `#[serde(skip)]`.
    pub skip: bool,
    /// `#[serde(rename_all = "...")]` on the variant. Renames *this
    /// variant's* struct fields — it does not touch the variant's own wire
    /// name, which comes from the enum's `rename_all` and this variant's
    /// `rename`. Overrides the container's `rename_all_fields`.
    pub rename_all: Option<RenameAll>,
}

impl RenameAll {
    /// Parse a serde `rename_all` literal (the string after `=`) into a
    /// [`RenameAll`] variant. Returns `None` if the literal isn't one of
    /// serde's eight recognized modes.
    pub(crate) fn from_serde_str(s: &str) -> Option<Self> {
        Some(match s {
            "lowercase" => Self::Lowercase,
            "UPPERCASE" => Self::Uppercase,
            "PascalCase" => Self::PascalCase,
            "camelCase" => Self::CamelCase,
            "snake_case" => Self::SnakeCase,
            "SCREAMING_SNAKE_CASE" => Self::ScreamingSnakeCase,
            "kebab-case" => Self::KebabCase,
            "SCREAMING-KEBAB-CASE" => Self::ScreamingKebabCase,
            _ => return None,
        })
    }
}

/// Container-level serde attrs that ontogen-ts rejects outright as
/// "shape-changing serde attributes" — these alter the JSON wire shape in
/// ways that need a dedicated emission path (phase 2 / OF-015 phase 2).
///
/// `flatten` is deliberately NOT in this list: it is a *field* attribute
/// with its own [`MetaKind::Flatten`] classification and a real emission
/// path (a TS intersection member). Anything listed here is rejected at
/// every level — all three are container attrs, so an occurrence on a field
/// or variant is a malformed input serde itself would refuse.
const REJECTED_SHAPE_ATTRS: &[&str] = &["tag", "content", "untagged"];

/// Shared tail for the "shape-changing container attr" rejection message.
const REJECTED_SHAPE_HINT: &str = "shape-changing attrs (tag/content/untagged) are phase 2 work; use \
                                   #[ontogen::ts_opaque(target = \"...\")] if a custom TS rendering is needed";

/// Ontogen-specific attributes on a type definition. Both attrs are
/// no-ops at Rust compile time (the proc-macro implementations in
/// `ontogen-macros` pass the annotated item through unchanged); ontogen-ts
/// reads them via this extractor during scanning.
#[derive(Debug, Clone, Default)]
pub(crate) struct OntogenAttrs {
    /// `#[ts_opaque(target = "...")]` — emitter treats the type as terminal
    /// and emits `target` verbatim at every reference site.
    pub ts_opaque: Option<String>,
    /// `#[ts_name = "..."]` — overrides the TS name emitted for the type.
    /// JSON wire is unaffected.
    pub ts_name: Option<String>,
}

/// Extract `#[ts_opaque(target = "...")]` and `#[ts_name = "..."]` from a
/// `&[syn::Attribute]`. Matches on the terminal segment of the attribute
/// path so the attrs work whether imported bare, via `ontogen_macros::`,
/// or via `ontogen::` (the umbrella re-export).
pub(crate) fn extract_ontogen_attrs(
    attrs: &[syn::Attribute],
    referenced_by: &TypePath,
) -> Result<OntogenAttrs, EmitError> {
    let mut out = OntogenAttrs::default();
    for attr in attrs {
        let terminal = match attr.path().segments.last() {
            Some(seg) => seg.ident.to_string(),
            None => continue,
        };
        match terminal.as_str() {
            "ts_opaque" => {
                // Shape: `#[ts_opaque(target = "literal")]`. The macro
                // validates this at Rust compile time, so we expect a
                // well-formed input — but parse defensively.
                let mut target: Option<String> = None;
                attr.parse_nested_meta(|meta| {
                    if meta.path.is_ident("target") {
                        let value = meta.value()?;
                        let lit: syn::LitStr = value.parse()?;
                        target = Some(lit.value());
                        Ok(())
                    } else {
                        Err(meta.error("ts_opaque expects `target = \"...\"`"))
                    }
                })
                .map_err(|err| EmitError::UnsupportedSerdeAttr {
                    type_path: referenced_by.clone(),
                    attr: format!("could not parse #[ts_opaque(...)]: {err}"),
                })?;
                out.ts_opaque = target;
            }
            "ts_name" => {
                // Shape: `#[ts_name = "literal"]` (bare string literal arg).
                let value = match &attr.meta {
                    syn::Meta::NameValue(nv) => &nv.value,
                    _ => {
                        return Err(EmitError::UnsupportedSerdeAttr {
                            type_path: referenced_by.clone(),
                            attr: "#[ts_name = \"...\"] expects the `= \"literal\"` form".to_string(),
                        });
                    }
                };
                let lit = match value {
                    syn::Expr::Lit(expr_lit) => match &expr_lit.lit {
                        syn::Lit::Str(s) => s.value(),
                        _ => {
                            return Err(EmitError::UnsupportedSerdeAttr {
                                type_path: referenced_by.clone(),
                                attr: "#[ts_name = ...] value must be a string literal".to_string(),
                            });
                        }
                    },
                    _ => {
                        return Err(EmitError::UnsupportedSerdeAttr {
                            type_path: referenced_by.clone(),
                            attr: "#[ts_name = ...] value must be a string literal".to_string(),
                        });
                    }
                };
                out.ts_name = Some(lit);
            }
            _ => {}
        }
    }
    Ok(out)
}

/// Parse a `rename_all`-family literal into a [`RenameAll`], naming the
/// offending attribute in the error so `rename_all` and `rename_all_fields`
/// are distinguishable in a build log.
fn parse_rename_all(value: &str, attr_name: &str, referenced_by: &TypePath) -> Result<RenameAll, EmitError> {
    RenameAll::from_serde_str(value).ok_or_else(|| EmitError::UnsupportedSerdeAttr {
        type_path: referenced_by.clone(),
        attr: format!("{attr_name} = \"{value}\" (not one of serde's eight recognized modes)"),
    })
}

/// Extract container-level serde attributes (struct or enum).
pub(crate) fn extract_container_attrs(
    attrs: &[syn::Attribute],
    referenced_by: &TypePath,
) -> Result<ContainerAttrs, EmitError> {
    let mut out = ContainerAttrs::default();
    for attr in attrs {
        if !attr.path().is_ident("serde") {
            continue;
        }
        walk_serde(attr, |meta_kind| {
            match meta_kind {
                MetaKind::RenameLit(value) => {
                    out.rename = Some(value);
                    Ok(())
                }
                MetaKind::RenameAllLit(value) => {
                    out.rename_all = Some(parse_rename_all(&value, "rename_all", referenced_by)?);
                    Ok(())
                }
                MetaKind::RenameAllFieldsLit(value) => {
                    out.rename_all_fields = Some(parse_rename_all(&value, "rename_all_fields", referenced_by)?);
                    Ok(())
                }
                MetaKind::SplitRename | MetaKind::SplitRenameAll => Err(EmitError::UnsupportedSerdeAttr {
                    type_path: referenced_by.clone(),
                    attr: "split-rename (rename(serialize = \"...\", deserialize = \"...\")) is not supported in \
                           phase 1 — use the symmetric form #[serde(rename = \"...\")] or \
                           #[ontogen::ts_opaque(target = \"...\")] if the serde asymmetry must be preserved for \
                           non-ontogen-ts consumers"
                        .to_string(),
                }),
                MetaKind::RejectedShape(name) => Err(EmitError::UnsupportedSerdeAttr {
                    type_path: referenced_by.clone(),
                    attr: format!("serde({name}) — {REJECTED_SHAPE_HINT}"),
                }),
                // serde only accepts `flatten` on a field. Seeing it here
                // means the source wouldn't compile; say so rather than
                // ignoring it.
                MetaKind::Flatten => Err(EmitError::UnsupportedSerdeAttr {
                    type_path: referenced_by.clone(),
                    attr: "serde(flatten) is a field attribute — serde does not accept it on a struct or enum \
                           declaration"
                        .to_string(),
                }),
                MetaKind::Skip => Ok(()), // ignore at container level
                // Container-level `#[serde(default)]` fills every absent field
                // from the struct's `Default`, so the whole body is optional
                // on the wire. Record it; `emit_struct_named` marks each field
                // TS-optional.
                MetaKind::Default => {
                    out.default = true;
                    Ok(())
                }
                MetaKind::Unknown => Ok(()),
            }
        })?;
    }
    Ok(out)
}

/// Extract field-level serde attributes.
pub(crate) fn extract_field_attrs(attrs: &[syn::Attribute], referenced_by: &TypePath) -> Result<FieldAttrs, EmitError> {
    let mut out = FieldAttrs::default();
    for attr in attrs {
        if !attr.path().is_ident("serde") {
            continue;
        }
        walk_serde(attr, |meta_kind| {
            match meta_kind {
                MetaKind::RenameLit(value) => {
                    out.rename = Some(value);
                    Ok(())
                }
                // Neither is meaningful on a field: `rename_all` applies to a
                // container's members, `rename_all_fields` to an enum's
                // struct-variant fields.
                MetaKind::RenameAllLit(_) | MetaKind::RenameAllFieldsLit(_) => Ok(()),
                MetaKind::Skip => {
                    out.skip = true;
                    Ok(())
                }
                MetaKind::Default => {
                    out.default = true;
                    Ok(())
                }
                MetaKind::Flatten => {
                    out.flatten = true;
                    Ok(())
                }
                MetaKind::SplitRename => Err(EmitError::UnsupportedSerdeAttr {
                    type_path: referenced_by.clone(),
                    attr: "split-rename (rename(serialize = \"...\", deserialize = \"...\")) on a field is not \
                           supported in phase 1 — use the symmetric form #[serde(rename = \"...\")] or \
                           #[ontogen::ts_opaque(target = \"...\")] on the parent type"
                        .to_string(),
                }),
                // tag/content/untagged are container attrs; serde rejects
                // them on a field, so reaching this arm means the input is
                // malformed. Surface it rather than swallowing it.
                MetaKind::RejectedShape(name) => Err(EmitError::UnsupportedSerdeAttr {
                    type_path: referenced_by.clone(),
                    attr: format!("serde({name}) on a field — {REJECTED_SHAPE_HINT}"),
                }),
                MetaKind::SplitRenameAll | MetaKind::Unknown => Ok(()),
            }
        })?;
    }
    Ok(out)
}

/// Extract variant-level serde attributes.
pub(crate) fn extract_variant_attrs(
    attrs: &[syn::Attribute],
    referenced_by: &TypePath,
) -> Result<VariantAttrs, EmitError> {
    let mut out = VariantAttrs::default();
    for attr in attrs {
        if !attr.path().is_ident("serde") {
            continue;
        }
        walk_serde(attr, |meta_kind| match meta_kind {
            MetaKind::RenameLit(value) => {
                out.rename = Some(value);
                Ok(())
            }
            MetaKind::Skip => {
                out.skip = true;
                Ok(())
            }
            MetaKind::SplitRename => Err(EmitError::UnsupportedSerdeAttr {
                type_path: referenced_by.clone(),
                attr: "split-rename on a variant is not supported in phase 1 — use the symmetric form \
                           #[serde(rename = \"...\")]"
                    .to_string(),
            }),
            // `#[serde(untagged)]` is legal on an individual variant (serde
            // 1.0.181+) and changes that variant's wire shape; `tag`/`content`
            // are container-only. Either way we have no faithful rendering,
            // so reject rather than emit the externally-tagged default.
            MetaKind::RejectedShape(name) => Err(EmitError::UnsupportedSerdeAttr {
                type_path: referenced_by.clone(),
                attr: format!("serde({name}) on a variant — {REJECTED_SHAPE_HINT}"),
            }),
            // serde only accepts `flatten` on a field.
            MetaKind::Flatten => Err(EmitError::UnsupportedSerdeAttr {
                type_path: referenced_by.clone(),
                attr: "serde(flatten) is a field attribute — serde does not accept it on an enum variant".to_string(),
            }),
            // On a variant, `rename_all` governs THIS variant's struct
            // fields — not the variant's own wire name. Capture it so the
            // emitter can apply it where serde does.
            MetaKind::RenameAllLit(value) => {
                out.rename_all = Some(parse_rename_all(&value, "rename_all", referenced_by)?);
                Ok(())
            }
            // `rename_all_fields` is an enum-container attr; serde doesn't
            // accept it on a variant.
            MetaKind::RenameAllFieldsLit(_) | MetaKind::SplitRenameAll | MetaKind::Default | MetaKind::Unknown => {
                Ok(())
            }
        })?;
    }
    Ok(out)
}

/// Classified shape of a single nested serde meta item.
enum MetaKind {
    /// `rename = "wireName"` — symmetric.
    RenameLit(String),
    /// `rename_all = "camelCase"` — symmetric.
    RenameAllLit(String),
    /// `rename_all_fields = "camelCase"` — symmetric. Enum containers only.
    RenameAllFieldsLit(String),
    /// `rename(serialize = "...", deserialize = "...")` — rejected.
    SplitRename,
    /// `rename_all(serialize = "...", deserialize = "...")` — rejected.
    SplitRenameAll,
    /// `tag`, `content`, `untagged` — rejected at every level.
    RejectedShape(String),
    /// `flatten` — supported on a field (TS intersection member), rejected
    /// on a container or variant where serde itself wouldn't accept it.
    Flatten,
    /// `skip`, `skip_serializing`, `skip_deserializing` — fold all three.
    Skip,
    /// `default` or `default = "path::to::fn"` — field is optional on the wire.
    Default,
    /// Anything we don't recognize is silently ignored.
    Unknown,
}

/// Helper for the outer walker: when an unknown / split-form inner meta has
/// a `= "lit"` value, consume the literal so the outer parser keeps going.
/// Used as the callback to `meta.parse_nested_meta(...)` when the outer code
/// doesn't care about the inner contents.
fn consume_inner_value(inner: syn::meta::ParseNestedMeta<'_>) -> syn::Result<()> {
    if let Ok(value) = inner.value() {
        let _: syn::Lit = value.parse()?;
    }
    Ok(())
}

/// Walk a `#[serde(...)]` attribute and call `f` on each classified nested
/// meta. Each invocation of `f` can return `Err(EmitError)` to short-circuit.
fn walk_serde<F>(attr: &syn::Attribute, mut f: F) -> Result<(), EmitError>
where
    F: FnMut(MetaKind) -> Result<(), EmitError>,
{
    // We collect both classification + any classifier-level EmitError, then
    // dispatch outside the parse_nested_meta closure (its return type is
    // syn::Result, not Result<_, EmitError>).
    let mut callbacks: Vec<MetaKind> = Vec::new();
    let parse_result = attr.parse_nested_meta(|meta| {
        let ident = match meta.path.get_ident() {
            Some(id) => id.to_string(),
            None => {
                callbacks.push(MetaKind::Unknown);
                return Ok(());
            }
        };
        match ident.as_str() {
            "rename" => {
                // Two shapes: `rename = "lit"` (symmetric) or `rename(...)`
                // (split). `meta.value()` returns Ok iff the next token is
                // `=`; an `Err` here means we're looking at the list form.
                match meta.value() {
                    Ok(value) => {
                        let lit: syn::LitStr = value.parse().map_err(|_| meta.error("expected string literal"))?;
                        callbacks.push(MetaKind::RenameLit(lit.value()));
                    }
                    Err(_) => {
                        // List form — split-rename. Consume the parens AND
                        // each inner `serialize = "..."` / `deserialize = "..."`
                        // so the outer parser doesn't choke. We don't care
                        // about the contents.
                        meta.parse_nested_meta(consume_inner_value)?;
                        callbacks.push(MetaKind::SplitRename);
                    }
                }
                Ok(())
            }
            // Same two shapes as `rename`, and both attrs share the
            // split-form rejection — but they target different things, so
            // they classify separately. `rename_all` renames a container's
            // members; `rename_all_fields` renames the fields inside an
            // enum's struct variants.
            "rename_all" | "rename_all_fields" => {
                let is_fields = ident == "rename_all_fields";
                match meta.value() {
                    Ok(value) => {
                        let lit: syn::LitStr = value.parse().map_err(|_| meta.error("expected string literal"))?;
                        callbacks.push(if is_fields {
                            MetaKind::RenameAllFieldsLit(lit.value())
                        } else {
                            MetaKind::RenameAllLit(lit.value())
                        });
                    }
                    Err(_) => {
                        meta.parse_nested_meta(consume_inner_value)?;
                        callbacks.push(MetaKind::SplitRenameAll);
                    }
                }
                Ok(())
            }
            "skip" | "skip_serializing" | "skip_deserializing" => {
                callbacks.push(MetaKind::Skip);
                Ok(())
            }
            "default" => {
                // Two shapes: bare `default` (no value) or the path form
                // `default = "module::fn"`. Both mean the same thing for TS
                // emission — the field may be absent on the wire — so consume
                // the value if present and classify both as `Default`.
                if let Ok(value) = meta.value() {
                    let _: syn::LitStr = value.parse().map_err(|_| meta.error("expected string literal"))?;
                }
                callbacks.push(MetaKind::Default);
                Ok(())
            }
            "flatten" => {
                // Serde's `flatten` is a bare word; be tolerant of a value
                // anyway so a malformed attr doesn't desync the parser.
                if let Ok(value) = meta.value() {
                    let _: syn::Lit = value.parse().map_err(|_| meta.error("expected literal"))?;
                }
                callbacks.push(MetaKind::Flatten);
                Ok(())
            }
            other if REJECTED_SHAPE_ATTRS.contains(&other) => {
                // These attrs may carry values; consume them if present so the
                // parser doesn't bail out.
                if let Ok(value) = meta.value() {
                    let _: syn::LitStr = value.parse().map_err(|_| meta.error("expected string literal"))?;
                }
                callbacks.push(MetaKind::RejectedShape(other.to_string()));
                Ok(())
            }
            _ => {
                // Unknown attr — consume any value or nested list form so the
                // outer parser stays in sync.
                if let Ok(value) = meta.value() {
                    let _: syn::Lit = value.parse().map_err(|_| meta.error("expected literal"))?;
                } else {
                    let _ = meta.parse_nested_meta(consume_inner_value);
                }
                callbacks.push(MetaKind::Unknown);
                Ok(())
            }
        }
    });
    if let Err(err) = parse_result {
        // syn parse errors on serde attrs are pretty rare in practice (well-
        // formed Rust source means the attribute parsed; this branch fires
        // only when serde syntax is malformed). Bubble it up as a generic
        // EmitError so callers can show the user where the problem is.
        return Err(EmitError::UnsupportedSerdeAttr {
            type_path: TypePath::new(vec!["<unknown>".to_string()]).expect("non-empty"),
            attr: format!("could not parse #[serde(...)]: {err}"),
        });
    }
    for cb in callbacks {
        f(cb)?;
    }
    Ok(())
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::types::{EmitError, TypePath};

    fn tp(name: &str) -> TypePath {
        TypePath::new(vec![name.to_string()]).expect("non-empty")
    }

    /// Parse a struct from source and return its attrs.
    fn struct_attrs(src: &str) -> Vec<syn::Attribute> {
        let item: syn::ItemStruct = syn::parse_str(src).expect("parse struct");
        item.attrs
    }

    /// Parse an enum from source and return its attrs.
    fn enum_attrs(src: &str) -> Vec<syn::Attribute> {
        let item: syn::ItemEnum = syn::parse_str(src).expect("parse enum");
        item.attrs
    }

    /// Parse the first named field of a struct and return its attrs.
    fn first_field_attrs(src: &str) -> Vec<syn::Attribute> {
        let item: syn::ItemStruct = syn::parse_str(src).expect("parse struct");
        let syn::Fields::Named(named) = item.fields else {
            panic!("test fixture must use named fields");
        };
        named.named.into_iter().next().expect("at least one field").attrs
    }

    /// Parse the first variant of an enum and return its attrs.
    fn first_variant_attrs(src: &str) -> Vec<syn::Attribute> {
        let item: syn::ItemEnum = syn::parse_str(src).expect("parse enum");
        item.variants.into_iter().next().expect("at least one variant").attrs
    }

    // ── Container: rename_all ─────────────────────────────────────────────

    #[test]
    fn container_rename_all_camel_case() {
        let attrs = struct_attrs(
            r#"
            #[serde(rename_all = "camelCase")]
            struct Foo { a: u32 }
            "#,
        );
        let out = extract_container_attrs(&attrs, &tp("Foo")).unwrap();
        assert_eq!(out.rename_all, Some(RenameAll::CamelCase));
    }

    #[test]
    fn container_rename_all_all_eight_modes() {
        let pairs = [
            ("lowercase", RenameAll::Lowercase),
            ("UPPERCASE", RenameAll::Uppercase),
            ("PascalCase", RenameAll::PascalCase),
            ("camelCase", RenameAll::CamelCase),
            ("snake_case", RenameAll::SnakeCase),
            ("SCREAMING_SNAKE_CASE", RenameAll::ScreamingSnakeCase),
            ("kebab-case", RenameAll::KebabCase),
            ("SCREAMING-KEBAB-CASE", RenameAll::ScreamingKebabCase),
        ];
        for (src, expected) in pairs {
            let attrs = struct_attrs(&format!(r#"#[serde(rename_all = "{src}")] struct Foo {{ a: u32 }}"#));
            let out = extract_container_attrs(&attrs, &tp("Foo")).unwrap();
            assert_eq!(out.rename_all, Some(expected), "rename_all = \"{src}\"");
        }
    }

    #[test]
    fn container_rename_all_unknown_mode_rejected() {
        let attrs = struct_attrs(
            r#"
            #[serde(rename_all = "Train-Case")]
            struct Foo { a: u32 }
            "#,
        );
        let err = extract_container_attrs(&attrs, &tp("Foo")).unwrap_err();
        match err {
            EmitError::UnsupportedSerdeAttr { attr, .. } => {
                assert!(attr.contains("Train-Case"), "attr was: {attr}");
                assert!(attr.contains("recognized modes"), "attr was: {attr}");
            }
            other => panic!("expected UnsupportedSerdeAttr, got {other:?}"),
        }
    }

    #[test]
    fn container_split_rename_all_rejected() {
        let attrs = struct_attrs(
            r#"
            #[serde(rename_all(serialize = "camelCase", deserialize = "snake_case"))]
            struct Foo { a: u32 }
            "#,
        );
        let err = extract_container_attrs(&attrs, &tp("Foo")).unwrap_err();
        match err {
            EmitError::UnsupportedSerdeAttr { attr, .. } => {
                assert!(attr.contains("split-rename"), "attr was: {attr}");
            }
            other => panic!("expected UnsupportedSerdeAttr, got {other:?}"),
        }
    }

    // ── Container: tag/content/untagged/flatten rejected ──────────────────

    #[test]
    fn container_tag_rejected() {
        let attrs = enum_attrs(
            r#"
            #[serde(tag = "type")]
            enum Msg { Click, Hover }
            "#,
        );
        let err = extract_container_attrs(&attrs, &tp("Msg")).unwrap_err();
        match err {
            EmitError::UnsupportedSerdeAttr { attr, .. } => {
                assert!(attr.contains("tag"), "attr was: {attr}");
                assert!(attr.contains("phase 2"), "attr was: {attr}");
            }
            other => panic!("expected UnsupportedSerdeAttr, got {other:?}"),
        }
    }

    #[test]
    fn container_untagged_rejected() {
        let attrs = enum_attrs(
            r#"
            #[serde(untagged)]
            enum U { A(u32), B(String) }
            "#,
        );
        let err = extract_container_attrs(&attrs, &tp("U")).unwrap_err();
        assert!(matches!(err, EmitError::UnsupportedSerdeAttr { .. }));
    }

    // ── Field: rename ─────────────────────────────────────────────────────

    #[test]
    fn field_rename() {
        let attrs = first_field_attrs(
            r#"
            struct Foo {
                #[serde(rename = "wireName")]
                pub a: u32,
            }
            "#,
        );
        let out = extract_field_attrs(&attrs, &tp("Foo")).unwrap();
        assert_eq!(out.rename.as_deref(), Some("wireName"));
        assert!(!out.skip);
    }

    #[test]
    fn field_skip() {
        let attrs = first_field_attrs(
            r#"
            struct Foo {
                #[serde(skip)]
                pub a: u32,
            }
            "#,
        );
        let out = extract_field_attrs(&attrs, &tp("Foo")).unwrap();
        assert!(out.skip);
    }

    #[test]
    fn field_skip_serializing_treated_as_skip() {
        let attrs = first_field_attrs(
            r#"
            struct Foo {
                #[serde(skip_serializing)]
                pub a: u32,
            }
            "#,
        );
        let out = extract_field_attrs(&attrs, &tp("Foo")).unwrap();
        assert!(out.skip);
    }

    #[test]
    fn field_split_rename_rejected() {
        let attrs = first_field_attrs(
            r#"
            struct Foo {
                #[serde(rename(serialize = "wire_name", deserialize = "wireName"))]
                pub a: u32,
            }
            "#,
        );
        let err = extract_field_attrs(&attrs, &tp("Foo")).unwrap_err();
        match err {
            EmitError::UnsupportedSerdeAttr { attr, .. } => {
                assert!(attr.contains("split-rename"), "attr was: {attr}");
                assert!(attr.contains("on a field"), "attr was: {attr}");
            }
            other => panic!("expected UnsupportedSerdeAttr, got {other:?}"),
        }
    }

    #[test]
    fn field_no_serde_attrs_returns_default() {
        let attrs = first_field_attrs(
            r#"
            struct Foo {
                pub a: u32,
            }
            "#,
        );
        let out = extract_field_attrs(&attrs, &tp("Foo")).unwrap();
        assert!(out.rename.is_none());
        assert!(!out.skip);
    }

    #[test]
    fn field_default_bare_sets_flag() {
        // `#[serde(default)]` marks the field optional on the wire.
        let attrs = first_field_attrs(
            r#"
            struct Foo {
                #[serde(default)]
                pub a: u32,
            }
            "#,
        );
        let out = extract_field_attrs(&attrs, &tp("Foo")).unwrap();
        assert!(out.default, "bare #[serde(default)] should set the default flag");
        assert!(out.rename.is_none());
        assert!(!out.skip);
    }

    #[test]
    fn field_default_path_form_sets_flag() {
        // `#[serde(default = "path")]` means the same thing for TS emission.
        let attrs = first_field_attrs(
            r#"
            struct Foo {
                #[serde(default = "defaults::a")]
                pub a: u32,
            }
            "#,
        );
        let out = extract_field_attrs(&attrs, &tp("Foo")).unwrap();
        assert!(out.default, "path-form #[serde(default = \"...\")] should set the default flag");
    }

    #[test]
    fn field_without_default_leaves_flag_unset() {
        let attrs = first_field_attrs(
            r#"
            struct Foo {
                pub a: u32,
            }
            "#,
        );
        let out = extract_field_attrs(&attrs, &tp("Foo")).unwrap();
        assert!(!out.default);
    }

    #[test]
    fn container_default_sets_flag() {
        // Container-level `#[serde(default)]` fills every absent field from
        // the struct's `Default`, so the emitter needs to know about it —
        // it used to be dropped here, and the whole body silently emitted as
        // required.
        let attrs = struct_attrs(
            r#"
            #[serde(default)]
            struct Foo { a: u32 }
            "#,
        );
        assert!(extract_container_attrs(&attrs, &tp("Foo")).unwrap().default);
    }

    #[test]
    fn container_default_path_form_sets_flag() {
        // `#[serde(default = "path")]` on a struct means the same thing.
        let attrs = struct_attrs(
            r#"
            #[serde(default = "defaults::foo")]
            struct Foo { a: u32 }
            "#,
        );
        assert!(extract_container_attrs(&attrs, &tp("Foo")).unwrap().default);
    }

    #[test]
    fn container_without_default_leaves_flag_unset() {
        let attrs = struct_attrs(
            r#"
            #[serde(rename_all = "camelCase")]
            struct Foo { a: u32 }
            "#,
        );
        assert!(!extract_container_attrs(&attrs, &tp("Foo")).unwrap().default);
    }

    // ── rename_all vs rename_all_fields (issue #133) ──────────────────────

    #[test]
    fn container_rename_all_fields_is_its_own_axis() {
        // Both attrs can appear together and must not overwrite each other:
        // one renames the enum's variants, the other its struct-variant
        // fields.
        let attrs = enum_attrs(
            r#"
            #[serde(rename_all = "camelCase", rename_all_fields = "SCREAMING_SNAKE_CASE")]
            enum Event { ToolCall { prompt_template: String } }
            "#,
        );
        let out = extract_container_attrs(&attrs, &tp("Event")).unwrap();
        assert_eq!(out.rename_all, Some(RenameAll::CamelCase));
        assert_eq!(out.rename_all_fields, Some(RenameAll::ScreamingSnakeCase));
    }

    #[test]
    fn container_rename_all_leaves_rename_all_fields_unset() {
        let attrs = enum_attrs(
            r#"
            #[serde(rename_all = "camelCase")]
            enum Event { ToolCall { prompt_template: String } }
            "#,
        );
        let out = extract_container_attrs(&attrs, &tp("Event")).unwrap();
        assert_eq!(out.rename_all, Some(RenameAll::CamelCase));
        assert_eq!(out.rename_all_fields, None, "rename_all must not imply rename_all_fields");
    }

    #[test]
    fn container_rename_all_fields_unknown_mode_names_the_right_attr() {
        let attrs = enum_attrs(
            r#"
            #[serde(rename_all_fields = "Train-Case")]
            enum Event { ToolCall { prompt_template: String } }
            "#,
        );
        match extract_container_attrs(&attrs, &tp("Event")).unwrap_err() {
            EmitError::UnsupportedSerdeAttr { attr, .. } => {
                assert!(attr.contains("rename_all_fields"), "attr was: {attr}");
                assert!(attr.contains("Train-Case"), "attr was: {attr}");
            }
            other => panic!("expected UnsupportedSerdeAttr, got {other:?}"),
        }
    }

    #[test]
    fn variant_rename_all_is_captured() {
        // On a variant, `rename_all` targets that variant's fields. It used
        // to be dropped, so there was no way to express it.
        let attrs = first_variant_attrs(
            r#"
            enum Event {
                #[serde(rename_all = "camelCase")]
                ToolCall { prompt_template: String },
            }
            "#,
        );
        let out = extract_variant_attrs(&attrs, &tp("Event")).unwrap();
        assert_eq!(out.rename_all, Some(RenameAll::CamelCase));
        assert!(out.rename.is_none(), "rename_all must not set the variant's own wire name");
    }

    #[test]
    fn variant_rename_and_rename_all_are_independent() {
        let attrs = first_variant_attrs(
            r#"
            enum Event {
                #[serde(rename = "call", rename_all = "UPPERCASE")]
                ToolCall { prompt_template: String },
            }
            "#,
        );
        let out = extract_variant_attrs(&attrs, &tp("Event")).unwrap();
        assert_eq!(out.rename.as_deref(), Some("call"));
        assert_eq!(out.rename_all, Some(RenameAll::Uppercase));
    }

    #[test]
    fn field_rename_all_family_is_ignored() {
        // Neither attr means anything on a field.
        for src in ["rename_all = \"camelCase\"", "rename_all_fields = \"camelCase\""] {
            let attrs = first_field_attrs(&format!(
                r#"
                struct Foo {{
                    #[serde({src})]
                    pub prompt_template: String,
                }}
                "#
            ));
            let out = extract_field_attrs(&attrs, &tp("Foo")).unwrap();
            assert!(out.rename.is_none(), "src `{src}` should be inert on a field");
            assert!(!out.skip);
        }
    }

    // ── flatten: classified at the level where serde allows it ────────────

    #[test]
    fn field_flatten_sets_flag() {
        // Issue #132: `flatten` is a field attribute, so the field extractor
        // is the only place it can legally show up — and it must not be
        // swallowed there.
        let attrs = first_field_attrs(
            r#"
            struct Step {
                #[serde(flatten)]
                pub meta: StepMeta,
            }
            "#,
        );
        let out = extract_field_attrs(&attrs, &tp("Step")).unwrap();
        assert!(out.flatten, "#[serde(flatten)] should set the flatten flag");
        assert!(out.rename.is_none());
        assert!(!out.skip);
        assert!(!out.default);
    }

    #[test]
    fn field_flatten_composes_with_default() {
        // Both flags are parsed; the emitter is what rejects the pairing.
        let attrs = first_field_attrs(
            r#"
            struct Step {
                #[serde(flatten, default)]
                pub meta: StepMeta,
            }
            "#,
        );
        let out = extract_field_attrs(&attrs, &tp("Step")).unwrap();
        assert!(out.flatten);
        assert!(out.default);
    }

    #[test]
    fn field_without_flatten_leaves_flag_unset() {
        let attrs = first_field_attrs(
            r#"
            struct Step {
                pub meta: StepMeta,
            }
            "#,
        );
        assert!(!extract_field_attrs(&attrs, &tp("Step")).unwrap().flatten);
    }

    #[test]
    fn container_flatten_rejected() {
        // Serde doesn't accept `flatten` on a container at all, so say that
        // rather than silently ignoring it.
        let attrs = struct_attrs(
            r#"
            #[serde(flatten)]
            struct Foo { a: u32 }
            "#,
        );
        let err = extract_container_attrs(&attrs, &tp("Foo")).unwrap_err();
        match err {
            EmitError::UnsupportedSerdeAttr { attr, .. } => {
                assert!(attr.contains("field attribute"), "attr was: {attr}");
            }
            other => panic!("expected UnsupportedSerdeAttr, got {other:?}"),
        }
    }

    #[test]
    fn variant_flatten_rejected() {
        let attrs = first_variant_attrs(
            r#"
            enum E {
                #[serde(flatten)]
                A,
            }
            "#,
        );
        let err = extract_variant_attrs(&attrs, &tp("E")).unwrap_err();
        assert!(matches!(err, EmitError::UnsupportedSerdeAttr { .. }));
    }

    #[test]
    fn field_level_container_shape_attrs_rejected() {
        // tag/content/untagged are container attrs. Reaching the field
        // extractor means the input is malformed; don't swallow it.
        for src in ["tag = \"type\"", "content = \"c\"", "untagged"] {
            let attrs = first_field_attrs(&format!(
                r#"
                struct Foo {{
                    #[serde({src})]
                    pub a: u32,
                }}
                "#
            ));
            let err = extract_field_attrs(&attrs, &tp("Foo")).unwrap_err();
            match err {
                EmitError::UnsupportedSerdeAttr { attr, .. } => {
                    assert!(attr.contains("on a field"), "src `{src}` — attr was: {attr}");
                }
                other => panic!("expected UnsupportedSerdeAttr for `{src}`, got {other:?}"),
            }
        }
    }

    #[test]
    fn variant_level_untagged_rejected() {
        // Variant-level `#[serde(untagged)]` is legal serde (1.0.181+) and
        // changes that variant's wire shape, so the externally-tagged
        // default we'd otherwise emit would be wrong.
        let attrs = first_variant_attrs(
            r#"
            enum U {
                #[serde(untagged)]
                Other(String),
            }
            "#,
        );
        let err = extract_variant_attrs(&attrs, &tp("U")).unwrap_err();
        match err {
            EmitError::UnsupportedSerdeAttr { attr, .. } => {
                assert!(attr.contains("on a variant"), "attr was: {attr}");
            }
            other => panic!("expected UnsupportedSerdeAttr, got {other:?}"),
        }
    }

    // ── Variant: rename ───────────────────────────────────────────────────

    #[test]
    fn variant_rename() {
        let attrs = first_variant_attrs(
            r#"
            enum Color {
                #[serde(rename = "rouge")]
                Red,
            }
            "#,
        );
        let out = extract_variant_attrs(&attrs, &tp("Color")).unwrap();
        assert_eq!(out.rename.as_deref(), Some("rouge"));
    }

    #[test]
    fn variant_split_rename_rejected() {
        let attrs = first_variant_attrs(
            r#"
            enum Color {
                #[serde(rename(serialize = "Red", deserialize = "red"))]
                Red,
            }
            "#,
        );
        let err = extract_variant_attrs(&attrs, &tp("Color")).unwrap_err();
        match err {
            EmitError::UnsupportedSerdeAttr { attr, .. } => {
                assert!(attr.contains("split-rename"), "attr was: {attr}");
                assert!(attr.contains("variant"), "attr was: {attr}");
            }
            other => panic!("expected UnsupportedSerdeAttr, got {other:?}"),
        }
    }

    // ── Combined: container + field interaction (parser side only) ────────

    #[test]
    fn container_rename_and_rename_all_both_parsed() {
        let attrs = struct_attrs(
            r#"
            #[serde(rename = "FooDto", rename_all = "camelCase")]
            struct Foo { a: u32 }
            "#,
        );
        let out = extract_container_attrs(&attrs, &tp("Foo")).unwrap();
        assert_eq!(out.rename.as_deref(), Some("FooDto"));
        assert_eq!(out.rename_all, Some(RenameAll::CamelCase));
    }
}