Skip to main content

arcadedb_record_macros/
lib.rs

1//! `#[derive(RecordDecode)]` — generated `TryFrom<&GrpcRecord>` / `FromGrpcValue`
2//! for model structs, decoding an ArcadeDB `GrpcRecord` (or an embedded/map
3//! `GrpcValue`) directly into a typed Rust DTO — no intermediate JSON.
4//!
5//! `#[derive(RecordEncode)]` — the write-side mirror: generates
6//! `ToGrpcRecord`, mapping each field's Rust type onto the matching
7//! `GrpcValue` wire kind. Same `rename`/`rename_all` naming; field
8//! attributes below apply with encode-side semantics (`skip` spellings,
9//! `Option` omission, nested maps — see [`RecordEncode`]).
10//!
11//! ## Field attributes
12//!
13//! Both derives understand serde's `rename`, `rename_all`, `default`,
14//! `default = "path"`, and `flatten`, plus `#[record(...)]` spellings:
15//!
16//! - `#[serde(rename = "logical_key")]` / `#[record(rename = "...")]` — wire property name.
17//! - `#[serde(default)]` / `#[record(default)]` — missing property → `Default::default()`.
18//! - `#[serde(default = "path")]` / `#[record(default = "path")]` — custom default fn.
19//! - `#[record(with = "path")]` / `#[record(deserialize_with = "path")]` — custom
20//!   conversion `fn(&GrpcValue) -> Result<T, RecordDecodeError>` for types
21//!   the macro cannot map itself.
22//! - `#[record(skip)]` — `Default::default()`, property never read.
23//! - `#[serde(flatten)]` — decode the *remaining* properties into a nested
24//!   `FromGrpcValue` struct.
25//! - `#[record(with = "path")]` + `#[serde(default)]` — run the custom fn when
26//!   the property is present, fall back to the default when absent.
27//!
28//! Custom types used across many DTOs can instead implement
29//! `FromGrpcValue` directly — then no per-field attribute is needed at all.
30//!
31//! ## Type support
32//!
33//! Any field type implementing `FromGrpcValue` works: `String`, `bool`,
34//! integers (`i8`–`i64`, `u8`–`u64`, range-checked), `f32`/`f64`,
35//! `Option<T>`, `Vec<T>` (list values), `HashMap<String, T>` (maps),
36//! `chrono::DateTime<Utc>` (timestamps), `serde_json::Value` (any kind),
37//! `Vec<u8>` (byte blobs), `Link` (`#bucket:pos` rids), single-field tuple
38//! structs (transparent newtypes), and nested structs deriving
39//! `RecordDecode`. Unit-variant enums decode from strings honoring
40//! `#[serde(rename)]` + `#[serde(rename_all)]`; internally-tagged
41//! struct-variant enums (`#[serde(tag = "...")]`) decode from embedded/map
42//! values via the discriminator key.
43//!
44//! ## Naming parity with serde
45//!
46//! `rename_all` uses serde's exact case dialect: fields are assumed
47//! snake_case, variants PascalCase, acronyms are NOT regrouped
48//! (`HTTPServer` + `snake_case` → `h_t_t_p_server`). Un-renamed names are
49//! the ident as-is; unknown rule names are compile errors.
50//!
51//! `@rid` / `@type` synthetic metadata: a field whose wire name is `@rid` or
52//! `@type` reads the property if the query returned it, else falls back to
53//! `GrpcRecord.rid` / `GrpcRecord.type`.
54//!
55//! ## Naming the runtime crate
56//!
57//! The generated code references `::arcadedb_protocol` by default; redirect
58//! with `#[record(crate_path = "crate::db::arcadedb")]` when the runtime
59//! is re-exported elsewhere.
60
61use proc_macro::TokenStream;
62use proc_macro2::TokenStream as TokenStream2;
63use quote::quote;
64use syn::spanned::Spanned;
65use syn::{
66    parse_macro_input, Data, DataEnum, DeriveInput, Fields, GenericArgument, Ident, PathArguments,
67    Type,
68};
69
70mod sql;
71
72/// `sql!` — write the statement as a literal, get a syntax check for free.
73///
74/// ```ignore
75/// use arcadedb_protocol::{params, sql};
76///
77/// client.execute_with_values(
78///     sql!("UPDATE users SET status = :status UPSERT WHERE user_id = :user_id"),
79///     params! { status: "active", user_id },
80/// ).await?;
81/// ```
82///
83/// Catches at compile time: UPDATE clause order, unbalanced delimiters,
84/// reserved-word placeholders (`:after`), pasted scripts, `DELETE` without
85/// `WHERE`, `INSERT` without `INTO`, `CREATE EDGE` without `FROM`/`TO`.
86/// Expands to the `&str` unchanged. Bound params are `params!`'s job, not
87/// this macro's; non-literal statements stay plain strings.
88#[proc_macro]
89pub fn sql(input: TokenStream) -> TokenStream {
90    sql::expand_sql(input)
91}
92
93/// `#[derive(RecordDecode)]`.
94// `serde` is registered here too (registration is additive across derives —
95// serde's own Deserialize/Serialize both register it), so decode-only DTOs
96// without a serde derive can still spell `#[serde(rename = "...")]`.
97#[proc_macro_derive(RecordDecode, attributes(record, serde))]
98pub fn derive_record_decode(input: TokenStream) -> TokenStream {
99    let input = parse_macro_input!(input as DeriveInput);
100    let output = match expand_derive(&input) {
101        Ok(tokens) => tokens,
102        Err(err) => err.to_compile_error(),
103    };
104    output.into()
105}
106
107/// `#[derive(RecordEncode)]` — the encode-side mirror of [`RecordDecode`]:
108/// generates `ToGrpcRecord` (see the module docs for the attribute reference).
109///
110/// The `serde` attribute namespace is registered here too — unlike
111/// [`RecordDecode`], these DTOs are write-only and typically have no serde
112/// derive to register it.
113#[proc_macro_derive(RecordEncode, attributes(record, serde))]
114pub fn derive_record_encode(input: TokenStream) -> TokenStream {
115    let input = parse_macro_input!(input as DeriveInput);
116    let output = match expand_encode_derive(&input) {
117        Ok(tokens) => tokens,
118        Err(err) => err.to_compile_error(),
119    };
120    output.into()
121}
122
123// ---------------------------------------------------------------------------
124// Expand
125// ---------------------------------------------------------------------------
126
127/// Reject the alternative-hasher map types (`ahash::AHashMap`,
128/// `rustc_hash::FxHashMap`) when the matching feature is off: the wire
129/// mapping needs the protocol's `FromGrpcValue` impl, which only exists
130/// with the feature. Failing here names the fix, instead of leaving the
131/// user with a trait-bound error deep in the generated code.
132fn check_alt_hasher_fields(input: &DeriveInput) -> syn::Result<()> {
133    match &input.data {
134        Data::Struct(d) => {
135            for field in d.fields.iter() {
136                check_alt_hasher_type(&field.ty)?;
137            }
138        }
139        Data::Enum(e) => {
140            for variant in &e.variants {
141                for field in variant.fields.iter() {
142                    check_alt_hasher_type(&field.ty)?;
143                }
144            }
145        }
146        Data::Union(_) => {}
147    }
148    Ok(())
149}
150
151/// Walk a field type looking for the alternative-hasher map types.
152fn check_alt_hasher_type(ty: &Type) -> syn::Result<()> {
153    match ty {
154        Type::Path(tp) => {
155            if let Some(seg) = tp.path.segments.last() {
156                let name = seg.ident.to_string();
157                if name == "AHashMap" && !cfg!(feature = "ahash") {
158                    return Err(syn::Error::new(
159                        ty.span(),
160                        "RecordEncode/RecordDecode: `AHashMap` fields need the `ahash` feature",
161                    ));
162                }
163                if name == "FxHashMap" && !cfg!(feature = "fxhash") {
164                    return Err(syn::Error::new(
165                        ty.span(),
166                        "RecordEncode/RecordDecode: `FxHashMap` fields need the `fxhash` feature",
167                    ));
168                }
169                if name == "AHashSet" && !cfg!(feature = "ahash") {
170                    return Err(syn::Error::new(
171                        ty.span(),
172                        "RecordEncode/RecordDecode: `AHashSet` fields need the `ahash` feature",
173                    ));
174                }
175                if name == "FxHashSet" && !cfg!(feature = "fxhash") {
176                    return Err(syn::Error::new(
177                        ty.span(),
178                        "RecordEncode/RecordDecode: `FxHashSet` fields need the `fxhash` feature",
179                    ));
180                }
181                // Recurse into the generic arguments (`Option<AHashMap<..>>`,
182                // `Vec<AHashMap<..>>`, …).
183                if let PathArguments::AngleBracketed(args) = &seg.arguments {
184                    for arg in &args.args {
185                        if let GenericArgument::Type(inner) = arg {
186                            check_alt_hasher_type(inner)?;
187                        }
188                    }
189                }
190            }
191            Ok(())
192        }
193        Type::Reference(r) => check_alt_hasher_type(&r.elem),
194        Type::Slice(s) => check_alt_hasher_type(&s.elem),
195        Type::Array(a) => check_alt_hasher_type(&a.elem),
196        Type::Paren(p) => check_alt_hasher_type(&p.elem),
197        Type::Group(g) => check_alt_hasher_type(&g.elem),
198        _ => Ok(()),
199    }
200}
201
202fn expand_derive(input: &DeriveInput) -> syn::Result<TokenStream2> {
203    let name = &input.ident;
204    check_alt_hasher_fields(input)?;
205    // Generic *lifetime* parameters are allowed (borrowed decode: a
206    // `Row<'a>` holding `&'a str` / `Cow<'a, str>` / `&'a [u8]` fields
207    // borrows from the record being decoded). Type/const generics remain
208    // unsupported — the wire mapping is fully concrete per type.
209    let mut lifetimes: Vec<&syn::LifetimeParam> = input
210        .generics
211        .params
212        .iter()
213        .filter_map(|p| match p {
214            syn::GenericParam::Lifetime(lt) => Some(lt),
215            _ => None,
216        })
217        .collect();
218    if lifetimes.len() > 1 {
219        return Err(syn::Error::new(
220            input.generics.span(),
221            "RecordDecode supports at most one lifetime parameter",
222        ));
223    }
224
225    let borrowed = lifetimes.pop();
226    let borrow = match borrowed {
227        Some(lt) => {
228            let life = &lt.lifetime;
229            BorrowCfg {
230                clause: quote! { <#life> },
231                inherent_clause: quote! { <#life> },
232                self_ty: quote! { #name<#life> },
233                helper_clause: quote! {},
234                lt: life.clone(),
235                owned_try_from: false,
236            }
237        }
238        None => BorrowCfg {
239            clause: quote! { <'de> },
240            inherent_clause: quote! {},
241            self_ty: quote! { #name },
242            helper_clause: quote! { <'de> },
243            lt: syn::Lifetime::new("'de", proc_macro2::Span::call_site()),
244            owned_try_from: true,
245        },
246    };
247    if let Some(p) = input
248        .generics
249        .params
250        .iter()
251        .find(|p| !matches!(p, syn::GenericParam::Lifetime(_)))
252    {
253        return Err(syn::Error::new(
254            p.span(),
255            "RecordDecode does not support type/const generic parameters",
256        ));
257    }
258
259    let container = ContainerCfg::parse(input)?;
260
261    match &input.data {
262        Data::Struct(data) => expand_struct(name, data, &container, &borrow),
263        Data::Enum(data) => expand_enum(name, data, &container, &borrow),
264        Data::Union(data) => Err(syn::Error::new(
265            data.union_token.span(),
266            "RecordDecode does not support unions",
267        )),
268    }
269}
270
271/// Lifetime scaffolding shared by every generated impl.
272struct BorrowCfg {
273    /// `impl<'de>` (owning DTOs) or `impl<'a>` (borrowed DTOs).
274    clause: TokenStream2,
275    /// The inherent helper's `impl` clause: `impl Name` (owning — the helper
276    /// declares its own `'de`) resp. `impl<'a> Name<'a>` (borrowed — the helper
277    /// uses the block's `'a`).
278    inherent_clause: TokenStream2,
279    /// `#name` resp. `#name<'a>` — the impl self type.
280    self_ty: TokenStream2,
281    /// Extra generic clause on the inherent decode helper when the DTO owns
282    /// its data: `fn __arcade_decode_from_map<'de>(...)`.
283    helper_clause: TokenStream2,
284    /// The lifetime ident (`'de`/`'a`) used on the trait and record types.
285    lt: syn::Lifetime,
286    /// Emit `TryFrom<GrpcRecord>` (owned) too — only possible when the DTO
287    /// owns its data (a borrowing struct can't outlive the owned record).
288    owned_try_from: bool,
289}
290
291fn expand_struct(
292    name: &Ident,
293    data: &syn::DataStruct,
294    container: &ContainerCfg,
295    borrow: &BorrowCfg,
296) -> syn::Result<TokenStream2> {
297    let Fields::Named(fields) = &data.fields else {
298        return expand_tuple_struct(name, data, container, borrow);
299    };
300
301    let crate_path = &container.crate_path;
302
303    // Parse + validate each field.
304    let mut field_lets = Vec::new();
305    let mut flat_fields: Vec<(Ident, Type, Option<Type>)> = Vec::new();
306    let mut non_flat_keys: Vec<String> = Vec::new();
307    let mut wire_kinds: Vec<(String, String)> = Vec::new();
308
309    for field in &fields.named {
310        let fident = field.ident.as_ref().expect("named field ident").clone();
311        let cfg = FieldCfg::parse(field)?;
312        let ty = &field.ty;
313
314        // Wire name: explicit rename > container rule (serde's exact
315        // `apply_to_field`) > the ident as-is (serde never transforms
316        // un-renamed names).
317        let wire = match (&cfg.rename, container.rename_all) {
318            (Some(r), _) => r.clone(),
319            (None, Some(rule)) => rule.apply_to_field(&fident.to_string()),
320            (None, None) => fident.to_string(),
321        };
322
323        if cfg.skip_decode {
324            field_lets.push(quote! {
325                let #fident: #ty = ::core::default::Default::default();
326            });
327            continue;
328        }
329
330        // Expected ArcadeDB column type for drift checks — fields with a
331        // known mapping only (custom `with` conversions and dynamic values
332        // are excluded; flatten targets describe their own kinds).
333        if cfg.with.is_none() {
334            if let Some(db_type) = db_type_of(ty) {
335                wire_kinds.push((wire.clone(), db_type));
336            }
337        }
338
339        // `#[serde(flatten)]` / `#[record(flatten)]` — decode remaining props.
340        if cfg.flatten {
341            if !flat_fields.is_empty() {
342                return Err(syn::Error::new(
343                    field.span(),
344                    "RecordDecode supports at most one flattened field per struct",
345                ));
346            }
347            if cfg.with.is_some() {
348                return Err(syn::Error::new(
349                    field.span(),
350                    "RecordDecode: `with` cannot be combined with a flattened field",
351                ));
352            }
353            let opt_inner = option_inner(ty);
354            flat_fields.push((fident, ty.clone(), opt_inner));
355            continue;
356        }
357
358        non_flat_keys.push(wire.clone());
359
360        // Synthetic `@rid` / `@type`: read the real property when present,
361        // otherwise fall back to the record's own `rid`/`type` — lazily, via
362        // the decode helper's synth args, instead of cloning the entire
363        // property map (the old approach). Synth fallbacks support owned
364        // targets only (a borrowed target like `Cow<'de, str>` couldn't
365        // outlive the fallback value).
366        if wire == "@rid" || wire == "@type" {
367            let syn = if wire == "@rid" {
368                quote! { __arcade_syn_rid }
369            } else {
370                quote! { __arcade_syn_type }
371            };
372            if cfg.with.is_some() {
373                return Err(syn::Error::new(
374                    field.span(),
375                    "RecordDecode: `with` cannot be combined with `@rid`/`@type` synthesis",
376                ));
377            }
378            field_lets.push(synth_field_let(
379                &fident,
380                ty,
381                &wire,
382                &cfg.default,
383                &syn,
384                crate_path,
385            )?);
386            continue;
387        }
388
389        // `#[record(with = "...")]` — custom conversion fn. Combined with
390        // `#[serde(default)]` the property is optional, falling back to the
391        // default when absent (e.g. custom containers).
392        if let Some(with_path) = &cfg.with {
393            let call = if let Some(inner) = option_inner(ty) {
394                quote! {
395                    #[allow(clippy::redundant_closure_call)]
396                    let #fident: #ty = #crate_path::record::get_opt_with::<#inner>(
397                        __arcade_props,
398                        __arcade_taken,
399                        #wire,
400                        #with_path,
401                    )?;
402                }
403            } else if cfg.default.is_some() {
404                let fallback = default_fallback(&cfg.default);
405                quote! {
406                    #[allow(clippy::redundant_closure_call)]
407                    let #fident: #ty = #crate_path::record::get_with_or::<#ty>(
408                        __arcade_props,
409                        __arcade_taken,
410                        #wire,
411                        #with_path,
412                        #fallback,
413                    )?;
414                }
415            } else {
416                quote! {
417                    #[allow(clippy::redundant_closure_call)]
418                    let #fident: #ty = #crate_path::record::get_with::<#ty>(
419                        __arcade_props,
420                        __arcade_taken,
421                        #wire,
422                        #with_path,
423                    )?;
424                }
425            };
426            field_lets.push(call);
427            continue;
428        }
429
430        // `Option<T>` — missing property or explicit null → `None`.
431        if let Some(inner) = option_inner(ty) {
432            let call = if vec_u8(&inner) {
433                // `Option<Vec<u8>>` — a nullable byte blob.
434                quote! {
435                    let #fident: #ty = #crate_path::record::get_opt_bytes(
436                        __arcade_props,
437                        __arcade_taken,
438                        #wire,
439                    )?;
440                }
441            } else {
442                quote! {
443                    let #fident: #ty = #crate_path::record::get_opt(
444                        __arcade_props,
445                        __arcade_taken,
446                        #wire,
447                    )?;
448                }
449            };
450            field_lets.push(call);
451            continue;
452        }
453
454        // `Vec<u8>` fields are byte blobs (wire `bytes` kind, or a list of
455        // small ints) — not generic int lists.
456        if vec_u8(ty) {
457            let call = match &cfg.default {
458                None => quote! {
459                    let #fident: #ty = #crate_path::record::get_bytes(__arcade_props, __arcade_taken, #wire)?;
460                },
461                Some(None) => quote! {
462                    let #fident: #ty = #crate_path::record::get_bytes_or(
463                        __arcade_props,
464                        __arcade_taken,
465                        #wire,
466                        ::core::default::Default::default,
467                    )?;
468                },
469                Some(Some(path)) => quote! {
470                    let #fident: #ty = #crate_path::record::get_bytes_or(
471                        __arcade_props,
472                        __arcade_taken,
473                        #wire,
474                        #path,
475                    )?;
476                },
477            };
478            field_lets.push(call);
479            continue;
480        }
481
482        // Missing-property policy: serde `default` → default value, else error.
483        match &cfg.default {
484            None => {
485                field_lets.push(quote! {
486                    let #fident: #ty = #crate_path::record::get(
487                        __arcade_props,
488                        __arcade_taken,
489                        #wire,
490                    )?;
491                });
492            }
493            Some(None) => {
494                field_lets.push(quote! {
495                    let #fident: #ty = #crate_path::record::get_or(
496                        __arcade_props,
497                        __arcade_taken,
498                        #wire,
499                        ::core::default::Default::default,
500                    )?;
501                });
502            }
503            Some(Some(path)) => {
504                field_lets.push(quote! {
505                    let #fident: #ty = #crate_path::record::get_or(
506                        __arcade_props,
507                        __arcade_taken,
508                        #wire,
509                        #path,
510                    )?;
511                });
512            }
513        }
514    }
515
516    let wire_kind_pairs: Vec<TokenStream2> = wire_kinds
517        .iter()
518        .map(|(w, k)| quote! { (#w, #k) })
519        .collect();
520
521    // Flattened fields consume everything not taken by named fields —
522    // ZERO-COPY: no rest map is materialized. The child decodes straight
523    // from the record's own map via `DecodeFromMap`, with the parent's
524    // consumed keys hidden (`taken`), so borrowed (`Cow<'de>`) flatten
525    // targets work and no entries are cloned.
526    for (fident, ty, opt_inner) in &flat_fields {
527        // The child must not see the parent's keys; a nested flatten child
528        // must not see this level's keys either — extend the incoming list.
529        let own_taken = &non_flat_keys;
530        let own_len = own_taken.len();
531        let taken_stmt = quote! {
532            let mut __arcade_t: ::std::vec::Vec<&str> =
533                ::std::vec::Vec::with_capacity(__arcade_taken.len() + #own_len);
534            __arcade_t.extend(__arcade_taken.iter().copied());
535            __arcade_t.extend([#(#own_taken),*]);
536        };
537        if let Some(inner) = opt_inner {
538            field_lets.push(quote! {
539                let #fident: #ty = {
540                    #taken_stmt
541                    // Visible-to-the-child check uses the CHILD's taken set —
542                    // the parent's incoming list alone would let an
543                    // all-consumed map through to a doomed decode.
544                    if __arcade_props
545                        .keys()
546                        .any(|__arcade_k| !__arcade_t.contains(&__arcade_k.as_str()))
547                    {
548                        ::core::option::Option::Some(
549                            <#inner as #crate_path::record::DecodeFromMap>::from_map(
550                                __arcade_props,
551                                &__arcade_t,
552                                ::core::option::Option::None,
553                                ::core::option::Option::None,
554                            )
555                            .map_err(|e| e.with_field(stringify!(#fident)))?
556                        )
557                    } else {
558                        ::core::option::Option::None
559                    }
560                };
561            });
562        } else {
563            field_lets.push(quote! {
564                #taken_stmt
565                let #fident: #ty = <#ty as #crate_path::record::DecodeFromMap>::from_map(
566                    __arcade_props,
567                    &__arcade_t,
568                    ::core::option::Option::None,
569                    ::core::option::Option::None,
570                )
571                .map_err(|e| e.with_field(stringify!(#fident)))?;
572            });
573        }
574    }
575
576    let assigns = fields.named.iter().map(|f| {
577        let ident = f.ident.as_ref().expect("named field ident");
578        quote! { #ident }
579    });
580
581    // The record path borrows the property map directly — `@rid`/`@type`
582    // fields read a fallback from the `rid`/`type` args lazily, so no whole
583    // property-map clone is needed when synthesizing metadata.
584    let synth = quote! {
585        let __arcade_props = &rec.properties;
586    };
587
588    let BorrowCfg {
589        clause,
590        inherent_clause,
591        self_ty,
592        helper_clause,
593        lt,
594        owned_try_from,
595    } = borrow;
596    // Record-level `TryFrom<GrpcRecord>` only makes sense when the DTO owns
597    // its data: a borrowing struct cannot outlive the owned record it would
598    // borrow from. The record-level path (repo rows) is owned anyway.
599    let owned_try_from = owned_try_from.then(|| {
600        quote! {
601            #[automatically_derived]
602            impl ::core::convert::TryFrom<#crate_path::GrpcRecord> for #self_ty {
603                type Error = #crate_path::record::RecordDecodeError;
604
605                fn try_from(
606                    rec: #crate_path::GrpcRecord,
607                ) -> ::std::result::Result<Self, Self::Error> {
608                    Self::try_from(&rec)
609                }
610            }
611        }
612    });
613
614    Ok(quote! {
615        #[automatically_derived]
616        // Field idents are re-used as local bindings in the decode helper;
617        // unconventional DTO names (e.g. acronym fields) must not warn from
618        // generated code.
619        #[allow(non_snake_case)]
620        impl #inherent_clause #self_ty {
621            #[doc(hidden)]
622            #[allow(clippy::too_many_arguments)]
623            fn __arcade_decode_from_map #helper_clause (
624                __arcade_props: & #lt ::std::collections::HashMap<
625                    ::std::string::String,
626                    #crate_path::GrpcValue,
627                >,
628                __arcade_taken: &[&str],
629                __arcade_syn_rid: ::core::option::Option<&::std::string::String>,
630                __arcade_syn_type: ::core::option::Option<&::std::string::String>,
631            ) -> ::std::result::Result<Self, #crate_path::record::RecordDecodeError> {
632                #(#field_lets)*
633                ::std::result::Result::Ok(Self { #(#assigns),* })
634            }
635
636            /// Wire names of every readable column, in declaration order —
637            /// the canonical SELECT list for this DTO. Skipped fields are
638            /// not read; flattened fields consume "the rest" (their own
639            /// `WIRES` describe their columns).
640            pub const WIRES: &'static [&'static str] = &[#(#non_flat_keys),*];
641
642            /// [`Self::WIRES`] as an inline SQL SELECT list (`"a, b, c"`),
643            /// computed once per DTO — callers invoke this per query, and
644            /// the join need not repeat. The leaked `String` lives for the
645            /// process lifetime, exactly once per type.
646            pub fn select_list() -> &'static str {
647                static LIST: ::std::sync::OnceLock<&'static str> = ::std::sync::OnceLock::new();
648                LIST.get_or_init(|| Self::WIRES.join(", ").leak())
649            }
650
651            /// Expected ArcadeDB column types, for schema-drift checks
652            /// (`arcadedb-migrate`'s `assert_dto_kinds`): `(wire name,
653            /// canonical type)` for every field with a known mapping.
654            /// Custom `with` fields, flatten targets, and dynamic values are
655            /// absent — they cannot be statically typed against a column.
656            pub const WIRE_KINDS: &'static [(&'static str, &'static str)] =
657                &[#(#wire_kind_pairs),*];
658        }
659
660        #[automatically_derived]
661        impl #clause #crate_path::record::DecodeFromMap<#lt> for #self_ty {
662            fn from_map(
663                __arcade_props: & #lt ::std::collections::HashMap<
664                    ::std::string::String,
665                    #crate_path::GrpcValue,
666                >,
667                __arcade_taken: &[&str],
668                __arcade_syn_rid: ::core::option::Option<&::std::string::String>,
669                __arcade_syn_type: ::core::option::Option<&::std::string::String>,
670            ) -> ::std::result::Result<Self, #crate_path::record::RecordDecodeError> {
671                Self::__arcade_decode_from_map(
672                    __arcade_props,
673                    __arcade_taken,
674                    __arcade_syn_rid,
675                    __arcade_syn_type,
676                )
677            }
678        }
679
680        #[automatically_derived]
681        impl #clause #crate_path::record::FromGrpcValue<#lt> for #self_ty {
682            fn from_grpc_value(
683                __arcade_v: & #lt #crate_path::GrpcValue,
684            ) -> ::std::result::Result<Self, #crate_path::record::RecordDecodeError> {
685                match &__arcade_v.kind {
686                    ::core::option::Option::Some(#crate_path::Kind::EmbeddedValue(__arcade_e)) => {
687                        Self::__arcade_decode_from_map(
688                            &__arcade_e.fields,
689                            &[],
690                            ::core::option::Option::None,
691                            ::core::option::Option::None,
692                        )
693                    }
694                    ::core::option::Option::Some(#crate_path::Kind::MapValue(__arcade_m)) => {
695                        Self::__arcade_decode_from_map(
696                            &__arcade_m.entries,
697                            &[],
698                            ::core::option::Option::None,
699                            ::core::option::Option::None,
700                        )
701                    }
702                    _ => ::std::result::Result::Err(
703                        #crate_path::record::RecordDecodeError::type_mismatch(
704                            "embedded record",
705                            #crate_path::record::kind_name(&__arcade_v.kind),
706                        ),
707                    ),
708                }
709            }
710        }
711
712        #[automatically_derived]
713        impl #clause ::core::convert::TryFrom<&#lt #crate_path::GrpcRecord>
714            for #self_ty
715        {
716            type Error = #crate_path::record::RecordDecodeError;
717
718            fn try_from(rec: &#lt #crate_path::GrpcRecord) -> ::std::result::Result<Self, Self::Error> {
719                #synth
720                Self::__arcade_decode_from_map(
721                    __arcade_props,
722                    &[],
723                    (!rec.rid.is_empty()).then_some(&rec.rid),
724                    (!rec.r#type.is_empty()).then_some(&rec.r#type),
725                )
726            }
727        }
728
729        #owned_try_from
730    })
731}
732
733// ---------------------------------------------------------------------------
734// Tuple structs
735// ---------------------------------------------------------------------------
736
737/// Single-field tuple structs (`#[serde(transparent)]` newtypes, like an id
738/// wrapper) delegate to their inner type: a field of `Wrapper(Inner)` decodes
739/// exactly like a field of `Inner`. A record-level `TryFrom` is intentionally
740/// NOT generated — a newtype has no property map of its own, so a missing
741/// impl fails at compile time.
742fn expand_tuple_struct(
743    name: &Ident,
744    data: &syn::DataStruct,
745    container: &ContainerCfg,
746    borrow: &BorrowCfg,
747) -> syn::Result<TokenStream2> {
748    let crate_path = &container.crate_path;
749    match &data.fields {
750        Fields::Unnamed(fields) if fields.unnamed.len() == 1 => {
751            let inner = &fields.unnamed[0].ty;
752            let BorrowCfg {
753                clause,
754                self_ty,
755                lt,
756                ..
757            } = borrow;
758
759            Ok(quote! {
760                #[automatically_derived]
761                impl #clause #crate_path::record::FromGrpcValue<#lt>
762                    for #self_ty
763                {
764                    fn from_grpc_value(
765                        __arcade_v: & #lt #crate_path::GrpcValue,
766                    ) -> ::std::result::Result<Self, #crate_path::record::RecordDecodeError> {
767                        let __arcade_inner =
768                            <#inner as #crate_path::record::FromGrpcValue<#lt>>::from_grpc_value(
769                                __arcade_v,
770                            )?;
771                        ::std::result::Result::Ok(#name(__arcade_inner))
772                    }
773                }
774            })
775        }
776        // Unit structs and multi-field tuple structs map to no property shape —
777        // no impls (a use site then fails to compile).
778        _ => Ok(quote! {}),
779    }
780}
781
782// ---------------------------------------------------------------------------
783// Enum expansion (unit variants only; string kind on the wire)
784// ---------------------------------------------------------------------------
785
786fn expand_enum(
787    name: &Ident,
788    data: &DataEnum,
789    container: &ContainerCfg,
790    borrow: &BorrowCfg,
791) -> syn::Result<TokenStream2> {
792    let crate_path = &container.crate_path;
793
794    // `#[serde(tag = "...")]` — internally-tagged: the wire is a map whose
795    // discriminator key selects the variant, then the remaining keys decode as
796    // the variant's struct fields.
797    if let Some(tag) = &container.tag {
798        return expand_internally_tagged_enum(name, data, container, tag, borrow);
799    }
800
801    let mut variants = Vec::new();
802    for variant in &data.variants {
803        if !matches!(variant.fields, Fields::Unit) {
804            return Err(syn::Error::new(
805                variant.span(),
806                "RecordDecode on enums supports unit variants only; \
807                 for data-carrying variants implement `FromGrpcValue` manually \
808                 (or decode with `#[record(with = \"...\")]`)",
809            ));
810        }
811        let vident = &variant.ident;
812        let wire = variant_wire_name(variant, container)?;
813        variants.push(quote! { #wire => ::core::result::Result::Ok(Self::#vident) });
814    }
815
816    let BorrowCfg {
817        clause,
818        self_ty,
819        lt,
820        ..
821    } = borrow;
822    Ok(quote! {
823        #[automatically_derived]
824        impl #clause #crate_path::record::FromGrpcValue<#lt> for #self_ty {
825            fn from_grpc_value(
826                __arcade_v: & #lt #crate_path::GrpcValue,
827            ) -> ::std::result::Result<Self, #crate_path::record::RecordDecodeError> {
828                let __arcade_s = match &__arcade_v.kind {
829                    ::core::option::Option::Some(#crate_path::Kind::StringValue(__arcade_s)) => {
830                        __arcade_s.as_str()
831                    }
832                    _ => {
833                        return ::std::result::Result::Err(
834                            #crate_path::record::RecordDecodeError::type_mismatch(
835                                "string",
836                                #crate_path::record::kind_name(&__arcade_v.kind),
837                            ),
838                        )
839                    }
840                };
841                match __arcade_s {
842                    #(#variants,)*
843                    __other => ::std::result::Result::Err(
844                        #crate_path::record::RecordDecodeError::unknown_variant(__other),
845                    ),
846                }
847            }
848        }
849    })
850}
851
852/// Internally-tagged enums (`#[serde(tag = "...")]`): the wire value is an
853/// embedded/map record carrying a discriminator key, followed by the selected
854/// variant's fields.
855///
856/// Emits BOTH decode routes: `FromGrpcValue` (embedded/map values) and
857/// `DecodeFromMap` (the zero-copy flatten path — reads the record's own map
858/// with the parent's taken keys hidden).
859fn expand_internally_tagged_enum(
860    _name: &Ident,
861    data: &DataEnum,
862    container: &ContainerCfg,
863    tag: &str,
864    borrow: &BorrowCfg,
865) -> syn::Result<TokenStream2> {
866    let crate_path = &container.crate_path;
867    let props = syn::Ident::new("__arcade_map", proc_macro2::Span::call_site());
868
869    let mut arms = Vec::new();
870    for variant in &data.variants {
871        let vident = &variant.ident;
872        let wire = variant_wire_name(variant, container)?;
873        match &variant.fields {
874            Fields::Unit => {
875                arms.push(quote! { #wire => ::std::result::Result::Ok(Self::#vident) });
876            }
877            Fields::Named(fields) => {
878                let lets = variant_field_lets(fields, container, &props)?;
879                let assigns = fields
880                    .named
881                    .iter()
882                    .map(|f| f.ident.as_ref().expect("named field ident"));
883                arms.push(quote! {
884                    #wire => {
885                        #(#lets)*
886                        ::std::result::Result::Ok(Self::#vident { #(#assigns),* })
887                    }
888                });
889            }
890            Fields::Unnamed(_) => {
891                return Err(syn::Error::new(
892                    variant.span(),
893                    "RecordDecode on internally-tagged enums supports struct variants only",
894                ));
895            }
896        }
897    }
898
899    let BorrowCfg {
900        clause,
901        self_ty,
902        lt,
903        ..
904    } = borrow;
905
906    // The discriminator walk: shared by the value path (from_grpc_value)
907    // and the map path (DecodeFromMap — the zero-copy flatten route).
908    let walk = quote! {
909        let __arcade_tag = match #crate_path::record::visible(__arcade_map, #tag, __arcade_taken) {
910            ::core::option::Option::Some(__arcade_t) => __arcade_t,
911            ::core::option::Option::None => {
912                return ::std::result::Result::Err(
913                    #crate_path::record::RecordDecodeError::missing_field(#tag),
914                )
915            }
916        };
917        let __arcade_wire = match &__arcade_tag.kind {
918            ::core::option::Option::Some(#crate_path::Kind::StringValue(__arcade_s)) => {
919                __arcade_s.as_str()
920            }
921            _ => {
922                return ::std::result::Result::Err(
923                    #crate_path::record::RecordDecodeError::type_mismatch(
924                        "string",
925                        #crate_path::record::kind_name(&__arcade_tag.kind),
926                    ),
927                )
928            }
929        };
930        match __arcade_wire {
931            #(#arms,)*
932            __other => ::std::result::Result::Err(
933                #crate_path::record::RecordDecodeError::unknown_variant(__other),
934            ),
935        }
936    };
937
938    Ok(quote! {
939        #[automatically_derived]
940        impl #clause #crate_path::record::FromGrpcValue<#lt> for #self_ty {
941            fn from_grpc_value(
942                __arcade_v: & #lt #crate_path::GrpcValue,
943            ) -> ::std::result::Result<Self, #crate_path::record::RecordDecodeError> {
944                // Via the value path no keys are ever hidden from the enum.
945                let __arcade_taken: &[&str] = &[];
946                let __arcade_map = match &__arcade_v.kind {
947                    ::core::option::Option::Some(#crate_path::Kind::EmbeddedValue(__arcade_e)) => {
948                        &__arcade_e.fields
949                    }
950                    ::core::option::Option::Some(#crate_path::Kind::MapValue(__arcade_m)) => {
951                        &__arcade_m.entries
952                    }
953                    _ => {
954                        return ::std::result::Result::Err(
955                            #crate_path::record::RecordDecodeError::type_mismatch(
956                                "record/map",
957                                #crate_path::record::kind_name(&__arcade_v.kind),
958                            ),
959                        )
960                    }
961                };
962                #walk
963            }
964        }
965
966        #[automatically_derived]
967        impl #clause #crate_path::record::DecodeFromMap<#lt> for #self_ty {
968            fn from_map(
969                __arcade_props: & #lt ::std::collections::HashMap<
970                    ::std::string::String,
971                    #crate_path::GrpcValue,
972                >,
973                __arcade_taken: &[&str],
974                _syn_rid: ::core::option::Option<&::std::string::String>,
975                _syn_type: ::core::option::Option<&::std::string::String>,
976            ) -> ::std::result::Result<Self, #crate_path::record::RecordDecodeError> {
977                let __arcade_map = __arcade_props;
978                #walk
979            }
980        }
981    })
982}
983
984/// Per-field decoders for a struct variant. Same policy as struct fields
985/// (rename/`Option`/`default`/`with`/`skip`) minus flatten, which is not
986/// supported inside variants.
987fn variant_field_lets(
988    fields: &syn::FieldsNamed,
989    container: &ContainerCfg,
990    props: &syn::Ident,
991) -> syn::Result<Vec<TokenStream2>> {
992    let crate_path = &container.crate_path;
993
994    let mut lets = Vec::new();
995    for field in &fields.named {
996        let fident = field.ident.as_ref().expect("named field ident").clone();
997        let cfg = FieldCfg::parse(field)?;
998        let ty = &field.ty;
999
1000        if cfg.flatten {
1001            return Err(syn::Error::new(
1002                field.span(),
1003                "RecordDecode: `flatten` is not supported inside enum variants",
1004            ));
1005        }
1006        if cfg.skip_decode {
1007            lets.push(quote! {
1008                let #fident: #ty = ::core::default::Default::default();
1009            });
1010            continue;
1011        }
1012
1013        let wire = match (&cfg.rename, container.rename_all_fields) {
1014            (Some(r), _) => r.clone(),
1015            (None, Some(rule)) => rule.apply_to_field(&fident.to_string()),
1016            (None, None) => fident.to_string(),
1017        };
1018
1019        // `#[record(with = "...")]` — honor `Option<T>` and `#[serde(default)]`.
1020        if let Some(with_path) = &cfg.with {
1021            if let Some(inner) = option_inner(ty) {
1022                lets.push(quote! {
1023                    let #fident: #ty = #crate_path::record::get_opt_with::<#inner>(
1024                        #props,
1025                        __arcade_taken,
1026                        #wire,
1027                        #with_path,
1028                    )?;
1029                });
1030            } else if cfg.default.is_some() {
1031                let fallback = default_fallback(&cfg.default);
1032                lets.push(quote! {
1033                    let #fident: #ty = #crate_path::record::get_with_or::<#ty>(
1034                        #props,
1035                        __arcade_taken,
1036                        #wire,
1037                        #with_path,
1038                        #fallback,
1039                    )?;
1040                });
1041            } else {
1042                lets.push(quote! {
1043                    let #fident: #ty = #crate_path::record::get_with::<#ty>(
1044                        #props,
1045                        __arcade_taken,
1046                        #wire,
1047                        #with_path,
1048                    )?;
1049                });
1050            }
1051            continue;
1052        }
1053
1054        if option_inner(ty).is_some() {
1055            lets.push(quote! {
1056                let #fident: #ty = #crate_path::record::get_opt(
1057                    #props,
1058                    __arcade_taken,
1059                    #wire,
1060                )?;
1061            });
1062            continue;
1063        }
1064
1065        match &cfg.default {
1066            None => {
1067                lets.push(quote! {
1068                    let #fident: #ty = #crate_path::record::get(#props, __arcade_taken, #wire)?;
1069                });
1070            }
1071            Some(None) => {
1072                lets.push(quote! {
1073                    let #fident: #ty = #crate_path::record::get_or(
1074                        #props,
1075                        __arcade_taken,
1076                        #wire,
1077                        ::core::default::Default::default,
1078                    )?;
1079                });
1080            }
1081            Some(Some(path)) => {
1082                lets.push(quote! {
1083                    let #fident: #ty = #crate_path::record::get_or(
1084                        #props,
1085                        __arcade_taken,
1086                        #wire,
1087                        #path,
1088                    )?;
1089                });
1090            }
1091        }
1092    }
1093    Ok(lets)
1094}
1095
1096/// Fallback expression for a parsed `#[serde(default)]` (the `Some(_)` side
1097/// only — callers guard on the default being present).
1098fn default_fallback(default: &Option<Option<syn::Path>>) -> TokenStream2 {
1099    match default {
1100        Some(None) => quote! { ::core::default::Default::default },
1101        Some(Some(path)) => quote! { #path },
1102        // Caller guarantees this branch only fires when a default is declared.
1103        None => quote! { ::core::default::Default::default },
1104    }
1105}
1106
1107/// Wire form of an enum variant: explicit `#[serde(rename)]` wins, else the
1108/// container rule (serde's exact `apply_to_variant`), else the variant ident
1109/// as-is.
1110fn variant_wire_name(variant: &syn::Variant, container: &ContainerCfg) -> syn::Result<String> {
1111    for attr in &variant.attrs {
1112        if attr.path().is_ident("serde") {
1113            let mut rename = None;
1114            let mut serialize_rename = None;
1115            attr.parse_nested_meta(|meta| {
1116                if meta.path.is_ident("rename") {
1117                    parse_rename(&meta, &mut rename, &mut serialize_rename)?;
1118                } else {
1119                    ignore_meta(&meta)?;
1120                }
1121                Ok(())
1122            })?;
1123            if let Some(r) = rename {
1124                return Ok(r);
1125            }
1126        }
1127    }
1128    if let Some(rule) = container.rename_all {
1129        return Ok(rule.apply_to_variant(&variant.ident.to_string()));
1130    }
1131    Ok(variant.ident.to_string())
1132}
1133
1134// ---------------------------------------------------------------------------
1135// Attribute parsing
1136// ---------------------------------------------------------------------------
1137
1138/// Container-level `#[record(...)]` / `#[serde(...)]` config.
1139struct ContainerCfg {
1140    crate_path: syn::Path,
1141    rename_all: Option<RenameRule>,
1142    /// `#[serde(rename_all = "...")]` applied to *variant fields* (serde's
1143    /// `rename_all_fields`) — names variant fields, unlike `rename_all`,
1144    /// which names variants.
1145    rename_all_fields: Option<RenameRule>,
1146    /// `#[serde(tag = "...")]` — the enum is internally tagged; the wire is a
1147    /// map carrying a discriminator key, followed by the variant's fields.
1148    tag: Option<String>,
1149}
1150
1151impl ContainerCfg {
1152    fn parse(input: &DeriveInput) -> syn::Result<Self> {
1153        let mut crate_path: Option<syn::Path> = None;
1154        let mut rename_all: Option<RenameRule> = None;
1155        let mut rename_all_fields: Option<RenameRule> = None;
1156        let mut tag: Option<String> = None;
1157
1158        for attr in &input.attrs {
1159            if attr.path().is_ident("serde") {
1160                attr.parse_nested_meta(|meta| {
1161                    if meta.path.is_ident("rename_all") || meta.path.is_ident("rename_all_fields") {
1162                        let value = meta.value()?;
1163                        let s: syn::LitStr = value.parse()?;
1164                        let rule = RenameRule::parse(&s.value()).ok_or_else(|| {
1165                            meta.error(format!(
1166                                "unknown rename_all rule `{}`; expected one of `lowercase`, \
1167                                 `UPPERCASE`, `PascalCase`, `camelCase`, `snake_case`, \
1168                                 `SCREAMING_SNAKE_CASE`, `kebab-case`, `SCREAMING-KEBAB-CASE`",
1169                                s.value(),
1170                            ))
1171                        })?;
1172                        if meta.path.is_ident("rename_all") {
1173                            rename_all = Some(rule);
1174                        } else {
1175                            rename_all_fields = Some(rule);
1176                        }
1177                        Ok(())
1178                    } else if meta.path.is_ident("tag") {
1179                        let value = meta.value()?;
1180                        let s: syn::LitStr = value.parse()?;
1181                        tag = Some(s.value());
1182                        Ok(())
1183                    } else {
1184                        // Foreign serde meta (`untagged`, `deny_unknown_fields`, ...).
1185                        ignore_meta(&meta)
1186                    }
1187                })?;
1188            } else if attr.path().is_ident("record") {
1189                attr.parse_nested_meta(|meta| {
1190                    if meta.path.is_ident("crate_path") {
1191                        let value = meta.value()?;
1192                        let s: syn::LitStr = value.parse()?;
1193                        crate_path = Some(s.parse()?);
1194                        Ok(())
1195                    } else {
1196                        Err(meta.error("unknown `record` container attribute"))
1197                    }
1198                })?;
1199            }
1200        }
1201
1202        Ok(Self {
1203            crate_path: crate_path.unwrap_or_else(|| syn::parse_quote!(::arcadedb_protocol)),
1204            rename_all,
1205            rename_all_fields,
1206            tag,
1207        })
1208    }
1209}
1210
1211/// Field-level `#[record(...)]` + relevant `#[serde(...)]` config.
1212struct FieldCfg {
1213    /// Wire property name (the `deserialize` side of a two-sided `rename`).
1214    rename: Option<String>,
1215    /// The `serialize` side of a two-sided `rename(serialize = "...",
1216    /// deserialize = "...")`; the `=` form sets both. `RecordEncode` prefers
1217    /// this and falls back to `rename` when only one side is declared.
1218    serialize_rename: Option<String>,
1219    /// `None` = no default attr; `Some(None)` = bare `default`;
1220    /// `Some(Some(path))` = `default = "path"`.
1221    default: Option<Option<syn::Path>>,
1222    /// Custom conversion: decode `fn(&GrpcValue) -> Result<T, RecordDecodeError>`,
1223    /// encode `fn(&T) -> GrpcValue`. Direction depends on which derive reads it.
1224    with: Option<syn::Path>,
1225    /// Skip the field when DECODING (serde's `skip` and `skip_deserializing`).
1226    skip_decode: bool,
1227    /// Skip the field when ENCODING (serde's `skip` and `skip_serializing`).
1228    skip_encode: bool,
1229    /// `#[serde(skip_serializing_if = "path")]` — omit the property at encode
1230    /// time when the predicate returns true.
1231    skip_serializing_if: Option<syn::Path>,
1232    /// `#[record(key)]` — the field is part of the bulk-conflict identity
1233    /// (`ToGrpcRecord::KEY_COLUMNS`). Record-namespace only: serde has no
1234    /// `key` spelling, and the tolerance policy must not swallow it.
1235    key: bool,
1236    flatten: bool,
1237}
1238
1239impl FieldCfg {
1240    fn parse(field: &syn::Field) -> syn::Result<Self> {
1241        let mut cfg = FieldCfg {
1242            rename: None,
1243            serialize_rename: None,
1244            default: None,
1245            with: None,
1246            skip_decode: false,
1247            skip_encode: false,
1248            skip_serializing_if: None,
1249            key: false,
1250            flatten: false,
1251        };
1252
1253        for attr in &field.attrs {
1254            if attr.path().is_ident("serde") {
1255                attr.parse_nested_meta(|meta| Self::parse_meta(&mut cfg, &meta, false))?;
1256            } else if attr.path().is_ident("record") {
1257                attr.parse_nested_meta(|meta| Self::parse_meta(&mut cfg, &meta, true))?;
1258            }
1259        }
1260        Ok(cfg)
1261    }
1262
1263    /// One dispatcher for both namespaces. Shared keys (`rename`, `default`,
1264    /// `flatten`) behave identically; `with`/`skip`/`crate_path` are
1265    /// `record`-only. The unknown-key policy differs by design: the `serde`
1266    /// namespace *tolerates* foreign serde meta we don't model
1267    /// (`skip_serializing_if`, `borrow`, ...), while the `record` namespace
1268    /// *rejects* unknown keys — typos of our own attributes must not pass
1269    /// silently.
1270    fn parse_meta(
1271        cfg: &mut FieldCfg,
1272        meta: &syn::meta::ParseNestedMeta<'_>,
1273        record_ns: bool,
1274    ) -> syn::Result<()> {
1275        if meta.path.is_ident("rename") {
1276            parse_rename(meta, &mut cfg.rename, &mut cfg.serialize_rename)
1277        } else if meta.path.is_ident("default") {
1278            parse_default(meta, &mut cfg.default)
1279        } else if meta.path.is_ident("flatten") {
1280            cfg.flatten = true;
1281            Ok(())
1282        } else if meta.path.is_ident("skip") {
1283            // serde's bare `skip` is bidirectional; the directional spellings
1284            // (`skip_serializing`, `skip_deserializing`) must stay directional.
1285            cfg.skip_decode = true;
1286            cfg.skip_encode = true;
1287            Ok(())
1288        } else if meta.path.is_ident("skip_serializing") {
1289            cfg.skip_encode = true;
1290            Ok(())
1291        } else if meta.path.is_ident("skip_deserializing") {
1292            cfg.skip_decode = true;
1293            Ok(())
1294        } else if meta.path.is_ident("skip_serializing_if") {
1295            let value = meta.value()?;
1296            let s: syn::LitStr = value.parse()?;
1297            cfg.skip_serializing_if = Some(s.parse()?);
1298            Ok(())
1299        } else if record_ns
1300            && (meta.path.is_ident("with") || meta.path.is_ident("deserialize_with"))
1301        {
1302            let value = meta.value()?;
1303            let s: syn::LitStr = value.parse()?;
1304            cfg.with = Some(s.parse()?);
1305            Ok(())
1306        } else if record_ns && meta.path.is_ident("key") {
1307            // Bulk-conflict identity (RecordEncode): the field's wire name
1308            // lands in `ToGrpcRecord::KEY_COLUMNS`.
1309            cfg.key = true;
1310            Ok(())
1311        } else if record_ns && meta.path.is_ident("crate_path") {
1312            Err(meta.error("`crate_path` is a container-level attribute"))
1313        } else if record_ns {
1314            Err(meta.error("unknown `record` attribute"))
1315        } else {
1316            // Foreign serde meta (`borrow`, `untagged`, ...) — tolerate rather
1317            // than reject.
1318            ignore_meta(meta)
1319        }
1320    }
1321}
1322
1323/// `rename = "..."` plus the two-sided `rename(serialize = "...",
1324/// deserialize = "...")` form (decode reads the deserialize side, encode the
1325/// serialize side). Shared by field and variant attribute parsing.
1326fn parse_rename(
1327    meta: &syn::meta::ParseNestedMeta<'_>,
1328    rename: &mut Option<String>,
1329    serialize_rename: &mut Option<String>,
1330) -> syn::Result<()> {
1331    if meta.input.peek(syn::Token![=]) {
1332        let value = meta.value()?;
1333        let s: syn::LitStr = value.parse()?;
1334        let name = s.value();
1335        *rename = Some(name.clone());
1336        *serialize_rename = Some(name);
1337    } else {
1338        meta.parse_nested_meta(|inner| {
1339            if inner.path.is_ident("deserialize") {
1340                let value = inner.value()?;
1341                let s: syn::LitStr = value.parse()?;
1342                *rename = Some(s.value());
1343            } else if inner.path.is_ident("serialize") {
1344                let value = inner.value()?;
1345                let s: syn::LitStr = value.parse()?;
1346                *serialize_rename = Some(s.value());
1347            }
1348            ignore_meta(&inner)
1349        })?;
1350    }
1351    Ok(())
1352}
1353
1354/// `default` (bare) / `default = "path"`.
1355fn parse_default(
1356    meta: &syn::meta::ParseNestedMeta<'_>,
1357    default: &mut Option<Option<syn::Path>>,
1358) -> syn::Result<()> {
1359    if meta.input.peek(syn::Token![=]) {
1360        let value = meta.value()?;
1361        let s: syn::LitStr = value.parse()?;
1362        *default = Some(Some(s.parse()?));
1363    } else {
1364        *default = Some(None);
1365    }
1366    Ok(())
1367}
1368
1369// ---------------------------------------------------------------------------
1370// Helpers
1371// ---------------------------------------------------------------------------
1372
1373/// Consume and discard an unknown nested meta so the surrounding
1374/// `parse_nested_meta` doesn't fail on its trailing tokens. Handles bare
1375/// `name`, `name = value`, and `name(...)` forms; used to tolerate foreign
1376/// `serde` attributes (`skip_serializing_if`, `borrow`, `untagged`, ...).
1377fn ignore_meta(meta: &syn::meta::ParseNestedMeta<'_>) -> syn::Result<()> {
1378    if meta.input.peek(syn::Token![=]) {
1379        let _: syn::Expr = meta.value()?.parse()?;
1380    } else if meta.input.peek(syn::token::Paren) {
1381        let content;
1382        syn::parenthesized!(content in meta.input);
1383        let _: syn::punctuated::Punctuated<syn::Meta, syn::Token![,]> =
1384            content.parse_terminated(syn::parse::Parse::parse, syn::Token![,])?;
1385    }
1386    Ok(())
1387}
1388
1389/// If `ty` is `Option<inner>` (any `Option` spelling), return `inner`.
1390fn option_inner(ty: &Type) -> Option<Type> {
1391    let Type::Path(tp) = ty else { return None };
1392    let seg = tp.path.segments.last()?;
1393    if seg.ident != "Option" {
1394        return None;
1395    }
1396    let PathArguments::AngleBracketed(args) = &seg.arguments else {
1397        return None;
1398    };
1399    match args.args.last() {
1400        Some(GenericArgument::Type(inner)) => Some(inner.clone()),
1401        _ => None,
1402    }
1403}
1404
1405/// If `ty` is `Vec<u8>` (any `Vec` spelling with a single `u8` argument),
1406/// true — such fields are byte blobs (wire `bytes`), not int lists.
1407fn vec_u8(ty: &Type) -> bool {
1408    let Type::Path(tp) = ty else { return false };
1409    let Some(seg) = tp.path.segments.last() else {
1410        return false;
1411    };
1412    if seg.ident != "Vec" {
1413        return false;
1414    }
1415    let PathArguments::AngleBracketed(args) = &seg.arguments else {
1416        return false;
1417    };
1418    matches!(
1419        args.args.last(),
1420        Some(GenericArgument::Type(Type::Path(t))) if t.path.is_ident("u8")
1421    )
1422}
1423
1424/// Does `ty` mention a (borrowed) lifetime anywhere? Borrowed field targets
1425/// (`&'de str`, `Cow<'de, str>`, …) cannot be the target of the `@rid`/`@type`
1426/// synth fallback — the fallback value is carried by a temporary that would
1427/// not outlive a borrowed view into it.
1428fn type_has_lifetime(ty: &Type) -> bool {
1429    match ty {
1430        Type::Path(tp) => tp.path.segments.iter().any(|seg| {
1431            let PathArguments::AngleBracketed(args) = &seg.arguments else {
1432                return false;
1433            };
1434            args.args.iter().any(|arg| match arg {
1435                GenericArgument::Lifetime(_) => true,
1436                GenericArgument::Type(inner) => type_has_lifetime(inner),
1437                _ => false,
1438            })
1439        }),
1440        Type::Reference(r) => r.lifetime.is_some() || type_has_lifetime(&r.elem),
1441        Type::Tuple(tuple) => tuple.elems.iter().any(type_has_lifetime),
1442        Type::Paren(paren) => type_has_lifetime(&paren.elem),
1443        Type::Group(group) => type_has_lifetime(&group.elem),
1444        _ => false,
1445    }
1446}
1447
1448/// Field-let for a synthetic `@rid` / `@type` property: decode the real
1449/// property when present, otherwise fall back to the record's own `rid` /
1450/// `type` (reached through the `__arcade_syn_*` args — no whole-map clone).
1451/// Honors `Option<T>` and `#[serde(default)]` like the regular field paths.
1452fn synth_field_let(
1453    fident: &Ident,
1454    ty: &Type,
1455    wire: &str,
1456    default: &Option<Option<syn::Path>>,
1457    syn: &TokenStream2,
1458    crate_path: &syn::Path,
1459) -> syn::Result<TokenStream2> {
1460    let owned_guard = |target: &Type| {
1461        if type_has_lifetime(target) {
1462            Err(syn::Error::new(
1463                fident.span(),
1464                "RecordDecode: `@rid`/`@type` synthesis supports owned targets \
1465                 only (a borrowed target can't outlive the fallback value)",
1466            ))
1467        } else {
1468            Ok(())
1469        }
1470    };
1471
1472    // `Option<T>` — absent + no synth → `None`.
1473    if let Some(inner) = option_inner(ty) {
1474        owned_guard(&inner)?;
1475        return Ok(quote! {
1476            let #fident: #ty = match __arcade_props.get(#wire) {
1477                ::core::option::Option::Some(__arcade_v) => {
1478                    <::core::option::Option<#inner> as #crate_path::record::FromGrpcValue>::from_grpc_value(
1479                        __arcade_v,
1480                    )
1481                    .map_err(|e| e.with_field(#wire))?
1482                }
1483                ::core::option::Option::None => match #syn {
1484                    ::core::option::Option::Some(__arcade_s) => {
1485                        let __arcade_syn_gv = #crate_path::GrpcValue {
1486                            kind: ::core::option::Option::Some(
1487                                #crate_path::Kind::StringValue(__arcade_s.clone()),
1488                            ),
1489                            logical_type: ::std::string::String::new(),
1490                        };
1491                        ::core::option::Option::Some(
1492                            <#inner as #crate_path::record::FromGrpcValue>::from_grpc_value(
1493                                &__arcade_syn_gv,
1494                            )
1495                            .map_err(|e| e.with_field(#wire))?,
1496                        )
1497                    }
1498                    ::core::option::Option::None => ::core::option::Option::None,
1499                },
1500            };
1501        });
1502    }
1503
1504    owned_guard(ty)?;
1505
1506    let synth_occurrence = quote! {
1507        let __arcade_syn_gv = #crate_path::GrpcValue {
1508            kind: ::core::option::Option::Some(#crate_path::Kind::StringValue(
1509                __arcade_s.clone(),
1510            )),
1511            logical_type: ::std::string::String::new(),
1512        };
1513        <#ty as #crate_path::record::FromGrpcValue>::from_grpc_value(&__arcade_syn_gv)
1514            .map_err(|e| e.with_field(#wire))?
1515    };
1516    let absent = match default {
1517        None => quote! {
1518            ::std::result::Result::Err(#crate_path::record::RecordDecodeError::missing_field(
1519                #wire,
1520            ))?
1521        },
1522        Some(_) => default_fallback(default),
1523    };
1524
1525    Ok(quote! {
1526        let #fident: #ty = match __arcade_props.get(#wire) {
1527            ::core::option::Option::Some(__arcade_v) => {
1528                <#ty as #crate_path::record::FromGrpcValue>::from_grpc_value(__arcade_v)
1529                    .map_err(|e| e.with_field(#wire))?
1530            }
1531            ::core::option::Option::None => match #syn {
1532                // Braced: the synth occurrence is a statement block, not a
1533                // bare expression (required-`@rid` path).
1534                ::core::option::Option::Some(__arcade_s) => { #synth_occurrence }
1535                ::core::option::Option::None => #absent,
1536            },
1537        };
1538    })
1539}
1540
1541// ---------------------------------------------------------------------------
1542// RecordEncode — the write-side mirror of RecordDecode
1543// ---------------------------------------------------------------------------
1544
1545fn expand_encode_derive(input: &DeriveInput) -> syn::Result<TokenStream2> {
1546    let name = &input.ident;
1547    check_alt_hasher_fields(input)?;
1548    // Same generics policy as the decode side: at most one lifetime parameter
1549    // (write DTOs borrow `&str` fields from their inputs), no type/const
1550    // generics — the wire mapping is fully concrete per type.
1551    let lifetimes: Vec<&syn::LifetimeParam> = input
1552        .generics
1553        .params
1554        .iter()
1555        .filter_map(|p| match p {
1556            syn::GenericParam::Lifetime(lt) => Some(lt),
1557            _ => None,
1558        })
1559        .collect();
1560    if lifetimes.len() > 1 {
1561        return Err(syn::Error::new(
1562            input.generics.span(),
1563            "RecordEncode supports at most one lifetime parameter",
1564        ));
1565    }
1566    if let Some(p) = input
1567        .generics
1568        .params
1569        .iter()
1570        .find(|p| !matches!(p, syn::GenericParam::Lifetime(_)))
1571    {
1572        return Err(syn::Error::new(
1573            p.span(),
1574            "RecordEncode does not support type/const generic parameters",
1575        ));
1576    }
1577    let (impl_clause, self_ty) = match lifetimes.first() {
1578        Some(lt) => {
1579            let life = &lt.lifetime;
1580            (quote! { <#life> }, quote! { #name<#life> })
1581        }
1582        None => (quote! {}, quote! { #name }),
1583    };
1584
1585    let container = ContainerCfg::parse(input)?;
1586
1587    match &input.data {
1588        Data::Struct(data) => expand_encode_struct(data, &container, &impl_clause, &self_ty),
1589        Data::Enum(data) => expand_encode_enum(data, &container, &impl_clause, &self_ty),
1590        Data::Union(data) => Err(syn::Error::new(
1591            data.union_token.span(),
1592            "RecordEncode does not support unions",
1593        )),
1594    }
1595}
1596
1597/// Expand a `RecordEncode` enum — the write mirror of `RecordDecode`'s enum
1598/// support. Enums are VALUE-shaped: `to_grpc_value` is the meaningful method
1599/// (unit variants → their wire string; `#[serde(tag = "...")]` variants → a
1600/// map carrying the discriminator plus the variant's fields, exactly what
1601/// decode reads back). `props()` mirrors the tagged form's pairs so a tagged
1602/// enum can also be stored as a record; unit enums return no pairs.
1603fn expand_encode_enum(
1604    data: &DataEnum,
1605    container: &ContainerCfg,
1606    impl_clause: &TokenStream2,
1607    self_ty: &TokenStream2,
1608) -> syn::Result<TokenStream2> {
1609    let crate_path = &container.crate_path;
1610    let tagged = container.tag.as_deref();
1611
1612    let mut value_arms = Vec::new();
1613    let mut props_arms = Vec::new();
1614    for variant in &data.variants {
1615        let vident = &variant.ident;
1616        let wire = variant_wire_name(variant, container)?;
1617        match &variant.fields {
1618            Fields::Unit => {
1619                value_arms.push(quote! {
1620                    Self::#vident => #crate_path::__private::str_v(#wire)
1621                });
1622                props_arms.push(quote! {
1623                    Self::#vident => ::std::vec::Vec::new()
1624                });
1625            }
1626            Fields::Named(fields) => {
1627                let Some(tag) = tagged else {
1628                    return Err(syn::Error::new(
1629                        variant.span(),
1630                        "RecordEncode: data-carrying variants require `#[serde(tag = \"...\")]` \
1631                         (internally-tagged); plain unit-variant enums need no tag",
1632                    ));
1633                };
1634                let bindings = fields
1635                    .named
1636                    .iter()
1637                    .map(|f| f.ident.as_ref().expect("named field ident"))
1638                    .collect::<Vec<_>>();
1639                let pairs = variant_field_pairs(fields, container)?;
1640                // Capacity hint: discriminator + fields.
1641                let pairs_len = fields.named.len() + 1;
1642                // Value form: discriminator + fields, as a map.
1643                value_arms.push(quote! {
1644                    Self::#vident { #(#bindings),* } => {
1645                        let mut __arcade_pairs: ::std::vec::Vec<(
1646                            &str,
1647                            #crate_path::GrpcValue,
1648                        )> = ::std::vec::Vec::with_capacity(#pairs_len);
1649                        __arcade_pairs.push((#tag, #crate_path::__private::str_v(#wire)));
1650                        #pairs
1651                        #crate_path::GrpcValue {
1652                            kind: ::core::option::Option::Some(#crate_path::Kind::MapValue(
1653                                #crate_path::GrpcMap {
1654                                    entries: __arcade_pairs
1655                                        .into_iter()
1656                                        .map(|(k, v)| (k.to_string(), v))
1657                                        .collect(),
1658                                },
1659                            )),
1660                            logical_type: ::std::string::String::new(),
1661                        }
1662                    }
1663                });
1664                // Record form: the same pairs.
1665                props_arms.push(quote! {
1666                    Self::#vident { #(#bindings),* } => {
1667                        let mut __arcade_pairs: ::std::vec::Vec<(
1668                            &str,
1669                            #crate_path::GrpcValue,
1670                        )> = ::std::vec::Vec::with_capacity(#pairs_len);
1671                        __arcade_pairs.push((#tag, #crate_path::__private::str_v(#wire)));
1672                        #pairs
1673                        __arcade_pairs
1674                    }
1675                });
1676            }
1677            Fields::Unnamed(_) => {
1678                return Err(syn::Error::new(
1679                    variant.span(),
1680                    "RecordEncode on enums supports struct variants only",
1681                ));
1682            }
1683        }
1684    }
1685
1686    Ok(quote! {
1687        #[automatically_derived]
1688        impl #impl_clause #crate_path::record::ToGrpcRecord for #self_ty {
1689            fn props(&self) -> ::std::vec::Vec<(&str, #crate_path::GrpcValue)> {
1690                match self {
1691                    #(#props_arms,)*
1692                }
1693            }
1694
1695            fn to_grpc_value(&self) -> #crate_path::GrpcValue {
1696                match self {
1697                    #(#value_arms,)*
1698                }
1699            }
1700        }
1701    })
1702}
1703
1704/// `(name, value)` pair pushes for one struct variant's fields — the
1705/// encode-side mirror of `variant_field_lets` (same policy: rename/
1706/// `Option`-omission/`with`/skip; `flatten` unsupported inside variants).
1707/// Pairs append to a `__arcade_pairs` binding declared by the caller.
1708fn variant_field_pairs(
1709    fields: &syn::FieldsNamed,
1710    container: &ContainerCfg,
1711) -> syn::Result<TokenStream2> {
1712    let crate_path = &container.crate_path;
1713    let mut pushes = Vec::new();
1714    for field in &fields.named {
1715        let fident = field.ident.as_ref().expect("named field ident").clone();
1716        let cfg = FieldCfg::parse(field)?;
1717        let ty = &field.ty;
1718
1719        if cfg.flatten {
1720            return Err(syn::Error::new(
1721                field.span(),
1722                "RecordEncode: `flatten` is not supported inside enum variants",
1723            ));
1724        }
1725        if cfg.key {
1726            return Err(syn::Error::new(
1727                field.span(),
1728                "RecordEncode: `key` is not supported inside enum variants",
1729            ));
1730        }
1731
1732        let wire = match (
1733            &cfg.serialize_rename,
1734            &cfg.rename,
1735            container.rename_all_fields,
1736        ) {
1737            (Some(r), _, _) => r.clone(),
1738            (None, Some(r), _) => r.clone(),
1739            (None, None, Some(rule)) => rule.apply_to_field(&fident.to_string()),
1740            (None, None, None) => fident.to_string(),
1741        };
1742
1743        if cfg.skip_encode {
1744            continue;
1745        }
1746
1747        if let Some(with) = &cfg.with {
1748            if option_inner(ty).is_some() {
1749                pushes.push(quote! {
1750                    if let ::core::option::Option::Some(__arcade_f) = #fident {
1751                        __arcade_pairs.push((#wire, #with(__arcade_f)));
1752                    }
1753                });
1754            } else {
1755                pushes.push(quote! {
1756                    __arcade_pairs.push((#wire, #with(#fident)));
1757                });
1758            }
1759            continue;
1760        }
1761
1762        if let Some(inner) = option_inner(ty) {
1763            let val = encode_field_value(&inner, &quote! { __arcade_f }, crate_path)?;
1764            pushes.push(quote! {
1765                if let ::core::option::Option::Some(__arcade_f) = #fident {
1766                    __arcade_pairs.push((#wire, #val));
1767                }
1768            });
1769            continue;
1770        }
1771
1772        let val = encode_field_value(ty, &quote! { #fident }, crate_path)?;
1773        let push = quote! { __arcade_pairs.push((#wire, #val)); };
1774        if let Some(pred) = &cfg.skip_serializing_if {
1775            pushes.push(quote! {
1776                if !#pred(#fident) {
1777                    #push
1778                }
1779            });
1780        } else {
1781            pushes.push(push);
1782        }
1783    }
1784    Ok(quote! { #(#pushes)* })
1785}
1786
1787/// Expand a `RecordEncode` struct: `props()` over the named fields, mapping
1788/// each Rust type onto the matching `GrpcValue` wire kind.
1789fn expand_encode_struct(
1790    data: &syn::DataStruct,
1791    container: &ContainerCfg,
1792    impl_clause: &TokenStream2,
1793    self_ty: &TokenStream2,
1794) -> syn::Result<TokenStream2> {
1795    let Fields::Named(fields) = &data.fields else {
1796        return Err(syn::Error::new(
1797            data.fields.span(),
1798            "RecordEncode supports named-field structs only; newtype wrappers \
1799             plug in through `#[record(with = \"...\")]` on the field instead",
1800        ));
1801    };
1802
1803    let crate_path = &container.crate_path;
1804    let mut pushes = Vec::new();
1805    let mut move_pushes = Vec::new();
1806    let mut diff_conds = Vec::new();
1807    let mut key_wires: Vec<String> = Vec::new();
1808    for field in &fields.named {
1809        let fident = field.ident.as_ref().expect("named field ident").clone();
1810        let cfg = FieldCfg::parse(field)?;
1811        let ty = &field.ty;
1812
1813        let wire = match (&cfg.serialize_rename, &cfg.rename, container.rename_all) {
1814            (Some(r), _, _) => r.clone(),
1815            (None, Some(r), _) => r.clone(),
1816            (None, None, Some(rule)) => rule.apply_to_field(&fident.to_string()),
1817            (None, None, None) => fident.to_string(),
1818        };
1819
1820        if cfg.key {
1821            if cfg.skip_encode {
1822                return Err(syn::Error::new(
1823                    fident.span(),
1824                    "RecordEncode: `key` cannot be combined with `skip`",
1825                ));
1826            }
1827            key_wires.push(wire.clone());
1828        }
1829
1830        pushes.push(encode_field_push(&fident, ty, &wire, &cfg, crate_path)?);
1831        move_pushes.push(encode_field_push_move(
1832            &fident, ty, &wire, &cfg, crate_path,
1833        )?);
1834        diff_conds.push(diff_cond(&fident, ty, &wire, &cfg, crate_path));
1835    }
1836    // Upper bound for `props()`: one pair per field (skips push nothing) —
1837    // exact for skip-free DTOs, and never a growth reallocation either way.
1838    let props_capacity = fields.named.len();
1839
1840    Ok(quote! {
1841        #[automatically_derived]
1842        // Generated code widens a couple of ints onto kinds the wire supports;
1843        // `automatically_derived`-style allowances keep consumer clippy quiet.
1844        #[allow(clippy::cast_possible_wrap, clippy::cast_possible_truncation)]
1845        impl #impl_clause #crate_path::record::ToGrpcRecord for #self_ty {
1846            /// Conflict identity from the `#[record(key)]` fields — see
1847            /// `ToGrpcRecord::KEY_COLUMNS`.
1848            const KEY_COLUMNS: &'static [&'static str] = &[#(#key_wires),*];
1849
1850            fn props(&self) -> ::std::vec::Vec<(&str, #crate_path::GrpcValue)> {
1851                let mut __out: ::std::vec::Vec<(&str, #crate_path::GrpcValue)> =
1852                    ::std::vec::Vec::with_capacity(#props_capacity);
1853                #(#pushes)*
1854                __out
1855            }
1856
1857            /// Rust-value diff — no wire encoding; allocation proportional
1858            /// to the changed-column count (identical rows allocate nothing).
1859            fn changed_wires(&self, other: &Self) -> ::std::vec::Vec<::std::string::String> {
1860                let mut __arcade_changed: ::std::vec::Vec<::std::string::String> =
1861                    ::std::vec::Vec::new();
1862                #(#diff_conds)*
1863                __arcade_changed
1864            }
1865
1866            /// The moving encode: owned payloads (`String`, `Vec<u8>`,
1867            /// `Vec<String>`, `Cow<str>`) become wire values by MOVE, not
1868            /// clone. Types without a moving mapping encode through a borrow,
1869            /// as in `props()`.
1870            fn into_grpc_record(self, class: &str) -> #crate_path::GrpcRecord {
1871                let mut __out: ::std::vec::Vec<(&str, #crate_path::GrpcValue)> =
1872                    ::std::vec::Vec::with_capacity(#props_capacity);
1873                #(#move_pushes)*
1874                #crate_path::rec(class, __out)
1875            }
1876        }
1877    })
1878}
1879
1880/// The `changed_wires` condition for one field. `self` = old, `other` = new:
1881/// a column the NEW snapshot omits (`skip_serializing_if`) is never reported,
1882/// and an `Option` going `Some → None` is not SET-expressible — both match
1883/// `props_diff`'s semantics.
1884fn diff_cond(
1885    fident: &Ident,
1886    ty: &Type,
1887    wire: &str,
1888    cfg: &FieldCfg,
1889    crate_path: &syn::Path,
1890) -> TokenStream2 {
1891    let wire = syn::LitStr::new(wire, proc_macro2::Span::call_site());
1892    if cfg.skip_encode {
1893        return quote! {};
1894    }
1895    let is_option = option_inner(ty).is_some();
1896    let differs = if cfg.flatten {
1897        // The flatten target has no field-wise comparison here — fall back
1898        // to its encoded form (allocates; flatten is the rare shape).
1899        quote! {
1900            <#ty as #crate_path::record::ToGrpcRecord>::to_grpc_value(&self.#fident)
1901                != <#ty as #crate_path::record::ToGrpcRecord>::to_grpc_value(&other.#fident)
1902        }
1903    } else if let Some(w) = &cfg.with {
1904        if is_option {
1905            quote! { other.#fident.is_some() && #w(&self.#fident) != #w(&other.#fident) }
1906        } else {
1907            quote! { #w(&self.#fident) != #w(&other.#fident) }
1908        }
1909    } else if is_option {
1910        quote! { other.#fident.is_some() && self.#fident != other.#fident }
1911    } else {
1912        quote! { self.#fident != other.#fident }
1913    };
1914    let guarded = match &cfg.skip_serializing_if {
1915        Some(pred) => quote! { !#pred(&other.#fident) && (#differs) },
1916        None => differs,
1917    };
1918    quote! {
1919        if #guarded {
1920            __arcade_changed.push(#wire.to_string());
1921        }
1922    }
1923}
1924
1925/// One `into_grpc_record` push: the moving analogue of [`encode_field_push`].
1926/// Owned payloads of movable types are MOVED into the wire value; everything
1927/// else encodes through a borrow exactly like `props()`.
1928fn encode_field_push_move(
1929    fident: &Ident,
1930    ty: &Type,
1931    wire: &str,
1932    cfg: &FieldCfg,
1933    crate_path: &syn::Path,
1934) -> syn::Result<TokenStream2> {
1935    let wire = syn::LitStr::new(wire, proc_macro2::Span::call_site());
1936    if cfg.skip_encode {
1937        return Ok(quote! {});
1938    }
1939
1940    // Flatten and `with` have no moving form — borrow as in `props()`.
1941    if cfg.flatten || cfg.with.is_some() {
1942        let borrow = encode_field_push(fident, ty, wire.value().as_str(), cfg, crate_path)?;
1943        return Ok(borrow);
1944    }
1945
1946    let val_plain = encode_field_value_move(ty, &quote! { self.#fident }, crate_path);
1947    let push_plain = quote! { __out.push((#wire, #val_plain)); };
1948    if let Some(inner) = option_inner(ty) {
1949        let val_opt = encode_field_value_move(&inner, &quote! { __arcade_f }, crate_path);
1950        return Ok(quote! {
1951            if let ::core::option::Option::Some(__arcade_f) = self.#fident {
1952                __out.push((#wire, #val_opt));
1953            }
1954        });
1955    }
1956    if let Some(pred) = &cfg.skip_serializing_if {
1957        // The predicate borrows BEFORE the field moves.
1958        return Ok(quote! {
1959            if !#pred(&self.#fident) {
1960                #push_plain
1961            }
1962        });
1963    }
1964    Ok(push_plain)
1965}
1966
1967/// A moved-value wire expression: `String`/`Cow<str>`/`Vec<u8>`/
1968/// `Vec<String>`/scalars move; every other type falls back to the borrowing
1969/// mapping on a reference (same wire output, clone cost as in `props()`).
1970fn encode_field_value_move(ty: &Type, expr: &TokenStream2, crate_path: &syn::Path) -> TokenStream2 {
1971    if let Type::Reference(r) = ty {
1972        return encode_field_value(&r.elem, expr, crate_path)
1973            .unwrap_or_else(|e| e.to_compile_error());
1974    }
1975    let Type::Path(tp) = ty else {
1976        return encode_field_value(ty, expr, crate_path).unwrap_or_else(|e| e.to_compile_error());
1977    };
1978    let Some(seg) = tp.path.segments.last() else {
1979        return encode_field_value(ty, expr, crate_path).unwrap_or_else(|e| e.to_compile_error());
1980    };
1981    match seg.ident.to_string().as_str() {
1982        "String" => quote! { #crate_path::__private::str_v(#expr) },
1983        "char" => quote! { #crate_path::__private::str_v((#expr).to_string()) },
1984        "Cow" => {
1985            if let Ok(inner) = container_inner(ty, seg, "Cow") {
1986                match inner {
1987                    Type::Path(p) if p.path.is_ident("str") => {
1988                        quote! { #crate_path::__private::str_v((#expr).into_owned()) }
1989                    }
1990                    Type::Slice(sl) if matches!(&*sl.elem, Type::Path(p) if p.path.is_ident("u8")) =>
1991                    {
1992                        quote! { #crate_path::__private::bytes_v((#expr).into_owned()) }
1993                    }
1994                    _ => encode_field_value(ty, &quote! { &#expr }, crate_path)
1995                        .unwrap_or_else(|e| e.to_compile_error()),
1996                }
1997            } else {
1998                encode_field_value(ty, &quote! { &#expr }, crate_path)
1999                    .unwrap_or_else(|e| e.to_compile_error())
2000            }
2001        }
2002        "bool" => quote! { #crate_path::__private::bool_v(#expr) },
2003        "i32" => quote! { #crate_path::__private::i32_v(#expr) },
2004        "i8" | "i16" | "u8" | "u16" => quote! { #crate_path::__private::i32_v(i32::from(#expr)) },
2005        "i64" | "u32" => quote! { #crate_path::__private::i64_v(i64::from(#expr)) },
2006        "u64" => quote! { #crate_path::__private::i64_v(#expr as i64) },
2007        "f32" => quote! { #crate_path::__private::f32_v(#expr) },
2008        "f64" => quote! { #crate_path::__private::f64_v(#expr) },
2009        "DateTime" => quote! {
2010            #crate_path::GrpcValue {
2011                kind: ::core::option::Option::Some(#crate_path::Kind::TimestampValue(
2012                    #crate_path::Timestamp {
2013                        seconds: (#expr).timestamp(),
2014                        nanos: (#expr).timestamp_subsec_nanos() as i32,
2015                    },
2016                )),
2017                logical_type: ::std::string::String::new(),
2018            }
2019        },
2020        "Value" => quote! { #crate_path::json_to_grpc_value(&#expr) },
2021        "Link" => quote! {
2022            #crate_path::GrpcValue {
2023                kind: ::core::option::Option::Some(#crate_path::Kind::LinkValue(
2024                    #crate_path::GrpcLink {
2025                        rid: (#expr).to_string(),
2026                        r#type: ::std::string::String::new(),
2027                    },
2028                )),
2029                logical_type: ::std::string::String::new(),
2030            }
2031        },
2032        _ => {
2033            // `Vec<u8>` moves as a blob; `Vec<String>` moves element-wise;
2034            // any other container encodes through a borrow. The `Vec` checks
2035            // are gated on the segment ident — `container_inner` would
2036            // happily read the value arg of a `HashMap<K, V>` otherwise.
2037            if seg.ident != "Vec" {
2038                encode_field_value(ty, &quote! { &#expr }, crate_path)
2039                    .unwrap_or_else(|e| e.to_compile_error())
2040            } else if vec_u8(ty) {
2041                quote! { #crate_path::__private::bytes_v(#expr) }
2042            } else if matches!(container_inner(ty, seg, "Vec"), Ok(inner)
2043                if matches!(inner, Type::Path(p) if p.path.is_ident("String")))
2044            {
2045                quote! {
2046                    #crate_path::GrpcValue {
2047                        kind: ::core::option::Option::Some(#crate_path::Kind::ListValue(
2048                            #crate_path::GrpcList {
2049                                values: (#expr)
2050                                    .into_iter()
2051                                    .map(|__arcade_e| #crate_path::__private::str_v(__arcade_e))
2052                                    .collect(),
2053                            },
2054                        )),
2055                        logical_type: ::std::string::String::new(),
2056                    }
2057                }
2058            } else {
2059                encode_field_value(ty, &quote! { &#expr }, crate_path)
2060                    .unwrap_or_else(|e| e.to_compile_error())
2061            }
2062        }
2063    }
2064}
2065
2066/// One `props()` push for a field: skip policy, `Option` → property omitted
2067/// when `None`, custom `with` fn, or the type-driven wire mapping.
2068fn encode_field_push(
2069    fident: &Ident,
2070    ty: &Type,
2071    wire: &str,
2072    cfg: &FieldCfg,
2073    crate_path: &syn::Path,
2074) -> syn::Result<TokenStream2> {
2075    let wire = syn::LitStr::new(wire, proc_macro2::Span::call_site());
2076    if cfg.skip_encode {
2077        return Ok(quote! {});
2078    }
2079
2080    // Flattened nested record — splice its property map into ours.
2081    if cfg.flatten {
2082        // Mirror the decode-side validation: a flattened field's wire shape
2083        // is the nested props, so `with` could never apply.
2084        if cfg.with.is_some() {
2085            return Err(syn::Error::new(
2086                fident.span(),
2087                "RecordEncode: `with` cannot be combined with a flattened field",
2088            ));
2089        }
2090        return if let Some(inner) = option_inner(ty) {
2091            Ok(quote! {
2092                if let ::core::option::Option::Some(__arcade_f) = &self.#fident {
2093                    __out.extend(<#inner as #crate_path::record::ToGrpcRecord>::props(
2094                        __arcade_f,
2095                    ));
2096                }
2097            })
2098        } else {
2099            Ok(quote! {
2100                __out.extend(<#ty as #crate_path::record::ToGrpcRecord>::props(
2101                    &self.#fident,
2102                ));
2103            })
2104        };
2105    }
2106
2107    // `Option<T>` — `None` means "don't write the property" (new rows get the
2108    // schema default; conflict rows keep the stored value).
2109    if let Some(inner) = option_inner(ty) {
2110        let val = match &cfg.with {
2111            Some(w) => quote! { #w(__arcade_f) },
2112            None => encode_field_value(&inner, &quote! { __arcade_f }, crate_path)?,
2113        };
2114        return Ok(quote! {
2115            if let ::core::option::Option::Some(__arcade_f) = &self.#fident {
2116                __out.push((#wire, #val));
2117            }
2118        });
2119    }
2120
2121    let val = match &cfg.with {
2122        Some(w) => quote! { #w(&self.#fident) },
2123        None => encode_field_value(ty, &quote! { &self.#fident }, crate_path)?,
2124    };
2125    let push = quote! { __out.push((#wire, #val)); };
2126    if let Some(pred) = &cfg.skip_serializing_if {
2127        return Ok(quote! {
2128            if !#pred(&self.#fident) {
2129                #push
2130            }
2131        });
2132    }
2133    Ok(push)
2134}
2135
2136// ===========================================================================
2137// Canonical record-type classification
2138// ===========================================================================
2139//
2140
2141/// The single type argument of a generic container (`Vec<T>`, `Cow<T>`, …).
2142fn container_inner<'a>(
2143    ty: &'a Type,
2144    seg: &'a syn::PathSegment,
2145    what: &str,
2146) -> syn::Result<&'a Type> {
2147    let PathArguments::AngleBracketed(args) = &seg.arguments else {
2148        return Err(syn::Error::new(
2149            ty.span(),
2150            format!("`{what}` needs a type argument"),
2151        ));
2152    };
2153    let Some(GenericArgument::Type(inner)) = args.args.last() else {
2154        return Err(syn::Error::new(
2155            ty.span(),
2156            format!("`{what}` needs a type argument"),
2157        ));
2158    };
2159    Ok(inner)
2160}
2161
2162/// The value type of a `HashMap<String, T>` / `BTreeMap<String, T>` /
2163/// `AHashMap<String, T>` / `FxHashMap<String, T>` (map keys must be
2164/// `String` — the wire map only carries string keys).
2165fn map_value_type<'a>(ty: &'a Type, seg: &'a syn::PathSegment) -> syn::Result<&'a Type> {
2166    let PathArguments::AngleBracketed(args) = &seg.arguments else {
2167        return Err(syn::Error::new(ty.span(), "`map` needs type arguments"));
2168    };
2169    let mut types = args.args.iter().filter_map(|a| match a {
2170        GenericArgument::Type(t) => Some(t),
2171        _ => None,
2172    });
2173    let key = types
2174        .next()
2175        .ok_or_else(|| syn::Error::new(ty.span(), "`map` needs a key type"))?;
2176    if !matches!(key, Type::Path(p) if p.path.is_ident("String")) {
2177        return Err(syn::Error::new(
2178            key.span(),
2179            "RecordEncode: map keys must be `String` (the wire map is string-keyed)",
2180        ));
2181    }
2182    let value = types
2183        .next()
2184        .ok_or_else(|| syn::Error::new(ty.span(), "`map` needs a value type"))?;
2185    if types.next().is_some() {
2186        return Err(syn::Error::new(
2187            ty.span(),
2188            "`map` expects exactly two type arguments",
2189        ));
2190    }
2191    Ok(value)
2192}
2193
2194/// The single table enumerating the Rust types the record derives support.
2195/// Both consumers — wire-kind/schema rendering ([`db_type_of`] via
2196/// [`render`]) and encode codegen ([`value_from_db`]) — dispatch on this
2197/// enum, so adding a supported type means adding **one variant here** plus
2198/// one arm each in `render` and `value_from_db`. Nothing else in the macro
2199/// matches on type idents.
2200///
2201/// Contract ripple when extending: `classify` (this file) → `render` →
2202/// `WIRE_KINDS` const → migrate-side `dto_drift` interpretation.
2203enum DbType {
2204    /// `str` / `String` / `Cow<str>`.
2205    Str,
2206    /// `char` (encodes as a one-character string).
2207    Char,
2208    Bool,
2209    /// Wire `Int32` family — exact source width drives the conversion.
2210    Int32(Int32W),
2211    /// Wire `Int64` family.
2212    Int64(Int64W),
2213    F32,
2214    F64,
2215    /// Byte blob (`Vec<u8>` / `Cow<[u8]>`) — wire `bytes`, no schema mapping
2216    /// (the column shape is ambiguous).
2217    Bytes,
2218    /// `serde_json::Value` dynamic catch-all.
2219    Json,
2220    Link,
2221    DateTime,
2222    NaiveDate,
2223    /// `rust_decimal::Decimal` (protocol `decimal` feature). Codegen emits
2224    /// `decimal_v` directly: a DTO naming the type without the feature fails
2225    /// loudly there, which is stricter than the old silent fallback.
2226    Decimal,
2227    /// `Vec<T>` / `HashSet<T>` / `BTreeSet<T>` / `AHashSet<T>` /
2228    /// `FxHashSet<T>` / `&[T]` — all wire lists
2229    /// (`SET OF` vs `LIST OF` intent lives in the DTO field's Rust type).
2230    /// Inner `None` = foreign element (a nested `RecordEncode` struct),
2231    /// encoded through its own fallback.
2232    List(Box<Option<DbType>>),
2233    /// `HashMap<String, T>` / `BTreeMap<String, T>` / `AHashMap<String, T>` /
2234    /// `FxHashMap<String, T>` — wire maps.
2235    Map(Box<Option<DbType>>),
2236}
2237
2238/// How an `Int32`-family value is obtained from the field expression.
2239enum Int32W {
2240    /// Already `i32`.
2241    Direct,
2242    /// `i8` / `i16` / `u8` / `u16` — losslessly widened.
2243    Widened,
2244}
2245
2246/// How an `Int64`-family value is obtained from the field expression.
2247enum Int64W {
2248    /// Already `i64`.
2249    Direct,
2250    /// `u32`.
2251    FromU32,
2252    /// `u64` narrowed (`as i64`; ArcadeDB has no unsigned 64-bit kind).
2253    NarrowedU64,
2254}
2255
2256/// Outcome of classifying a field type. `Foreign` types fall back to the
2257/// `ToGrpcRecord` path (nested derive structs); `Err` is a malformed usage
2258/// of a *known* family (e.g. `Cow<f64>`) and must surface as a compile error.
2259enum Classification {
2260    Known(DbType),
2261    Foreign,
2262}
2263
2264/// The one matcher over `syn::Type` for the record universe. Handles the
2265/// transparent wrappers first (references, slices as list views, `Option`
2266/// unwrapping), then dispatches on the last path segment.
2267fn classify(ty: &Type) -> syn::Result<Classification> {
2268    if let Type::Reference(r) = ty {
2269        return classify(&r.elem);
2270    }
2271    if let Type::Slice(s) = ty {
2272        // `&[T]` — a borrowed list view.
2273        return Ok(Classification::Known(DbType::List(Box::new(
2274            elem_classification(&s.elem)?,
2275        ))));
2276    }
2277    if let Some(ref inner) = option_inner(ty) {
2278        return classify(inner);
2279    }
2280    let Type::Path(tp) = ty else {
2281        return Ok(Classification::Foreign);
2282    };
2283    let seg = tp.path.segments.last().expect("path always has segments");
2284
2285    if seg.ident == "Cow" {
2286        let inner = container_inner(ty, seg, "Cow")?;
2287        return match inner {
2288            Type::Path(p) if p.path.is_ident("str") => Ok(Classification::Known(DbType::Str)),
2289            Type::Slice(s) if matches!(&*s.elem, Type::Path(p) if p.path.is_ident("u8")) => {
2290                Ok(Classification::Known(DbType::Bytes))
2291            }
2292            _ => Err(syn::Error::new(
2293                ty.span(),
2294                "RecordEncode: `Cow` fields must be `Cow<str>` or `Cow<[u8]>`",
2295            )),
2296        };
2297    }
2298
2299    let db = match seg.ident.to_string().as_str() {
2300        "str" | "String" => DbType::Str,
2301        "char" => DbType::Char,
2302        "bool" => DbType::Bool,
2303        "i8" => DbType::Int32(Int32W::Widened),
2304        "i16" => DbType::Int32(Int32W::Widened),
2305        "i32" => DbType::Int32(Int32W::Direct),
2306        "u8" => DbType::Int32(Int32W::Widened),
2307        "u16" => DbType::Int32(Int32W::Widened),
2308        "i64" => DbType::Int64(Int64W::Direct),
2309        "u32" => DbType::Int64(Int64W::FromU32),
2310        // ArcadeDB has no unsigned 64-bit kind; values over i64::MAX cannot
2311        // be round-tripped (ordinary ids are well below it).
2312        "u64" => DbType::Int64(Int64W::NarrowedU64),
2313        "f32" => DbType::F32,
2314        "f64" => DbType::F64,
2315        "Value" => DbType::Json,
2316        "Link" => DbType::Link,
2317        "DateTime" => DbType::DateTime,
2318        "NaiveDate" => DbType::NaiveDate,
2319        "Decimal" => DbType::Decimal,
2320        "Vec" | "HashSet" | "BTreeSet" | "AHashSet" | "FxHashSet" => {
2321            if seg.ident == "AHashSet" && !cfg!(feature = "ahash") {
2322                return Err(syn::Error::new(
2323                    ty.span(),
2324                    "RecordEncode/RecordDecode: `AHashSet` fields need the `ahash` feature",
2325                ));
2326            }
2327            if seg.ident == "FxHashSet" && !cfg!(feature = "fxhash") {
2328                return Err(syn::Error::new(
2329                    ty.span(),
2330                    "RecordEncode/RecordDecode: `FxHashSet` fields need the `fxhash` feature",
2331                ));
2332            }
2333            if vec_u8(ty) {
2334                DbType::Bytes
2335            } else {
2336                let elem_ty = container_inner(ty, seg, "list container")?;
2337                DbType::List(Box::new(elem_classification(elem_ty)?))
2338            }
2339        }
2340        "HashMap" | "BTreeMap" | "AHashMap" | "FxHashMap" => {
2341            // The alternative hashers are wire maps like the std ones, but
2342            // their decode side needs the protocol's `FromGrpcValue` impl —
2343            // which only exists with the matching feature. Fail with the
2344            // fix, not with a trait-bound error deep in the generated code.
2345            if seg.ident == "AHashMap" && !cfg!(feature = "ahash") {
2346                return Err(syn::Error::new(
2347                    ty.span(),
2348                    "RecordEncode/RecordDecode: `AHashMap` fields need the `ahash` feature",
2349                ));
2350            }
2351            if seg.ident == "FxHashMap" && !cfg!(feature = "fxhash") {
2352                return Err(syn::Error::new(
2353                    ty.span(),
2354                    "RecordEncode/RecordDecode: `FxHashMap` fields need the `fxhash` feature",
2355                ));
2356            }
2357            let value_ty = map_value_type(ty, seg)?;
2358            DbType::Map(Box::new(elem_classification(value_ty)?))
2359        }
2360        _ => return Ok(Classification::Foreign),
2361    };
2362    Ok(Classification::Known(db))
2363}
2364
2365/// Classify a container's element/value type: known → `Some`, foreign (a
2366/// nested `RecordEncode` struct) → `None`, malformed → error.
2367fn elem_classification(ty: &Type) -> syn::Result<Option<DbType>> {
2368    match classify(ty)? {
2369        Classification::Known(db) => Ok(Some(db)),
2370        Classification::Foreign => Ok(None),
2371    }
2372}
2373
2374/// Schema column type for drift checks — the vocabulary migrate's
2375/// `dto_drift` interprets. `None` = no clean column correspondence (byte
2376/// blobs, dynamic values, foreign elements).
2377fn render(db: &DbType) -> Option<String> {
2378    match db {
2379        DbType::Str | DbType::Char => Some("STRING".to_string()),
2380        DbType::Bool => Some("BOOLEAN".to_string()),
2381        DbType::Int32(_) => Some("INTEGER".to_string()),
2382        DbType::Int64(_) => Some("LONG".to_string()),
2383        DbType::F32 => Some("FLOAT".to_string()),
2384        DbType::F64 => Some("DOUBLE".to_string()),
2385        DbType::Bytes | DbType::Json => None,
2386        DbType::Link => Some("LINK".to_string()),
2387        DbType::DateTime => Some("DATETIME".to_string()),
2388        DbType::NaiveDate => Some("DATE".to_string()),
2389        // Emitted whenever a DTO names the rust_decimal type — implies the
2390        // consumer enabled the protocol's `decimal` feature.
2391        DbType::Decimal => Some("DECIMAL".to_string()),
2392        // The declaration cannot distinguish LIST OF vs SET OF; the drift
2393        // checker treats both spellings as one class.
2394        DbType::List(inner) => render_inner(inner).map(|s| format!("LIST OF {s}")),
2395        DbType::Map(_) => Some("MAP".to_string()),
2396    }
2397}
2398
2399fn render_inner(inner: &Option<DbType>) -> Option<String> {
2400    inner.as_ref().and_then(render)
2401}
2402
2403/// Encode codegen for a classified type. Total over `DbType` — `classify`
2404/// has already rejected malformed usages. Numeric arms preserve the exact
2405/// expressions the previous per-width matcher emitted (`*#expr`,
2406/// `i32::from(*#expr)`, …).
2407fn value_from_db(db: &DbType, expr: &TokenStream2, crate_path: &syn::Path) -> TokenStream2 {
2408    match db {
2409        DbType::Str | DbType::Char => quote! { #crate_path::__private::str_v((#expr).to_string()) },
2410        DbType::Bool => quote! { #crate_path::__private::bool_v(*#expr) },
2411        DbType::Int32(Int32W::Direct) => quote! { #crate_path::__private::i32_v(*#expr) },
2412        DbType::Int32(Int32W::Widened) => {
2413            quote! { #crate_path::__private::i32_v(i32::from(*#expr)) }
2414        }
2415        DbType::Int64(Int64W::Direct) => quote! { #crate_path::__private::i64_v(*#expr) },
2416        DbType::Int64(Int64W::FromU32) => {
2417            quote! { #crate_path::__private::i64_v(i64::from(*#expr)) }
2418        }
2419        DbType::Int64(Int64W::NarrowedU64) => {
2420            quote! { #crate_path::__private::i64_v(*#expr as i64) }
2421        }
2422        DbType::F32 => quote! { #crate_path::__private::f32_v(*#expr) },
2423        DbType::F64 => quote! { #crate_path::__private::f64_v(*#expr) },
2424        DbType::Bytes => quote! { #crate_path::__private::bytes_v((#expr).clone()) },
2425        DbType::Json => quote! { #crate_path::json_to_grpc_value(#expr) },
2426        DbType::Link => quote! {
2427            #crate_path::GrpcValue {
2428                kind: ::core::option::Option::Some(#crate_path::Kind::LinkValue(
2429                    #crate_path::GrpcLink {
2430                        rid: (#expr).to_string(),
2431                        r#type: ::std::string::String::new(),
2432                    },
2433                )),
2434                logical_type: ::std::string::String::new(),
2435            }
2436        },
2437        // chrono `DateTime` (any timezone) → the protobuf well-known
2438        // `Timestamp` — the wire's date/datetime kind. Sub-second nanos are
2439        // always < 2³¹, so the `as i32` narrowing is total.
2440        DbType::DateTime => quote! {
2441            #crate_path::GrpcValue {
2442                kind: ::core::option::Option::Some(#crate_path::Kind::TimestampValue(
2443                    #crate_path::Timestamp {
2444                        seconds: (#expr).timestamp(),
2445                        nanos: (#expr).timestamp_subsec_nanos() as i32,
2446                    },
2447                )),
2448                logical_type: ::std::string::String::new(),
2449            }
2450        },
2451        DbType::NaiveDate => quote! { #crate_path::__private::date_v(*#expr) },
2452        DbType::Decimal => quote! { #crate_path::__private::decimal_v(*#expr) },
2453        DbType::List(inner) => {
2454            let inner: &Option<DbType> = inner;
2455            let elem = elem_tokens(inner.as_ref(), &quote! { __arcade_e }, crate_path);
2456            quote! {
2457                #crate_path::GrpcValue {
2458                    kind: ::core::option::Option::Some(#crate_path::Kind::ListValue(
2459                        #crate_path::GrpcList {
2460                            values: (#expr)
2461                                .iter()
2462                                .map(|__arcade_e| #elem)
2463                                .collect(),
2464                        },
2465                    )),
2466                    logical_type: ::std::string::String::new(),
2467                }
2468            }
2469        }
2470        DbType::Map(inner) => {
2471            let inner: &Option<DbType> = inner;
2472            let value = elem_tokens(inner.as_ref(), &quote! { __arcade_v }, crate_path);
2473            quote! {
2474                #crate_path::GrpcValue {
2475                    kind: ::core::option::Option::Some(#crate_path::Kind::MapValue(
2476                        #crate_path::GrpcMap {
2477                            entries: (#expr)
2478                                .iter()
2479                                .map(|(__arcade_k, __arcade_v)| (__arcade_k.clone(), #value))
2480                                .collect(),
2481                        },
2482                    )),
2483                    logical_type: ::std::string::String::new(),
2484                }
2485            }
2486        }
2487    }
2488}
2489
2490/// Element/value tokens inside a container: known kinds encode per their
2491/// variant (bound to the iteration variable); foreign elements fall back to
2492/// the record-map form.
2493fn elem_tokens(inner: Option<&DbType>, var: &TokenStream2, crate_path: &syn::Path) -> TokenStream2 {
2494    match inner {
2495        Some(db) => value_from_db(db, var, crate_path),
2496        None => quote! {
2497            <_ as #crate_path::record::ToGrpcRecord>::to_grpc_value(#var)
2498        },
2499    }
2500}
2501
2502/// Wire-value codegen for one field expression. `Foreign` types route to
2503/// their `ToGrpcRecord` impl (nested derive structs).
2504fn encode_field_value(
2505    ty: &Type,
2506    expr: &TokenStream2,
2507    crate_path: &syn::Path,
2508) -> syn::Result<TokenStream2> {
2509    match classify(ty)? {
2510        Classification::Known(db) => Ok(value_from_db(&db, expr, crate_path)),
2511        Classification::Foreign => Ok(quote! {
2512            <#ty as #crate_path::record::ToGrpcRecord>::to_grpc_value(#expr)
2513        }),
2514    }
2515}
2516
2517/// The expected ArcadeDB column type for a decode field, when statically
2518/// knowable — feeds `WIRE_KINDS` for schema-drift checks. Returns `None`
2519/// for types without a clean column correspondence (custom types, dynamic
2520/// values, byte blobs — `Vec<u8>` legitimately lives in several column
2521/// shapes). `Option<T>` unwraps to `T`; nested `Vec<T>` renders as
2522/// `LIST OF <T>`; the migrate-side checker treats the integer and float
2523/// families as decodable across their widths (the decoder is range-checked
2524/// and float-tolerant, so `i64` reading an `INTEGER` column is fine).
2525fn db_type_of(ty: &Type) -> Option<String> {
2526    match classify(ty) {
2527        Ok(Classification::Known(db)) => render(&db),
2528        _ => None,
2529    }
2530}
2531
2532// ---------------------------------------------------------------------------
2533// rename_all rules — serde's exact case dialect
2534// ---------------------------------------------------------------------------
2535
2536/// A `rename_all` case rule, with serde's exact transformation semantics
2537/// (ported from `serde_derive`'s `internals/case.rs`). Parity with serde is
2538/// the point: wire keys are produced by serde's `Serialize`, so the decode
2539/// side must apply the identical rules — including serde's deliberate
2540/// no-acronym-grouping (`HTTPServer` → snake_case → `h_t_t_p_server`).
2541#[derive(Clone, Copy)]
2542enum RenameRule {
2543    Lower,
2544    Upper,
2545    Pascal,
2546    Camel,
2547    Snake,
2548    ScreamingSnake,
2549    Kebab,
2550    ScreamingKebab,
2551}
2552
2553impl RenameRule {
2554    /// Parse one of serde's eight rule names; anything else is a compile
2555    /// error, mirroring serde's own unknown-`rename_all` error.
2556    fn parse(s: &str) -> Option<Self> {
2557        match s {
2558            "lowercase" => Some(Self::Lower),
2559            "UPPERCASE" => Some(Self::Upper),
2560            "PascalCase" => Some(Self::Pascal),
2561            "camelCase" => Some(Self::Camel),
2562            "snake_case" => Some(Self::Snake),
2563            "SCREAMING_SNAKE_CASE" => Some(Self::ScreamingSnake),
2564            "kebab-case" => Some(Self::Kebab),
2565            "SCREAMING-KEBAB-CASE" => Some(Self::ScreamingKebab),
2566            _ => None,
2567        }
2568    }
2569
2570    /// Apply to a *variant* name (PascalCase input, serde's
2571    /// `apply_to_variant`): snake/kebab split before every uppercase char.
2572    fn apply_to_variant(self, variant: &str) -> String {
2573        match self {
2574            Self::Pascal => variant.to_owned(),
2575            Self::Lower => variant.to_ascii_lowercase(),
2576            Self::Upper => variant.to_ascii_uppercase(),
2577            Self::Camel => lower_first(variant),
2578            Self::Snake => {
2579                let mut snake = String::with_capacity(variant.len() + 4);
2580                for (i, ch) in variant.char_indices() {
2581                    if i > 0 && ch.is_uppercase() {
2582                        snake.push('_');
2583                    }
2584                    snake.push(ch.to_ascii_lowercase());
2585                }
2586                snake
2587            }
2588            Self::ScreamingSnake => Self::Snake.apply_to_variant(variant).to_ascii_uppercase(),
2589            Self::Kebab => Self::Snake.apply_to_variant(variant).replace('_', "-"),
2590            Self::ScreamingKebab => Self::ScreamingSnake
2591                .apply_to_variant(variant)
2592                .replace('_', "-"),
2593        }
2594    }
2595
2596    /// Apply to a *field* name (snake_case input, serde's `apply_to_field`):
2597    /// `lowercase`/`snake_case` are identities — serde assumes Rust's
2598    /// snake_case convention and never regroups case runs.
2599    fn apply_to_field(self, field: &str) -> String {
2600        match self {
2601            Self::Lower | Self::Snake => field.to_owned(),
2602            Self::Upper => field.to_ascii_uppercase(),
2603            Self::Pascal => {
2604                let mut pascal = String::with_capacity(field.len());
2605                let mut capitalize = true;
2606                for ch in field.chars() {
2607                    if ch == '_' {
2608                        capitalize = true;
2609                    } else if capitalize {
2610                        pascal.push(ch.to_ascii_uppercase());
2611                        capitalize = false;
2612                    } else {
2613                        pascal.push(ch);
2614                    }
2615                }
2616                pascal
2617            }
2618            Self::Camel => lower_first(&Self::Pascal.apply_to_field(field)),
2619            Self::ScreamingSnake => field.to_ascii_uppercase(),
2620            Self::Kebab => field.replace('_', "-"),
2621            Self::ScreamingKebab => Self::ScreamingSnake.apply_to_field(field).replace('_', "-"),
2622        }
2623    }
2624}
2625
2626/// Lowercase the first char, keep the rest (serde's camelCase final step).
2627fn lower_first(s: &str) -> String {
2628    let mut chars = s.chars();
2629    chars
2630        .next()
2631        .map(|c| c.to_lowercase().collect::<String>())
2632        .unwrap_or_default()
2633        + chars.as_str()
2634}
2635
2636#[cfg(test)]
2637mod dbtype_tests {
2638    use super::*;
2639    use syn::parse_quote;
2640
2641    fn rendered(ty: Type) -> Option<String> {
2642        match classify(&ty).expect("type must classify") {
2643            Classification::Known(db) => render(&db),
2644            Classification::Foreign => None,
2645        }
2646    }
2647
2648    /// Every supported type classifies, renders, and agrees with the
2649    /// schema-drift vocabulary — the matrix that dies if a new `DbType`
2650    /// variant (or matcher arm) is added to one consumer but not the other.
2651    #[test]
2652    fn classification_matrix_is_complete() {
2653        let cases: Vec<(Type, Option<&str>)> = vec![
2654            (parse_quote!(String), Some("STRING")),
2655            (parse_quote!(char), Some("STRING")),
2656            (parse_quote!(bool), Some("BOOLEAN")),
2657            (parse_quote!(i8), Some("INTEGER")),
2658            (parse_quote!(u16), Some("INTEGER")),
2659            (parse_quote!(i32), Some("INTEGER")),
2660            (parse_quote!(i64), Some("LONG")),
2661            (parse_quote!(u32), Some("LONG")),
2662            (parse_quote!(f32), Some("FLOAT")),
2663            (parse_quote!(f64), Some("DOUBLE")),
2664            (
2665                parse_quote!(chrono::DateTime<chrono::Utc>),
2666                Some("DATETIME"),
2667            ),
2668            (parse_quote!(chrono::NaiveDate), Some("DATE")),
2669            (parse_quote!(rust_decimal::Decimal), Some("DECIMAL")),
2670            (parse_quote!(arcadedb_protocol::Link), Some("LINK")),
2671            (parse_quote!(Vec<i32>), Some("LIST OF INTEGER")),
2672            (
2673                parse_quote!(std::collections::HashSet<String>),
2674                Some("LIST OF STRING"),
2675            ),
2676            (
2677                parse_quote!(std::collections::BTreeSet<u8>),
2678                Some("LIST OF INTEGER"),
2679            ),
2680            (parse_quote!(Vec<Vec<f64>>), Some("LIST OF LIST OF DOUBLE")),
2681            (
2682                parse_quote!(std::collections::HashMap<String, i64>),
2683                Some("MAP"),
2684            ),
2685            (
2686                parse_quote!(std::collections::BTreeMap<String, f64>),
2687                Some("MAP"),
2688            ),
2689            // Excluded from drift, but still encodable.
2690            (parse_quote!(Vec<u8>), None),
2691            // Foreign types render nothing (ToGrpcRecord fallback).
2692            (parse_quote!(SomeExternalStruct), None),
2693            (parse_quote!(Option<i64>), Some("LONG")),
2694            (parse_quote!(&[i32]), Some("LIST OF INTEGER")),
2695        ];
2696        for (ty, expected) in cases {
2697            assert_eq!(rendered(ty), expected.map(str::to_string));
2698        }
2699    }
2700
2701    /// Malformed known-family usages are hard errors, never silent fallbacks.
2702    #[test]
2703    fn malformed_cow_is_an_error() {
2704        let ty: Type = parse_quote!(Cow<f64>);
2705        assert!(classify(&ty).is_err());
2706    }
2707}