obj-derive 1.1.1

Procedural macros (#[derive(Document)]) for the obj embedded document database.
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
//! `obj-derive` — procedural macros for `obj`.
//!
//! # ⚠️ UNSTABLE — consume via `obj-db`, not directly
//!
//! `obj-derive` is an implementation detail of `obj-db` (re-exported as
//! `obj::Document`). It is published only so `obj-db` can depend on it and
//! carries **no `SemVer` guarantee** as a standalone crate — depend on
//! `obj-db` and write `#[derive(obj::Document)]`. Only `obj-db`'s public
//! surface is frozen at 1.0; `obj-derive` is excluded from the public-api
//! freeze gate (see `docs/public-api.md`).
//!
//! This crate provides `#[derive(obj::Document)]`, which emits the
//! [`obj_core::Document`](https://docs.rs/obj/latest/obj/trait.Document.html)
//! implementation for a user struct. The derive is intentionally
//! small — it fills in the trait's associated constants
//! (`COLLECTION`, `VERSION`) from optional `#[obj(...)]` attributes
//! and emits an `indexes()` override whenever any field carries an
//! `#[obj(index ...)]` attribute.
//!
//! # Supported attributes
//!
//! Struct-level (`#[obj(...)]` directly above the `struct` keyword):
//!
//! - `version = N` (integer ≥ 0) — sets `Document::VERSION`.
//! - `collection = "name"` (non-empty string literal) — sets
//!   `Document::COLLECTION`.
//!
//! Multiple `#[obj(...)]` attributes compose; the same scalar key
//! (`version`, `collection`) declared twice is a compile error.
//!
//! Struct-level composite (one or more occurrences compose, each
//! adding one `Composite` `IndexSpec`):
//!
//! - `index_composite(fields = ("a", "b"), name = "by_a_b")` — emit a
//!   `Composite` `IndexSpec` spanning the listed fields. `name`
//!   defaults to the field names joined with `__`. The referenced
//!   fields must exist on the struct; fewer than two is a compile
//!   error.
//! - `index = ("a", "b")` — short form, equivalent to
//!   `index_composite(fields = ("a", "b"))`. Same downstream
//!   validation (≥ 2 fields, each declared on the struct). The
//!   default index name is the fields joined with `__`; there is no
//!   `name = "..."` slot on the short form — use `index_composite`
//!   when a custom name is required. Both syntaxes coexist; the
//!   short form mirrors `design.md` § Indexes verbatim.
//!
//! Field-level (`#[obj(...)]` on a struct field):
//!
//! - `index` — emit a `Standard` `IndexSpec` for this field.
//! - `index = unique` — emit a `Unique` `IndexSpec` for this field.
//! - `index = each` — emit an `Each` `IndexSpec` for this field. The
//!   field type must syntactically be `Vec<...>` — otherwise the
//!   derive errors at compile time.
//! - `name = "..."` — alongside any `index = ...`, overrides the
//!   default index name (which is the field name).
//!
//! Struct-level historical schema registry (M10 #82):
//!
//! - `history(v1 = OldType1, v2 = OldType2)` — emit a
//!   `Document::historical_schemas()` override that lifts each
//!   version into a `(version, DynamicSchema)` pair via
//!   `<OldType as ::obj::Schema>::schema()`. The keys (`v1`, `v2`,
//!   …) must be `vN` for integer `N` ≥ 1; the values are arbitrary
//!   type paths. Each named type must implement `::obj::Schema`
//!   (hand-impls are accepted; the derive auto-implements `Schema`
//!   for types that opt in via `#[obj(history(...))]` or
//!   `#[obj(schema)]`). Entries are emitted in ascending version
//!   order.
//! - `schema` — explicitly opt the current type into a derived
//!   `Schema` impl WITHOUT declaring any history. Useful when the
//!   type is referenced from a future version's `history(...)`.
//!
//! When either `history(...)` or `schema` is declared, the derive
//! emits a companion `impl ::obj::Schema` block whose `schema()`
//! body maps each field to a `DynamicSchema` variant. Scalar
//! primitives (bool, u\*, i\*, f\*, String) map directly; `Vec<T>`
//! maps to `DynamicSchema::seq(<T as Schema>::schema())`; anything
//! else delegates via `<T as ::obj::Schema>::schema()`, which fails
//! to compile if `T` lacks a `Schema` impl.
//!
//! # Serde requirements
//!
//! The derive does **NOT** emit `serde::Serialize` or
//! `serde::Deserialize` for you. Users still write
//! `#[derive(serde::Serialize, serde::Deserialize)]` on the struct
//! alongside `#[derive(obj::Document)]`.
//!
//! # Power-of-ten posture
//!
//! - **Rule 4** — every function in this crate is ≤ 60 lines.
//! - **Rule 7** — every fallible path returns `syn::Result<...>`;
//!   `unwrap`/`expect` appear only on infallible primitives.
//! - **Rule 9** — generated code is minimal and inspectable. Every
//!   emitted item is prefixed by a `// auto-generated by
//!   #[derive(Document)]` marker so `cargo expand` output is easy
//!   to spot.

#![forbid(unsafe_code)]
#![deny(missing_docs)]
#![deny(rustdoc::broken_intra_doc_links)]

use proc_macro::TokenStream;
use quote::quote;
use syn::spanned::Spanned;
use syn::{
    parse_macro_input, Attribute, Data, DataStruct, DeriveInput, Field, Fields, LitInt, LitStr,
    Type, TypePath,
};

/// Derive macro for `obj::Document`.
///
/// Emits `impl ::obj::Document for <Ident> { ... }` with sensible
/// defaults:
///
/// - `COLLECTION` defaults to the unqualified type name as a string;
///   `#[obj(collection = "explicit_name")]` overrides.
/// - `VERSION` defaults to `1`; `#[obj(version = N)]` overrides.
/// - `indexes()` is omitted (the trait default `Vec::new()` is used)
///   when the struct carries no index-related attributes; otherwise
///   the derive emits a `Vec<::obj::IndexSpec>` in field-declaration
///   order.
///
/// All emitted paths are absolute (`::obj::Document`,
/// `::obj::IndexSpec`) so the derive is hygienic against local items
/// that shadow these names.
#[proc_macro_derive(Document, attributes(obj))]
pub fn derive_document(input: TokenStream) -> TokenStream {
    let input = parse_macro_input!(input as DeriveInput);
    match emit_impl(&input) {
        Ok(ts) => ts.into(),
        Err(err) => err.to_compile_error().into(),
    }
}

/// Build the `impl ::obj::Document` block for `input`. Also emits
/// the companion `impl ::obj::Schema` and a `historical_schemas()`
/// override when the user supplied `#[obj(history(...))]`.
///
/// The `Schema` impl is emitted ONLY when at least one of these is
/// true:
///
/// - the struct carries `#[obj(history(...))]` (the user is
///   opting into schema-evolution at this site, and the current
///   type needs a self-describing schema so that *future* versions
///   can reference it via `history(vN = ThisType)`);
/// - the struct carries `#[obj(schema)]` (explicit opt-in).
///
/// Bare-derive sites do NOT emit `Schema` — a `Document` with no
/// historical versions has no need for one, and emitting the impl
/// would require every nested field type to also be `Schema`
/// (which is too aggressive an ask for types that never participate
/// in migration).
fn emit_impl(input: &DeriveInput) -> syn::Result<proc_macro2::TokenStream> {
    let attrs = parse_struct_attrs(input)?;
    // Enums get a `Schema`-only emission. A `Document` impl on an
    // enum is rejected: collections store records, not bare variants.
    // The user opts in to the Schema impl via `#[obj(schema)]` or
    // `#[obj(history(...))]`; bare `#[derive(Document)]` on an enum
    // is a compile error so the diagnostic is loud.
    if matches!(input.data, Data::Enum(_)) {
        if !attrs.emit_schema {
            return Err(syn::Error::new(
                input.span(),
                "#[derive(obj::Document)] on an enum requires `#[obj(schema)]` \
                 (or `#[obj(history(...))]`); an enum is never a Document itself",
            ));
        }
        return emit_schema_impl(input);
    }
    emit_struct_impl(input, &attrs)
}

/// Build the `impl ::obj::Document` block for a struct + emit the
/// companion `impl ::obj::Schema` when `attrs.emit_schema` is set.
fn emit_struct_impl(
    input: &DeriveInput,
    attrs: &StructAttrs,
) -> syn::Result<proc_macro2::TokenStream> {
    let ident = &input.ident;
    let collection = attrs
        .collection
        .clone()
        .unwrap_or_else(|| ident.to_string());
    let version: u32 = attrs.version.unwrap_or(1);
    let mut index_specs = collect_field_indexes(input)?;
    let composite_specs = validate_and_lift_composites(input, &attrs.composites)?;
    index_specs.extend(composite_specs);
    let indexes_body = emit_indexes_body(&index_specs);
    let schema_impl = if attrs.emit_schema {
        emit_schema_impl(input)?
    } else {
        proc_macro2::TokenStream::new()
    };
    let history_body = emit_history_body(&attrs.history);
    let out = quote! {
        // auto-generated by #[derive(Document)]
        #[automatically_derived]
        impl ::obj::Document for #ident {
            const COLLECTION: &'static str = #collection;
            const VERSION: u32 = #version;
            #indexes_body
            #history_body
        }
        #schema_impl
    };
    Ok(out)
}

/// Emit an `impl ::obj::Schema for <Ident>` block whose `schema()`
/// returns the `DynamicSchema::Map(...)` corresponding to the
/// struct's declared fields.
///
/// The mapping from Rust field type to `DynamicSchema` is the
/// syntactic table documented in `obj_core::codec::schema`:
/// scalar primitives map directly; `Vec<T>` maps to
/// `DynamicSchema::seq(<T as Schema>::schema())`; anything else is
/// treated as a `Schema`-implementing path and delegates via
/// `<T as ::obj::Schema>::schema()`.
fn emit_schema_impl(input: &DeriveInput) -> syn::Result<proc_macro2::TokenStream> {
    let ident = &input.ident;
    let body = match &input.data {
        Data::Struct(_) => emit_schema_body_struct(input)?,
        Data::Enum(data) => emit_schema_body_enum(data)?,
        Data::Union(_) => {
            return Err(syn::Error::new(
                input.span(),
                "#[derive(obj::Document)] does not support unions",
            ));
        }
    };
    Ok(quote! {
        // auto-generated by #[derive(Document)]
        #[automatically_derived]
        impl ::obj::Schema for #ident {
            fn schema() -> ::obj::DynamicSchema {
                #body
            }
        }
    })
}

/// Build the `Schema::schema()` body for a struct: a
/// `DynamicSchema::Map` over each named field's syntactic type.
fn emit_schema_body_struct(input: &DeriveInput) -> syn::Result<proc_macro2::TokenStream> {
    let fields = named_fields(input)?;
    let entries = fields
        .iter()
        .map(|f| {
            let name = named_field_name(f)?;
            let ty_schema = field_type_to_schema(&f.ty);
            Ok(quote! { (::std::string::String::from(#name), #ty_schema) })
        })
        .collect::<syn::Result<Vec<_>>>()?;
    Ok(quote! {
        ::obj::DynamicSchema::Map(::std::vec![ #( #entries ),* ])
    })
}

/// Pull the string name out of a named struct/variant field, returning
/// a `syn::Error` (never a panic) if the field has no `ident`.
///
/// `syn` only constructs `Field` values with `ident == None` inside
/// `Fields::Unnamed`. Every call site here is already guarded by a
/// `Fields::Named(_)` pattern, so the `None` branch is structurally
/// unreachable — but Power-of-Ten Rule 7 forbids panicking unwraps
/// in production paths regardless. A surfaced `syn::Error` is the
/// safe fallback if a future refactor breaks the invariant.
fn named_field_name(field: &Field) -> syn::Result<String> {
    field
        .ident
        .as_ref()
        .map(ToString::to_string)
        .ok_or_else(|| syn::Error::new(field.span(), "expected named field"))
}

/// Build the `Schema::schema()` body for an enum: a
/// `DynamicSchema::Enum` over each variant in declaration order
/// (postcard assigns discriminants by declaration order; the derive
/// matches that). Unit variants get `Null` payloads; newtype
/// variants get the inner type's schema; tuple variants get a
/// synthetic `Map` keyed by `"0"`, `"1"`, …; struct variants get a
/// `Map` keyed by the field names.
fn emit_schema_body_enum(data: &syn::DataEnum) -> syn::Result<proc_macro2::TokenStream> {
    let entries = data
        .variants
        .iter()
        .enumerate()
        .map(|(idx, v)| {
            let discriminant = u32::try_from(idx).unwrap_or(u32::MAX);
            let name = v.ident.to_string();
            let payload = variant_payload_schema(&v.fields)?;
            Ok(quote! {
                ::obj::EnumVariantSchema::new(
                    #discriminant,
                    #name,
                    #payload,
                )
            })
        })
        .collect::<syn::Result<Vec<_>>>()?;
    Ok(quote! {
        ::obj::DynamicSchema::Enum(::std::vec![ #( #entries ),* ])
    })
}

/// Map an enum variant's `Fields` shape to the token stream that
/// constructs its payload [`DynamicSchema`] at runtime.
fn variant_payload_schema(fields: &Fields) -> syn::Result<proc_macro2::TokenStream> {
    match fields {
        Fields::Unit => Ok(quote! { ::obj::DynamicSchema::Null }),
        Fields::Unnamed(unnamed) => {
            // Newtype variant `V(T)` → use `T`'s schema directly. Tuple
            // variants `V(T, U, ...)` → synthesise a Map keyed by
            // `"0"`, `"1"`, …; postcard writes the inner fields
            // positionally, same wire shape as a struct's bytes.
            let count = unnamed.unnamed.len();
            if count == 1 {
                let ty = &unnamed.unnamed[0].ty;
                Ok(field_type_to_schema(ty))
            } else {
                let entries = unnamed.unnamed.iter().enumerate().map(|(i, f)| {
                    let key = i.to_string();
                    let ty_schema = field_type_to_schema(&f.ty);
                    quote! { (::std::string::String::from(#key), #ty_schema) }
                });
                Ok(quote! {
                    ::obj::DynamicSchema::Map(::std::vec![ #( #entries ),* ])
                })
            }
        }
        Fields::Named(named) => {
            let entries = named
                .named
                .iter()
                .map(|f| {
                    let name = named_field_name(f)?;
                    let ty_schema = field_type_to_schema(&f.ty);
                    Ok(quote! { (::std::string::String::from(#name), #ty_schema) })
                })
                .collect::<syn::Result<Vec<_>>>()?;
            Ok(quote! {
                ::obj::DynamicSchema::Map(::std::vec![ #( #entries ),* ])
            })
        }
    }
}

/// Emit either a `Document::historical_schemas()` override or an
/// empty token stream (which leaves the trait default in place).
fn emit_history_body(entries: &[HistoryAttr]) -> proc_macro2::TokenStream {
    if entries.is_empty() {
        return proc_macro2::TokenStream::new();
    }
    // Pre-sort entries by version so the emitted vector is sorted
    // ascending — the codec's `decode` dispatch binary-searches and
    // debug-asserts on order.
    let mut sorted: Vec<&HistoryAttr> = entries.iter().collect();
    sorted.sort_by_key(|h| h.version);
    let items = sorted.iter().map(|h| {
        let version = h.version;
        let path = &h.ty_path;
        quote! { (#version, <#path as ::obj::Schema>::schema()) }
    });
    quote! {
        fn historical_schemas() -> ::std::vec::Vec<(u32, ::obj::DynamicSchema)> {
            // auto-generated by #[derive(Document)]
            ::std::vec![ #( #items ),* ]
        }
    }
}

/// Map a struct field's syntactic Rust type to a token-stream that
/// constructs a [`DynamicSchema`] value at runtime.
fn field_type_to_schema(ty: &Type) -> proc_macro2::TokenStream {
    if let Some(name) = scalar_schema_for(ty) {
        let ident = quote::format_ident!("{name}");
        return quote! { ::obj::DynamicSchema::#ident };
    }
    if let Some(inner) = vec_inner_type(ty) {
        let inner_schema = field_type_to_schema(inner);
        return quote! { ::obj::DynamicSchema::seq(#inner_schema) };
    }
    // Fallback: treat the type as `Schema`-implementing. This is
    // the path used for nested user structs and for any type the
    // syntactic scan does not recognise — the resulting expansion
    // fails to compile if the type lacks a `Schema` impl, which is
    // the diagnostic we want.
    quote! { <#ty as ::obj::Schema>::schema() }
}

/// Return the [`DynamicSchema`] variant name for `ty` if `ty` is one
/// of the built-in scalars; `None` otherwise. The result is used by
/// [`field_type_to_schema`] to construct the leaf token stream.
fn scalar_schema_for(ty: &Type) -> Option<&'static str> {
    let Type::Path(TypePath { qself: None, path }) = ty else {
        return None;
    };
    let segment = path.segments.last()?;
    if !segment.arguments.is_none() {
        return None;
    }
    let s = segment.ident.to_string();
    match s.as_str() {
        "bool" => Some("Bool"),
        "u8" | "u16" | "u32" | "u64" | "usize" => Some("U64"),
        "i8" | "i16" | "i32" | "i64" | "isize" => Some("I64"),
        "f32" | "f64" => Some("F64"),
        "String" => Some("String"),
        _ => None,
    }
}

/// If `ty` is `Vec<T>`, return `&T`; otherwise `None`.
fn vec_inner_type(ty: &Type) -> Option<&Type> {
    let Type::Path(TypePath { qself: None, path }) = ty else {
        return None;
    };
    let seg = path.segments.last()?;
    if seg.ident != "Vec" {
        return None;
    }
    let syn::PathArguments::AngleBracketed(args) = &seg.arguments else {
        return None;
    };
    args.args.iter().find_map(|a| match a {
        syn::GenericArgument::Type(t) => Some(t),
        _ => None,
    })
}

/// Validate every composite declaration against the struct's named
/// fields and lift each one into an `IndexSpecEmit`. Errors on:
///
/// - composite with fewer than 2 fields,
/// - a referenced field name that is not declared on the struct.
fn validate_and_lift_composites(
    input: &DeriveInput,
    composites: &[CompositeAttr],
) -> syn::Result<Vec<IndexSpecEmit>> {
    if composites.is_empty() {
        return Ok(Vec::new());
    }
    let fields = named_fields(input)?;
    let known: std::collections::HashSet<String> = fields
        .iter()
        .filter_map(|f| f.ident.as_ref().map(ToString::to_string))
        .collect();
    let mut out: Vec<IndexSpecEmit> = Vec::with_capacity(composites.len());
    for c in composites {
        if c.fields.len() < 2 {
            return Err(syn::Error::new(c.span, "composite needs ≥ 2 fields"));
        }
        for field in &c.fields {
            if !known.contains(field) {
                return Err(syn::Error::new(
                    c.span,
                    format!("field '{field}' not declared on struct"),
                ));
            }
        }
        let index_name = c.custom_name.clone().unwrap_or_else(|| c.fields.join("__"));
        out.push(IndexSpecEmit {
            kind: IndexKind::Composite(c.fields.clone()),
            field_name: String::new(),
            index_name,
        });
    }
    Ok(out)
}

/// Emit either an `indexes()` override or an empty token stream
/// (which leaves the trait default in place).
fn emit_indexes_body(specs: &[IndexSpecEmit]) -> proc_macro2::TokenStream {
    if specs.is_empty() {
        return proc_macro2::TokenStream::new();
    }
    let entries = specs.iter().map(IndexSpecEmit::emit);
    quote! {
        fn indexes() -> ::std::vec::Vec<::obj::IndexSpec> {
            // auto-generated by #[derive(Document)]
            //
            // Each entry is an `IndexSpec::{standard,unique,each,composite}`
            // call returning `Result`. Inputs were validated at derive
            // expansion time, so the error arm is statically unreachable;
            // we still handle it explicitly (push only `Ok`) so the
            // generated code is panic-free (Power-of-Ten Rule 7).
            let mut out: ::std::vec::Vec<::obj::IndexSpec> = ::std::vec::Vec::new();
            #(
                if let ::std::result::Result::Ok(spec) = #entries {
                    out.push(spec);
                }
            )*
            out
        }
    }
}

/// One parsed `#[obj(index_composite(...))]` declaration.
#[derive(Debug)]
struct CompositeAttr {
    /// User-provided field names. Each MUST exist on the struct.
    fields: Vec<String>,
    /// Optional `name = "..."` override; default is the fields joined
    /// with `__`.
    custom_name: Option<String>,
    /// Span used for "field 'x' not declared on struct" diagnostics.
    span: proc_macro2::Span,
}

/// Parsed struct-level attributes.
#[derive(Default, Debug)]
struct StructAttrs {
    /// `#[obj(version = N)]` override.
    version: Option<u32>,
    /// `#[obj(collection = "name")]` override.
    collection: Option<String>,
    /// Zero or more `#[obj(index_composite(...))]` declarations,
    /// preserved in declaration order so the emitted `indexes()` is
    /// deterministic.
    composites: Vec<CompositeAttr>,
    /// `#[obj(history(v1 = Type1, v2 = Type2))]` entries — one per
    /// historical version. Parsed in declaration order; the emitter
    /// re-sorts by `version` before emitting.
    history: Vec<HistoryAttr>,
    /// `true` iff the user opted into emitting a companion
    /// `impl ::obj::Schema` block. Set implicitly when
    /// `#[obj(history(...))]` is present (the current type needs a
    /// `Schema` impl so future versions can reference it from their
    /// own `history(...)`), or explicitly via `#[obj(schema)]`.
    emit_schema: bool,
}

/// One `vN = Type` pair from a `#[obj(history(...))]` declaration.
#[derive(Debug)]
struct HistoryAttr {
    /// Version number parsed from the `vN` key.
    version: u32,
    /// The Rust type path naming the historical schema producer.
    ty_path: syn::Path,
}

/// Walk every `#[obj(...)]` on the struct and merge them into a
/// single `StructAttrs`. Duplicates (within one `#[obj(...)]` OR
/// across two) error.
fn parse_struct_attrs(input: &DeriveInput) -> syn::Result<StructAttrs> {
    let mut acc = StructAttrs::default();
    for attr in &input.attrs {
        if !attr.path().is_ident("obj") {
            continue;
        }
        parse_one_struct_attr(attr, &mut acc)?;
    }
    Ok(acc)
}

/// Parse a single `#[obj(...)]` attribute into `acc`. Duplicate
/// scalar keys (within this attribute OR already present in `acc`)
/// error; `index_composite(...)` / `history(...)` are non-scalar
/// and append new entries.
fn parse_one_struct_attr(attr: &Attribute, acc: &mut StructAttrs) -> syn::Result<()> {
    attr.parse_nested_meta(|meta| {
        if meta.path.is_ident("version") {
            return parse_struct_version(&meta, acc);
        }
        if meta.path.is_ident("collection") {
            return parse_struct_collection(&meta, acc);
        }
        if meta.path.is_ident("index_composite") {
            let composite = parse_index_composite(&meta)?;
            acc.composites.push(composite);
            return Ok(());
        }
        if meta.path.is_ident("index") {
            let composite = parse_struct_index_short(&meta)?;
            acc.composites.push(composite);
            return Ok(());
        }
        if meta.path.is_ident("history") {
            parse_history(&meta, acc)?;
            // Opting into history implies opting into Schema —
            // future versions will reference this type from their
            // own history(...) and need a `Schema` impl to lift it
            // into a `DynamicSchema`.
            acc.emit_schema = true;
            return Ok(());
        }
        if meta.path.is_ident("schema") {
            if acc.emit_schema {
                // Redundant with an earlier `history` /
                // `schema` declaration; surface anyway so the user
                // notices the duplication.
                return Err(meta.error("`schema` declared twice or already implied by `history`"));
            }
            acc.emit_schema = true;
            return Ok(());
        }
        Err(meta.error(
            "unknown obj attribute (expected `version`, `collection`, `index`, `index_composite`, `history`, or `schema`)",
        ))
    })
}

/// Parse the short composite-index form `#[obj(index = ("a", "b"))]`
/// at struct level. The only valid RHS is a parenthesised tuple of
/// string literals — `unique` / `each` / a bare path are field-level
/// shapes and yield a struct-level diagnostic that points back at
/// `index_composite` / field-level placement.
///
/// The returned [`CompositeAttr`] is validated downstream by
/// [`validate_and_lift_composites`], which already enforces the
/// `≥ 2 fields` and "field declared on struct" invariants — both the
/// long and short forms share the same downstream gate.
fn parse_struct_index_short(meta: &syn::meta::ParseNestedMeta<'_>) -> syn::Result<CompositeAttr> {
    let span = meta.path.span();
    let kind = parse_index_kind(meta)?;
    match kind {
        IndexKind::Composite(fields) => Ok(CompositeAttr {
            fields,
            custom_name: None,
            span,
        }),
        _ => Err(syn::Error::new(
            span,
            "struct-level `index = ...` only accepts a tuple of field-name string literals \
             (e.g. `index = (\"a\", \"b\")`); place `index`, `index = unique`, or `index = each` \
             on a field instead",
        )),
    }
}

/// Parse `history(v1 = Type1, v2 = Type2, ...)`. Each key is of the
/// form `vN` for a `u32` `N`; the value is a Rust path naming a
/// `Schema`-implementing type. Pushes one `HistoryAttr` per pair
/// into `acc.history` (preserving declaration order; the emitter
/// re-sorts before emitting).
fn parse_history(meta: &syn::meta::ParseNestedMeta<'_>, acc: &mut StructAttrs) -> syn::Result<()> {
    meta.parse_nested_meta(|inner| {
        let ident = inner
            .path
            .get_ident()
            .ok_or_else(|| inner.error("expected `vN = Type` key"))?;
        let key = ident.to_string();
        let version = parse_history_key(&key).ok_or_else(|| {
            syn::Error::new(
                ident.span(),
                "history keys must be of the form `vN` (e.g. `v1`, `v2`, ...)",
            )
        })?;
        if acc.history.iter().any(|h| h.version == version) {
            return Err(syn::Error::new(
                ident.span(),
                format!("history key `v{version}` declared twice"),
            ));
        }
        let value = inner.value()?;
        let ty_path: syn::Path = value.parse()?;
        acc.history.push(HistoryAttr { version, ty_path });
        Ok(())
    })
}

/// Decode the `vN` key shape into the numeric version. Returns
/// `None` on any other shape.
fn parse_history_key(key: &str) -> Option<u32> {
    let rest = key.strip_prefix('v')?;
    rest.parse::<u32>().ok()
}

/// Parse `version = N`.
fn parse_struct_version(
    meta: &syn::meta::ParseNestedMeta<'_>,
    acc: &mut StructAttrs,
) -> syn::Result<()> {
    if acc.version.is_some() {
        return Err(meta.error("`version` declared twice"));
    }
    let value = meta.value()?;
    let lit: LitInt = value.parse()?;
    let n: u32 = lit
        .base10_parse()
        .map_err(|_| syn::Error::new(lit.span(), "expected unsigned integer for `version`"))?;
    acc.version = Some(n);
    Ok(())
}

/// Parse `collection = "name"`.
fn parse_struct_collection(
    meta: &syn::meta::ParseNestedMeta<'_>,
    acc: &mut StructAttrs,
) -> syn::Result<()> {
    if acc.collection.is_some() {
        return Err(meta.error("`collection` declared twice"));
    }
    let value = meta.value()?;
    let lit: LitStr = value.parse()?;
    let s = lit.value();
    if s.is_empty() {
        return Err(syn::Error::new(
            lit.span(),
            "collection name must not be empty",
        ));
    }
    acc.collection = Some(s);
    Ok(())
}

/// Parse `index_composite(fields = ("a", "b"), name = "by_a_b")`.
///
/// `fields` is required. `name` is optional and defaults to the
/// fields joined with `__`. Field-existence validation runs after
/// the struct's named fields are known — see
/// `validate_and_emit_composites`.
fn parse_index_composite(meta: &syn::meta::ParseNestedMeta<'_>) -> syn::Result<CompositeAttr> {
    let span = meta.path.span();
    let mut fields: Option<Vec<String>> = None;
    let mut custom_name: Option<String> = None;
    meta.parse_nested_meta(|inner| {
        if inner.path.is_ident("fields") {
            if fields.is_some() {
                return Err(inner.error("`fields` declared twice"));
            }
            fields = Some(parse_composite_fields(&inner)?);
            return Ok(());
        }
        if inner.path.is_ident("name") {
            if custom_name.is_some() {
                return Err(inner.error("`name` declared twice"));
            }
            let value = inner.value()?;
            let lit: LitStr = value.parse()?;
            let s = lit.value();
            if s.is_empty() {
                return Err(syn::Error::new(
                    lit.span(),
                    "composite index name must not be empty",
                ));
            }
            custom_name = Some(s);
            return Ok(());
        }
        Err(inner.error("expected `fields = (...)` or `name = \"...\"`"))
    })?;
    let fields = fields.ok_or_else(|| {
        syn::Error::new(
            span,
            "index_composite requires `fields = (\"a\", \"b\", ...)`",
        )
    })?;
    Ok(CompositeAttr {
        fields,
        custom_name,
        span,
    })
}

/// Parse the `fields = ("a", "b", ...)` parenthesised tuple of
/// string literals. Returns the literal values verbatim.
///
/// Delegates to [`parse_composite_paren_paths`] so the long-form
/// (`index_composite(fields = (...))`) and short-form
/// (`index = (...)`) syntaxes go through one shared parser.
fn parse_composite_fields(meta: &syn::meta::ParseNestedMeta<'_>) -> syn::Result<Vec<String>> {
    let value = meta.value()?;
    parse_composite_paren_paths(value)
}

/// Index-kind discriminator parsed from `#[obj(index = ...)]` or
/// `#[obj(index_composite(...))]`.
#[derive(Debug, Clone)]
enum IndexKind {
    Standard,
    Unique,
    Each,
    /// Composite over the listed field paths (always ≥ 2).
    Composite(Vec<String>),
}

/// One index emitted by the derive — carries the kind discriminator
/// and the (key path, index name) pair to render.
#[derive(Debug)]
struct IndexSpecEmit {
    kind: IndexKind,
    /// The single struct field this index reads from (Standard /
    /// Unique / Each). Unused for `Composite` — paths live inside
    /// `IndexKind::Composite(...)`.
    field_name: String,
    /// User override via `#[obj(index, name = "...")]` or
    /// `index_composite(name = "...")`, or the default name if none
    /// was provided.
    index_name: String,
}

impl IndexSpecEmit {
    /// Emit the constructor call for this spec.
    ///
    /// We route through the kind-specific `IndexSpec` constructors
    /// (`IndexSpec::standard` / `::unique` / `::each` / `::composite`)
    /// rather than a struct literal: `IndexSpec` is `#[non_exhaustive]`
    /// and so cannot be struct-literal-constructed from a downstream
    /// user crate. The constructors return `Result`, but the derive
    /// has already validated their inputs at proc-macro time (empty
    /// struct field names are syntactically impossible, empty
    /// `name = "..."` is rejected at parse time, and composites are
    /// checked for ≥ 2 fields). The emitted code therefore handles the
    /// (statically-unreachable) error arm by skipping rather than
    /// panicking — keeping the generated `indexes()` panic-free.
    fn emit(&self) -> proc_macro2::TokenStream {
        let name = &self.index_name;
        match &self.kind {
            IndexKind::Standard => self.emit_scalar(name, &quote! { standard }),
            IndexKind::Unique => self.emit_scalar(name, &quote! { unique }),
            IndexKind::Each => self.emit_scalar(name, &quote! { each }),
            IndexKind::Composite(paths) => Self::emit_composite(name, paths),
        }
    }

    fn emit_scalar(&self, name: &str, ctor: &proc_macro2::TokenStream) -> proc_macro2::TokenStream {
        let path = &self.field_name;
        quote! {
            ::obj::IndexSpec::#ctor(
                ::std::string::String::from(#name),
                ::std::string::String::from(#path),
            )
        }
    }

    fn emit_composite(name: &str, paths: &[String]) -> proc_macro2::TokenStream {
        let path_tokens = paths.iter().map(|p| quote! { #p });
        quote! {
            ::obj::IndexSpec::composite(
                ::std::string::String::from(#name),
                &[ #( #path_tokens ),* ],
            )
        }
    }
}

/// Iterate the struct's fields and collect every field-level
/// `#[obj(index ...)]` declaration in declaration order.
fn collect_field_indexes(input: &DeriveInput) -> syn::Result<Vec<IndexSpecEmit>> {
    let fields = named_fields(input)?;
    let mut out: Vec<IndexSpecEmit> = Vec::new();
    for field in fields {
        for spec in parse_field_attrs(field)? {
            out.push(spec);
        }
    }
    Ok(out)
}

/// Extract `&FieldsNamed` from the `DeriveInput`. The derive is
/// defined only for braced structs; anything else is a compile
/// error at the struct's span.
fn named_fields(
    input: &DeriveInput,
) -> syn::Result<&syn::punctuated::Punctuated<Field, syn::Token![,]>> {
    match &input.data {
        Data::Struct(DataStruct {
            fields: Fields::Named(named),
            ..
        }) => Ok(&named.named),
        _ => Err(syn::Error::new(
            input.span(),
            "#[derive(obj::Document)] only supports structs with named fields",
        )),
    }
}

/// Parse all `#[obj(...)]` attributes on a single field. Returns the
/// list of `IndexSpecEmit`s contributed by this field (typically 0 or
/// 1, but multiple `#[obj(index ...)]` attributes compose).
fn parse_field_attrs(field: &Field) -> syn::Result<Vec<IndexSpecEmit>> {
    let mut specs: Vec<IndexSpecEmit> = Vec::new();
    let field_name = field
        .ident
        .as_ref()
        .ok_or_else(|| syn::Error::new(field.span(), "expected named field"))?
        .to_string();
    for attr in &field.attrs {
        if !attr.path().is_ident("obj") {
            continue;
        }
        parse_one_field_attr(attr, field, &field_name, &mut specs)?;
    }
    Ok(specs)
}

/// Parse a single `#[obj(...)]` field attribute, contributing any
/// `IndexSpecEmit` it declares into `specs`.
fn parse_one_field_attr(
    attr: &Attribute,
    field: &Field,
    field_name: &str,
    specs: &mut Vec<IndexSpecEmit>,
) -> syn::Result<()> {
    let mut kind: Option<IndexKind> = None;
    let mut custom_name: Option<String> = None;
    attr.parse_nested_meta(|meta| {
        if meta.path.is_ident("index") {
            if kind.is_some() {
                return Err(meta.error("`index` declared twice on the same field"));
            }
            let parsed = parse_index_kind(&meta)?;
            if matches!(parsed, IndexKind::Composite(_)) {
                return Err(syn::Error::new(
                    meta.path.span(),
                    "tuple-form `index = (\"a\", \"b\")` is struct-level only; \
                     place it directly above the struct, not on a field",
                ));
            }
            kind = Some(parsed);
            return Ok(());
        }
        if meta.path.is_ident("name") {
            if custom_name.is_some() {
                return Err(meta.error("`name` declared twice on the same field"));
            }
            let value = meta.value()?;
            let lit: LitStr = value.parse()?;
            let s = lit.value();
            if s.is_empty() {
                return Err(syn::Error::new(lit.span(), "index name must not be empty"));
            }
            custom_name = Some(s);
            return Ok(());
        }
        Err(meta.error("unknown obj field attribute (expected `index`, `name`)"))
    })?;
    finalize_field_index(field, field_name, kind, custom_name, specs)
}

/// Decode the right-hand side of `index = ...` into an `IndexKind`.
///
/// Three syntactic shapes are accepted:
///
/// - `#[obj(index)]` (no `= ...`) → [`IndexKind::Standard`].
/// - `#[obj(index = unique)]` / `#[obj(index = each)]` → the keyword
///   variants. Field-level only; the struct-level caller rejects
///   them with a more specific diagnostic.
/// - `#[obj(index = ("a", "b", ...))]` → [`IndexKind::Composite`]
///   over the listed field-name string literals. Struct-level only;
///   the field-level caller rejects it for the same reason.
///
/// Single-element tuples (`("a",)`) are accepted and degenerate to
/// `IndexKind::Composite(vec!["a".into()])`. The struct-level caller
/// then runs the same field-existence + ≥-2 validation it runs for
/// the long form, so a one-element short tuple produces the existing
/// "composite needs ≥ 2 fields" diagnostic without bespoke handling.
fn parse_index_kind(meta: &syn::meta::ParseNestedMeta<'_>) -> syn::Result<IndexKind> {
    if !meta.input.peek(syn::Token![=]) {
        return Ok(IndexKind::Standard);
    }
    let value = meta.value()?;
    if value.peek(syn::token::Paren) {
        let paths = parse_composite_paren_paths(value)?;
        return Ok(IndexKind::Composite(paths));
    }
    let id: syn::Ident = value.parse().map_err(|_| {
        syn::Error::new(
            value.span(),
            "expected one of: unique, each, or a tuple of field-name string literals like (\"a\", \"b\")",
        )
    })?;
    if id == "unique" {
        return Ok(IndexKind::Unique);
    }
    if id == "each" {
        return Ok(IndexKind::Each);
    }
    Err(syn::Error::new(
        id.span(),
        "expected one of: unique, each (or omit `= ...` for a standard index)",
    ))
}

/// Parse a parenthesised tuple of string literals into a `Vec<String>`.
///
/// Shared by the short composite form `index = ("a", "b")`; the long
/// form `index_composite(fields = ("a", "b"))` runs through
/// [`parse_composite_fields`] which wraps an outer
/// `meta.value()` call before delegating here.
///
/// Non-`LitStr` entries (`(1, 2)`, `(foo, bar)`, …) produce a
/// `syn::Error` pointing at the offending token with the message
/// `expected a tuple of field-name string literals, e.g. ("a", "b")`,
/// rather than the bare `expected string literal` diagnostic that
/// `LitStr::parse` would otherwise emit.
fn parse_composite_paren_paths(value: syn::parse::ParseStream<'_>) -> syn::Result<Vec<String>> {
    const MAX_FIELDS: usize = 64;
    let content;
    syn::parenthesized!(content in value);
    if content.is_empty() {
        return Err(syn::Error::new(
            content.span(),
            "expected a tuple of field-name string literals, e.g. (\"a\", \"b\")",
        ));
    }
    let mut out: Vec<String> = Vec::new();
    // Bounded loop (Power-of-Ten Rule 2): a single derive attribute
    // can never reasonably span more than `MAX_FIELDS` columns; any
    // input exceeding that is malformed.
    while !content.is_empty() {
        if out.len() >= MAX_FIELDS {
            return Err(syn::Error::new(
                content.span(),
                "too many composite-index fields (limit 64)",
            ));
        }
        let lit: LitStr = content.parse().map_err(|e| {
            syn::Error::new(
                e.span(),
                "expected a tuple of field-name string literals, e.g. (\"a\", \"b\")",
            )
        })?;
        let s = lit.value();
        if s.is_empty() {
            return Err(syn::Error::new(
                lit.span(),
                "composite field name must not be empty",
            ));
        }
        out.push(s);
        if content.is_empty() {
            break;
        }
        content.parse::<syn::Token![,]>()?;
    }
    Ok(out)
}

/// Combine the parsed `kind` + `custom_name` into an `IndexSpecEmit`.
/// Enforces the `each` ⇒ `Vec<_>` invariant.
fn finalize_field_index(
    field: &Field,
    field_name: &str,
    kind: Option<IndexKind>,
    custom_name: Option<String>,
    specs: &mut Vec<IndexSpecEmit>,
) -> syn::Result<()> {
    let Some(kind) = kind else {
        if custom_name.is_some() {
            return Err(syn::Error::new(
                field.span(),
                "`#[obj(name = \"...\")]` requires an `index` declaration on the same field",
            ));
        }
        return Ok(());
    };
    if matches!(kind, IndexKind::Each) && !type_is_vec(&field.ty) {
        return Err(syn::Error::new(
            field.ty.span(),
            "#[obj(index = each)] requires Vec<T>",
        ));
    }
    specs.push(IndexSpecEmit {
        kind,
        field_name: field_name.to_owned(),
        index_name: custom_name.unwrap_or_else(|| field_name.to_owned()),
    });
    Ok(())
}

/// Cheap syntactic check: is `ty` a `Vec<...>`?
///
/// We accept any path whose last segment ident is `Vec`. That covers
/// `Vec`, `::std::vec::Vec`, `alloc::vec::Vec` etc. Anything else
/// (including `Option<Vec<T>>` or a typedef) is rejected — the user
/// can use `#[obj(index)]` instead.
fn type_is_vec(ty: &Type) -> bool {
    let Type::Path(TypePath { qself: None, path }) = ty else {
        return false;
    };
    match path.segments.last() {
        Some(seg) => seg.ident == "Vec",
        None => false,
    }
}

#[cfg(test)]
mod tests {
    //! Internal proc-macro tests. Tests live next to the derive's
    //! helpers so they can exercise the emit pipeline without
    //! depending on the `obj` crate (which would be a cycle, since
    //! `obj` depends on `obj-derive`).

    use super::*;
    use syn::parse_str;

    /// M9 #80 exit gate: expanded code for a typical struct must
    /// stay under ~200 lines.
    ///
    /// "Typical struct" per the issue notes: 5 fields + 3 indexes.
    /// We pick a shape representative of an everyday user document:
    /// two scalar fields, one unique index, one each-index over a
    /// `Vec`, one composite spanning two of the scalars.
    #[test]
    fn typical_struct_expansion_is_under_200_lines() {
        let input: DeriveInput = parse_str(
            r#"
            #[obj(version = 2, collection = "orders")]
            #[obj(index_composite(fields = ("customer_id", "placed_at")))]
            struct Order {
                #[obj(index)]
                customer_id: u64,
                #[obj(index = unique)]
                order_no: String,
                #[obj(index = each)]
                tags: Vec<String>,
                placed_at: u64,
                total_cents: u64,
            }
            "#,
        )
        .expect("parse typical struct");
        let ts = emit_impl(&input).expect("emit");
        let expanded = ts.to_string();
        let line_count = expanded.lines().count();
        // proc-macro2's `to_string()` collapses formatting onto one
        // logical line per group. `lines()` gives the logical line
        // count post-collapse — for a real `cargo expand`-style
        // count we re-format via prettyplease-equivalent and count
        // those. To keep the test free of additional dependencies we
        // approximate by counting top-level groups using `;` + `{`
        // separators, which is a stable upper bound for an
        // unformatted impl block.
        let approx_lines = expanded.matches(';').count()
            + expanded.matches('{').count()
            + expanded.matches('}').count();
        assert!(
            approx_lines <= 200,
            "expanded `#[derive(Document)]` exceeds 200-line budget: \
             approx_lines = {approx_lines}; line_count = {line_count}; \
             expansion = {expanded}",
        );
    }

    /// Bare-derive shape: emitted impl carries only COLLECTION +
    /// VERSION + the `// auto-generated` marker. Confirms #75's
    /// "minimal output" promise is still true after the M9 stack.
    #[test]
    fn bare_derive_expansion_is_small() {
        let input: DeriveInput = parse_str("struct Bare { x: u32 }").expect("parse");
        let ts = emit_impl(&input).expect("emit");
        let expanded = ts.to_string();
        // No `indexes()` override.
        assert!(
            !expanded.contains("fn indexes"),
            "bare derive must NOT emit an indexes() override (expanded: {expanded})",
        );
        // COLLECTION + VERSION are present.
        assert!(expanded.contains("COLLECTION"));
        assert!(expanded.contains("VERSION"));
    }
}