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
//! Struct code generation for LlmDeserialize derive macro.
use proc_macro2::TokenStream;
use quote::quote;
use syn::{Fields, GenericArgument, PathArguments, Type};
/// Generate deserialization code for structs with named fields.
pub fn generate_struct_deserialize(name: &syn::Ident, data: &syn::DataStruct) -> TokenStream {
match &data.fields {
Fields::Named(fields) => {
let field_names: Vec<_> = fields.named.iter().map(|f| &f.ident).collect();
let field_types: Vec<_> = fields.named.iter().map(|f| &f.ty).collect();
let field_name_strs: Vec<_> = fields
.named
.iter()
.map(|f| f.ident.as_ref().unwrap().to_string())
.collect();
// Check if each field is Option<T>
let is_optional: Vec<_> = field_types.iter().map(|ty| is_option_type(ty)).collect();
// Extract inner type for Option<T> fields
let inner_types: Vec<_> = field_types
.iter()
.zip(&is_optional)
.map(|(ty, opt)| {
if *opt {
extract_option_inner(ty)
} else {
(*ty).clone()
}
})
.collect();
let name_str = name.to_string();
// Generate field descriptor setup (collect to Vec for reuse)
let field_descriptors: Vec<_> = field_name_strs
.iter()
.zip(&field_types)
.zip(&is_optional)
.map(|((name, ty), opt)| {
let type_name = quote!(stringify!(#ty)).to_string();
quote! {
.field(::tryparse::deserializer::FieldDescriptor::new(
#name,
#type_name,
#opt
))
}
})
.collect();
// Generate field extraction for try_deserialize (returns Option)
let field_extractions_strict: Vec<_> = field_names
.iter()
.zip(&inner_types)
.zip(&is_optional)
.map(|((field_name, inner_ty), opt)| {
let field_name_str = field_name.as_ref().unwrap().to_string();
if *opt {
// Optional field
quote! {
let #field_name = fields.get(#field_name_str)
.and_then(|v| v.downcast_ref::<#inner_ty>())
.cloned();
}
} else {
// Required field - return None if missing
quote! {
let #field_name = fields.get(#field_name_str)
.and_then(|v| v.downcast_ref::<#inner_ty>())
.cloned()?;
}
}
})
.collect();
// Generate field extraction for deserialize (returns Result)
let field_extractions_lenient: Vec<_> = field_names.iter().zip(&inner_types).zip(&is_optional).map(|((field_name, inner_ty), opt)| {
let field_name_str = field_name.as_ref().unwrap().to_string();
if *opt {
// Optional field
quote! {
let #field_name = fields.get(#field_name_str)
.and_then(|v| v.downcast_ref::<#inner_ty>())
.cloned();
}
} else {
// Required field
quote! {
let #field_name = fields.get(#field_name_str)
.and_then(|v| v.downcast_ref::<#inner_ty>())
.cloned()
.ok_or_else(|| ::tryparse::error::ParseError::DeserializeFailed(
::tryparse::error::DeserializeError::missing_field(#field_name_str)
))?;
}
}
}).collect();
quote! {
fn try_deserialize(
value: &::tryparse::value::FlexValue,
ctx: &mut ::tryparse::deserializer::CoercionContext,
) -> Option<Self> {
use std::any::Any;
let mut deserializer = ::tryparse::deserializer::StructDeserializer::new()
#(#field_descriptors)*;
let fields = deserializer.try_deserialize(
value,
ctx,
#name_str,
|field_name, field_value, field_ctx| {
// Dispatch to the appropriate field type's LlmDeserialize impl (strict mode only)
match field_name {
#(
#field_name_strs => {
// Try strict deserialization
<#inner_types as ::tryparse::deserializer::LlmDeserialize>::try_deserialize(field_value, field_ctx)
.map(|v| Box::new(v) as Box<dyn Any>)
}
)*
_ => None
}
}
).ok()?;
// Extract fields from Box<dyn Any> (strict mode - return None on failure)
#(#field_extractions_strict)*
Some(Self {
#(#field_names),*
})
}
fn deserialize(
value: &::tryparse::value::FlexValue,
ctx: &mut ::tryparse::deserializer::CoercionContext,
) -> ::tryparse::error::Result<Self> {
use std::any::Any;
let mut deserializer = ::tryparse::deserializer::StructDeserializer::new()
#(#field_descriptors)*;
let fields = deserializer.deserialize(
value,
ctx,
#name_str,
|field_name, field_value, field_ctx, strict| {
// Dispatch to the appropriate field type's LlmDeserialize impl
match field_name {
#(
#field_name_strs => {
if strict {
// Try strict deserialization
if let Some(v) = <#inner_types as ::tryparse::deserializer::LlmDeserialize>::try_deserialize(field_value, field_ctx) {
Ok(Box::new(v) as Box<dyn Any>)
} else {
Err(::tryparse::error::ParseError::DeserializeFailed(
::tryparse::error::DeserializeError::type_mismatch(
stringify!(#inner_types),
"value"
)
))
}
} else {
// Lenient deserialization
let v = <#inner_types as ::tryparse::deserializer::LlmDeserialize>::deserialize(field_value, field_ctx)?;
Ok(Box::new(v) as Box<dyn Any>)
}
}
)*
_ => Err(::tryparse::error::ParseError::DeserializeFailed(
::tryparse::error::DeserializeError::Custom(
format!("Unknown field: {}", field_name)
)
))
}
}
)?;
// Extract fields from Box<dyn Any> (lenient mode - return error on failure)
#(#field_extractions_lenient)*
Ok(Self {
#(#field_names),*
})
}
}
}
Fields::Unnamed(_) => syn::Error::new_spanned(
data.fields.clone(),
"LlmDeserialize does not support tuple structs yet",
)
.to_compile_error(),
Fields::Unit => syn::Error::new_spanned(
data.fields.clone(),
"LlmDeserialize does not support unit structs",
)
.to_compile_error(),
}
}
/// Check if a type is Option<T>
fn is_option_type(ty: &Type) -> bool {
if let Type::Path(type_path) = ty {
if let Some(segment) = type_path.path.segments.last() {
return segment.ident == "Option";
}
}
false
}
/// Extract the inner type T from Option<T>
fn extract_option_inner(ty: &Type) -> Type {
if let Type::Path(type_path) = ty {
if let Some(segment) = type_path.path.segments.last() {
if segment.ident == "Option" {
if let PathArguments::AngleBracketed(args) = &segment.arguments {
if let Some(GenericArgument::Type(inner)) = args.args.first() {
return inner.clone();
}
}
}
}
}
// Fallback: return the original type
ty.clone()
}