Skip to main content

alef_codegen/conversions/
core_to_binding.rs

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