Skip to main content

jshift_derive/
lib.rs

1use proc_macro::TokenStream;
2use quote::quote;
3use std::collections::BTreeSet;
4use syn::{parse_macro_input, Data, DeriveInput, Fields, Ident, Type};
5
6/// Derive typed JSON path readers/mutators and implement [`jshift::JsonView`].
7///
8/// Same as [`JsonView`] — kept for backward compatibility.
9///
10/// # Structs
11/// Named fields with `#[json(path = "...")]` (optional `default`, `jmes`,
12/// `flatten`, `nested`, `map`, `from_slice`).
13///
14/// * **Scalars** — built-in `FromJsonSlice` types; custom newtypes need
15///   `#[json(from_slice)]`
16/// * **Nested** — serde-like default: non-scalar types are nested `JsonView`
17///   at path (`{"meta":{...}}`); force with `#[json(nested)]`
18/// * **Maps** — `HashMap<String, V>` / `BTreeMap<String, V>` (`V: FromJsonSlice`)
19/// * **Flatten** — `#[json(flatten)]` spreads a child view into the parent object
20///
21/// # Enums (external default; internal / adjacent / untagged via `#[json(…)]`)
22/// * Unit → JSON string (`"Ready"`)
23/// * Newtype → `{"Tag": <payload>}` (`FromJsonSlice` payload)
24/// * Struct → `{"Tag":{...}}` (flat top-level field keys)
25/// * `#[json(rename = "...")]` on variants
26#[proc_macro_derive(JsonMutatorSchema, attributes(json))]
27pub fn derive_json_mutator_schema(input: TokenStream) -> TokenStream {
28    derive_inner(input)
29}
30
31/// Alias for [`JsonMutatorSchema`]: a Rust type is a projection of JSON bytes.
32///
33/// Prefer this name when thinking in views / partial records (prost-like messages).
34/// Supports **structs** (scalars, nested views, maps, flatten) and **enums**
35/// (external / internal / adjacent / untagged — see `jshift::enums` / API guide).
36#[proc_macro_derive(JsonView, attributes(json))]
37pub fn derive_json_view(input: TokenStream) -> TokenStream {
38    derive_inner(input)
39}
40
41fn derive_inner(input: TokenStream) -> TokenStream {
42    let input = parse_macro_input!(input as DeriveInput);
43    match expand_derive(&input) {
44        Ok(tokens) => tokens.into(),
45        Err(err) => err.to_compile_error().into(),
46    }
47}
48
49fn expand_derive(input: &DeriveInput) -> Result<proc_macro2::TokenStream, syn::Error> {
50    match &input.data {
51        Data::Struct(_) => expand_struct(input),
52        Data::Enum(_) => expand_enum(input),
53        Data::Union(_) => Err(syn::Error::new_spanned(
54            input,
55            "JsonMutatorSchema / JsonView cannot be derived on unions",
56        )),
57    }
58}
59
60fn expand_struct(input: &DeriveInput) -> Result<proc_macro2::TokenStream, syn::Error> {
61    let struct_name = &input.ident;
62    let mutator_name = Ident::new(&format!("{}Mutator", struct_name), struct_name.span());
63
64    let data = match &input.data {
65        Data::Struct(s) => s,
66        _ => unreachable!(),
67    };
68
69    let fields = match &data.fields {
70        Fields::Named(f) => &f.named,
71        _ => {
72            return Err(syn::Error::new_spanned(
73                input,
74                "JsonMutatorSchema / JsonView can only be derived on structs with named fields",
75            ));
76        }
77    };
78
79    let mut field_reads = Vec::new();
80    let mut field_reads_indexed = Vec::new();
81    let mut field_reads_doc = Vec::new();
82    let mut mutator_setters = Vec::new();
83    let mut path_statics = Vec::new();
84    let mut write_fields = Vec::new();
85    let mut field_path_lits = Vec::new();
86    let mut field_jmes_lits = Vec::new();
87    let mut has_any_jmes = false;
88    let mut array_prefixes: BTreeSet<String> = BTreeSet::new();
89    // Single-key paths for one-pass ObjectBuilder schema emit (0.6).
90    enum SchemaEmit {
91        Key { key: String, fname: Ident },
92        Flatten { fname: Ident, is_option: bool },
93        /// Nested JsonView → raw_field(key, to_schema_bytes)
94        Nested {
95            key: String,
96            fname: Ident,
97            is_option: bool,
98        },
99        /// HashMap/BTreeMap → encode object at key
100        Map {
101            key: String,
102            fname: Ident,
103            is_option: bool,
104            kind: MapKind,
105        },
106    }
107    let mut schema_emits: Vec<SchemaEmit> = Vec::new();
108    let mut all_paths_flat = true;
109    let mut has_flatten = false;
110    let mut flatten_child_types: Vec<Type> = Vec::new();
111    // For multi-select hash project: only non-flatten fields participate by name.
112    let mut project_hash_names: Vec<String> = Vec::new();
113    let mut project_hash_jmes: Vec<String> = Vec::new();
114
115    for field in fields {
116        let field_name = field.ident.as_ref().ok_or_else(|| {
117            syn::Error::new_spanned(field, "JsonMutatorSchema requires named fields")
118        })?;
119        let field_type = &field.ty;
120        let attrs = get_json_attrs(field)?;
121
122        // ── flatten ─────────────────────────────────────────────────────────
123        if attrs.flatten {
124            has_flatten = true;
125            if attrs.jmes.is_some() {
126                return Err(syn::Error::new_spanned(
127                    field,
128                    "#[json(flatten)] cannot be combined with jmes",
129                ));
130            }
131            if attrs.path_explicit {
132                return Err(syn::Error::new_spanned(
133                    field,
134                    "#[json(flatten)] does not use path= (child paths are relative to the parent object)",
135                ));
136            }
137            let is_option = is_option_type(field_type);
138            let child_ty: &Type = if is_option {
139                option_inner_type(field_type).ok_or_else(|| {
140                    syn::Error::new_spanned(field, "Option flatten requires Option<T>")
141                })?
142            } else {
143                field_type
144            };
145            flatten_child_types.push(child_ty.clone());
146            schema_emits.push(SchemaEmit::Flatten {
147                fname: field_name.clone(),
148                is_option,
149            });
150
151            if is_option {
152                field_reads.push(quote! {
153                    #field_name: jshift::read_flattened_opt::<#child_ty>(json)?
154                });
155                field_reads_indexed.push(quote! {
156                    #field_name: jshift::read_flattened_opt::<#child_ty>(doc.as_bytes())?
157                });
158                field_reads_doc.push(quote! {
159                    #field_name: jshift::read_flattened_opt::<#child_ty>(doc.as_bytes())?
160                });
161                write_fields.push(quote! {
162                    jshift::write_flattened_opt(json, self.#field_name.as_ref())?;
163                });
164            } else if attrs.use_default {
165                field_reads.push(quote! {
166                    #field_name: match jshift::read_flattened::<#field_type>(json) {
167                        Ok(v) => v,
168                        Err(jshift::Error::PathNotFound) => {
169                            <#field_type as core::default::Default>::default()
170                        }
171                        Err(e) => return Err(e),
172                    }
173                });
174                field_reads_indexed.push(quote! {
175                    #field_name: match jshift::read_flattened::<#field_type>(doc.as_bytes()) {
176                        Ok(v) => v,
177                        Err(jshift::Error::PathNotFound) => {
178                            <#field_type as core::default::Default>::default()
179                        }
180                        Err(e) => return Err(e),
181                    }
182                });
183                field_reads_doc.push(quote! {
184                    #field_name: match jshift::read_flattened::<#field_type>(doc.as_bytes()) {
185                        Ok(v) => v,
186                        Err(jshift::Error::PathNotFound) => {
187                            <#field_type as core::default::Default>::default()
188                        }
189                        Err(e) => return Err(e),
190                    }
191                });
192                write_fields.push(quote! {
193                    jshift::write_flattened(json, &self.#field_name)?;
194                });
195            } else {
196                field_reads.push(quote! {
197                    #field_name: jshift::read_flattened::<#field_type>(json)?
198                });
199                field_reads_indexed.push(quote! {
200                    #field_name: jshift::read_flattened::<#field_type>(doc.as_bytes())?
201                });
202                field_reads_doc.push(quote! {
203                    #field_name: jshift::read_flattened::<#field_type>(doc.as_bytes())?
204                });
205                write_fields.push(quote! {
206                    jshift::write_flattened(json, &self.#field_name)?;
207                });
208            }
209
210            let setter_name = Ident::new(&format!("set_{}", field_name), field_name.span());
211            if is_option {
212                mutator_setters.push(quote! {
213                    /// Flatten-write `Some(child)` into the parent object (open upsert).
214                    pub fn #setter_name(
215                        &mut self,
216                        val: Option<&#child_ty>,
217                    ) -> Result<(), jshift::Error> {
218                        jshift::write_flattened_opt(self.json, val)
219                    }
220                });
221            } else {
222                mutator_setters.push(quote! {
223                    /// Flatten-write this child view into the parent object (open upsert).
224                    pub fn #setter_name(&mut self, val: &#field_type) -> Result<(), jshift::Error> {
225                        jshift::write_flattened(self.json, val)
226                    }
227                });
228            }
229            continue;
230        }
231
232        // ── normal path field ───────────────────────────────────────────────
233        let raw_path = attrs.path.clone();
234        let jmes_opt = attrs.jmes.clone();
235        let use_default = attrs.use_default;
236        if jmes_opt.is_some() {
237            has_any_jmes = true;
238        }
239
240        let path_segments = parse_path_segments(&raw_path).map_err(|msg| {
241            syn::Error::new_spanned(
242                field,
243                format!("invalid #[json(path = ...)] value `{raw_path}`: {msg}"),
244            )
245        })?;
246
247        let path_const_name = Ident::new(
248            &format!("__JSHIFT_PATH_{}", field_name.to_string().to_uppercase()),
249            field_name.span(),
250        );
251        let jmes_const_name = Ident::new(
252            &format!("__JSHIFT_JMES_{}", field_name.to_string().to_uppercase()),
253            field_name.span(),
254        );
255        let jmes_expr = jmes_opt.clone().unwrap_or_else(|| raw_path.clone());
256
257        let seg_tokens: Vec<_> = path_segments
258            .iter()
259            .map(|s| match s {
260                DerSegment::Key(k) => quote! { jshift::PathSegment::Key(#k) },
261                DerSegment::Index(i) => quote! { jshift::PathSegment::Index(#i) },
262            })
263            .collect();
264
265        path_statics.push(quote! {
266            const #path_const_name: &'static [jshift::PathSegment<'static>] = &[
267                #(#seg_tokens),*
268            ];
269            const #jmes_const_name: &'static str = #jmes_expr;
270        });
271
272        for pref in static_array_prefixes_from_segments(&path_segments) {
273            array_prefixes.insert(pref);
274        }
275
276        let is_option = is_option_type(field_type);
277        let setter_name = Ident::new(&format!("set_{}", field_name), field_name.span());
278
279        // ── map field (HashMap/BTreeMap<String, V>) ──────────────────────────
280        let map_ty = if is_option {
281            option_inner_type(field_type)
282        } else {
283            Some(field_type)
284        };
285        let map_info = map_ty.and_then(map_string_value_type);
286        let treat_as_map = attrs.map || map_info.is_some();
287        if treat_as_map {
288            if jmes_opt.is_some() {
289                return Err(syn::Error::new_spanned(
290                    field,
291                    "#[json(map)] cannot be combined with jmes",
292                ));
293            }
294            let (kind, val_ty) = map_info.ok_or_else(|| {
295                syn::Error::new_spanned(
296                    field,
297                    "#[json(map)] requires HashMap<String, V> or BTreeMap<String, V> (V: FromJsonSlice)",
298                )
299            })?;
300            field_path_lits.push(raw_path.clone());
301            field_jmes_lits.push(raw_path.clone());
302            project_hash_names.push(field_name.to_string());
303            project_hash_jmes.push(raw_path.clone());
304
305            if let [DerSegment::Key(k)] = path_segments.as_slice() {
306                schema_emits.push(SchemaEmit::Map {
307                    key: k.clone(),
308                    fname: field_name.clone(),
309                    is_option,
310                    kind,
311                });
312            } else {
313                all_paths_flat = false;
314            }
315
316            let (read_fn, write_fn) = match kind {
317                MapKind::HashMap => (
318                    quote! { jshift::read_hashmap_at },
319                    quote! { jshift::write_hashmap_at },
320                ),
321                MapKind::BTreeMap => (
322                    quote! { jshift::read_btreemap_at },
323                    quote! { jshift::write_btreemap_at },
324                ),
325            };
326
327            if is_option {
328                // Shared null/missing policy with nested Option (PathNotFound | null → None).
329                let map_opt_read = quote! {
330                    {
331                        match jshift::find_value(__json, Self::#path_const_name) {
332                            Ok(slice) => {
333                                let start = {
334                                    let mut p = 0usize;
335                                    while p < slice.len()
336                                        && matches!(slice[p], b' ' | b'\t' | b'\n' | b'\r')
337                                    {
338                                        p += 1;
339                                    }
340                                    p
341                                };
342                                let mut end = slice.len();
343                                while end > start
344                                    && matches!(slice[end - 1], b' ' | b'\t' | b'\n' | b'\r')
345                                {
346                                    end -= 1;
347                                }
348                                if &slice[start..end] == b"null" {
349                                    None
350                                } else {
351                                    Some(#read_fn::<#val_ty>(__json, Self::#path_const_name)?)
352                                }
353                            }
354                            Err(jshift::Error::PathNotFound) => None,
355                            Err(e) => return Err(e),
356                        }
357                    }
358                };
359                field_reads.push(quote! {
360                    #field_name: {
361                        let __json = json;
362                        #map_opt_read
363                    }
364                });
365                field_reads_indexed.push(quote! {
366                    #field_name: {
367                        let __json = doc.as_bytes();
368                        #map_opt_read
369                    }
370                });
371                field_reads_doc.push(quote! {
372                    #field_name: {
373                        let __json = doc.as_bytes();
374                        #map_opt_read
375                    }
376                });
377                write_fields.push(quote! {
378                    if let Some(ref m) = self.#field_name {
379                        #write_fn(json, Self::#path_const_name, m)?;
380                    }
381                });
382                let map_inner_ty = option_inner_type(field_type).unwrap_or(field_type);
383                mutator_setters.push(quote! {
384                    /// Replace the map object at this path (`None` = no-op).
385                    pub fn #setter_name(
386                        &mut self,
387                        val: Option<&#map_inner_ty>,
388                    ) -> Result<(), jshift::Error> {
389                        if let Some(m) = val {
390                            #write_fn(self.json, #struct_name::#path_const_name, m)?;
391                        }
392                        Ok(())
393                    }
394                });
395            } else if use_default {
396                field_reads.push(quote! {
397                    #field_name: match #read_fn::<#val_ty>(json, Self::#path_const_name) {
398                        Ok(m) => m,
399                        Err(jshift::Error::PathNotFound) => Default::default(),
400                        Err(e) => return Err(e),
401                    }
402                });
403                field_reads_indexed.push(quote! {
404                    #field_name: match #read_fn::<#val_ty>(doc.as_bytes(), Self::#path_const_name) {
405                        Ok(m) => m,
406                        Err(jshift::Error::PathNotFound) => Default::default(),
407                        Err(e) => return Err(e),
408                    }
409                });
410                field_reads_doc.push(quote! {
411                    #field_name: match #read_fn::<#val_ty>(doc.as_bytes(), Self::#path_const_name) {
412                        Ok(m) => m,
413                        Err(jshift::Error::PathNotFound) => Default::default(),
414                        Err(e) => return Err(e),
415                    }
416                });
417                write_fields.push(quote! {
418                    #write_fn(json, Self::#path_const_name, &self.#field_name)?;
419                });
420                mutator_setters.push(quote! {
421                    /// Replace the map object at this path.
422                    pub fn #setter_name(&mut self, val: &#field_type) -> Result<(), jshift::Error> {
423                        #write_fn(self.json, #struct_name::#path_const_name, val)
424                    }
425                });
426            } else {
427                field_reads.push(quote! {
428                    #field_name: #read_fn::<#val_ty>(json, Self::#path_const_name)?
429                });
430                field_reads_indexed.push(quote! {
431                    #field_name: #read_fn::<#val_ty>(doc.as_bytes(), Self::#path_const_name)?
432                });
433                field_reads_doc.push(quote! {
434                    #field_name: #read_fn::<#val_ty>(doc.as_bytes(), Self::#path_const_name)?
435                });
436                write_fields.push(quote! {
437                    #write_fn(json, Self::#path_const_name, &self.#field_name)?;
438                });
439                mutator_setters.push(quote! {
440                    /// Replace the map object at this path.
441                    pub fn #setter_name(&mut self, val: &#field_type) -> Result<(), jshift::Error> {
442                        #write_fn(self.json, #struct_name::#path_const_name, val)
443                    }
444                });
445            }
446            continue;
447        }
448
449        // ── nested JsonView at path ─────────────────────────────────────────
450        let inner_for_nested = if is_option {
451            option_inner_type(field_type).unwrap_or(field_type)
452        } else {
453            field_type
454        };
455        // Serde-like default: unknown types are nested JsonView objects at `path`.
456        // Compile-time `T: JsonView` (via read_view_at) fails with a diagnostic note.
457        // Custom FromJsonSlice newtypes must opt out with `#[json(from_slice)]`.
458        let treat_as_nested = attrs.nested
459            || (!attrs.from_slice
460                && !attrs.map
461                && !is_from_json_slice_type(field_type)
462                && map_string_value_type(inner_for_nested).is_none());
463        if treat_as_nested {
464            if jmes_opt.is_some() {
465                return Err(syn::Error::new_spanned(
466                    field,
467                    "nested JsonView fields cannot use jmes (use path to the child object)",
468                ));
469            }
470            field_path_lits.push(raw_path.clone());
471            field_jmes_lits.push(raw_path.clone());
472            project_hash_names.push(field_name.to_string());
473            project_hash_jmes.push(raw_path.clone());
474
475            if let [DerSegment::Key(k)] = path_segments.as_slice() {
476                schema_emits.push(SchemaEmit::Nested {
477                    key: k.clone(),
478                    fname: field_name.clone(),
479                    is_option,
480                });
481            } else {
482                all_paths_flat = false;
483            }
484
485            let nest_ty = if is_option {
486                option_inner_type(field_type).ok_or_else(|| {
487                    syn::Error::new_spanned(field, "Option nested requires Option<T: JsonView>")
488                })?
489            } else {
490                field_type
491            };
492
493            if is_option {
494                field_reads.push(quote! {
495                    #field_name: jshift::read_view_at_opt::<#nest_ty>(json, Self::#path_const_name)?
496                });
497                field_reads_indexed.push(quote! {
498                    #field_name: jshift::read_view_at_opt::<#nest_ty>(
499                        doc.as_bytes(),
500                        Self::#path_const_name,
501                    )?
502                });
503                field_reads_doc.push(quote! {
504                    #field_name: jshift::read_view_at_opt::<#nest_ty>(
505                        doc.as_bytes(),
506                        Self::#path_const_name,
507                    )?
508                });
509                write_fields.push(quote! {
510                    jshift::write_view_at_opt(
511                        json,
512                        Self::#path_const_name,
513                        self.#field_name.as_ref(),
514                    )?;
515                });
516                mutator_setters.push(quote! {
517                    /// Upsert nested view schema at this path (`None` = no-op).
518                    pub fn #setter_name(
519                        &mut self,
520                        val: Option<&#nest_ty>,
521                    ) -> Result<(), jshift::Error> {
522                        jshift::write_view_at_opt(self.json, #struct_name::#path_const_name, val)
523                    }
524                });
525            } else if use_default {
526                field_reads.push(quote! {
527                    #field_name: match jshift::read_view_at::<#field_type>(json, Self::#path_const_name)
528                    {
529                        Ok(v) => v,
530                        Err(jshift::Error::PathNotFound) => {
531                            <#field_type as core::default::Default>::default()
532                        }
533                        Err(e) => return Err(e),
534                    }
535                });
536                field_reads_indexed.push(quote! {
537                    #field_name: match jshift::read_view_at::<#field_type>(
538                        doc.as_bytes(),
539                        Self::#path_const_name,
540                    ) {
541                        Ok(v) => v,
542                        Err(jshift::Error::PathNotFound) => {
543                            <#field_type as core::default::Default>::default()
544                        }
545                        Err(e) => return Err(e),
546                    }
547                });
548                field_reads_doc.push(quote! {
549                    #field_name: match jshift::read_view_at::<#field_type>(
550                        doc.as_bytes(),
551                        Self::#path_const_name,
552                    ) {
553                        Ok(v) => v,
554                        Err(jshift::Error::PathNotFound) => {
555                            <#field_type as core::default::Default>::default()
556                        }
557                        Err(e) => return Err(e),
558                    }
559                });
560                write_fields.push(quote! {
561                    jshift::write_view_at(json, Self::#path_const_name, &self.#field_name)?;
562                });
563                mutator_setters.push(quote! {
564                    pub fn #setter_name(&mut self, val: &#field_type) -> Result<(), jshift::Error> {
565                        jshift::write_view_at(self.json, #struct_name::#path_const_name, val)
566                    }
567                });
568            } else {
569                field_reads.push(quote! {
570                    #field_name: jshift::read_view_at::<#field_type>(json, Self::#path_const_name)?
571                });
572                field_reads_indexed.push(quote! {
573                    #field_name: jshift::read_view_at::<#field_type>(
574                        doc.as_bytes(),
575                        Self::#path_const_name,
576                    )?
577                });
578                field_reads_doc.push(quote! {
579                    #field_name: jshift::read_view_at::<#field_type>(
580                        doc.as_bytes(),
581                        Self::#path_const_name,
582                    )?
583                });
584                write_fields.push(quote! {
585                    jshift::write_view_at(json, Self::#path_const_name, &self.#field_name)?;
586                });
587                mutator_setters.push(quote! {
588                    pub fn #setter_name(&mut self, val: &#field_type) -> Result<(), jshift::Error> {
589                        jshift::write_view_at(self.json, #struct_name::#path_const_name, val)
590                    }
591                });
592            }
593            continue;
594        }
595
596        // ── scalar FromJsonSlice field ──────────────────────────────────────
597        field_path_lits.push(raw_path.clone());
598        field_jmes_lits.push(jmes_expr.clone());
599        project_hash_names.push(field_name.to_string());
600        project_hash_jmes.push(jmes_expr.clone());
601
602        match path_segments.as_slice() {
603            [DerSegment::Key(k)] => {
604                schema_emits.push(SchemaEmit::Key {
605                    key: k.clone(),
606                    fname: field_name.clone(),
607                });
608            }
609            _ => {
610                all_paths_flat = false;
611            }
612        }
613
614        let uses_jmes_read = jmes_opt.is_some();
615
616        if is_option {
617            if uses_jmes_read {
618                field_reads.push(quote! {
619                    #field_name: {
620                        match jshift::project_jmespath(json, Self::#jmes_const_name) {
621                            Ok(bytes) => {
622                                if bytes == b"null" {
623                                    None
624                                } else {
625                                    jshift::FromJsonSlice::from_json_slice(&bytes)
626                                        .ok_or(jshift::Error::TypeMismatch {
627                                            expected: stringify!(#field_type),
628                                            found: "invalid format",
629                                        })?
630                                }
631                            }
632                            Err(jshift::Error::PathNotFound) => None,
633                            Err(e) => return Err(e),
634                        }
635                    }
636                });
637            } else {
638                field_reads.push(quote! {
639                    #field_name: {
640                        match jshift::find_value(json, Self::#path_const_name) {
641                            Ok(slice) => {
642                                jshift::FromJsonSlice::from_json_slice(slice)
643                                    .ok_or(jshift::Error::TypeMismatch {
644                                        expected: stringify!(#field_type),
645                                        found: "invalid format",
646                                    })?
647                            }
648                            Err(jshift::Error::PathNotFound) => None,
649                            Err(e) => return Err(e),
650                        }
651                    }
652                });
653            }
654            field_reads_indexed.push(quote! {
655                #field_name: {
656                    match doc.find(Self::#path_const_name) {
657                        Ok(slice) => {
658                            jshift::FromJsonSlice::from_json_slice(slice)
659                                .ok_or(jshift::Error::TypeMismatch {
660                                    expected: stringify!(#field_type),
661                                    found: "invalid format",
662                                })?
663                        }
664                        Err(jshift::Error::PathNotFound) => None,
665                        Err(e) => return Err(e),
666                    }
667                }
668            });
669            field_reads_doc.push(quote! {
670                #field_name: {
671                    match doc.find(Self::#path_const_name) {
672                        Ok(slice) => {
673                            jshift::FromJsonSlice::from_json_slice(slice)
674                                .ok_or(jshift::Error::TypeMismatch {
675                                    expected: stringify!(#field_type),
676                                    found: "invalid format",
677                                })?
678                        }
679                        Err(jshift::Error::PathNotFound) => None,
680                        Err(e) => return Err(e),
681                    }
682                }
683            });
684        } else if uses_jmes_read {
685            field_reads.push(quote! {
686                #field_name: {
687                    let bytes = jshift::project_jmespath(json, Self::#jmes_const_name)?;
688                    jshift::FromJsonSlice::from_json_slice(&bytes)
689                        .ok_or(jshift::Error::TypeMismatch {
690                            expected: stringify!(#field_type),
691                            found: "invalid format",
692                        })?
693                }
694            });
695            field_reads_indexed.push(quote! {
696                #field_name: {
697                    let bytes = jshift::project_jmespath(doc.as_bytes(), Self::#jmes_const_name)?;
698                    jshift::FromJsonSlice::from_json_slice(&bytes)
699                        .ok_or(jshift::Error::TypeMismatch {
700                            expected: stringify!(#field_type),
701                            found: "invalid format",
702                        })?
703                }
704            });
705            field_reads_doc.push(quote! {
706                #field_name: {
707                    let bytes = jshift::project_jmespath(doc.as_bytes(), Self::#jmes_const_name)?;
708                    jshift::FromJsonSlice::from_json_slice(&bytes)
709                        .ok_or(jshift::Error::TypeMismatch {
710                            expected: stringify!(#field_type),
711                            found: "invalid format",
712                        })?
713                }
714            });
715        } else if use_default {
716            field_reads.push(quote! {
717                #field_name: {
718                    match jshift::find_value(json, Self::#path_const_name) {
719                        Ok(slice) => {
720                            jshift::FromJsonSlice::from_json_slice(slice)
721                                .ok_or(jshift::Error::TypeMismatch {
722                                    expected: stringify!(#field_type),
723                                    found: "invalid format",
724                                })?
725                        }
726                        Err(jshift::Error::PathNotFound) => {
727                            <#field_type as core::default::Default>::default()
728                        }
729                        Err(e) => return Err(e),
730                    }
731                }
732            });
733            field_reads_indexed.push(quote! {
734                #field_name: {
735                    match doc.find(Self::#path_const_name) {
736                        Ok(slice) => {
737                            jshift::FromJsonSlice::from_json_slice(slice)
738                                .ok_or(jshift::Error::TypeMismatch {
739                                    expected: stringify!(#field_type),
740                                    found: "invalid format",
741                                })?
742                        }
743                        Err(jshift::Error::PathNotFound) => {
744                            <#field_type as core::default::Default>::default()
745                        }
746                        Err(e) => return Err(e),
747                    }
748                }
749            });
750            field_reads_doc.push(quote! {
751                #field_name: {
752                    match doc.find(Self::#path_const_name) {
753                        Ok(slice) => {
754                            jshift::FromJsonSlice::from_json_slice(slice)
755                                .ok_or(jshift::Error::TypeMismatch {
756                                    expected: stringify!(#field_type),
757                                    found: "invalid format",
758                                })?
759                        }
760                        Err(jshift::Error::PathNotFound) => {
761                            <#field_type as core::default::Default>::default()
762                        }
763                        Err(e) => return Err(e),
764                    }
765                }
766            });
767        } else {
768            field_reads.push(quote! {
769                #field_name: {
770                    let slice = jshift::find_value(json, Self::#path_const_name)?;
771                    jshift::FromJsonSlice::from_json_slice(slice)
772                        .ok_or(jshift::Error::TypeMismatch {
773                            expected: stringify!(#field_type),
774                            found: "invalid format",
775                        })?
776                }
777            });
778            field_reads_indexed.push(quote! {
779                #field_name: {
780                    let slice = doc.find(Self::#path_const_name)?;
781                    jshift::FromJsonSlice::from_json_slice(slice)
782                        .ok_or(jshift::Error::TypeMismatch {
783                            expected: stringify!(#field_type),
784                            found: "invalid format",
785                        })?
786                }
787            });
788            field_reads_doc.push(quote! {
789                #field_name: {
790                    let slice = doc.find(Self::#path_const_name)?;
791                    jshift::FromJsonSlice::from_json_slice(slice)
792                        .ok_or(jshift::Error::TypeMismatch {
793                            expected: stringify!(#field_type),
794                            found: "invalid format",
795                        })?
796                }
797            });
798        }
799
800        write_fields.push(quote! {
801            {
802                let bytes = jshift::ToJsonBytes::to_json_bytes(&self.#field_name);
803                jshift::upsert_at_path(json, Self::#path_const_name, &bytes)?;
804            }
805        });
806
807        mutator_setters.push(quote! {
808            pub fn #setter_name(&mut self, val: &(impl jshift::ToJsonBytes + ?Sized)) -> Result<(), jshift::Error> {
809                let bytes = jshift::ToJsonBytes::to_json_bytes(val);
810                jshift::mutate_value(self.json, #struct_name::#path_const_name, &bytes)
811            }
812        });
813
814        if let Some((parent_segs, last_key)) = parent_and_last_key(&path_segments) {
815            let delete_name = Ident::new(&format!("delete_{}", field_name), field_name.span());
816            let parent_tokens: Vec<_> = parent_segs
817                .iter()
818                .map(|s| match s {
819                    DerSegment::Key(k) => quote! { jshift::PathSegment::Key(#k) },
820                    DerSegment::Index(i) => quote! { jshift::PathSegment::Index(#i) },
821                })
822                .collect();
823            mutator_setters.push(quote! {
824                /// Remove this field’s object member (`delete_key` on parent + last key).
825                ///
826                /// Early keys in a large document still **memmove the buffer tail** —
827                /// prefer trailing keys / sparse open-view edits when possible.
828                /// See [`jshift::delete_key`].
829                pub fn #delete_name(&mut self) -> Result<(), jshift::Error> {
830                    const PARENT: &[jshift::PathSegment<'static>] = &[#(#parent_tokens),*];
831                    jshift::delete_key(self.json, PARENT, #last_key)
832                }
833            });
834        }
835
836        if is_vec_type(field_type) {
837            let append_name = Ident::new(&format!("append_{}", field_name), field_name.span());
838            let prepend_name = Ident::new(&format!("prepend_{}", field_name), field_name.span());
839            let insert_name = Ident::new(&format!("insert_{}", field_name), field_name.span());
840            let delete_at_name =
841                Ident::new(&format!("delete_{}_at", field_name), field_name.span());
842            mutator_setters.push(quote! {
843                pub fn #append_name(&mut self, val: &(impl jshift::ToJsonBytes + ?Sized)) -> Result<(), jshift::Error> {
844                    let bytes = jshift::ToJsonBytes::to_json_bytes(val);
845                    jshift::append_to_array(self.json, #struct_name::#path_const_name, &bytes)
846                }
847
848                pub fn #prepend_name(&mut self, val: &(impl jshift::ToJsonBytes + ?Sized)) -> Result<(), jshift::Error> {
849                    let bytes = jshift::ToJsonBytes::to_json_bytes(val);
850                    jshift::prepend_to_array(self.json, #struct_name::#path_const_name, &bytes)
851                }
852
853                pub fn #insert_name(
854                    &mut self,
855                    index: usize,
856                    val: &(impl jshift::ToJsonBytes + ?Sized),
857                ) -> Result<(), jshift::Error> {
858                    let bytes = jshift::ToJsonBytes::to_json_bytes(val);
859                    jshift::insert_array_element(
860                        self.json,
861                        #struct_name::#path_const_name,
862                        index,
863                        &bytes,
864                    )
865                }
866
867                /// Remove element `index` from this `Vec` field’s JSON array.
868                ///
869                /// Shifts the buffer tail after the removed span (cheaper near the
870                /// array end). See [`jshift::delete_index`].
871                pub fn #delete_at_name(&mut self, index: usize) -> Result<(), jshift::Error> {
872                    jshift::delete_index(self.json, #struct_name::#path_const_name, index)
873                }
874            });
875        }
876    }
877
878    let array_path_lits: Vec<_> = array_prefixes.iter().map(|s| quote! { #s }).collect();
879    let field_path_tokens: Vec<_> = field_path_lits.iter().map(|s| quote! { #s }).collect();
880    let field_jmes_tokens: Vec<_> = field_jmes_lits.iter().map(|s| quote! { #s }).collect();
881    let project_hash_name_tokens: Vec<_> =
882        project_hash_names.iter().map(|s| quote! { #s }).collect();
883    let project_hash_jmes_tokens: Vec<_> =
884        project_hash_jmes.iter().map(|s| quote! { #s }).collect();
885
886    let flatten_child_path_refs: Vec<_> = flatten_child_types
887        .iter()
888        .map(|ty| quote! { #ty::FIELD_PATHS })
889        .collect();
890
891    let project_plan_body = if has_any_jmes && has_flatten {
892        return Err(syn::Error::new_spanned(
893            input,
894            "#[json(jmes)] and #[json(flatten)] on the same struct are not supported together yet",
895        ));
896    } else if has_any_jmes {
897        quote! {
898            {
899                let mut fields = Vec::new();
900                let names: &[&str] = &[#(#project_hash_name_tokens),*];
901                let exprs: &[&str] = &[#(#project_hash_jmes_tokens),*];
902                for (name, expr) in names.iter().zip(exprs.iter()) {
903                    let sel = jshift::parse_jmespath_expr(expr)
904                        .expect("FIELD_JMES entries must be valid JMESPath");
905                    fields.push(jshift::HashField::new((*name).to_string(), sel));
906                }
907                jshift::ProjectPlan::from_select(jshift::SelectExpr::MultiSelectHash(fields))
908            }
909        }
910    } else if has_flatten {
911        quote! {
912            jshift::project_plan_with_flatten(
913                Self::FIELD_PATHS,
914                &[#(#flatten_child_path_refs),*],
915            )
916            .expect("FIELD_PATHS + flattened FIELD_PATHS must be valid project paths")
917        }
918    } else {
919        quote! {
920            jshift::ProjectPlan::from_paths(Self::FIELD_PATHS)
921                .expect("FIELD_PATHS must be valid project paths")
922        }
923    };
924
925    // One-pass ObjectBuilder when every non-flatten path is a single key
926    // (flatten members are raw-copied from child schema objects).
927    let schema_bytes_override = if all_paths_flat && !schema_emits.is_empty() {
928        let builder_stmts: Vec<_> = schema_emits
929            .iter()
930            .map(|e| match e {
931                SchemaEmit::Key { key, fname } => {
932                    quote! { b = b.field(#key, &self.#fname); }
933                }
934                SchemaEmit::Flatten { fname, is_option: false } => {
935                    quote! {
936                        b = b.flatten_view(&self.#fname)?;
937                    }
938                }
939                SchemaEmit::Flatten { fname, is_option: true } => {
940                    quote! {
941                        if let Some(ref child) = self.#fname {
942                            b = b.flatten_view(child)?;
943                        }
944                    }
945                }
946                SchemaEmit::Nested {
947                    key,
948                    fname,
949                    is_option: false,
950                } => {
951                    quote! {
952                        b = b.raw_field(#key, &self.#fname.to_schema_bytes()?);
953                    }
954                }
955                SchemaEmit::Nested {
956                    key,
957                    fname,
958                    is_option: true,
959                } => {
960                    quote! {
961                        if let Some(ref child) = self.#fname {
962                            b = b.raw_field(#key, &child.to_schema_bytes()?);
963                        }
964                    }
965                }
966                SchemaEmit::Map {
967                    key,
968                    fname,
969                    is_option: false,
970                    kind,
971                } => {
972                    let write_local = match kind {
973                        MapKind::HashMap => quote! {
974                            {
975                                let mut mb = jshift::ObjectBuilder::new();
976                                for (k, v) in &self.#fname {
977                                    mb = mb.field(k, v);
978                                }
979                                mb.finish()
980                            }
981                        },
982                        MapKind::BTreeMap => quote! {
983                            {
984                                let mut mb = jshift::ObjectBuilder::new();
985                                for (k, v) in &self.#fname {
986                                    mb = mb.field(k, v);
987                                }
988                                mb.finish()
989                            }
990                        },
991                    };
992                    quote! {
993                        b = b.raw_field(#key, &#write_local);
994                    }
995                }
996                SchemaEmit::Map {
997                    key,
998                    fname,
999                    is_option: true,
1000                    ..
1001                } => {
1002                    quote! {
1003                        if let Some(ref m) = self.#fname {
1004                            let mut mb = jshift::ObjectBuilder::new();
1005                            for (k, v) in m {
1006                                mb = mb.field(k, v);
1007                            }
1008                            b = b.raw_field(#key, &mb.finish());
1009                        }
1010                    }
1011                }
1012            })
1013            .collect();
1014        quote! {
1015            /// Single-pass schema emit (flat keys + byte-level flatten spreads).
1016            #[inline]
1017            fn to_schema_bytes(&self) -> Result<Vec<u8>, jshift::Error> {
1018                let mut b = jshift::ObjectBuilder::new();
1019                #(#builder_stmts)*
1020                Ok(b.finish())
1021            }
1022        }
1023    } else {
1024        quote! {}
1025    };
1026
1027    Ok(quote! {
1028        impl #struct_name {
1029            #(#path_statics)*
1030
1031            /// All `#[json(path = ...)]` paths for this view (schema surface).
1032            pub const FIELD_PATHS: &'static [&'static str] = &[
1033                #(#field_path_tokens),*
1034            ];
1035
1036            /// Per-field JMESPath (or path fallback) used for schema projection.
1037            ///
1038            /// Set with `#[json(jmes = "...")]`. When unset, equals the path string.
1039            pub const FIELD_JMES: &'static [&'static str] = &[
1040                #(#field_jmes_tokens),*
1041            ];
1042
1043            /// Static array path prefixes inferred from field paths (for auto-index).
1044            ///
1045            /// e.g. `products[0].title` contributes `"products"`.
1046            /// Schema-complete index plan: runtime only builds what paths need.
1047            pub const INDEXED_ARRAY_PATHS: &'static [&'static str] = &[
1048                #(#array_path_lits),*
1049            ];
1050
1051            pub fn read_from_json(json: &[u8]) -> Result<Self, jshift::Error> {
1052                Ok(Self {
1053                    #(#field_reads),*
1054                })
1055            }
1056
1057            /// Build an [`jshift::IndexedDocument`] for this schema's array paths
1058            /// (Stage-1 structural + array side-tables).
1059            pub fn indexed_document(json: &[u8]) -> Result<jshift::IndexedDocument<'_>, jshift::Error> {
1060                let mut doc = jshift::IndexedDocument::empty(json);
1061                doc.index_structural()?;
1062                for p in Self::INDEXED_ARRAY_PATHS {
1063                    doc.index_array_str(p)?;
1064                }
1065                Ok(doc)
1066            }
1067
1068            /// Schema-guided prepare: same as [`Self::indexed_document`].
1069            #[inline]
1070            pub fn prepare(json: &[u8]) -> Result<jshift::IndexedDocument<'_>, jshift::Error> {
1071                Self::indexed_document(json)
1072            }
1073
1074            /// Like [`Self::read_from_json`] but uses [`Self::indexed_document`] so
1075            /// paths through large arrays jump via side-tables.
1076            pub fn read_from_json_indexed(json: &[u8]) -> Result<Self, jshift::Error> {
1077                let doc = Self::indexed_document(json)?;
1078                Ok(Self {
1079                    #(#field_reads_indexed),*
1080                })
1081            }
1082
1083            /// Read using a pre-built index (reuses side-tables across views).
1084            ///
1085            /// Prefer [`jshift::JsonView::read_from_doc`] in generic code.
1086            pub fn from_indexed_document(
1087                doc: &jshift::IndexedDocument<'_>,
1088            ) -> Result<Self, jshift::Error> {
1089                Ok(Self {
1090                    #(#field_reads_doc),*
1091                })
1092            }
1093
1094            /// Upsert all schema fields into `json` (unmentioned paths preserved).
1095            pub fn write_into_json(&self, json: &mut Vec<u8>) -> Result<(), jshift::Error> {
1096                #(#write_fields)*
1097                Ok(())
1098            }
1099
1100            /// Build a new buffer with only this schema’s fields (0.6 schema writer).
1101            ///
1102            /// Flat top-level paths: single-pass [`jshift::ObjectBuilder`]. Nested paths:
1103            /// upsert onto `{}` + project keep-list.
1104            #[inline]
1105            pub fn to_schema_json(&self) -> Result<Vec<u8>, jshift::Error> {
1106                jshift::JsonView::to_schema_bytes(self)
1107            }
1108
1109            /// Rough projected size if only this schema's fields were kept.
1110            pub fn estimate_projected_len(json: &[u8]) -> Result<usize, jshift::Error> {
1111                jshift::estimate_projected_len(json, Self::FIELD_PATHS)
1112            }
1113
1114            /// Schema project plan: keep-list paths, or multi-select hash when any
1115            /// field uses `#[json(jmes = "...")]`.
1116            pub fn schema_project_plan() -> jshift::ProjectPlan {
1117                #project_plan_body
1118            }
1119
1120            /// Project a document down to this schema (new buffer).
1121            pub fn project_json(json: &[u8]) -> Result<Vec<u8>, jshift::Error> {
1122                jshift::project(json, &Self::schema_project_plan())
1123            }
1124
1125            /// Project using a shared [`jshift::IndexedDocument`] snapshot.
1126            pub fn project_indexed(doc: &jshift::IndexedDocument<'_>) -> Result<Vec<u8>, jshift::Error> {
1127                jshift::project_indexed(doc, &Self::schema_project_plan())
1128            }
1129
1130            /// Index arrays from the schema plan (if missing), then project.
1131            pub fn project_indexed_prepare(
1132                doc: &mut jshift::IndexedDocument<'_>,
1133            ) -> Result<Vec<u8>, jshift::Error> {
1134                jshift::project_indexed_prepare(doc, &Self::schema_project_plan())
1135            }
1136
1137            /// One-shot: build plan indexes + project (see [`jshift::project_auto_indexed`]).
1138            pub fn project_auto_indexed(json: &[u8]) -> Result<Vec<u8>, jshift::Error> {
1139                jshift::project_auto_indexed(json, &Self::schema_project_plan())
1140            }
1141
1142            pub fn mutator(json: &mut Vec<u8>) -> #mutator_name {
1143                #mutator_name { json }
1144            }
1145        }
1146
1147        impl jshift::JsonView for #struct_name {
1148            #[inline]
1149            fn read_from(json: &[u8]) -> Result<Self, jshift::Error> {
1150                Self::read_from_json(json)
1151            }
1152
1153            #[inline]
1154            fn read_from_indexed(json: &[u8]) -> Result<Self, jshift::Error> {
1155                Self::read_from_json_indexed(json)
1156            }
1157
1158            #[inline]
1159            fn read_from_doc(doc: &jshift::IndexedDocument<'_>) -> Result<Self, jshift::Error> {
1160                Self::from_indexed_document(doc)
1161            }
1162
1163            #[inline]
1164            fn write_into(&self, json: &mut Vec<u8>) -> Result<(), jshift::Error> {
1165                self.write_into_json(json)
1166            }
1167
1168            #[inline]
1169            fn project_plan() -> jshift::ProjectPlan {
1170                Self::schema_project_plan()
1171            }
1172
1173            #[inline]
1174            fn project_bytes(json: &[u8]) -> Result<Vec<u8>, jshift::Error> {
1175                Self::project_json(json)
1176            }
1177
1178            #schema_bytes_override
1179        }
1180
1181        pub struct #mutator_name<'a> {
1182            json: &'a mut Vec<u8>,
1183        }
1184
1185        impl<'a> #mutator_name<'a> {
1186            #(#mutator_setters)*
1187        }
1188    })
1189}
1190
1191struct JsonFieldAttrs {
1192    path: String,
1193    jmes: Option<String>,
1194    use_default: bool,
1195    flatten: bool,
1196    /// Force nested `JsonView` at `path` (also auto when type is not a scalar/map).
1197    nested: bool,
1198    /// Force map decode (`HashMap`/`BTreeMap`); usually auto-detected.
1199    map: bool,
1200    /// Force `FromJsonSlice` (custom newtypes that are not built-in scalars).
1201    from_slice: bool,
1202    /// True when `path = "..."` was written explicitly (not field-name default).
1203    path_explicit: bool,
1204}
1205
1206/// Parse `#[json(...)]` on a field.
1207///
1208/// * `path` — defaults to the field name
1209/// * `jmes` — optional JMESPath read
1210/// * `default` — `PathNotFound` → `Default::default()`
1211/// * `flatten` — byte-level serde-style flatten (`T: JsonView` on same parent object)
1212/// * `nested` — nested `JsonView` at path (`{"meta":{...}}`)
1213/// * `map` — string-key map (`HashMap`/`BTreeMap`) at path
1214/// * `from_slice` — decode with `FromJsonSlice` (custom scalar newtypes)
1215fn get_json_attrs(field: &syn::Field) -> Result<JsonFieldAttrs, syn::Error> {
1216    let mut path_str = None;
1217    let mut jmes_str = None;
1218    let mut use_default = false;
1219    let mut flatten = false;
1220    let mut nested = false;
1221    let mut map = false;
1222    let mut from_slice = false;
1223    for attr in &field.attrs {
1224        if attr.path().is_ident("json") {
1225            attr.parse_nested_meta(|meta| {
1226                if meta.path.is_ident("path") {
1227                    let value = meta.value()?;
1228                    let lit: syn::LitStr = value.parse()?;
1229                    path_str = Some(lit.value());
1230                    Ok(())
1231                } else if meta.path.is_ident("jmes") {
1232                    let value = meta.value()?;
1233                    let lit: syn::LitStr = value.parse()?;
1234                    jmes_str = Some(lit.value());
1235                    Ok(())
1236                } else if meta.path.is_ident("default") {
1237                    use_default = true;
1238                    Ok(())
1239                } else if meta.path.is_ident("flatten") {
1240                    flatten = true;
1241                    Ok(())
1242                } else if meta.path.is_ident("nested") {
1243                    nested = true;
1244                    Ok(())
1245                } else if meta.path.is_ident("map") {
1246                    map = true;
1247                    Ok(())
1248                } else if meta.path.is_ident("from_slice") {
1249                    from_slice = true;
1250                    Ok(())
1251                } else {
1252                    Err(meta.error(
1253                        "unsupported json attribute; expected `path`, `jmes`, `default`, `flatten`, `nested`, `map`, or `from_slice`",
1254                    ))
1255                }
1256            })?;
1257        }
1258    }
1259
1260    if nested && from_slice {
1261        return Err(syn::Error::new_spanned(
1262            field,
1263            "`nested` and `from_slice` are mutually exclusive",
1264        ));
1265    }
1266    if flatten && (nested || from_slice || map) {
1267        return Err(syn::Error::new_spanned(
1268            field,
1269            "`flatten` cannot be combined with `nested`, `from_slice`, or `map`",
1270        ));
1271    }
1272
1273    let path_explicit = path_str.is_some();
1274    let path = path_str.unwrap_or_else(|| {
1275        field
1276            .ident
1277            .as_ref()
1278            .expect("named field")
1279            .to_string()
1280    });
1281    Ok(JsonFieldAttrs {
1282        path,
1283        jmes: jmes_str,
1284        use_default,
1285        flatten,
1286        nested,
1287        map,
1288        from_slice,
1289        path_explicit,
1290    })
1291}
1292
1293/// Inner type of `Option<T>`, if any.
1294fn option_inner_type(ty: &Type) -> Option<&Type> {
1295    type_path_last(ty).and_then(|seg| {
1296        if seg.ident == "Option" {
1297            first_type_arg(seg)
1298        } else {
1299            None
1300        }
1301    })
1302}
1303
1304fn type_path_last(ty: &Type) -> Option<&syn::PathSegment> {
1305    match ty {
1306        Type::Path(type_path) => type_path.path.segments.last(),
1307        _ => None,
1308    }
1309}
1310
1311fn first_type_arg(seg: &syn::PathSegment) -> Option<&Type> {
1312    if let syn::PathArguments::AngleBracketed(args) = &seg.arguments {
1313        for arg in &args.args {
1314            if let syn::GenericArgument::Type(inner) = arg {
1315                return Some(inner);
1316            }
1317        }
1318    }
1319    None
1320}
1321
1322fn type_args(seg: &syn::PathSegment) -> Vec<&Type> {
1323    let mut out = Vec::new();
1324    if let syn::PathArguments::AngleBracketed(args) = &seg.arguments {
1325        for arg in &args.args {
1326            if let syn::GenericArgument::Type(inner) = arg {
1327                out.push(inner);
1328            }
1329        }
1330    }
1331    out
1332}
1333
1334fn is_string_type(ty: &Type) -> bool {
1335    type_path_last(ty).is_some_and(|s| s.ident == "String")
1336}
1337
1338/// Scalar / container types that use `FromJsonSlice` (not nested JsonView).
1339fn is_from_json_slice_type(ty: &Type) -> bool {
1340    if let Some(inner) = option_inner_type(ty) {
1341        return is_from_json_slice_type(inner);
1342    }
1343    if is_vec_type(ty) {
1344        if let Some(seg) = type_path_last(ty) {
1345            if let Some(inner) = first_type_arg(seg) {
1346                return is_from_json_slice_type(inner);
1347            }
1348        }
1349        return false;
1350    }
1351    let Some(seg) = type_path_last(ty) else {
1352        return false;
1353    };
1354    matches!(
1355        seg.ident.to_string().as_str(),
1356        "String"
1357            | "bool"
1358            | "u8"
1359            | "u16"
1360            | "u32"
1361            | "u64"
1362            | "usize"
1363            | "i8"
1364            | "i16"
1365            | "i32"
1366            | "i64"
1367            | "isize"
1368            | "f32"
1369            | "f64"
1370            | "RawJson"
1371    )
1372}
1373
1374#[derive(Clone, Copy)]
1375enum MapKind {
1376    HashMap,
1377    BTreeMap,
1378}
1379
1380/// `HashMap<String, V>` / `BTreeMap<String, V>` → (kind, V).
1381fn map_string_value_type(ty: &Type) -> Option<(MapKind, &Type)> {
1382    let seg = type_path_last(ty)?;
1383    let kind = if seg.ident == "HashMap" {
1384        MapKind::HashMap
1385    } else if seg.ident == "BTreeMap" {
1386        MapKind::BTreeMap
1387    } else {
1388        return None;
1389    };
1390    let args = type_args(seg);
1391    if args.len() != 2 {
1392        return None;
1393    }
1394    if !is_string_type(args[0]) {
1395        return None;
1396    }
1397    Some((kind, args[1]))
1398}
1399
1400fn is_vec_type(ty: &Type) -> bool {
1401    type_last_ident(ty).is_some_and(|id| id == "Vec")
1402}
1403
1404fn is_option_type(ty: &Type) -> bool {
1405    type_last_ident(ty).is_some_and(|id| id == "Option")
1406}
1407
1408fn type_last_ident(ty: &Type) -> Option<&syn::Ident> {
1409    if let Type::Path(type_path) = ty {
1410        type_path.path.segments.last().map(|s| &s.ident)
1411    } else {
1412        None
1413    }
1414}
1415
1416enum DerSegment {
1417    Key(String),
1418    Index(usize),
1419}
1420
1421fn parse_path_segments(s: &str) -> Result<Vec<DerSegment>, &'static str> {
1422    let mut rest = s;
1423    let mut segments = Vec::new();
1424    while !rest.is_empty() {
1425        if rest.starts_with('.') {
1426            rest = &rest[1..];
1427            continue;
1428        }
1429        if rest.starts_with('[') {
1430            match rest.find(']') {
1431                Some(end_idx) => {
1432                    let idx_str = &rest[1..end_idx];
1433                    if idx_str.is_empty() {
1434                        return Err("empty array index brackets");
1435                    }
1436                    if !idx_str.bytes().all(|b| b.is_ascii_digit()) {
1437                        return Err("non-numeric array index");
1438                    }
1439                    let idx = idx_str
1440                        .parse::<usize>()
1441                        .map_err(|_| "array index out of range for usize")?;
1442                    segments.push(DerSegment::Index(idx));
1443                    rest = &rest[end_idx + 1..];
1444                }
1445                None => return Err("unclosed array index bracket '['"),
1446            }
1447        } else {
1448            let end_key = rest.find(['.', '[']).unwrap_or(rest.len());
1449            let key = &rest[..end_key];
1450            if !key.is_empty() {
1451                segments.push(DerSegment::Key(key.to_string()));
1452            }
1453            rest = &rest[end_key..];
1454        }
1455    }
1456    Ok(segments)
1457}
1458
1459fn static_array_prefixes_from_segments(segs: &[DerSegment]) -> Vec<String> {
1460    let mut out = Vec::new();
1461    let mut keys: Vec<&str> = Vec::new();
1462    for s in segs {
1463        match s {
1464            DerSegment::Key(k) => keys.push(k.as_str()),
1465            DerSegment::Index(_) => {
1466                if !keys.is_empty() {
1467                    out.push(keys.join("."));
1468                }
1469                break;
1470            }
1471        }
1472    }
1473    out
1474}
1475
1476/// Split `a.b.c` → parent `[a, b]` + key `"c"` for [`jshift::delete_key`].
1477/// Returns `None` when the path is empty or does not end in a key segment.
1478fn parent_and_last_key(segs: &[DerSegment]) -> Option<(Vec<&DerSegment>, String)> {
1479    let last = segs.last()?;
1480    let DerSegment::Key(key) = last else {
1481        return None;
1482    };
1483    Some((segs[..segs.len() - 1].iter().collect(), key.clone()))
1484}
1485
1486/// Enum tagging (serde-compatible shapes).
1487///
1488/// | Attribute on enum | Wire |
1489/// | --- | --- |
1490/// | (default) | external: `"Ready"` / `{"Click":{…}}` |
1491/// | `#[json(tag = "type")]` | internal: `{"type":"Click","x":1}` |
1492/// | `#[json(tag = "t", content = "c")]` | adjacent: `{"t":"Click","c":{…}}` |
1493/// | `#[json(untagged)]` | try variants in declaration order |
1494///
1495/// Struct-variant fields: single top-level key paths. Newtype: `FromJsonSlice`.
1496/// Internal tagging does not support newtype variants (serde same limit).
1497fn expand_enum(input: &DeriveInput) -> Result<proc_macro2::TokenStream, syn::Error> {
1498    let enum_name = &input.ident;
1499    let data = match &input.data {
1500        Data::Enum(e) => e,
1501        _ => unreachable!(),
1502    };
1503    let repr = get_enum_repr(input)?;
1504
1505    let mut read_unit_arms = Vec::new();
1506    let mut read_obj_arms = Vec::new();
1507    let mut read_internal_arms = Vec::new();
1508    let mut read_adj_arms = Vec::new();
1509    let mut untagged_try = Vec::new();
1510    let mut write_arms = Vec::new();
1511    let mut has_unit = false;
1512    let mut has_obj = false;
1513
1514    for variant in &data.variants {
1515        let v_ident = &variant.ident;
1516        let tag = variant_rename(variant)?.unwrap_or_else(|| v_ident.to_string());
1517
1518        match &variant.fields {
1519            Fields::Unit => {
1520                has_unit = true;
1521                read_unit_arms.push(quote! { #tag => Some(Self::#v_ident), });
1522                read_internal_arms.push(quote! {
1523                    #tag => Ok(Self::#v_ident),
1524                });
1525                read_adj_arms.push(quote! {
1526                    (#tag, None) => Ok(Self::#v_ident),
1527                });
1528                untagged_try.push(quote! {
1529                    |j: &[u8]| {
1530                        jshift::read_external_unit(j, |n| {
1531                            if n == #tag { Some(Self::#v_ident) } else { None }
1532                        })
1533                    }
1534                });
1535                match &repr {
1536                    EnumRepr::External => {
1537                        write_arms.push(quote! {
1538                            Self::#v_ident => {
1539                                jshift::write_external_unit(out, #tag);
1540                                Ok(())
1541                            }
1542                        });
1543                    }
1544                    EnumRepr::Internal { tag: tk } => {
1545                        write_arms.push(quote! {
1546                            Self::#v_ident => {
1547                                jshift::write_internal_unit(out, #tk, #tag);
1548                                Ok(())
1549                            }
1550                        });
1551                    }
1552                    EnumRepr::Adjacent { tag: tk, .. } => {
1553                        write_arms.push(quote! {
1554                            Self::#v_ident => {
1555                                jshift::write_adjacent_unit(out, #tk, #tag);
1556                                Ok(())
1557                            }
1558                        });
1559                    }
1560                    EnumRepr::Untagged => {
1561                        write_arms.push(quote! {
1562                            Self::#v_ident => {
1563                                jshift::write_external_unit(out, #tag);
1564                                Ok(())
1565                            }
1566                        });
1567                    }
1568                }
1569            }
1570            Fields::Unnamed(f) if f.unnamed.len() == 1 => {
1571                if matches!(repr, EnumRepr::Internal { .. }) {
1572                    return Err(syn::Error::new_spanned(
1573                        variant,
1574                        "newtype variants are not supported with #[json(tag = …)] internal tagging (use adjacent content or external)",
1575                    ));
1576                }
1577                has_obj = true;
1578                let ty = &f.unnamed[0].ty;
1579                read_obj_arms.push(quote! {
1580                    #tag => {
1581                        let v = <#ty as jshift::FromJsonSlice>::from_json_slice(payload)
1582                            .ok_or(jshift::Error::TypeMismatch {
1583                                expected: stringify!(#ty),
1584                                found: "invalid format",
1585                            })?;
1586                        Ok(Self::#v_ident(v))
1587                    }
1588                });
1589                read_adj_arms.push(quote! {
1590                    (#tag, Some(payload)) => {
1591                        let v = <#ty as jshift::FromJsonSlice>::from_json_slice(payload)
1592                            .ok_or(jshift::Error::TypeMismatch {
1593                                expected: stringify!(#ty),
1594                                found: "invalid format",
1595                            })?;
1596                        Ok(Self::#v_ident(v))
1597                    }
1598                });
1599                untagged_try.push(quote! {
1600                    |j: &[u8]| {
1601                        let v = <#ty as jshift::FromJsonSlice>::from_json_slice(j)
1602                            .ok_or(jshift::Error::TypeMismatch {
1603                                expected: stringify!(#ty),
1604                                found: "invalid format",
1605                            })?;
1606                        Ok(Self::#v_ident(v))
1607                    }
1608                });
1609                match &repr {
1610                    EnumRepr::External => {
1611                        write_arms.push(quote! {
1612                            Self::#v_ident(v) => {
1613                                let payload = jshift::ToJsonBytes::to_json_bytes(v);
1614                                jshift::write_external_object(out, #tag, &payload);
1615                                Ok(())
1616                            }
1617                        });
1618                    }
1619                    EnumRepr::Adjacent { tag: tk, content: ck } => {
1620                        write_arms.push(quote! {
1621                            Self::#v_ident(v) => {
1622                                let payload = jshift::ToJsonBytes::to_json_bytes(v);
1623                                jshift::write_adjacent_content(out, #tk, #tag, #ck, &payload);
1624                                Ok(())
1625                            }
1626                        });
1627                    }
1628                    EnumRepr::Untagged => {
1629                        write_arms.push(quote! {
1630                            Self::#v_ident(v) => {
1631                                out.extend_from_slice(&jshift::ToJsonBytes::to_json_bytes(v));
1632                                Ok(())
1633                            }
1634                        });
1635                    }
1636                    EnumRepr::Internal { .. } => unreachable!(),
1637                }
1638            }
1639            Fields::Named(named) => {
1640                has_obj = true;
1641                let (field_reads, field_write_stmts, field_pats, field_keys) =
1642                    enum_struct_fields(named)?;
1643                let field_reads_payload = field_reads.clone();
1644                let field_reads_obj = field_reads;
1645
1646                read_obj_arms.push(quote! {
1647                    #tag => Ok(Self::#v_ident {
1648                        #(#field_reads_payload),*
1649                    }),
1650                });
1651                // Internal: fields live on the same object as the tag.
1652                read_internal_arms.push(quote! {
1653                    #tag => Ok(Self::#v_ident {
1654                        #(#field_reads_obj),*
1655                    }),
1656                });
1657                read_adj_arms.push(quote! {
1658                    (#tag, Some(payload)) => Ok(Self::#v_ident {
1659                        #(#field_reads_payload),*
1660                    }),
1661                });
1662                untagged_try.push(quote! {
1663                    |payload: &[u8]| {
1664                        Ok(Self::#v_ident {
1665                            #(#field_reads_payload),*
1666                        })
1667                    }
1668                });
1669
1670                match &repr {
1671                    EnumRepr::External => {
1672                        write_arms.push(quote! {
1673                            Self::#v_ident { #(#field_pats),* } => {
1674                                let mut b = jshift::ObjectBuilder::new();
1675                                #(#field_write_stmts)*
1676                                let payload = b.finish();
1677                                jshift::write_external_object(out, #tag, &payload);
1678                                Ok(())
1679                            }
1680                        });
1681                    }
1682                    EnumRepr::Internal { tag: tk } => {
1683                        write_arms.push(quote! {
1684                            Self::#v_ident { #(#field_pats),* } => {
1685                                let mut b = jshift::ObjectBuilder::new();
1686                                #(#field_write_stmts)*
1687                                let fields = b.finish();
1688                                jshift::write_internal_fields(out, #tk, #tag, &fields);
1689                                Ok(())
1690                            }
1691                        });
1692                    }
1693                    EnumRepr::Adjacent { tag: tk, content: ck } => {
1694                        write_arms.push(quote! {
1695                            Self::#v_ident { #(#field_pats),* } => {
1696                                let mut b = jshift::ObjectBuilder::new();
1697                                #(#field_write_stmts)*
1698                                let payload = b.finish();
1699                                jshift::write_adjacent_content(out, #tk, #tag, #ck, &payload);
1700                                Ok(())
1701                            }
1702                        });
1703                    }
1704                    EnumRepr::Untagged => {
1705                        let _ = field_keys;
1706                        write_arms.push(quote! {
1707                            Self::#v_ident { #(#field_pats),* } => {
1708                                let mut b = jshift::ObjectBuilder::new();
1709                                #(#field_write_stmts)*
1710                                out.extend_from_slice(&b.finish());
1711                                Ok(())
1712                            }
1713                        });
1714                    }
1715                }
1716            }
1717            Fields::Unnamed(_) => {
1718                return Err(syn::Error::new_spanned(
1719                    variant,
1720                    "tuple variants with != 1 field are not supported (use newtype or named fields)",
1721                ));
1722            }
1723        }
1724    }
1725
1726    if data.variants.is_empty() {
1727        return Err(syn::Error::new_spanned(input, "enum has no variants"));
1728    }
1729
1730    let read_from_body = match &repr {
1731        EnumRepr::External => {
1732            if has_unit && !has_obj {
1733                quote! {
1734                    jshift::read_external_unit(json, |name| match name {
1735                        #(#read_unit_arms)*
1736                        _ => None,
1737                    })
1738                }
1739            } else if !has_unit && has_obj {
1740                quote! {
1741                    jshift::read_external_object(json, |name, payload| match name {
1742                        #(#read_obj_arms)*
1743                        other => Err(jshift::Error::Decode {
1744                            path: other.to_string(),
1745                            expected: "known enum variant",
1746                            found: "unknown variant",
1747                            pos: None,
1748                        }),
1749                    })
1750                }
1751            } else {
1752                quote! {
1753                    jshift::read_external(
1754                        json,
1755                        |name| match name {
1756                            #(#read_unit_arms)*
1757                            _ => None,
1758                        },
1759                        |name, payload| match name {
1760                            #(#read_obj_arms)*
1761                            other => Err(jshift::Error::Decode {
1762                                path: other.to_string(),
1763                                expected: "known enum variant",
1764                                found: "unknown variant",
1765                                pos: None,
1766                            }),
1767                        },
1768                    )
1769                }
1770            }
1771        }
1772        EnumRepr::Internal { tag: tk } => {
1773            quote! {
1774                jshift::read_internal(json, #tk, |name, payload| match name {
1775                    #(#read_internal_arms)*
1776                    other => Err(jshift::Error::Decode {
1777                        path: other.to_string(),
1778                        expected: "known enum variant",
1779                        found: "unknown variant",
1780                        pos: None,
1781                    }),
1782                })
1783            }
1784        }
1785        EnumRepr::Adjacent { tag: tk, content: ck } => {
1786            quote! {
1787                jshift::read_adjacent(json, #tk, #ck, |name, content| match (name, content) {
1788                    #(#read_adj_arms)*
1789                    (other, _) => Err(jshift::Error::Decode {
1790                        path: other.to_string(),
1791                        expected: "known enum variant",
1792                        found: "unknown variant",
1793                        pos: None,
1794                    }),
1795                })
1796            }
1797        }
1798        EnumRepr::Untagged => {
1799            quote! {
1800                jshift::read_untagged(json, [
1801                    #(#untagged_try),*
1802                ])
1803            }
1804        }
1805    };
1806
1807    Ok(quote! {
1808        impl #enum_name {
1809            /// Encode this enum to a new JSON buffer (tagging style from `#[json(…)]`).
1810            pub fn to_schema_json(&self) -> Result<Vec<u8>, jshift::Error> {
1811                let mut out = Vec::with_capacity(32);
1812                self.write_tagged_to(&mut out)?;
1813                Ok(out)
1814            }
1815
1816            #[inline]
1817            fn write_tagged_to(&self, out: &mut Vec<u8>) -> Result<(), jshift::Error> {
1818                match self {
1819                    #(#write_arms),*
1820                }
1821            }
1822        }
1823
1824        impl jshift::JsonView for #enum_name {
1825            #[inline]
1826            fn read_from(json: &[u8]) -> Result<Self, jshift::Error> {
1827                #read_from_body
1828            }
1829
1830            fn write_into(&self, json: &mut Vec<u8>) -> Result<(), jshift::Error> {
1831                let bytes = self.to_schema_json()?;
1832                json.clear();
1833                json.extend_from_slice(&bytes);
1834                Ok(())
1835            }
1836
1837            #[inline]
1838            fn to_schema_bytes(&self) -> Result<Vec<u8>, jshift::Error> {
1839                self.to_schema_json()
1840            }
1841
1842            fn project_plan() -> jshift::ProjectPlan {
1843                jshift::ProjectPlan::identity()
1844            }
1845        }
1846    })
1847}
1848
1849enum EnumRepr {
1850    External,
1851    Internal { tag: String },
1852    Adjacent { tag: String, content: String },
1853    Untagged,
1854}
1855
1856fn get_enum_repr(input: &DeriveInput) -> Result<EnumRepr, syn::Error> {
1857    let mut tag: Option<String> = None;
1858    let mut content: Option<String> = None;
1859    let mut untagged = false;
1860    for attr in &input.attrs {
1861        if !attr.path().is_ident("json") {
1862            continue;
1863        }
1864        attr.parse_nested_meta(|meta| {
1865            if meta.path.is_ident("tag") {
1866                let value = meta.value()?;
1867                let lit: syn::LitStr = value.parse()?;
1868                tag = Some(lit.value());
1869                Ok(())
1870            } else if meta.path.is_ident("content") {
1871                let value = meta.value()?;
1872                let lit: syn::LitStr = value.parse()?;
1873                content = Some(lit.value());
1874                Ok(())
1875            } else if meta.path.is_ident("untagged") {
1876                untagged = true;
1877                Ok(())
1878            } else {
1879                Err(meta.error(
1880                    "unsupported enum json attribute; expected `tag`, `content`, or `untagged`",
1881                ))
1882            }
1883        })?;
1884    }
1885    if untagged && (tag.is_some() || content.is_some()) {
1886        return Err(syn::Error::new_spanned(
1887            input,
1888            "`untagged` cannot be combined with `tag` / `content`",
1889        ));
1890    }
1891    if let Some(c) = content {
1892        let Some(t) = tag else {
1893            return Err(syn::Error::new_spanned(
1894                input,
1895                "`content` requires `tag` (adjacent tagging)",
1896            ));
1897        };
1898        return Ok(EnumRepr::Adjacent { tag: t, content: c });
1899    }
1900    if let Some(t) = tag {
1901        return Ok(EnumRepr::Internal { tag: t });
1902    }
1903    if untagged {
1904        return Ok(EnumRepr::Untagged);
1905    }
1906    Ok(EnumRepr::External)
1907}
1908
1909/// Shared struct-variant field decode/encode for enums.
1910fn enum_struct_fields(
1911    named: &syn::FieldsNamed,
1912) -> Result<
1913    (
1914        Vec<proc_macro2::TokenStream>,
1915        Vec<proc_macro2::TokenStream>,
1916        Vec<&syn::Ident>,
1917        Vec<String>,
1918    ),
1919    syn::Error,
1920> {
1921    let mut field_reads = Vec::new();
1922    let mut field_write_stmts = Vec::new();
1923    let mut field_pats = Vec::new();
1924    let mut field_keys = Vec::new();
1925    for field in &named.named {
1926        let fname = field.ident.as_ref().unwrap();
1927        field_pats.push(fname);
1928        let attrs = get_json_attrs(field)?;
1929        if attrs.flatten {
1930            return Err(syn::Error::new_spanned(
1931                field,
1932                "#[json(flatten)] is not supported inside enum struct variants",
1933            ));
1934        }
1935        let path_segs = parse_path_segments(&attrs.path)
1936            .map_err(|msg| syn::Error::new_spanned(field, format!("invalid path: {msg}")))?;
1937        if path_segs.len() != 1 {
1938            return Err(syn::Error::new_spanned(
1939                field,
1940                "enum struct-variant fields must use a single top-level key path",
1941            ));
1942        }
1943        let DerSegment::Key(k) = &path_segs[0] else {
1944            return Err(syn::Error::new_spanned(
1945                field,
1946                "enum struct-variant fields must use a single top-level key path",
1947            ));
1948        };
1949        field_keys.push(k.clone());
1950        let seg_tokens: Vec<_> = path_segs
1951            .iter()
1952            .map(|s| match s {
1953                DerSegment::Key(key) => quote! { jshift::PathSegment::Key(#key) },
1954                DerSegment::Index(i) => quote! { jshift::PathSegment::Index(#i) },
1955            })
1956            .collect();
1957        let fty = &field.ty;
1958        let is_option = is_option_type(fty);
1959        let use_default = attrs.use_default;
1960        // `payload` is the name used in generated match arms (object or content).
1961        if is_option {
1962            field_reads.push(quote! {
1963                #fname: {
1964                    const P: &[jshift::PathSegment<'static>] = &[#(#seg_tokens),*];
1965                    match jshift::find_value(payload, P) {
1966                        Ok(slice) => {
1967                            jshift::FromJsonSlice::from_json_slice(slice)
1968                                .ok_or(jshift::Error::TypeMismatch {
1969                                    expected: stringify!(#fty),
1970                                    found: "invalid format",
1971                                })?
1972                        }
1973                        Err(jshift::Error::PathNotFound) => None,
1974                        Err(e) => return Err(e),
1975                    }
1976                }
1977            });
1978        } else if use_default {
1979            field_reads.push(quote! {
1980                #fname: {
1981                    const P: &[jshift::PathSegment<'static>] = &[#(#seg_tokens),*];
1982                    match jshift::find_value(payload, P) {
1983                        Ok(slice) => {
1984                            jshift::FromJsonSlice::from_json_slice(slice)
1985                                .ok_or(jshift::Error::TypeMismatch {
1986                                    expected: stringify!(#fty),
1987                                    found: "invalid format",
1988                                })?
1989                        }
1990                        Err(jshift::Error::PathNotFound) => {
1991                            <#fty as core::default::Default>::default()
1992                        }
1993                        Err(e) => return Err(e),
1994                    }
1995                }
1996            });
1997        } else {
1998            field_reads.push(quote! {
1999                #fname: {
2000                    const P: &[jshift::PathSegment<'static>] = &[#(#seg_tokens),*];
2001                    let slice = jshift::find_value(payload, P)?;
2002                    jshift::FromJsonSlice::from_json_slice(slice)
2003                        .ok_or(jshift::Error::TypeMismatch {
2004                            expected: stringify!(#fty),
2005                            found: "invalid format",
2006                        })?
2007                }
2008            });
2009        }
2010        field_write_stmts.push(quote! {
2011            b = b.field(#k, #fname);
2012        });
2013    }
2014    Ok((field_reads, field_write_stmts, field_pats, field_keys))
2015}
2016
2017fn variant_rename(variant: &syn::Variant) -> Result<Option<String>, syn::Error> {
2018    let mut rename = None;
2019    for attr in &variant.attrs {
2020        if attr.path().is_ident("json") {
2021            attr.parse_nested_meta(|meta| {
2022                if meta.path.is_ident("rename") {
2023                    let value = meta.value()?;
2024                    let lit: syn::LitStr = value.parse()?;
2025                    rename = Some(lit.value());
2026                    Ok(())
2027                } else {
2028                    Err(meta.error(
2029                        "unsupported enum variant attribute; expected `rename = \"...\"`",
2030                    ))
2031                }
2032            })?;
2033        }
2034    }
2035    Ok(rename)
2036}