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        // Map<K, Named>: each value needs .into() to convert core→binding
367        TypeRef::Map(_k, v) if matches!(v.as_ref(), TypeRef::Named(_)) => {
368            if optional {
369                format!("{name}: val.{name}.map(|m| m.into_iter().map(|(k, v)| (k, v.into())).collect())")
370            } else {
371                format!("{name}: val.{name}.into_iter().map(|(k, v)| (k, v.into())).collect()")
372            }
373        }
374        // Optional(Map<K, Named>): same but wrapped in Option
375        TypeRef::Optional(inner) if matches!(inner.as_ref(), TypeRef::Map(_k, v) if matches!(v.as_ref(), TypeRef::Named(_))) =>
376        {
377            format!("{name}: val.{name}.map(|m| m.into_iter().map(|(k, v)| (k, v.into())).collect())")
378        }
379        // Vec<Named>: each element needs .into() to convert core→binding
380        TypeRef::Vec(inner) if matches!(inner.as_ref(), TypeRef::Named(_)) => {
381            if optional {
382                format!("{name}: val.{name}.map(|v| v.into_iter().map(Into::into).collect())")
383            } else {
384                format!("{name}: val.{name}.into_iter().map(Into::into).collect()")
385            }
386        }
387        // Optional(Vec<Named>): same but wrapped in Option
388        TypeRef::Optional(inner) if matches!(inner.as_ref(), TypeRef::Vec(vi) if matches!(vi.as_ref(), TypeRef::Named(_))) =>
389        {
390            format!("{name}: val.{name}.map(|v| v.into_iter().map(Into::into).collect())")
391        }
392        // Everything else is symmetric
393        _ => field_conversion_to_core(name, ty, optional),
394    }
395}
396
397/// Core→binding field conversion with backend-specific config.
398pub fn field_conversion_from_core_cfg(
399    name: &str,
400    ty: &TypeRef,
401    optional: bool,
402    sanitized: bool,
403    opaque_types: &AHashSet<String>,
404    config: &ConversionConfig,
405) -> String {
406    // Sanitized fields: for WASM (map_uses_jsvalue), Map and Vec<Json> fields target JsValue
407    // and need serde_wasm_bindgen::to_value() instead of iterator-based .collect().
408    // Note: Vec<String> sanitized does NOT use the JsValue path because Vec<String> maps to
409    // Vec<String> in WASM (not JsValue) — use the normal sanitized iterator path instead.
410    if sanitized {
411        if config.map_uses_jsvalue {
412            // Map(String, String) sanitized → JsValue (HashMap maps to JsValue in WASM)
413            if let TypeRef::Map(k, v) = ty {
414                if matches!(k.as_ref(), TypeRef::String) && matches!(v.as_ref(), TypeRef::String) {
415                    if optional {
416                        return format!(
417                            "{name}: val.{name}.as_ref().and_then(|v| serde_wasm_bindgen::to_value(v).ok())"
418                        );
419                    }
420                    return format!("{name}: serde_wasm_bindgen::to_value(&val.{name}).unwrap_or(JsValue::NULL)");
421                }
422            }
423            // Vec<Json> sanitized → JsValue (Vec<Json> maps to JsValue in WASM via nested-vec path)
424            if let TypeRef::Vec(inner) = ty {
425                if matches!(inner.as_ref(), TypeRef::Json) {
426                    if optional {
427                        return format!(
428                            "{name}: val.{name}.as_ref().and_then(|v| serde_wasm_bindgen::to_value(v).ok())"
429                        );
430                    }
431                    return format!("{name}: serde_wasm_bindgen::to_value(&val.{name}).unwrap_or(JsValue::NULL)");
432                }
433            }
434        }
435        return field_conversion_from_core(name, ty, optional, sanitized, opaque_types);
436    }
437
438    // Vec<Named>→String core→binding: binding holds JSON string, core has Vec<Named>.
439    // Only apply serde round-trip for Vec<Named> types (complex structs that can't cross FFI).
440    // Vec<String>, Vec<Primitive>, etc. stay as-is since they map directly.
441    if config.vec_named_to_string {
442        if let TypeRef::Vec(inner) = ty {
443            if matches!(inner.as_ref(), TypeRef::Named(_)) {
444                if optional {
445                    return format!("{name}: val.{name}.as_ref().and_then(|v| serde_json::to_string(v).ok())");
446                }
447                return format!("{name}: serde_json::to_string(&val.{name}).unwrap_or_default()");
448            }
449        }
450    }
451
452    // WASM JsValue: use serde_wasm_bindgen for Map and nested Vec types
453    if config.map_uses_jsvalue {
454        let is_nested_vec = matches!(ty, TypeRef::Vec(inner) if matches!(inner.as_ref(), TypeRef::Vec(_)));
455        let is_map = matches!(ty, TypeRef::Map(_, _));
456        if is_nested_vec || is_map {
457            if optional {
458                return format!("{name}: val.{name}.as_ref().and_then(|v| serde_wasm_bindgen::to_value(v).ok())");
459            }
460            return format!("{name}: serde_wasm_bindgen::to_value(&val.{name}).unwrap_or(JsValue::NULL)");
461        }
462        if let TypeRef::Optional(inner) = ty {
463            let is_inner_nested = matches!(inner.as_ref(), TypeRef::Vec(vi) if matches!(vi.as_ref(), TypeRef::Vec(_)));
464            let is_inner_map = matches!(inner.as_ref(), TypeRef::Map(_, _));
465            if is_inner_nested || is_inner_map {
466                return format!("{name}: val.{name}.as_ref().and_then(|v| serde_wasm_bindgen::to_value(v).ok())");
467            }
468        }
469    }
470
471    let prefix = config.type_name_prefix;
472    let is_enum_string = |n: &str| -> bool { config.enum_string_names.as_ref().is_some_and(|names| names.contains(n)) };
473
474    match ty {
475        // i64 casting for large int primitives
476        TypeRef::Primitive(p) if config.cast_large_ints_to_i64 && needs_i64_cast(p) => {
477            let cast_to = binding_prim_str(p);
478            if optional {
479                format!("{name}: val.{name}.map(|v| v as {cast_to})")
480            } else {
481                format!("{name}: val.{name} as {cast_to}")
482            }
483        }
484        // Optional(large_int) with i64 casting
485        TypeRef::Optional(inner)
486            if config.cast_large_ints_to_i64
487                && matches!(inner.as_ref(), TypeRef::Primitive(p) if needs_i64_cast(p)) =>
488        {
489            if let TypeRef::Primitive(p) = inner.as_ref() {
490                let cast_to = binding_prim_str(p);
491                format!("{name}: val.{name}.map(|v| v as {cast_to})")
492            } else {
493                field_conversion_from_core(name, ty, optional, sanitized, opaque_types)
494            }
495        }
496        // f32→f64 casting (NAPI only)
497        TypeRef::Primitive(PrimitiveType::F32) if config.cast_f32_to_f64 => {
498            if optional {
499                format!("{name}: val.{name}.map(|v| v as f64)")
500            } else {
501                format!("{name}: val.{name} as f64")
502            }
503        }
504        // Duration with i64 casting
505        TypeRef::Duration if config.cast_large_ints_to_i64 => {
506            if optional {
507                format!("{name}: val.{name}.map(|d| d.as_millis() as u64 as i64)")
508            } else {
509                format!("{name}: val.{name}.as_millis() as u64 as i64")
510            }
511        }
512        // Opaque Named types with prefix: wrap in Arc with prefixed binding name
513        TypeRef::Named(n) if opaque_types.contains(n.as_str()) && !prefix.is_empty() => {
514            let prefixed = format!("{prefix}{n}");
515            if optional {
516                format!("{name}: val.{name}.map(|v| {prefixed} {{ inner: Arc::new(v) }})")
517            } else {
518                format!("{name}: {prefixed} {{ inner: Arc::new(val.{name}) }}")
519            }
520        }
521        // Enum-to-String Named types (PHP pattern)
522        TypeRef::Named(n) if is_enum_string(n) => {
523            // Use serde serialization to get the correct serde(rename) value, not Debug format.
524            // serde_json::to_value gives Value::String("auto") which we extract.
525            if optional {
526                format!(
527                    "{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())"
528                )
529            } else {
530                format!(
531                    "{name}: serde_json::to_value(val.{name}).ok().and_then(|s| s.as_str().map(String::from)).unwrap_or_default()"
532                )
533            }
534        }
535        // Vec<Enum-to-String> Named types: element-wise serde serialization
536        TypeRef::Vec(inner) if matches!(inner.as_ref(), TypeRef::Named(n) if is_enum_string(n)) => {
537            if optional {
538                format!(
539                    "{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())"
540                )
541            } else {
542                format!(
543                    "{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()"
544                )
545            }
546        }
547        // Optional(Vec<Enum-to-String>) Named types (PHP pattern)
548        TypeRef::Optional(inner) if matches!(inner.as_ref(), TypeRef::Vec(vi) if matches!(vi.as_ref(), TypeRef::Named(n) if is_enum_string(n))) =>
549        {
550            format!(
551                "{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())"
552            )
553        }
554        // Vec<f32> needs element-wise cast to f64 when f32→f64 mapping is active
555        TypeRef::Vec(inner)
556            if config.cast_f32_to_f64 && matches!(inner.as_ref(), TypeRef::Primitive(PrimitiveType::F32)) =>
557        {
558            if optional {
559                format!("{name}: val.{name}.as_ref().map(|v| v.iter().map(|&x| x as f64).collect())")
560            } else {
561                format!("{name}: val.{name}.iter().map(|&v| v as f64).collect()")
562            }
563        }
564        // Optional(Vec(f32)) needs element-wise cast to f64
565        TypeRef::Optional(inner)
566            if config.cast_f32_to_f64
567                && matches!(inner.as_ref(), TypeRef::Vec(vi) if matches!(vi.as_ref(), TypeRef::Primitive(PrimitiveType::F32))) =>
568        {
569            format!("{name}: val.{name}.as_ref().map(|v| v.iter().map(|&x| x as f64).collect())")
570        }
571        // Optional(Vec(u64/usize/isize)) needs element-wise i64 casting
572        TypeRef::Optional(inner)
573            if config.cast_large_ints_to_i64
574                && matches!(inner.as_ref(), TypeRef::Vec(vi) if matches!(vi.as_ref(), TypeRef::Primitive(p) if needs_i64_cast(p))) =>
575        {
576            if let TypeRef::Vec(vi) = inner.as_ref() {
577                if let TypeRef::Primitive(p) = vi.as_ref() {
578                    let cast_to = binding_prim_str(p);
579                    if sanitized {
580                        // Sanitized from Option<(T, T)> → Option<Vec<T>>: destructure tuple
581                        format!("{name}: val.{name}.map(|(a, b)| vec![a as {cast_to}, b as {cast_to}])")
582                    } else {
583                        format!("{name}: val.{name}.as_ref().map(|v| v.iter().map(|&x| x as {cast_to}).collect())")
584                    }
585                } else {
586                    field_conversion_from_core(name, ty, optional, sanitized, opaque_types)
587                }
588            } else {
589                field_conversion_from_core(name, ty, optional, sanitized, opaque_types)
590            }
591        }
592        // Vec<Vec<f32>> needs nested element-wise cast to f64 (for embeddings, etc.)
593        TypeRef::Vec(outer)
594            if config.cast_f32_to_f64
595                && matches!(outer.as_ref(), TypeRef::Vec(inner) if matches!(inner.as_ref(), TypeRef::Primitive(PrimitiveType::F32))) =>
596        {
597            if optional {
598                format!(
599                    "{name}: val.{name}.as_ref().map(|v| v.iter().map(|inner| inner.iter().map(|&x| x as f64).collect()).collect())"
600                )
601            } else {
602                format!("{name}: val.{name}.iter().map(|inner| inner.iter().map(|&x| x as f64).collect()).collect()")
603            }
604        }
605        // Optional(Vec<Vec<f32>>) needs nested element-wise cast to f64
606        TypeRef::Optional(inner)
607            if config.cast_f32_to_f64
608                && matches!(inner.as_ref(), TypeRef::Vec(outer) if matches!(outer.as_ref(), TypeRef::Vec(prim) if matches!(prim.as_ref(), TypeRef::Primitive(PrimitiveType::F32)))) =>
609        {
610            format!(
611                "{name}: val.{name}.as_ref().map(|v| v.iter().map(|inner| inner.iter().map(|&x| x as f64).collect()).collect())"
612            )
613        }
614        // Optional with i64-cast inner
615        TypeRef::Optional(inner)
616            if config.cast_large_ints_to_i64
617                && matches!(inner.as_ref(), TypeRef::Primitive(p) if needs_i64_cast(p)) =>
618        {
619            if let TypeRef::Primitive(p) = inner.as_ref() {
620                let cast_to = binding_prim_str(p);
621                format!("{name}: val.{name}.map(|v| v as {cast_to})")
622            } else {
623                field_conversion_from_core(name, ty, optional, sanitized, opaque_types)
624            }
625        }
626        // HashMap value type casting: when value type needs i64 casting
627        TypeRef::Map(_k, v)
628            if config.cast_large_ints_to_i64 && matches!(v.as_ref(), TypeRef::Primitive(p) if needs_i64_cast(p)) =>
629        {
630            if let TypeRef::Primitive(p) = v.as_ref() {
631                let cast_to = binding_prim_str(p);
632                if optional {
633                    format!(
634                        "{name}: val.{name}.as_ref().map(|m| m.iter().map(|(k, v)| (k.clone(), *v as {cast_to})).collect())"
635                    )
636                } else {
637                    format!("{name}: val.{name}.iter().map(|(k, v)| (k.clone(), *v as {cast_to})).collect()")
638                }
639            } else {
640                field_conversion_from_core(name, ty, optional, sanitized, opaque_types)
641            }
642        }
643        // Vec<u64/usize/isize> needs element-wise i64 casting (core→binding)
644        TypeRef::Vec(inner)
645            if config.cast_large_ints_to_i64
646                && matches!(inner.as_ref(), TypeRef::Primitive(p) if needs_i64_cast(p)) =>
647        {
648            if let TypeRef::Primitive(p) = inner.as_ref() {
649                let cast_to = binding_prim_str(p);
650                if sanitized {
651                    // Sanitized from tuple (T, T) → Vec<T>: destructure tuple into vec
652                    if optional {
653                        format!("{name}: val.{name}.map(|(a, b)| vec![a as {cast_to}, b as {cast_to}])")
654                    } else {
655                        format!("{name}: {{ let (a, b) = val.{name}; vec![a as {cast_to}, b as {cast_to}] }}")
656                    }
657                } else if optional {
658                    format!("{name}: val.{name}.as_ref().map(|v| v.iter().map(|&x| x as {cast_to}).collect())")
659                } else {
660                    format!("{name}: val.{name}.iter().map(|&v| v as {cast_to}).collect()")
661                }
662            } else {
663                field_conversion_from_core(name, ty, optional, sanitized, opaque_types)
664            }
665        }
666        // Vec<Vec<u64/usize/isize>> needs nested element-wise i64 casting (core→binding)
667        TypeRef::Vec(outer)
668            if config.cast_large_ints_to_i64
669                && matches!(outer.as_ref(), TypeRef::Vec(inner) if matches!(inner.as_ref(), TypeRef::Primitive(p) if needs_i64_cast(p))) =>
670        {
671            if let TypeRef::Vec(inner) = outer.as_ref() {
672                if let TypeRef::Primitive(p) = inner.as_ref() {
673                    let cast_to = binding_prim_str(p);
674                    if optional {
675                        format!(
676                            "{name}: val.{name}.as_ref().map(|v| v.iter().map(|inner| inner.iter().map(|&x| x as {cast_to}).collect()).collect())"
677                        )
678                    } else {
679                        format!(
680                            "{name}: val.{name}.iter().map(|inner| inner.iter().map(|&x| x as {cast_to}).collect()).collect()"
681                        )
682                    }
683                } else {
684                    field_conversion_from_core(name, ty, optional, sanitized, opaque_types)
685                }
686            } else {
687                field_conversion_from_core(name, ty, optional, sanitized, opaque_types)
688            }
689        }
690        // Json→String: core uses serde_json::Value, binding uses String (PHP)
691        TypeRef::Json if config.json_to_string => {
692            if optional {
693                format!("{name}: val.{name}.as_ref().map(ToString::to_string)")
694            } else {
695                format!("{name}: val.{name}.to_string()")
696            }
697        }
698        // Json→JsValue: core uses serde_json::Value, binding uses JsValue (WASM)
699        TypeRef::Json if config.map_uses_jsvalue => {
700            if optional {
701                format!("{name}: val.{name}.as_ref().and_then(|v| serde_wasm_bindgen::to_value(v).ok())")
702            } else {
703                format!("{name}: serde_wasm_bindgen::to_value(&val.{name}).unwrap_or(JsValue::NULL)")
704            }
705        }
706        // Vec<Json>→JsValue: core uses Vec<serde_json::Value>, binding uses JsValue (WASM)
707        TypeRef::Vec(inner) if config.map_uses_jsvalue && matches!(inner.as_ref(), TypeRef::Json) => {
708            if optional {
709                format!("{name}: val.{name}.as_ref().and_then(|v| serde_wasm_bindgen::to_value(v).ok())")
710            } else {
711                format!("{name}: serde_wasm_bindgen::to_value(&val.{name}).unwrap_or(JsValue::NULL)")
712            }
713        }
714        // Optional(Vec<Json>)→JsValue (WASM)
715        TypeRef::Optional(inner)
716            if config.map_uses_jsvalue
717                && matches!(inner.as_ref(), TypeRef::Vec(vi) if matches!(vi.as_ref(), TypeRef::Json)) =>
718        {
719            format!("{name}: val.{name}.as_ref().and_then(|v| serde_wasm_bindgen::to_value(v).ok())")
720        }
721        // Fall through to default (handles paths, opaque without prefix, etc.)
722        _ => field_conversion_from_core(name, ty, optional, sanitized, opaque_types),
723    }
724}
725
726/// Apply CoreWrapper transformations for core→binding direction.
727/// Unwraps Arc, converts Cow→String, Bytes→Vec<u8>.
728fn apply_core_wrapper_from_core(
729    conversion: &str,
730    name: &str,
731    core_wrapper: &CoreWrapper,
732    vec_inner_core_wrapper: &CoreWrapper,
733    optional: bool,
734) -> String {
735    // Handle Vec<Arc<T>>: unwrap Arc elements
736    if *vec_inner_core_wrapper == CoreWrapper::Arc {
737        return conversion
738            .replace(".map(Into::into).collect()", ".map(|v| (*v).clone().into()).collect()")
739            .replace(
740                "map(|v| v.into_iter().map(Into::into)",
741                "map(|v| v.into_iter().map(|v| (*v).clone().into())",
742            );
743    }
744
745    match core_wrapper {
746        CoreWrapper::None => conversion.to_string(),
747        CoreWrapper::Cow => {
748            // Cow<str> → String: core val.name is Cow, binding needs String
749            // The conversion already emits "name: val.name" for strings which works
750            // since Cow<str> derefs to &str and String: From<Cow<str>> exists.
751            // But if it's "val.name" directly, add .into_owned() or .to_string()
752            if let Some(expr) = conversion.strip_prefix(&format!("{name}: ")) {
753                if optional {
754                    // Already handled by map
755                    conversion.to_string()
756                } else if expr == format!("val.{name}") {
757                    format!("{name}: val.{name}.into_owned()")
758                } else {
759                    conversion.to_string()
760                }
761            } else {
762                conversion.to_string()
763            }
764        }
765        CoreWrapper::Arc => {
766            // Arc<T> → T: unwrap via clone.
767            //
768            // Special case: opaque Named types build the binding wrapper with
769            // `{ inner: Arc::new(v) }` in the base conversion, but when the core
770            // field is `Arc<T>`, `v` IS already the `Arc<T>` — wrapping it again
771            // with `Arc::new` produces `Arc<Arc<T>>`.  Detect this pattern and
772            // replace `Arc::new(v)` with `v`, and `Arc::new(val.{name})` with
773            // `val.{name}`, then return without adding an extra unwrap chain.
774            if conversion.contains("{ inner: Arc::new(") {
775                return conversion.replace("{ inner: Arc::new(v) }", "{ inner: v }").replace(
776                    &format!("{{ inner: Arc::new(val.{name}) }}"),
777                    &format!("{{ inner: val.{name} }}"),
778                );
779            }
780            if let Some(expr) = conversion.strip_prefix(&format!("{name}: ")) {
781                if optional {
782                    format!("{name}: {expr}.map(|v| (*v).clone().into())")
783                } else {
784                    let unwrapped = expr.replace(&format!("val.{name}"), &format!("(*val.{name}).clone()"));
785                    format!("{name}: {unwrapped}")
786                }
787            } else {
788                conversion.to_string()
789            }
790        }
791        CoreWrapper::Bytes => {
792            // Bytes → Vec<u8>: .to_vec()
793            if let Some(expr) = conversion.strip_prefix(&format!("{name}: ")) {
794                if optional {
795                    format!("{name}: {expr}.map(|v| v.to_vec())")
796                } else if expr == format!("val.{name}") {
797                    format!("{name}: val.{name}.to_vec()")
798                } else {
799                    conversion.to_string()
800                }
801            } else {
802                conversion.to_string()
803            }
804        }
805        CoreWrapper::ArcMutex => {
806            // Arc<Mutex<T>> → T: lock and clone
807            if let Some(expr) = conversion.strip_prefix(&format!("{name}: ")) {
808                if optional {
809                    format!("{name}: {expr}.map(|v| v.lock().unwrap().clone().into())")
810                } else if expr == format!("val.{name}") {
811                    format!("{name}: val.{name}.lock().unwrap().clone().into()")
812                } else {
813                    conversion.to_string()
814                }
815            } else {
816                conversion.to_string()
817            }
818        }
819    }
820}