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