Skip to main content

alef_codegen/conversions/
core_to_binding.rs

1use ahash::AHashSet;
2use alef_core::ir::{CoreWrapper, PrimitiveType, TypeDef, TypeRef};
3use std::fmt::Write;
4
5use super::ConversionConfig;
6use super::binding_to_core::field_conversion_to_core;
7use super::helpers::is_newtype;
8use super::helpers::{binding_prim_str, core_type_path, needs_i64_cast};
9
10/// Generate `impl From<core::Type> for BindingType` (core -> binding).
11pub fn gen_from_core_to_binding(typ: &TypeDef, core_import: &str, opaque_types: &AHashSet<String>) -> String {
12    gen_from_core_to_binding_cfg(typ, core_import, opaque_types, &ConversionConfig::default())
13}
14
15/// Generate `impl From<core::Type> for BindingType` with backend-specific config.
16pub fn gen_from_core_to_binding_cfg(
17    typ: &TypeDef,
18    core_import: &str,
19    opaque_types: &AHashSet<String>,
20    config: &ConversionConfig,
21) -> String {
22    let core_path = core_type_path(typ, core_import);
23    let binding_name = format!("{}{}", config.type_name_prefix, typ.name);
24    let mut out = String::with_capacity(256);
25    writeln!(out, "impl From<{core_path}> for {binding_name} {{").ok();
26    writeln!(out, "    fn from(val: {core_path}) -> Self {{").ok();
27
28    // Newtype structs: extract inner value with val.0
29    if is_newtype(typ) {
30        let field = &typ.fields[0];
31        let inner_expr = match &field.ty {
32            TypeRef::Named(_) => "val.0.into()".to_string(),
33            TypeRef::Path => "val.0.to_string_lossy().to_string()".to_string(),
34            TypeRef::Duration => "val.0.as_millis() as u64".to_string(),
35            _ => "val.0".to_string(),
36        };
37        writeln!(out, "        Self {{ _0: {inner_expr} }}").ok();
38        writeln!(out, "    }}").ok();
39        write!(out, "}}").ok();
40        return out;
41    }
42
43    let optionalized = config.optionalize_defaults && typ.has_default;
44    writeln!(out, "        Self {{").ok();
45    for field in &typ.fields {
46        // Fields referencing excluded types are not present in the binding struct — skip
47        if !config.exclude_types.is_empty()
48            && super::helpers::field_references_excluded_type(&field.ty, config.exclude_types)
49        {
50            continue;
51        }
52        let base_conversion = field_conversion_from_core_cfg(
53            &field.name,
54            &field.ty,
55            field.optional,
56            field.sanitized,
57            opaque_types,
58            config,
59        );
60        // Box<T> fields: dereference before conversion.
61        let base_conversion = if field.is_boxed && matches!(&field.ty, TypeRef::Named(_)) {
62            if field.optional {
63                // Optional<Box<T>>: replace .map(Into::into) with .map(|v| (*v).into())
64                let src = format!("{}: val.{}.map(Into::into)", field.name, field.name);
65                let dst = format!("{}: val.{}.map(|v| (*v).into())", field.name, field.name);
66                if base_conversion == src { dst } else { base_conversion }
67            } else {
68                // Box<T>: replace `val.{name}` with `(*val.{name})`
69                base_conversion.replace(&format!("val.{}", field.name), &format!("(*val.{})", field.name))
70            }
71        } else {
72            base_conversion
73        };
74        // Newtype unwrapping: when the field was resolved from a newtype (e.g. NodeIndex → u32),
75        // unwrap the core newtype by accessing `.0`.
76        // e.g. `source: val.source` → `source: val.source.0`
77        //      `parent: val.parent` → `parent: val.parent.map(|v| v.0)`
78        //      `children: val.children` → `children: val.children.iter().map(|v| v.0).collect()`
79        let base_conversion = if field.newtype_wrapper.is_some() {
80            match &field.ty {
81                TypeRef::Optional(_) => {
82                    // Replace `val.{name}` with `val.{name}.map(|v| v.0)` in the generated expression
83                    base_conversion.replace(
84                        &format!("val.{}", field.name),
85                        &format!("val.{}.map(|v| v.0)", field.name),
86                    )
87                }
88                TypeRef::Vec(_) => {
89                    // Replace `val.{name}` with `val.{name}.iter().map(|v| v.0).collect()` in expression
90                    base_conversion.replace(
91                        &format!("val.{}", field.name),
92                        &format!("val.{}.iter().map(|v| v.0).collect::<Vec<_>>()", field.name),
93                    )
94                }
95                // When `optional=true` and `ty` is a plain Primitive (not TypeRef::Optional), the core
96                // field is actually `Option<NewtypeT>`, so we must use `.map(|v| v.0)` not `.0`.
97                _ if field.optional => base_conversion.replace(
98                    &format!("val.{}", field.name),
99                    &format!("val.{}.map(|v| v.0)", field.name),
100                ),
101                _ => {
102                    // Direct field: append `.0` to access the inner primitive
103                    base_conversion.replace(&format!("val.{}", field.name), &format!("val.{}.0", field.name))
104                }
105            }
106        } else {
107            base_conversion
108        };
109        // When field.optional=true AND field.ty=Optional(T), the binding struct flattens
110        // Option<Option<T>> to Option<T>. Core produces Option<Option<T>>, binding needs
111        // Option<T>. Generate the conversion by treating the pre-flattened field as Option<T>:
112        // call the standard conversion for the inner type T with optional=true, substituting
113        // val.{name}.flatten() for val.{name} so all cast/conversion logic applies to T.
114        let is_flattened_optional = field.optional && matches!(field.ty, TypeRef::Optional(_));
115        let base_conversion = if is_flattened_optional {
116            if let TypeRef::Optional(inner) = &field.ty {
117                // Produce the conversion as if the field is Option<inner> with value val.name.flatten()
118                let inner_conv = field_conversion_from_core_cfg(
119                    &field.name,
120                    inner.as_ref(),
121                    true,
122                    field.sanitized,
123                    opaque_types,
124                    config,
125                );
126                // inner_conv references val.{name}; replace with val.{name}.flatten()
127                inner_conv.replace(&format!("val.{}", field.name), &format!("val.{}.flatten()", field.name))
128            } else {
129                base_conversion
130            }
131        } else {
132            base_conversion
133        };
134        // Optionalized non-optional fields need Some() wrapping in core→binding direction.
135        // This covers both NAPI-style full optionalization and PyO3-style Duration optionalization.
136        // Flattened-optional fields are already handled above with the correct type.
137        let needs_some_wrap = !is_flattened_optional
138            && ((optionalized && !field.optional)
139                || (config.option_duration_on_defaults
140                    && typ.has_default
141                    && !field.optional
142                    && matches!(field.ty, TypeRef::Duration)));
143        let conversion = if needs_some_wrap {
144            // Extract the value expression after "name: " and wrap in Some()
145            if let Some(expr) = base_conversion.strip_prefix(&format!("{}: ", field.name)) {
146                format!("{}: Some({})", field.name, expr)
147            } else {
148                base_conversion
149            }
150        } else {
151            base_conversion
152        };
153        // CoreWrapper: unwrap Arc, convert Cow→String, Bytes→Vec<u8>
154        // Skip for sanitized fields since their conversion already handles the type mismatch via format!("{:?}", ...)
155        let conversion = if !field.sanitized {
156            apply_core_wrapper_from_core(
157                &conversion,
158                &field.name,
159                &field.core_wrapper,
160                &field.vec_inner_core_wrapper,
161                field.optional,
162            )
163        } else {
164            conversion
165        };
166        // Skip cfg-gated fields — they don't exist in the binding struct
167        if field.cfg.is_some() {
168            continue;
169        }
170        writeln!(out, "            {conversion},").ok();
171    }
172
173    writeln!(out, "        }}").ok();
174    writeln!(out, "    }}").ok();
175    write!(out, "}}").ok();
176    out
177}
178
179/// Same but for core -> binding direction.
180/// Some types are asymmetric (PathBuf→String, sanitized fields need .to_string()).
181pub fn field_conversion_from_core(
182    name: &str,
183    ty: &TypeRef,
184    optional: bool,
185    sanitized: bool,
186    opaque_types: &AHashSet<String>,
187) -> String {
188    // Sanitized fields: the binding type differs from core (e.g. Box<str>→String, Cow<str>→String).
189    // Box<str>, Cow<str>, and Arc<str> all implement Display, so use .to_string() not {:?}.
190    // {:?} on string-like types produces debug-escaped output with surrounding quotes.
191    if sanitized {
192        // Map(String, String): sanitized from Map(Box<str>, Box<str>) etc.
193        if let TypeRef::Map(k, v) = ty {
194            if matches!(k.as_ref(), TypeRef::String) && matches!(v.as_ref(), TypeRef::String) {
195                if optional {
196                    return format!(
197                        "{name}: val.{name}.as_ref().map(|m| m.iter().map(|(k, v)| (k.to_string(), v.to_string())).collect())"
198                    );
199                }
200                return format!(
201                    "{name}: val.{name}.into_iter().map(|(k, v)| (k.to_string(), v.to_string())).collect()"
202                );
203            }
204        }
205        // Vec<String>: sanitized from Vec<Box<str>>, Vec<Cow<str>>, Vec<Named>, etc.
206        // Use Debug formatting — the original core type may not implement Display.
207        if let TypeRef::Vec(inner) = ty {
208            if matches!(inner.as_ref(), TypeRef::String) {
209                if optional {
210                    return format!(
211                        "{name}: val.{name}.as_ref().map(|v| v.iter().map(|i| format!(\"{{:?}}\", i)).collect())"
212                    );
213                }
214                return format!("{name}: val.{name}.iter().map(|i| format!(\"{{:?}}\", i)).collect()");
215            }
216        }
217        // Optional<Vec<String>>: sanitized from Optional<Vec<Box<str>>>, Optional<Vec<Cow<str>>>, etc.
218        if let TypeRef::Optional(opt_inner) = ty {
219            if let TypeRef::Vec(vec_inner) = opt_inner.as_ref() {
220                if matches!(vec_inner.as_ref(), TypeRef::String) {
221                    return format!(
222                        "{name}: val.{name}.as_ref().map(|v| v.iter().map(|i| format!(\"{{:?}}\", i)).collect())"
223                    );
224                }
225            }
226        }
227        // String: sanitized from Box<str>, Cow<str>, (u32, u32), etc.
228        // Use Debug formatting — it works for all types (including tuples) and avoids Display
229        // trait bound failures when the original core type doesn't implement Display.
230        if matches!(ty, TypeRef::String) {
231            if optional {
232                return format!("{name}: val.{name}.as_ref().map(|v| format!(\"{{v:?}}\"))");
233            }
234            return format!("{name}: format!(\"{{:?}}\", val.{name})");
235        }
236        // Named (optional or non-optional): sanitized from excluded types
237        // (e.g. Optional<Arc<SchemaValidator>> → optional=true, ty=Named("SchemaValidator")).
238        // These types may not implement Debug, so we cannot use format!("{:?}").
239        // Return None for optional, empty String for non-optional.
240        if matches!(ty, TypeRef::Named(_)) {
241            if optional {
242                return format!("{name}: None");
243            }
244            return format!("{name}: String::new()");
245        }
246        // Optional<Named>: double-optional case (Option<Option<Arc<T>>>).
247        if let TypeRef::Optional(inner) = ty {
248            if matches!(inner.as_ref(), TypeRef::Named(_)) {
249                return format!("{name}: None");
250            }
251        }
252        // Fallback for truly unknown sanitized types — the core type may not implement Display,
253        // so use Debug formatting which is always available (required by the sanitized field's derive).
254        if optional {
255            return format!("{name}: val.{name}.as_ref().map(|v| format!(\"{{v:?}}\"))");
256        }
257        return format!("{name}: format!(\"{{:?}}\", val.{name})");
258    }
259    match ty {
260        // Duration: core uses std::time::Duration, binding uses u64 (millis)
261        TypeRef::Duration => {
262            if optional {
263                return format!("{name}: val.{name}.map(|d| d.as_millis() as u64)");
264            }
265            format!("{name}: val.{name}.as_millis() as u64")
266        }
267        // Path: core uses PathBuf, binding uses String — PathBuf→String needs special handling
268        TypeRef::Path => {
269            if optional {
270                format!("{name}: val.{name}.map(|p| p.to_string_lossy().to_string())")
271            } else {
272                format!("{name}: val.{name}.to_string_lossy().to_string()")
273            }
274        }
275        TypeRef::Optional(inner) if matches!(inner.as_ref(), TypeRef::Path) => {
276            format!("{name}: val.{name}.map(|p| p.to_string_lossy().to_string())")
277        }
278        // Char: core uses char, binding uses String — convert char to string
279        TypeRef::Char => {
280            if optional {
281                format!("{name}: val.{name}.map(|c| c.to_string())")
282            } else {
283                format!("{name}: val.{name}.to_string()")
284            }
285        }
286        // Bytes: core uses bytes::Bytes, binding uses Vec<u8>
287        TypeRef::Bytes => {
288            if optional {
289                format!("{name}: val.{name}.map(|v| v.to_vec())")
290            } else {
291                format!("{name}: val.{name}.to_vec()")
292            }
293        }
294        // Opaque Named types: wrap in Arc to create the binding wrapper
295        TypeRef::Named(n) if opaque_types.contains(n.as_str()) => {
296            if optional {
297                format!("{name}: val.{name}.map(|v| {n} {{ inner: Arc::new(v) }})")
298            } else {
299                format!("{name}: {n} {{ inner: Arc::new(val.{name}) }}")
300            }
301        }
302        // Json: core uses serde_json::Value, binding uses String — use .to_string()
303        TypeRef::Json => {
304            if optional {
305                format!("{name}: val.{name}.as_ref().map(ToString::to_string)")
306            } else {
307                format!("{name}: val.{name}.to_string()")
308            }
309        }
310        TypeRef::Optional(inner) if matches!(inner.as_ref(), TypeRef::Json) => {
311            format!("{name}: val.{name}.as_ref().map(ToString::to_string)")
312        }
313        TypeRef::Vec(inner) if matches!(inner.as_ref(), TypeRef::Json) => {
314            if optional {
315                format!("{name}: val.{name}.as_ref().map(|v| v.iter().map(|i| i.to_string()).collect())")
316            } else {
317                format!("{name}: val.{name}.iter().map(ToString::to_string).collect()")
318            }
319        }
320        // Vec<Optional<Json>>: each element is Option<Value> → Option<String>
321        TypeRef::Vec(inner) if matches!(inner.as_ref(), TypeRef::Optional(oi) if matches!(oi.as_ref(), TypeRef::Json)) => {
322            if optional {
323                format!(
324                    "{name}: val.{name}.as_ref().map(|v| v.iter().map(|i| i.as_ref().map(ToString::to_string)).collect())"
325                )
326            } else {
327                format!("{name}: val.{name}.iter().map(|i| i.as_ref().map(ToString::to_string)).collect()")
328            }
329        }
330        // Map with Json values: core uses HashMap<K, serde_json::Value>, binding uses HashMap<K, String>
331        TypeRef::Map(k, v) if matches!(v.as_ref(), TypeRef::Json) => {
332            let k_is_json = matches!(k.as_ref(), TypeRef::Json);
333            let k_expr = if k_is_json { "k.to_string()" } else { "k" };
334            if optional {
335                format!("{name}: val.{name}.map(|m| m.into_iter().map(|(k, v)| ({k_expr}, v.to_string())).collect())")
336            } else {
337                format!("{name}: val.{name}.into_iter().map(|(k, v)| ({k_expr}, v.to_string())).collect()")
338            }
339        }
340        // Map with Json keys: core uses HashMap<serde_json::Value, V>, binding uses HashMap<String, V>
341        TypeRef::Map(k, _v) if matches!(k.as_ref(), TypeRef::Json) => {
342            if optional {
343                format!("{name}: val.{name}.map(|m| m.into_iter().map(|(k, v)| (k.to_string(), v)).collect())")
344            } else {
345                format!("{name}: val.{name}.into_iter().map(|(k, v)| (k.to_string(), v)).collect()")
346            }
347        }
348        // Everything else is symmetric
349        _ => field_conversion_to_core(name, ty, optional),
350    }
351}
352
353/// Core→binding field conversion with backend-specific config.
354pub fn field_conversion_from_core_cfg(
355    name: &str,
356    ty: &TypeRef,
357    optional: bool,
358    sanitized: bool,
359    opaque_types: &AHashSet<String>,
360    config: &ConversionConfig,
361) -> String {
362    // Sanitized fields: for WASM (map_uses_jsvalue), Map and Vec<Json> fields target JsValue
363    // and need serde_wasm_bindgen::to_value() instead of iterator-based .collect().
364    // Note: Vec<String> sanitized does NOT use the JsValue path because Vec<String> maps to
365    // Vec<String> in WASM (not JsValue) — use the normal sanitized iterator path instead.
366    if sanitized {
367        if config.map_uses_jsvalue {
368            // Map(String, String) sanitized → JsValue (HashMap maps to JsValue in WASM)
369            if let TypeRef::Map(k, v) = ty {
370                if matches!(k.as_ref(), TypeRef::String) && matches!(v.as_ref(), TypeRef::String) {
371                    if optional {
372                        return format!(
373                            "{name}: val.{name}.as_ref().and_then(|v| serde_wasm_bindgen::to_value(v).ok())"
374                        );
375                    }
376                    return format!("{name}: serde_wasm_bindgen::to_value(&val.{name}).unwrap_or(JsValue::NULL)");
377                }
378            }
379            // Vec<Json> sanitized → JsValue (Vec<Json> maps to JsValue in WASM via nested-vec path)
380            if let TypeRef::Vec(inner) = ty {
381                if matches!(inner.as_ref(), TypeRef::Json) {
382                    if optional {
383                        return format!(
384                            "{name}: val.{name}.as_ref().and_then(|v| serde_wasm_bindgen::to_value(v).ok())"
385                        );
386                    }
387                    return format!("{name}: serde_wasm_bindgen::to_value(&val.{name}).unwrap_or(JsValue::NULL)");
388                }
389            }
390        }
391        return field_conversion_from_core(name, ty, optional, sanitized, opaque_types);
392    }
393
394    // Vec<T>→String core→binding: binding holds JSON string, core has Vec<T>.
395    // field_type_for_serde collapses any Vec<T> not explicitly handled (including Vec<String>,
396    // Vec<Named>, etc.) to String. Apply serde serialization for all Vec types.
397    if config.vec_named_to_string {
398        if let TypeRef::Vec(_) = ty {
399            if optional {
400                return format!("{name}: val.{name}.as_ref().and_then(|v| serde_json::to_string(v).ok())");
401            }
402            return format!("{name}: serde_json::to_string(&val.{name}).unwrap_or_default()");
403        }
404    }
405
406    // WASM JsValue: use serde_wasm_bindgen for Map and nested Vec types
407    if config.map_uses_jsvalue {
408        let is_nested_vec = matches!(ty, TypeRef::Vec(inner) if matches!(inner.as_ref(), TypeRef::Vec(_)));
409        let is_map = matches!(ty, TypeRef::Map(_, _));
410        if is_nested_vec || is_map {
411            if optional {
412                return format!("{name}: val.{name}.as_ref().and_then(|v| serde_wasm_bindgen::to_value(v).ok())");
413            }
414            return format!("{name}: serde_wasm_bindgen::to_value(&val.{name}).unwrap_or(JsValue::NULL)");
415        }
416        if let TypeRef::Optional(inner) = ty {
417            let is_inner_nested = matches!(inner.as_ref(), TypeRef::Vec(vi) if matches!(vi.as_ref(), TypeRef::Vec(_)));
418            let is_inner_map = matches!(inner.as_ref(), TypeRef::Map(_, _));
419            if is_inner_nested || is_inner_map {
420                return format!("{name}: val.{name}.as_ref().and_then(|v| serde_wasm_bindgen::to_value(v).ok())");
421            }
422        }
423    }
424
425    let prefix = config.type_name_prefix;
426    let is_enum_string = |n: &str| -> bool { config.enum_string_names.as_ref().is_some_and(|names| names.contains(n)) };
427
428    match ty {
429        // i64 casting for large int primitives
430        TypeRef::Primitive(p) if config.cast_large_ints_to_i64 && needs_i64_cast(p) => {
431            let cast_to = binding_prim_str(p);
432            if optional {
433                format!("{name}: val.{name}.map(|v| v as {cast_to})")
434            } else {
435                format!("{name}: val.{name} as {cast_to}")
436            }
437        }
438        // Optional(large_int) with i64 casting
439        TypeRef::Optional(inner)
440            if config.cast_large_ints_to_i64
441                && matches!(inner.as_ref(), TypeRef::Primitive(p) if needs_i64_cast(p)) =>
442        {
443            if let TypeRef::Primitive(p) = inner.as_ref() {
444                let cast_to = binding_prim_str(p);
445                format!("{name}: val.{name}.map(|v| v as {cast_to})")
446            } else {
447                field_conversion_from_core(name, ty, optional, sanitized, opaque_types)
448            }
449        }
450        // f32→f64 casting (NAPI only)
451        TypeRef::Primitive(PrimitiveType::F32) if config.cast_f32_to_f64 => {
452            if optional {
453                format!("{name}: val.{name}.map(|v| v as f64)")
454            } else {
455                format!("{name}: val.{name} as f64")
456            }
457        }
458        // Duration with i64 casting
459        TypeRef::Duration if config.cast_large_ints_to_i64 => {
460            if optional {
461                format!("{name}: val.{name}.map(|d| d.as_millis() as u64 as i64)")
462            } else {
463                format!("{name}: val.{name}.as_millis() as u64 as i64")
464            }
465        }
466        // Opaque Named types with prefix: wrap in Arc with prefixed binding name
467        TypeRef::Named(n) if opaque_types.contains(n.as_str()) && !prefix.is_empty() => {
468            let prefixed = format!("{prefix}{n}");
469            if optional {
470                format!("{name}: val.{name}.map(|v| {prefixed} {{ inner: Arc::new(v) }})")
471            } else {
472                format!("{name}: {prefixed} {{ inner: Arc::new(val.{name}) }}")
473            }
474        }
475        // Enum-to-String Named types (PHP pattern)
476        TypeRef::Named(n) if is_enum_string(n) => {
477            // Use serde serialization to get the correct serde(rename) value, not Debug format.
478            // serde_json::to_value gives Value::String("auto") which we extract.
479            if optional {
480                format!(
481                    "{name}: val.{name}.as_ref().map(|v| serde_json::to_value(v).ok().and_then(|s| s.as_str().map(String::from)).unwrap_or_default())"
482                )
483            } else {
484                format!(
485                    "{name}: serde_json::to_value(val.{name}).ok().and_then(|s| s.as_str().map(String::from)).unwrap_or_default()"
486                )
487            }
488        }
489        // Vec<Enum-to-String> Named types: element-wise serde serialization
490        TypeRef::Vec(inner) if matches!(inner.as_ref(), TypeRef::Named(n) if is_enum_string(n)) => {
491            if optional {
492                format!(
493                    "{name}: val.{name}.as_ref().map(|v| v.iter().map(|x| serde_json::to_value(x).ok().and_then(|s| s.as_str().map(String::from)).unwrap_or_default()).collect())"
494                )
495            } else {
496                format!(
497                    "{name}: val.{name}.iter().map(|v| serde_json::to_value(v).ok().and_then(|s| s.as_str().map(String::from)).unwrap_or_default()).collect()"
498                )
499            }
500        }
501        // Optional(Vec<Enum-to-String>) Named types (PHP pattern)
502        TypeRef::Optional(inner) if matches!(inner.as_ref(), TypeRef::Vec(vi) if matches!(vi.as_ref(), TypeRef::Named(n) if is_enum_string(n))) =>
503        {
504            format!(
505                "{name}: val.{name}.as_ref().map(|v| v.iter().map(|x| serde_json::to_value(x).ok().and_then(|s| s.as_str().map(String::from)).unwrap_or_default()).collect())"
506            )
507        }
508        // Vec<f32> needs element-wise cast to f64 when f32→f64 mapping is active
509        TypeRef::Vec(inner)
510            if config.cast_f32_to_f64 && matches!(inner.as_ref(), TypeRef::Primitive(PrimitiveType::F32)) =>
511        {
512            if optional {
513                format!("{name}: val.{name}.as_ref().map(|v| v.iter().map(|&x| x as f64).collect())")
514            } else {
515                format!("{name}: val.{name}.iter().map(|&v| v as f64).collect()")
516            }
517        }
518        // Optional(Vec(f32)) needs element-wise cast to f64
519        TypeRef::Optional(inner)
520            if config.cast_f32_to_f64
521                && matches!(inner.as_ref(), TypeRef::Vec(vi) if matches!(vi.as_ref(), TypeRef::Primitive(PrimitiveType::F32))) =>
522        {
523            format!("{name}: val.{name}.as_ref().map(|v| v.iter().map(|&x| x as f64).collect())")
524        }
525        // Vec<Vec<f32>> needs nested element-wise cast to f64 (for embeddings, etc.)
526        TypeRef::Vec(outer)
527            if config.cast_f32_to_f64
528                && matches!(outer.as_ref(), TypeRef::Vec(inner) if matches!(inner.as_ref(), TypeRef::Primitive(PrimitiveType::F32))) =>
529        {
530            if optional {
531                format!(
532                    "{name}: val.{name}.as_ref().map(|v| v.iter().map(|inner| inner.iter().map(|&x| x as f64).collect()).collect())"
533                )
534            } else {
535                format!("{name}: val.{name}.iter().map(|inner| inner.iter().map(|&x| x as f64).collect()).collect()")
536            }
537        }
538        // Optional(Vec<Vec<f32>>) needs nested element-wise cast to f64
539        TypeRef::Optional(inner)
540            if config.cast_f32_to_f64
541                && matches!(inner.as_ref(), TypeRef::Vec(outer) if matches!(outer.as_ref(), TypeRef::Vec(prim) if matches!(prim.as_ref(), TypeRef::Primitive(PrimitiveType::F32)))) =>
542        {
543            format!(
544                "{name}: val.{name}.as_ref().map(|v| v.iter().map(|inner| inner.iter().map(|&x| x as f64).collect()).collect())"
545            )
546        }
547        // Optional with i64-cast inner
548        TypeRef::Optional(inner)
549            if config.cast_large_ints_to_i64
550                && matches!(inner.as_ref(), TypeRef::Primitive(p) if needs_i64_cast(p)) =>
551        {
552            if let TypeRef::Primitive(p) = inner.as_ref() {
553                let cast_to = binding_prim_str(p);
554                format!("{name}: val.{name}.map(|v| v as {cast_to})")
555            } else {
556                field_conversion_from_core(name, ty, optional, sanitized, opaque_types)
557            }
558        }
559        // HashMap value type casting: when value type needs i64 casting
560        TypeRef::Map(_k, v)
561            if config.cast_large_ints_to_i64 && matches!(v.as_ref(), TypeRef::Primitive(p) if needs_i64_cast(p)) =>
562        {
563            if let TypeRef::Primitive(p) = v.as_ref() {
564                let cast_to = binding_prim_str(p);
565                if optional {
566                    format!(
567                        "{name}: val.{name}.as_ref().map(|m| m.iter().map(|(k, v)| (k.clone(), *v as {cast_to})).collect())"
568                    )
569                } else {
570                    format!("{name}: val.{name}.iter().map(|(k, v)| (k.clone(), *v as {cast_to})).collect()")
571                }
572            } else {
573                field_conversion_from_core(name, ty, optional, sanitized, opaque_types)
574            }
575        }
576        // Vec<u64/usize/isize> needs element-wise i64 casting (core→binding)
577        TypeRef::Vec(inner)
578            if config.cast_large_ints_to_i64
579                && matches!(inner.as_ref(), TypeRef::Primitive(p) if needs_i64_cast(p)) =>
580        {
581            if let TypeRef::Primitive(p) = inner.as_ref() {
582                let cast_to = binding_prim_str(p);
583                if optional {
584                    format!("{name}: val.{name}.as_ref().map(|v| v.iter().map(|&x| x as {cast_to}).collect())")
585                } else {
586                    format!("{name}: val.{name}.iter().map(|&v| v as {cast_to}).collect()")
587                }
588            } else {
589                field_conversion_from_core(name, ty, optional, sanitized, opaque_types)
590            }
591        }
592        // Vec<Vec<u64/usize/isize>> needs nested element-wise i64 casting (core→binding)
593        TypeRef::Vec(outer)
594            if config.cast_large_ints_to_i64
595                && matches!(outer.as_ref(), TypeRef::Vec(inner) if matches!(inner.as_ref(), TypeRef::Primitive(p) if needs_i64_cast(p))) =>
596        {
597            if let TypeRef::Vec(inner) = outer.as_ref() {
598                if let TypeRef::Primitive(p) = inner.as_ref() {
599                    let cast_to = binding_prim_str(p);
600                    if optional {
601                        format!(
602                            "{name}: val.{name}.as_ref().map(|v| v.iter().map(|inner| inner.iter().map(|&x| x as {cast_to}).collect()).collect())"
603                        )
604                    } else {
605                        format!(
606                            "{name}: val.{name}.iter().map(|inner| inner.iter().map(|&x| x as {cast_to}).collect()).collect()"
607                        )
608                    }
609                } else {
610                    field_conversion_from_core(name, ty, optional, sanitized, opaque_types)
611                }
612            } else {
613                field_conversion_from_core(name, ty, optional, sanitized, opaque_types)
614            }
615        }
616        // Json→String: core uses serde_json::Value, binding uses String (PHP)
617        TypeRef::Json if config.json_to_string => {
618            if optional {
619                format!("{name}: val.{name}.as_ref().map(ToString::to_string)")
620            } else {
621                format!("{name}: val.{name}.to_string()")
622            }
623        }
624        // Json→JsValue: core uses serde_json::Value, binding uses JsValue (WASM)
625        TypeRef::Json if config.map_uses_jsvalue => {
626            if optional {
627                format!("{name}: val.{name}.as_ref().and_then(|v| serde_wasm_bindgen::to_value(v).ok())")
628            } else {
629                format!("{name}: serde_wasm_bindgen::to_value(&val.{name}).unwrap_or(JsValue::NULL)")
630            }
631        }
632        // Vec<Json>→JsValue: core uses Vec<serde_json::Value>, binding uses JsValue (WASM)
633        TypeRef::Vec(inner) if config.map_uses_jsvalue && matches!(inner.as_ref(), TypeRef::Json) => {
634            if optional {
635                format!("{name}: val.{name}.as_ref().and_then(|v| serde_wasm_bindgen::to_value(v).ok())")
636            } else {
637                format!("{name}: serde_wasm_bindgen::to_value(&val.{name}).unwrap_or(JsValue::NULL)")
638            }
639        }
640        // Optional(Vec<Json>)→JsValue (WASM)
641        TypeRef::Optional(inner)
642            if config.map_uses_jsvalue
643                && matches!(inner.as_ref(), TypeRef::Vec(vi) if matches!(vi.as_ref(), TypeRef::Json)) =>
644        {
645            format!("{name}: val.{name}.as_ref().and_then(|v| serde_wasm_bindgen::to_value(v).ok())")
646        }
647        // Fall through to default (handles paths, opaque without prefix, etc.)
648        _ => field_conversion_from_core(name, ty, optional, sanitized, opaque_types),
649    }
650}
651
652/// Apply CoreWrapper transformations for core→binding direction.
653/// Unwraps Arc, converts Cow→String, Bytes→Vec<u8>.
654fn apply_core_wrapper_from_core(
655    conversion: &str,
656    name: &str,
657    core_wrapper: &CoreWrapper,
658    vec_inner_core_wrapper: &CoreWrapper,
659    optional: bool,
660) -> String {
661    // Handle Vec<Arc<T>>: unwrap Arc elements
662    if *vec_inner_core_wrapper == CoreWrapper::Arc {
663        return conversion
664            .replace(".map(Into::into).collect()", ".map(|v| (*v).clone().into()).collect()")
665            .replace(
666                "map(|v| v.into_iter().map(Into::into)",
667                "map(|v| v.into_iter().map(|v| (*v).clone().into())",
668            );
669    }
670
671    match core_wrapper {
672        CoreWrapper::None => conversion.to_string(),
673        CoreWrapper::Cow => {
674            // Cow<str> → String: core val.name is Cow, binding needs String
675            // The conversion already emits "name: val.name" for strings which works
676            // since Cow<str> derefs to &str and String: From<Cow<str>> exists.
677            // But if it's "val.name" directly, add .into_owned() or .to_string()
678            if let Some(expr) = conversion.strip_prefix(&format!("{name}: ")) {
679                if optional {
680                    // Already handled by map
681                    conversion.to_string()
682                } else if expr == format!("val.{name}") {
683                    format!("{name}: val.{name}.into_owned()")
684                } else {
685                    conversion.to_string()
686                }
687            } else {
688                conversion.to_string()
689            }
690        }
691        CoreWrapper::Arc => {
692            // Arc<T> → T: unwrap via clone
693            if let Some(expr) = conversion.strip_prefix(&format!("{name}: ")) {
694                if optional {
695                    format!("{name}: {expr}.map(|v| (*v).clone().into())")
696                } else {
697                    let unwrapped = expr.replace(&format!("val.{name}"), &format!("(*val.{name}).clone()"));
698                    format!("{name}: {unwrapped}")
699                }
700            } else {
701                conversion.to_string()
702            }
703        }
704        CoreWrapper::Bytes => {
705            // Bytes → Vec<u8>: .to_vec()
706            if let Some(expr) = conversion.strip_prefix(&format!("{name}: ")) {
707                if optional {
708                    format!("{name}: {expr}.map(|v| v.to_vec())")
709                } else if expr == format!("val.{name}") {
710                    format!("{name}: val.{name}.to_vec()")
711                } else {
712                    conversion.to_string()
713                }
714            } else {
715                conversion.to_string()
716            }
717        }
718        CoreWrapper::ArcMutex => {
719            // Arc<Mutex<T>> → T: lock and clone
720            if let Some(expr) = conversion.strip_prefix(&format!("{name}: ")) {
721                if optional {
722                    format!("{name}: {expr}.map(|v| v.lock().unwrap().clone().into())")
723                } else if expr == format!("val.{name}") {
724                    format!("{name}: val.{name}.lock().unwrap().clone().into()")
725                } else {
726                    conversion.to_string()
727                }
728            } else {
729                conversion.to_string()
730            }
731        }
732    }
733}