sui-graphql-macros 0.3.1

Procedural macros for sui-graphql with compile-time validation
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
//! Compile-time validated macros for the Sui GraphQL API.
//!
//! Two macros, both validated against the embedded Sui GraphQL schema:
//!
//! - [`Response`] — derive macro for response types. Generates JSON
//!   deserialization from declarative field paths, catching unknown fields
//!   and type mismatches before your code runs.
//! - [`graphql_query!`] — function-style macro for query/mutation strings.
//!   Validates the source against the schema, so unknown fields, undefined
//!   variables, and bad arguments fail to compile.
//!
//! For a complete client that uses both, see
//! [`sui-graphql`](https://docs.rs/sui-graphql).
//!
//! # Quick Start
//!
//! ```no_run
//! use sui_graphql_macros::Response;
//!
//! #[derive(Response)]
//! struct ObjectData {
//!     #[field(path = "object.address")]
//!     address: String,
//!     #[field(path = "object.version")]
//!     version: u64,
//! }
//! fn main() {}
//! ```
//!
//! The macro validates that `object.address` and `object.version` exist in the schema
//! and that their types match at compile time. It then generates a
//! `from_value(serde_json::Value) -> Result<Self, String>` method and a `Deserialize`
//! implementation, so the struct can be used directly with
//! `serde_json::from_value` or as a response type in GraphQL client calls.
//!
//! # Path Syntax
//!
//! Paths use dot-separated segments with optional suffixes:
//!
//! | Syntax | Meaning | Rust Type |
//! |--------|---------|-----------|
//! | `field` | Required field | `T` |
//! | `field?` | Nullable field | `Option<T>` |
//! | `field[]` | Required list | `Vec<T>` |
//! | `field?[]` | Nullable list | `Option<Vec<T>>` |
//! | `field[]?` | List with nullable elements | `Vec<Option<T>>` |
//! | `field?[]?` | Nullable list, nullable elements | `Option<Vec<Option<T>>>` |
//!
//! Multiple `?` markers between `[]` boundaries share one `Option` wrapper.
//! Each `?` controls null tolerance at that specific segment.
//!
//! The macro enforces that path suffixes match the Rust type at compile time.
//! For example, `field?` requires `Option<T>`, and `field[]` requires `Vec<T>`.
//! A mismatch (e.g., `field?` with `String` or `field` with `Option<String>`)
//! produces a compile error.
//!
//! ## Null Handling
//!
//! ```no_run
//! use sui_graphql_macros::Response;
//!
//! #[derive(Response)]
//! struct Example {
//!     // null at `object` → error, null at `address` → error
//!     #[field(path = "object.address")]
//!     strict: String,
//!
//!     // null at `object` → Ok(None), null at `address` → Ok(None)
//!     #[field(path = "object?.address?")]
//!     flexible: Option<String>,
//!
//!     // null at `object` → Ok(None), null at `address` → error
//!     #[field(path = "object?.address")]
//!     partial: Option<String>,
//! }
//! fn main() {}
//! ```
//!
//! ## Lists
//!
//! Use `[]` to mark list fields. The macro validates this matches the schema.
//!
//! ```no_run
//! use sui_graphql_macros::Response;
//!
//! #[derive(Response)]
//! struct CheckpointDigests {
//!     #[field(path = "checkpoints.nodes[].digest")]
//!     digests: Vec<String>,
//!
//!     // Nullable list with nullable elements
//!     #[field(path = "checkpoints?.nodes?[]?.digest?")]
//!     maybe_digests: Option<Vec<Option<String>>>,
//! }
//! fn main() {}
//! ```
//!
//! ## Aliases
//!
//! Use `alias:field` when your GraphQL query uses aliases. The alias (before `:`) is the
//! JSON key used for extraction, while the field name (after `:`) is validated against
//! the schema. The alias itself is not schema-validated since it is user-defined in the
//! query.
//!
//! ```no_run
//! use sui_graphql_macros::Response;
//!
//! #[derive(Response)]
//! struct EpochCheckpoints {
//!     // GraphQL alias "firstCp" maps to schema field "checkpoints"
//!     #[field(path = "epoch.firstCp:checkpoints.nodes[].sequenceNumber")]
//!     first_checkpoints: Vec<u64>,
//! }
//! fn main() {}
//! ```
//!
//! ## Enums (GraphQL Unions)
//!
//! Use `#[response(root_type = "UnionType")]` on enums with newtype variants:
//!
//! ```ignore
//! #[derive(Response)]
//! #[response(root_type = "DynamicFieldValue")]
//! enum FieldValue {
//!     #[response(on = "MoveValue")]
//!     Value(MoveValueData),
//!     MoveObject(MoveObjectData), // `on` defaults to variant name
//! }
//! ```
//!
//! The macro dispatches on `__typename` in the JSON response.
//!
//! ## Attributes
//!
//! | Attribute | Level | Description |
//! |-----------|-------|-------------|
//! | `#[response(root_type = "Type")]` | struct/enum | Schema type to validate against (default: `"Query"`) |
//! | `#[response(schema = "path")]` | struct/enum | Custom schema file (relative to `CARGO_MANIFEST_DIR`) |
//! | `#[field(path = "...")]` | field | Dot-separated path with optional `?`/`[]`/alias |
//! | `#[field(skip_schema_validation)]` | field | Skip compile-time schema checks for this field |
//! | `#[response(on = "TypeName")]` | variant | GraphQL `__typename` to match (default: variant name) |

extern crate proc_macro;

mod path;
mod query;
mod schema;
mod validation;

use darling::FromDeriveInput;
use darling::FromField;
use darling::FromVariant;
use darling::util::SpannedValue;
use proc_macro::TokenStream;
use proc_macro2::TokenStream as TokenStream2;
use quote::quote;
use syn::DeriveInput;
use syn::parse_macro_input;

// ---------------------------------------------------------------------------
// Darling input structures — define the "schema" for macro input.
// Darling generates parsing code automatically, including error messages.
// ---------------------------------------------------------------------------

#[derive(Debug, FromDeriveInput)]
#[darling(attributes(response), supports(struct_named, enum_newtype))]
struct ResponseInput {
    ident: syn::Ident,
    generics: syn::Generics,
    data: darling::ast::Data<ResponseVariant, ResponseField>,
    #[darling(default)]
    schema: Option<String>,
    #[darling(default)]
    root_type: Option<SpannedValue<String>>,
}

/// A struct field (requires `#[field(path = "...")]`).
#[derive(Debug, FromField)]
#[darling(attributes(field))]
struct ResponseField {
    ident: Option<syn::Ident>,
    ty: syn::Type,
    path: SpannedValue<String>,
    #[darling(default)]
    skip_schema_validation: bool,
}

/// The inner type of a newtype enum variant.
#[derive(Debug, FromField)]
struct VariantInner {
    ty: syn::Type,
}

/// An enum variant mapping to a GraphQL union member.
#[derive(Debug, FromVariant)]
#[darling(attributes(response))]
struct ResponseVariant {
    ident: syn::Ident,
    fields: darling::ast::Fields<VariantInner>,
    /// The GraphQL type name this variant maps to (e.g., `#[response(on = "MoveValue")]`).
    /// Defaults to the variant ident if not specified.
    #[darling(default)]
    on: Option<SpannedValue<String>>,
}

/// Derive macro for GraphQL response types with nested field extraction.
///
/// Use `#[field(path = "...")]` to specify the JSON path to extract each field.
/// Paths are dot-separated (e.g., `"object.address"` extracts `json["object"]["address"]`).
///
/// # Root Type
///
/// By default, field paths are validated against the `Query` type. Use
/// `#[response(root_type = "...")]` to validate against a different type instead.
///
/// # Generated Code
///
/// The macro generates:
/// - `from_value(serde_json::Value) -> Result<Self, String>` method
/// - `Deserialize` implementation that uses `from_value`
///
/// # Example
///
/// ```ignore
/// // Query response (default)
/// #[derive(Response)]
/// struct ChainInfo {
///     #[field(path = "chainIdentifier")]
///     chain_id: String,
///
///     #[field(path = "epoch.epochId")]
///     epoch_id: Option<u64>,
/// }
///
/// // Mutation response
/// #[derive(Response)]
/// #[response(root_type = "Mutation")]
/// struct ExecuteResult {
///     #[field(path = "executeTransaction.effects.effectsBcs")]
///     effects_bcs: Option<String>,
/// }
/// ```
#[proc_macro_derive(Response, attributes(response, field))]
pub fn derive_query_response(input: TokenStream) -> TokenStream {
    let input = parse_macro_input!(input as DeriveInput);

    match derive_query_response_impl(input) {
        Ok(tokens) => tokens.into(),
        Err(err) => err.to_compile_error().into(),
    }
}

/// Validate a GraphQL query or mutation against the embedded Sui schema at
/// compile time and return it as a `&'static str`.
///
/// On a syntactically or semantically invalid input (unknown field, wrong
/// argument type, undefined variable, etc.) the macro emits one
/// `compile_error!` per apollo-compiler diagnostic, so the offending call
/// site fails to build with the diagnostic text inline.
#[proc_macro]
pub fn graphql_query(input: TokenStream) -> TokenStream {
    query::expand(input)
}

fn derive_query_response_impl(input: DeriveInput) -> Result<TokenStream2, syn::Error> {
    let parsed = ResponseInput::from_derive_input(&input)?;

    // Load the GraphQL schema for validation.
    // If a custom schema path is provided, load it; otherwise use the embedded Sui schema.
    let loaded_schema = if let Some(path) = &parsed.schema {
        // Resolve path relative to the crate's directory.
        // SUI_GRAPHQL_SCHEMA_DIR is used by trybuild tests (which run from a temp directory).
        let base_dir = std::env::var("SUI_GRAPHQL_SCHEMA_DIR")
            .or_else(|_| std::env::var("CARGO_MANIFEST_DIR"))
            .unwrap();
        let full_path = std::path::Path::new(&base_dir).join(path);
        let sdl = std::fs::read_to_string(&full_path).map_err(|e| {
            syn::Error::new(
                proc_macro2::Span::call_site(),
                format!(
                    "Failed to read schema from '{}': {}",
                    full_path.display(),
                    e
                ),
            )
        })?;
        Some(schema::Schema::from_sdl(&sdl)?)
    } else {
        None
    };
    let schema = if let Some(schema) = &loaded_schema {
        schema
    } else {
        schema::Schema::load()?
    };

    // Determine root type: use specified root_type or default to "Query"
    let root_type = parsed
        .root_type
        .as_ref()
        .map(|s| s.as_str())
        .unwrap_or("Query");

    // Validate that the root type exists in the schema
    if !schema.has_type(root_type) {
        use std::fmt::Write;

        let type_names = schema.type_names();
        let suggestion = validation::find_similar(&type_names, root_type);

        let mut msg = format!("Type '{}' not found in GraphQL schema", root_type);
        if let Some(suggested) = suggestion {
            write!(msg, ". Did you mean '{}'?", suggested).unwrap();
        }

        // We only enter this block if root_type was explicitly specified (and invalid),
        // since "Query" (the default) always exists in a valid schema.
        let span = parsed.root_type.as_ref().unwrap().span();

        return Err(syn::Error::new(span, msg));
    }

    match parsed.data {
        darling::ast::Data::Struct(ref fields) => {
            generate_struct_impl(&parsed, &fields.fields, schema, root_type)
        }
        darling::ast::Data::Enum(ref variants) => {
            generate_enum_impl(&parsed, variants, schema, root_type)
        }
    }
}

/// Generate `from_value` and `Deserialize` for a struct.
fn generate_struct_impl(
    input: &ResponseInput,
    fields: &[ResponseField],
    schema: &schema::Schema,
    root_type: &str,
) -> Result<TokenStream2, syn::Error> {
    let ident = &input.ident;
    let (impl_generics, ty_generics, where_clause) = input.generics.split_for_impl();

    // Generate extraction code for each field
    let mut field_extractions = Vec::new();
    let mut field_names = Vec::new();

    for field in fields {
        let field_ident = field
            .ident
            .as_ref()
            .expect("darling ensures named fields only");

        let spanned_path = &field.path;
        let parsed_path = path::ParsedPath::parse(spanned_path.as_str())
            .map_err(|e| syn::Error::new(spanned_path.span(), e.to_string()))?;

        let terminal_type = if !field.skip_schema_validation {
            Some(validation::validate_path_against_schema(
                schema,
                root_type,
                &parsed_path,
                spanned_path.span(),
            )?)
        } else {
            None
        };

        // Skip Vec excess check when schema validation is skipped (user takes full
        // responsibility) or when the terminal type is an object-like scalar (e.g., JSON)
        // whose value can be an array.
        let skip_vec_excess_check = field.skip_schema_validation
            || terminal_type.is_some_and(validation::is_object_like_scalar);
        validation::validate_type_matches_path(&parsed_path, &field.ty, skip_vec_excess_check)?;

        // Generate extraction code using the same parsed path
        let type_structure = validation::analyze_type(&field.ty);
        let extraction = generate_field_extraction(&parsed_path, &type_structure, field_ident);
        field_extractions.push(extraction);
        field_names.push(field_ident);
    }

    // Generate both `from_value` and `Deserialize` impl:
    //
    // - `from_value`: Core extraction logic, parses from serde_json::Value
    // - `Deserialize`: Allows direct use with serde (e.g., `serde_json::from_str::<MyStruct>(...)`)
    //   and with the GraphQL client's `query::<T>()` which requires `T: DeserializeOwned`
    Ok(quote! {
        impl #impl_generics #ident #ty_generics #where_clause {
            pub fn from_value(value: serde_json::Value) -> Result<Self, String> {
                #(#field_extractions)*

                Ok(Self {
                    #(#field_names),*
                })
            }
        }

        // TODO: Implement efficient deserialization that only extracts the fields we need.
        impl<'de> serde::Deserialize<'de> for #ident #ty_generics #where_clause {
            fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
            where
                D: serde::Deserializer<'de>,
            {
                let value = serde_json::Value::deserialize(deserializer)?;
                Self::from_value(value).map_err(serde::de::Error::custom)
            }
        }
    })
}

/// Generate `from_value` and `Deserialize` for an enum (GraphQL union).
///
/// Each variant wraps a type that implements `from_value`. Dispatches on `__typename`.
fn generate_enum_impl(
    input: &ResponseInput,
    variants: &[ResponseVariant],
    schema: &schema::Schema,
    root_type: &str,
) -> Result<TokenStream2, syn::Error> {
    let ident = &input.ident;
    let (impl_generics, ty_generics, where_clause) = input.generics.split_for_impl();

    let root_type_span = input
        .root_type
        .as_ref()
        .map(|s| s.span())
        .unwrap_or_else(|| ident.span());

    if !schema.is_union(root_type) {
        return Err(syn::Error::new(
            root_type_span,
            format!(
                "'{}' is not a union type. \
                 Enum Response requires root_type to be a GraphQL union",
                root_type
            ),
        ));
    }

    let mut match_arms = Vec::new();

    for variant in variants {
        let variant_ident = &variant.ident;

        // Resolve the GraphQL typename: explicit `on` or variant ident
        let graphql_typename = variant
            .on
            .as_ref()
            .map(|s| s.as_str().to_string())
            .unwrap_or_else(|| variant_ident.to_string());

        let span = variant
            .on
            .as_ref()
            .map(|s| s.span())
            .unwrap_or_else(|| variant_ident.span());

        if let Err(mut err) =
            validation::validate_union_member(schema, root_type, &graphql_typename, span)
        {
            if variant.on.is_none() {
                err.combine(syn::Error::new(
                    span,
                    "hint: use #[response(on = \"...\")] to specify a GraphQL type name different from the variant name",
                ));
            }
            return Err(err);
        }

        // Newtype variant: delegate to inner type's from_value
        let inner_ty = &variant.fields.fields[0].ty;
        match_arms.push(quote! {
            #graphql_typename => {
                Ok(Self::#variant_ident(
                    <#inner_ty>::from_value(value)?
                ))
            }
        });
    }

    let root_type_str = root_type;
    let enum_name_str = ident.to_string();

    Ok(quote! {
        impl #impl_generics #ident #ty_generics #where_clause {
            pub fn from_value(value: serde_json::Value) -> Result<Self, String> {
                let typename = value.get("__typename")
                    .and_then(|v| v.as_str())
                    .ok_or_else(|| format!(
                        "union '{}' requires '__typename' in the response to distinguish variants. \
                         Make sure your query requests '__typename' on this field ({})",
                        #root_type_str, #enum_name_str
                    ))?;

                match typename {
                    #(#match_arms)*
                    other => Err(format!(
                        "unknown __typename '{}' for union '{}' ({})",
                        other, #root_type_str, #enum_name_str
                    )),
                }
            }
        }

        impl<'de> serde::Deserialize<'de> for #ident #ty_generics #where_clause {
            fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
            where
                D: serde::Deserializer<'de>,
            {
                let value = serde_json::Value::deserialize(deserializer)?;
                Self::from_value(value).map_err(serde::de::Error::custom)
            }
        }
    })
}

/// Generate code to extract a single field from JSON using its path.
///
/// Supports multiple path formats:
/// - Simple: `"object.address"` - navigates to nested field
/// - Array: `"nodes[].name"` - iterates over array, extracts field from each element
/// - Nested arrays: `"nodes[].edges[].id"` - nested iteration, returns `Vec<Vec<T>>`
/// - Aliased: `"alias:field"` - uses alias for JSON extraction, field for validation
fn generate_field_extraction(
    path: &path::ParsedPath,
    type_structure: &validation::TypeStructure,
    field_ident: &syn::Ident,
) -> TokenStream2 {
    let full_path = &path.raw;
    let inner = generate_from_segments(full_path, &path.segments, type_structure);
    // The inner expression returns Result<T, String>, so we use ? to unwrap
    quote! {
        let #field_ident = {
            let current = &value;
            #inner?
        };
    }
}

/// Recursively generate extraction code by traversing path segments.
///
/// For JSON extraction, uses the alias if present, otherwise uses the field name.
/// Returns code that evaluates to `Result<T, String>` (caller adds `?` to unwrap).
///
/// ## Example: `"data.nodes[].edges[].id"` with `Option<Vec<Vec<String>>>`
///
/// Each `[]` in the path corresponds to one `Vec<_>` wrapper in the type.
///
/// For `Option<_>` types, null at the outer level returns `Ok(None)`. This is achieved
/// by wrapping the extraction in a closure to capture early returns. However, once
/// inside an array iteration, the element type (`Vec<String>`) is not Optional, so
/// null values there return errors instead.
///
/// ```ignore
/// (|| {
///     // "data" (non-list) - missing/null returns None (outer Optional)
///     let current = current.get("data").unwrap_or(&serde_json::Value::Null);
///     if current.is_null() { return Ok(None); }
///
///     // "nodes[]" (list) - missing/null returns None (outer Optional)
///     let field_value = current.get("nodes").unwrap_or(&serde_json::Value::Null);
///     if field_value.is_null() { return Ok(None); }
///     let array = field_value.as_array().ok_or_else(|| "expected array")?;
///     array.iter().map(|current| {
///         // Element type: Vec<String> (not Optional, so null = error)
///
///         // "edges[]" (list) - missing/null returns Err
///         let field_value = current.get("edges").unwrap_or(&serde_json::Value::Null);
///         if field_value.is_null() { return Err("null at 'edges'"); }
///         let array = field_value.as_array().ok_or_else(|| "expected array")?;
///         array.iter().map(|current| {
///             // Element type: String (not Optional, so null = error)
///
///             // "id" (scalar) - missing/null returns Err
///             let current = current.get("id").unwrap_or(&serde_json::Value::Null);
///             if current.is_null() { return Err("null at 'id'"); }
///             serde_json::from_value(current.clone())
///         }).collect::<Result<Vec<_>, _>>()
///     }).collect::<Result<Vec<_>, _>>()
///     .map(Some)  // Wrap in Some for Option
/// })()
/// ```
fn generate_from_segments(
    full_path: &str,
    segments: &[path::PathSegment],
    type_structure: &validation::TypeStructure,
) -> TokenStream2 {
    // Step 1: Check if outer type is Optional and unwrap it
    let (is_optional, inner_type) = match type_structure {
        validation::TypeStructure::Optional(inner) => (true, inner.as_ref()),
        other => (false, other),
    };

    // Step 2: Generate core extraction code
    let core = generate_from_segments_core(full_path, segments, inner_type);

    // Step 3: Wrap Optional types in a closure so `return Ok(None)` stays local to this field.
    if is_optional {
        quote! {
            (|| {
                // Handle null elements (from `[]?`) and null top-level values
                if current.is_null() { return Ok(None) }
                #core.map(Some)
            })()
        }
    } else {
        core
    }
}

/// Core extraction logic that handles both list and non-list segments.
///
/// Each segment determines its own null behavior via `is_nullable`:
/// - `is_nullable = true` (`?` marker): null → `return Ok(None)`
/// - `is_nullable = false` (no `?`): null → `return Err(...)`
fn generate_from_segments_core(
    full_path: &str,
    segments: &[path::PathSegment],
    type_structure: &validation::TypeStructure,
) -> TokenStream2 {
    // Base case: no more segments, deserialize the current value
    let Some((segment, rest)) = segments.split_first() else {
        return quote! {
            serde_json::from_value(current.clone())
                .map_err(|e| format!("failed to deserialize '{}': {}", #full_path, e))
        };
    };

    let name = segment.field;
    // Use alias for JSON extraction if present, otherwise use field name
    let json_key = segment.json_key();

    // Generate null handling based on this segment's `?` marker
    let on_null = if segment.is_nullable {
        quote! { return Ok(None) }
    } else {
        quote! {
            return Err(format!("null value at '{}' in path '{}'", #name, #full_path))
        }
    };

    if segment.is_list() {
        // For list segments, unwrap Vector to get element type
        let element_type = match type_structure {
            validation::TypeStructure::Vector(inner) => inner.as_ref(),
            _ => unreachable!("validated: list segment requires Vec type"),
        };

        // Each array element is processed independently with its own type structure.
        // Use generate_from_segments (not _core) to handle element-level Optional.
        let rest_code = generate_from_segments(full_path, rest, element_type);

        quote! {
            // Treat missing fields as null (allows Option<T> to deserialize as None)
            let field_value = current.get(#json_key).unwrap_or(&serde_json::Value::Null);
            if field_value.is_null() {
                #on_null
            }
            let array = field_value.as_array()
                .ok_or_else(|| format!("expected array at '{}' in path '{}'", #json_key, #full_path))?;
            array.iter()
                .map(|current| { #rest_code })
                .collect::<Result<Vec<_>, String>>()
        }
    } else {
        // For non-list segments, pass type unchanged to handle nested structures
        let rest_code = generate_from_segments_core(full_path, rest, type_structure);

        quote! {
            // Treat missing fields as null (allows Option<T> to deserialize as None)
            let current = current.get(#json_key).unwrap_or(&serde_json::Value::Null);
            if current.is_null() {
                #on_null
            }
            #rest_code
        }
    }
}