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