Skip to main content

alef_codegen/conversions/
core_to_binding.rs

1use ahash::AHashSet;
2use alef_core::ir::{CoreWrapper, PrimitiveType, TypeDef, TypeRef};
3
4use super::ConversionConfig;
5use super::binding_to_core::field_conversion_to_core;
6use super::helpers::is_newtype;
7use super::helpers::{binding_prim_str, core_type_path_remapped, needs_f64_cast, needs_i32_cast, needs_i64_cast};
8
9/// Generate `impl From<core::Type> for BindingType` (core -> binding).
10pub fn gen_from_core_to_binding(typ: &TypeDef, core_import: &str, opaque_types: &AHashSet<String>) -> String {
11    gen_from_core_to_binding_cfg(typ, core_import, opaque_types, &ConversionConfig::default())
12}
13
14/// Generate `impl From<core::Type> for BindingType` with backend-specific config.
15pub fn gen_from_core_to_binding_cfg(
16    typ: &TypeDef,
17    core_import: &str,
18    opaque_types: &AHashSet<String>,
19    config: &ConversionConfig,
20) -> String {
21    let core_path = core_type_path_remapped(typ, core_import, config.source_crate_remaps);
22    let binding_name = format!("{}{}", config.type_name_prefix, typ.name);
23
24    // Newtype structs: extract inner value with val.0
25    if is_newtype(typ) {
26        let field = &typ.fields[0];
27        let newtype_inner_expr = match &field.ty {
28            TypeRef::Named(_) => "val.0.into()".to_string(),
29            TypeRef::Path => "val.0.to_string_lossy().to_string()".to_string(),
30            TypeRef::Duration => "val.0.as_millis() as u64".to_string(),
31            _ => "val.0".to_string(),
32        };
33        return crate::template_env::render(
34            "conversions/core_to_binding_impl",
35            minijinja::context! {
36                core_path => core_path,
37                binding_name => binding_name,
38                is_newtype => true,
39                newtype_inner_expr => newtype_inner_expr,
40                fields => vec![] as Vec<String>,
41            },
42        );
43    }
44
45    let optionalized = config.optionalize_defaults && typ.has_default;
46
47    // Pre-compute all field conversions
48    let mut fields = Vec::new();
49    for field in &typ.fields {
50        if field.binding_excluded {
51            continue;
52        }
53        // Fields referencing excluded types are not present in the binding struct — skip
54        if !config.exclude_types.is_empty()
55            && super::helpers::field_references_excluded_type(&field.ty, config.exclude_types)
56        {
57            continue;
58        }
59        // When the binding crate strips cfg-gated fields from the struct
60        // (typically because the backend doesn't carry feature gates into the binding
61        // crate's Cargo.toml — e.g. extendr), the From impl cannot assign
62        // <field>: val.<field> because the binding struct has no slot for it.
63        if field.cfg.is_some()
64            && !config.never_skip_cfg_field_names.contains(&field.name)
65            && config.strip_cfg_fields_from_binding_struct
66        {
67            continue;
68        }
69        let base_conversion = field_conversion_from_core_cfg(
70            &field.name,
71            &field.ty,
72            field.optional,
73            field.sanitized,
74            opaque_types,
75            config,
76        );
77        // Box<T> fields: dereference before conversion.
78        let base_conversion = if field.is_boxed && matches!(&field.ty, TypeRef::Named(_)) {
79            if field.optional {
80                // Optional<Box<T>>: replace .map(Into::into) with .map(|v| (*v).into())
81                let src = format!("{}: val.{}.map(Into::into)", field.name, field.name);
82                let dst = format!("{}: val.{}.map(|v| (*v).into())", field.name, field.name);
83                if base_conversion == src { dst } else { base_conversion }
84            } else {
85                // Box<T>: replace `val.{name}` with `(*val.{name})`
86                base_conversion.replace(&format!("val.{}", field.name), &format!("(*val.{})", field.name))
87            }
88        } else {
89            base_conversion
90        };
91        // Newtype unwrapping: when the field was resolved from a newtype (e.g. NodeIndex → u32),
92        // unwrap the core newtype by accessing `.0`.
93        // e.g. `source: val.source` → `source: val.source.0`
94        //      `parent: val.parent` → `parent: val.parent.map(|v| v.0)`
95        //      `children: val.children` → `children: val.children.iter().map(|v| v.0).collect()`
96        let base_conversion = if field.newtype_wrapper.is_some() {
97            match &field.ty {
98                TypeRef::Optional(_) => {
99                    // Replace `val.{name}` with `val.{name}.map(|v| v.0)` in the generated expression
100                    base_conversion.replace(
101                        &format!("val.{}", field.name),
102                        &format!("val.{}.map(|v| v.0)", field.name),
103                    )
104                }
105                TypeRef::Vec(_) => {
106                    // Replace `val.{name}` with `val.{name}.iter().map(|v| v.0).collect()` in expression
107                    base_conversion.replace(
108                        &format!("val.{}", field.name),
109                        &format!("val.{}.iter().map(|v| v.0).collect::<Vec<_>>()", field.name),
110                    )
111                }
112                // When `optional=true` and `ty` is a plain Primitive (not TypeRef::Optional), the core
113                // field is actually `Option<NewtypeT>`, so we must use `.map(|v| v.0)` not `.0`.
114                _ if field.optional => base_conversion.replace(
115                    &format!("val.{}", field.name),
116                    &format!("val.{}.map(|v| v.0)", field.name),
117                ),
118                _ => {
119                    // Direct field: append `.0` to access the inner primitive
120                    base_conversion.replace(&format!("val.{}", field.name), &format!("val.{}.0", field.name))
121                }
122            }
123        } else {
124            base_conversion
125        };
126        // When field.optional=true AND field.ty=Optional(T), the binding struct flattens
127        // Option<Option<T>> to Option<T>. Core produces Option<Option<T>>, binding needs
128        // Option<T>. Generate the conversion by treating the pre-flattened field as Option<T>:
129        // call the standard conversion for the inner type T with optional=true, substituting
130        // val.{name}.flatten() for val.{name} so all cast/conversion logic applies to T.
131        let is_flattened_optional = field.optional && matches!(field.ty, TypeRef::Optional(_));
132        let base_conversion = if is_flattened_optional {
133            if let TypeRef::Optional(inner) = &field.ty {
134                // Produce the conversion as if the field is Option<inner> with value val.name.flatten()
135                let inner_conv = field_conversion_from_core_cfg(
136                    &field.name,
137                    inner.as_ref(),
138                    true,
139                    field.sanitized,
140                    opaque_types,
141                    config,
142                );
143                // inner_conv references val.{name}; replace with val.{name}.flatten()
144                inner_conv.replace(&format!("val.{}", field.name), &format!("val.{}.flatten()", field.name))
145            } else {
146                base_conversion
147            }
148        } else {
149            base_conversion
150        };
151        // Optionalized non-optional fields need Some() wrapping in core→binding direction.
152        // This covers both NAPI-style full optionalization and PyO3-style Duration optionalization.
153        // Flattened-optional fields are already handled above with the correct type.
154        let needs_some_wrap = !is_flattened_optional
155            && ((optionalized && !field.optional)
156                || (config.option_duration_on_defaults
157                    && typ.has_default
158                    && !field.optional
159                    && matches!(field.ty, TypeRef::Duration)));
160        let conversion = if needs_some_wrap {
161            // Extract the value expression after "name: " and wrap in Some()
162            if let Some(expr) = base_conversion.strip_prefix(&format!("{}: ", field.name)) {
163                format!("{}: Some({})", field.name, expr)
164            } else {
165                base_conversion
166            }
167        } else {
168            base_conversion
169        };
170        // Opaque Named fields without CoreWrapper::Arc (e.g. visitor: Object<'static>) cannot be
171        // auto-converted via Arc::new — the binding stores a raw host object that needs a bridge.
172        // Emit Default::default() and let the caller (e.g. the convert function) set it separately.
173        let is_opaque_no_wrapper_field = field.core_wrapper == CoreWrapper::None
174            && matches!(&field.ty, TypeRef::Named(n) if config
175                .opaque_types
176                .is_some_and(|opaque| opaque.contains(n.as_str())));
177        // CoreWrapper: unwrap Arc, convert Cow→String, Bytes→Vec<u8>
178        // For sanitized fields, still apply Cow→String conversion: Cow<'_, str> sanitizes to
179        // TypeRef::String and the Debug-formatted fallback produces quotes, but Cow implements
180        // Display so .to_string() (emitted by apply_core_wrapper_from_core for Cow) is correct.
181        // Other sanitized fields (unknown Named types) still fall through to Debug formatting.
182        let conversion = if is_opaque_no_wrapper_field {
183            // Trait-bridge OptionsField fields wrap the core handle in `Arc<core::T>` on the
184            // binding side. Construct the wrapper so the value round-trips through `.into()`
185            // (e.g. PHP's `builder().visitor(v).build()` -> `convert(html, opts)`) instead of
186            // being silently dropped. Other backends (e.g. NAPI where the binding stores a raw
187            // host Object) keep the Default::default() fallback.
188            if config.trait_bridge_field_is_arc_wrapper(&field.name) {
189                if let TypeRef::Named(name) = &field.ty {
190                    let wrapper = format!("{}{}", config.type_name_prefix, name);
191                    if field.optional {
192                        format!(
193                            "{}: val.{}.map(|v| {wrapper} {{ inner: std::sync::Arc::new(v) }})",
194                            field.name, field.name
195                        )
196                    } else {
197                        format!(
198                            "{}: {wrapper} {{ inner: std::sync::Arc::new(val.{}) }}",
199                            field.name, field.name
200                        )
201                    }
202                } else {
203                    format!("{}: Default::default()", field.name)
204                }
205            } else {
206                format!("{}: Default::default()", field.name)
207            }
208        } else if !field.sanitized || field.core_wrapper == alef_core::ir::CoreWrapper::Cow {
209            apply_core_wrapper_from_core(
210                &conversion,
211                &field.name,
212                &field.core_wrapper,
213                &field.vec_inner_core_wrapper,
214                field.optional,
215            )
216        } else {
217            conversion
218        };
219        // In core→binding direction, the binding struct field may be keyword-escaped
220        // (e.g. `class_` for `class`). The generated conversion has `field.name: expr`
221        // on the left side — rename it to `binding_name: expr` when needed.
222        let binding_field = config.binding_field_name_owned(&typ.name, &field.name);
223        let conversion = if binding_field != field.name {
224            if let Some(expr) = conversion.strip_prefix(&format!("{}: ", field.name)) {
225                format!("{binding_field}: {expr}")
226            } else {
227                conversion
228            }
229        } else {
230            conversion
231        };
232        fields.push(conversion);
233    }
234
235    crate::template_env::render(
236        "conversions/core_to_binding_impl",
237        minijinja::context! {
238            core_path => core_path,
239            binding_name => binding_name,
240            is_newtype => false,
241            newtype_inner_expr => "",
242            fields => fields,
243        },
244    )
245}
246
247/// Same but for core -> binding direction.
248/// Some types are asymmetric (PathBuf→String, sanitized fields need .to_string()).
249pub fn field_conversion_from_core(
250    name: &str,
251    ty: &TypeRef,
252    optional: bool,
253    sanitized: bool,
254    opaque_types: &AHashSet<String>,
255) -> String {
256    // Sanitized fields: the binding type differs from core (e.g. Box<str>→String, Cow<str>→String).
257    // Box<str>, Cow<str>, and Arc<str> all implement Display, so use .to_string() not {:?}.
258    // {:?} on string-like types produces debug-escaped output with surrounding quotes.
259    if sanitized {
260        // Vec<Primitive>: sanitized from tuple types like (u32, u32) → Vec<u32>.
261        // Core has a tuple, binding expects Vec — destructure the tuple.
262        if let TypeRef::Vec(inner) = ty {
263            if matches!(inner.as_ref(), TypeRef::Primitive(_)) {
264                if optional {
265                    return format!(
266                        "{name}: val.{name}.map(|t| {{ let arr: Vec<_> = [t.0, t.1].into_iter().map(|v| v as _).collect(); arr }})"
267                    );
268                }
269                return format!("{name}: vec![val.{name}.0 as _, val.{name}.1 as _]");
270            }
271        }
272        // Optional(Vec<Primitive>): sanitized from Option<(T, T)> → Option<Vec<T>>.
273        if let TypeRef::Optional(opt_inner) = ty {
274            if let TypeRef::Vec(vec_inner) = opt_inner.as_ref() {
275                if matches!(vec_inner.as_ref(), TypeRef::Primitive(_)) {
276                    return format!("{name}: val.{name}.map(|t| vec![t.0 as _, t.1 as _])");
277                }
278            }
279        }
280        // Map(String, String): sanitized from Map(Box<str>, Box<str>) etc.
281        if let TypeRef::Map(k, v) = ty {
282            if matches!(k.as_ref(), TypeRef::String) && matches!(v.as_ref(), TypeRef::String) {
283                if optional {
284                    return format!(
285                        "{name}: val.{name}.as_ref().map(|m| m.iter().map(|(k, v)| (k.to_string(), v.to_string())).collect())"
286                    );
287                }
288                return format!(
289                    "{name}: val.{name}.into_iter().map(|(k, v)| (k.to_string(), v.to_string())).collect()"
290                );
291            }
292        }
293        // Vec<String>: sanitized from Vec<Box<str>>, Vec<Cow<str>>, Vec<Named>, etc.
294        // Use Debug formatting — the original core type may not implement Display.
295        if let TypeRef::Vec(inner) = ty {
296            if matches!(inner.as_ref(), TypeRef::String) {
297                if optional {
298                    return format!(
299                        "{name}: val.{name}.as_ref().map(|v| v.iter().map(|i| format!(\"{{:?}}\", i)).collect())"
300                    );
301                }
302                return format!("{name}: val.{name}.iter().map(|i| format!(\"{{:?}}\", i)).collect()");
303            }
304        }
305        // Optional<Vec<String>>: sanitized from Optional<Vec<Box<str>>>, Optional<Vec<Cow<str>>>, etc.
306        if let TypeRef::Optional(opt_inner) = ty {
307            if let TypeRef::Vec(vec_inner) = opt_inner.as_ref() {
308                if matches!(vec_inner.as_ref(), TypeRef::String) {
309                    return format!(
310                        "{name}: val.{name}.as_ref().map(|v| v.iter().map(|i| format!(\"{{:?}}\", i)).collect())"
311                    );
312                }
313            }
314        }
315        // String: sanitized from Box<str>, Cow<str>, (u32, u32), etc.
316        // Use Debug formatting — it works for all types (including tuples) and avoids Display
317        // trait bound failures when the original core type doesn't implement Display.
318        // Note: Cow<str> is handled before this point via the CoreWrapper::Cow path above.
319        if matches!(ty, TypeRef::String) {
320            if optional {
321                return format!("{name}: val.{name}.as_ref().map(|v| format!(\"{{v:?}}\"))");
322            }
323            return format!("{name}: format!(\"{{:?}}\", val.{name})");
324        }
325        // Fallback for truly unknown sanitized types — the core type may not implement Display,
326        // so use Debug formatting which is always available (required by the sanitized field's derive).
327        if optional {
328            return format!("{name}: val.{name}.as_ref().map(|v| format!(\"{{v:?}}\"))");
329        }
330        return format!("{name}: format!(\"{{:?}}\", val.{name})");
331    }
332    match ty {
333        // Duration: core uses std::time::Duration, binding uses u64 (millis)
334        TypeRef::Duration => {
335            if optional {
336                return format!("{name}: val.{name}.map(|d| d.as_millis() as u64)");
337            }
338            format!("{name}: val.{name}.as_millis() as u64")
339        }
340        // Path: core uses PathBuf, binding uses String — PathBuf→String needs special handling
341        TypeRef::Path => {
342            if optional {
343                format!("{name}: val.{name}.map(|p| p.to_string_lossy().to_string())")
344            } else {
345                format!("{name}: val.{name}.to_string_lossy().to_string()")
346            }
347        }
348        TypeRef::Optional(inner) if matches!(inner.as_ref(), TypeRef::Path) => {
349            format!("{name}: val.{name}.map(|p| p.to_string_lossy().to_string())")
350        }
351        // Char: core uses char, binding uses String — convert char to string
352        TypeRef::Char => {
353            if optional {
354                format!("{name}: val.{name}.map(|c| c.to_string())")
355            } else {
356                format!("{name}: val.{name}.to_string()")
357            }
358        }
359        // Bytes: core uses bytes::Bytes, binding uses Vec<u8> or napi `Buffer`.
360        // `.into()` is a no-op when destination is Vec<u8> (identity From) and
361        // a Vec→Buffer wrap when destination is `napi::bindgen_prelude::Buffer`.
362        TypeRef::Bytes => {
363            if optional {
364                format!("{name}: val.{name}.map(|v| v.to_vec().into())")
365            } else {
366                format!("{name}: val.{name}.to_vec().into()")
367            }
368        }
369        // Opaque Named types: wrap in Arc to create the binding wrapper
370        TypeRef::Named(n) if opaque_types.contains(n.as_str()) => {
371            if optional {
372                format!("{name}: val.{name}.map(|v| {n} {{ inner: Arc::new(v) }})")
373            } else {
374                format!("{name}: {n} {{ inner: Arc::new(val.{name}) }}")
375            }
376        }
377        // Json: core uses serde_json::Value, binding uses String — use .to_string()
378        TypeRef::Json => {
379            if optional {
380                format!("{name}: val.{name}.as_ref().map(ToString::to_string)")
381            } else {
382                format!("{name}: val.{name}.to_string()")
383            }
384        }
385        TypeRef::Optional(inner) if matches!(inner.as_ref(), TypeRef::Json) => {
386            format!("{name}: val.{name}.as_ref().map(ToString::to_string)")
387        }
388        TypeRef::Vec(inner) if matches!(inner.as_ref(), TypeRef::Json) => {
389            if optional {
390                format!("{name}: val.{name}.as_ref().map(|v| v.iter().map(|i| i.to_string()).collect())")
391            } else {
392                format!("{name}: val.{name}.iter().map(ToString::to_string).collect()")
393            }
394        }
395        // Vec<Optional<Json>>: each element is Option<Value> → Option<String>
396        TypeRef::Vec(inner) if matches!(inner.as_ref(), TypeRef::Optional(oi) if matches!(oi.as_ref(), TypeRef::Json)) => {
397            if optional {
398                format!(
399                    "{name}: val.{name}.as_ref().map(|v| v.iter().map(|i| i.as_ref().map(ToString::to_string)).collect())"
400                )
401            } else {
402                format!("{name}: val.{name}.iter().map(|i| i.as_ref().map(ToString::to_string)).collect()")
403            }
404        }
405        // Map with Json values: core uses HashMap<K, serde_json::Value>, binding uses HashMap<K, String>.
406        // Always emit `k.to_string()` so Cow<'_, str> / Box<str> / Arc<str> keys (which the type
407        // resolver normalizes to TypeRef::String) convert correctly. For an actual `String` key
408        // this is a clone, accepted under the existing `#[allow(clippy::useless_conversion)]`.
409        TypeRef::Map(_k, v) if matches!(v.as_ref(), TypeRef::Json) => {
410            if optional {
411                format!(
412                    "{name}: val.{name}.map(|m| m.into_iter().map(|(k, v)| (k.to_string(), v.to_string())).collect())"
413                )
414            } else {
415                format!("{name}: val.{name}.into_iter().map(|(k, v)| (k.to_string(), v.to_string())).collect()")
416            }
417        }
418        // Map with Json keys: core uses HashMap<serde_json::Value, V>, binding uses HashMap<String, V>
419        TypeRef::Map(k, _v) if matches!(k.as_ref(), TypeRef::Json) => {
420            if optional {
421                format!("{name}: val.{name}.map(|m| m.into_iter().map(|(k, v)| (k.to_string(), v)).collect())")
422            } else {
423                format!("{name}: val.{name}.into_iter().map(|(k, v)| (k.to_string(), v)).collect()")
424            }
425        }
426        // Map<String, String>: core may have Box<str> keys/values, binding has String keys/values.
427        // Emit .map() with .into() conversions, which are no-ops when both sides are String.
428        // This handles cases like HashMap<Box<str>, Box<str>> (core) → HashMap<String, String> (binding).
429        TypeRef::Map(k, v) if matches!(k.as_ref(), TypeRef::String) && matches!(v.as_ref(), TypeRef::String) => {
430            if optional {
431                format!("{name}: val.{name}.map(|m| m.into_iter().map(|(k, v)| (k.into(), v.into())).collect())")
432            } else {
433                format!("{name}: val.{name}.into_iter().map(|(k, v)| (k.into(), v.into())).collect()")
434            }
435        }
436        // Map<K, Bytes>: core uses bytes::Bytes (or Vec<u8>), binding uses Vec<u8> or napi Buffer.
437        // `.to_vec().into()` converts Bytes→Vec<u8> (identity for Vec<u8>) or Bytes→Buffer (napi).
438        TypeRef::Map(_k, v) if matches!(v.as_ref(), TypeRef::Bytes) => {
439            if optional {
440                format!("{name}: val.{name}.map(|m| m.into_iter().map(|(k, v)| (k, v.to_vec().into())).collect())")
441            } else {
442                format!("{name}: val.{name}.into_iter().map(|(k, v)| (k, v.to_vec().into())).collect()")
443            }
444        }
445        // Map<K, Named>: each value needs .into() to convert core→binding
446        TypeRef::Map(_k, v) if matches!(v.as_ref(), TypeRef::Named(_)) => {
447            if optional {
448                format!("{name}: val.{name}.map(|m| m.into_iter().map(|(k, v)| (k, v.into())).collect())")
449            } else {
450                format!("{name}: val.{name}.into_iter().map(|(k, v)| (k, v.into())).collect()")
451            }
452        }
453        // Optional(Map<K, Named>): same but wrapped in Option
454        TypeRef::Optional(inner) if matches!(inner.as_ref(), TypeRef::Map(_k, v) if matches!(v.as_ref(), TypeRef::Named(_))) =>
455        {
456            format!("{name}: val.{name}.map(|m| m.into_iter().map(|(k, v)| (k, v.into())).collect())")
457        }
458        // Vec<Named>: each element needs .into() to convert core→binding
459        TypeRef::Vec(inner) if matches!(inner.as_ref(), TypeRef::Named(_)) => {
460            if optional {
461                format!("{name}: val.{name}.map(|v| v.into_iter().map(Into::into).collect())")
462            } else {
463                format!("{name}: val.{name}.into_iter().map(Into::into).collect()")
464            }
465        }
466        // Optional(Vec<Named>): same but wrapped in Option
467        TypeRef::Optional(inner) if matches!(inner.as_ref(), TypeRef::Vec(vi) if matches!(vi.as_ref(), TypeRef::Named(_))) =>
468        {
469            format!("{name}: val.{name}.map(|v| v.into_iter().map(Into::into).collect())")
470        }
471        // Everything else is symmetric
472        _ => field_conversion_to_core(name, ty, optional),
473    }
474}
475
476/// Core→binding field conversion with backend-specific config.
477pub fn field_conversion_from_core_cfg(
478    name: &str,
479    ty: &TypeRef,
480    optional: bool,
481    sanitized: bool,
482    opaque_types: &AHashSet<String>,
483    config: &ConversionConfig,
484) -> String {
485    // Sanitized fields: for WASM (map_uses_jsvalue), Map and Vec<Json> fields target JsValue
486    // and need serde_wasm_bindgen::to_value() instead of iterator-based .collect().
487    // Note: Vec<String> sanitized does NOT use the JsValue path because Vec<String> maps to
488    // Vec<String> in WASM (not JsValue) — use the normal sanitized iterator path instead.
489    if sanitized {
490        if config.map_uses_jsvalue {
491            // Map(String, String) sanitized → JsValue (HashMap maps to JsValue in WASM)
492            // Use js_sys::JSON::parse(json_str) to get a plain JS object (not ES6 Map).
493            if let TypeRef::Map(k, v) = ty {
494                if matches!(k.as_ref(), TypeRef::String) && matches!(v.as_ref(), TypeRef::String) {
495                    if optional {
496                        return format!(
497                            "{name}: val.{name}.as_ref().and_then(|v| serde_json::to_string(v).ok()).and_then(|s| js_sys::JSON::parse(&s).ok())"
498                        );
499                    }
500                    return format!(
501                        "{name}: js_sys::JSON::parse(&serde_json::to_string(&val.{name}).unwrap_or_default()).unwrap_or(JsValue::NULL)"
502                    );
503                }
504            }
505            // Vec<Json> sanitized → JsValue (Vec<Json> maps to JsValue in WASM via nested-vec path)
506            if let TypeRef::Vec(inner) = ty {
507                if matches!(inner.as_ref(), TypeRef::Json) {
508                    if optional {
509                        return format!(
510                            "{name}: val.{name}.as_ref().and_then(|v| serde_wasm_bindgen::to_value(v).ok())"
511                        );
512                    }
513                    return format!("{name}: serde_wasm_bindgen::to_value(&val.{name}).unwrap_or(JsValue::NULL)");
514                }
515            }
516        }
517        return field_conversion_from_core(name, ty, optional, sanitized, opaque_types);
518    }
519
520    // Tagged-data enum field (WASM only; binding stores JsValue / Option<JsValue> instead of
521    // WasmEnum / Option<WasmEnum>). Handles bare Named, Option<Named>, Vec<Named>, and
522    // Option<Vec<Named>> so the JS side always receives the serde-tagged wire shape
523    // (plain objects) rather than wasm-bindgen class instances.
524    if config.map_uses_jsvalue {
525        if let Some(tagged_names) = config.tagged_data_enum_names {
526            let bare_named = matches!(ty, TypeRef::Named(n) if tagged_names.contains(n));
527            let optional_named = matches!(ty, TypeRef::Optional(inner)
528                if matches!(inner.as_ref(), TypeRef::Named(n) if tagged_names.contains(n)));
529            let vec_named = matches!(ty, TypeRef::Vec(inner)
530                if matches!(inner.as_ref(), TypeRef::Named(n) if tagged_names.contains(n)));
531            let optional_vec_named = matches!(ty, TypeRef::Optional(outer)
532                if matches!(outer.as_ref(), TypeRef::Vec(inner)
533                    if matches!(inner.as_ref(), TypeRef::Named(n) if tagged_names.contains(n))));
534            if bare_named {
535                // Bare TaggedDataEnum: serialize to JsValue directly.
536                if optional {
537                    return format!("{name}: val.{name}.as_ref().and_then(|v| serde_wasm_bindgen::to_value(v).ok())");
538                }
539                return format!("{name}: serde_wasm_bindgen::to_value(&val.{name}).unwrap_or(JsValue::NULL)");
540            }
541            if optional_named {
542                // Option<TaggedDataEnum>: serialize when Some, yield Option<JsValue>.
543                return format!("{name}: val.{name}.as_ref().and_then(|v| serde_wasm_bindgen::to_value(v).ok())");
544            }
545            if vec_named {
546                if optional {
547                    return format!("{name}: val.{name}.as_ref().and_then(|v| serde_wasm_bindgen::to_value(v).ok())");
548                }
549                return format!("{name}: serde_wasm_bindgen::to_value(&val.{name}).unwrap_or(JsValue::NULL)");
550            }
551            if optional_vec_named {
552                return format!("{name}: val.{name}.as_ref().and_then(|v| serde_wasm_bindgen::to_value(v).ok())");
553            }
554        }
555    }
556
557    // Untagged data enum field (core holds the typed enum, binding holds serde_json::Value):
558    // serialize via serde_json::to_value.  Handles direct, Optional, and Vec wrappings.
559    if let Some(untagged_names) = config.untagged_data_enum_names {
560        let direct_named = matches!(ty, TypeRef::Named(n) if untagged_names.contains(n));
561        let optional_named = matches!(ty, TypeRef::Optional(inner)
562            if matches!(inner.as_ref(), TypeRef::Named(n) if untagged_names.contains(n)));
563        let vec_named = matches!(ty, TypeRef::Vec(inner)
564            if matches!(inner.as_ref(), TypeRef::Named(n) if untagged_names.contains(n)));
565        let optional_vec_named = matches!(ty, TypeRef::Optional(outer)
566            if matches!(outer.as_ref(), TypeRef::Vec(inner)
567                if matches!(inner.as_ref(), TypeRef::Named(n) if untagged_names.contains(n))));
568        if direct_named {
569            if optional {
570                return format!("{name}: val.{name}.as_ref().and_then(|v| serde_json::to_value(v).ok())");
571            }
572            return format!("{name}: serde_json::to_value(&val.{name}).unwrap_or(serde_json::Value::Null)");
573        }
574        if optional_named {
575            return format!("{name}: val.{name}.as_ref().and_then(|v| serde_json::to_value(v).ok())");
576        }
577        if vec_named {
578            if optional {
579                return format!(
580                    "{name}: val.{name}.as_ref().map(|v| v.iter().filter_map(|x| serde_json::to_value(x).ok()).collect())"
581                );
582            }
583            return format!("{name}: val.{name}.iter().filter_map(|x| serde_json::to_value(x).ok()).collect()");
584        }
585        if optional_vec_named {
586            return format!(
587                "{name}: val.{name}.as_ref().map(|v| v.iter().filter_map(|x| serde_json::to_value(x).ok()).collect())"
588            );
589        }
590    }
591
592    // Vec<Named>→String core→binding: binding holds JSON string, core has Vec<Named>.
593    // Only apply serde round-trip for Vec<Named> types (complex structs that can't cross FFI).
594    // Vec<String>, Vec<Primitive>, etc. stay as-is since they map directly.
595    if config.vec_named_to_string {
596        if let TypeRef::Vec(inner) = ty {
597            if matches!(inner.as_ref(), TypeRef::Named(_)) {
598                if optional {
599                    return format!("{name}: val.{name}.as_ref().and_then(|v| serde_json::to_string(v).ok())");
600                }
601                return format!("{name}: serde_json::to_string(&val.{name}).unwrap_or_default()");
602            }
603        }
604    }
605
606    // Map→String core→binding: binding holds Debug-formatted string, core has HashMap.
607    // Used by Rustler (Elixir NIFs) where HashMap cannot cross the NIF boundary directly.
608    if config.map_as_string && matches!(ty, TypeRef::Map(_, _)) {
609        if optional {
610            return format!("{name}: val.{name}.as_ref().map(|m| format!(\"{{m:?}}\"))");
611        }
612        return format!("{name}: format!(\"{{:?}}\", val.{name})");
613    }
614    if config.map_as_string {
615        if let TypeRef::Optional(inner) = ty {
616            if matches!(inner.as_ref(), TypeRef::Map(_, _)) {
617                return format!("{name}: val.{name}.as_ref().map(|m| format!(\"{{m:?}}\"))");
618            }
619        }
620    }
621
622    // WASM JsValue: use js_sys::JSON::parse for Map types (produces plain JS objects, not ES6
623    // Maps which serde_wasm_bindgen would produce for serialize_map calls). Use
624    // serde_wasm_bindgen for nested Vec types.
625    if config.map_uses_jsvalue {
626        let is_nested_vec = matches!(ty, TypeRef::Vec(inner) if matches!(inner.as_ref(), TypeRef::Vec(_)));
627        let is_map = matches!(ty, TypeRef::Map(_, _));
628        if is_map {
629            if optional {
630                return format!(
631                    "{name}: val.{name}.as_ref().and_then(|v| serde_json::to_string(v).ok()).and_then(|s| js_sys::JSON::parse(&s).ok())"
632                );
633            }
634            return format!(
635                "{name}: js_sys::JSON::parse(&serde_json::to_string(&val.{name}).unwrap_or_default()).unwrap_or(JsValue::NULL)"
636            );
637        }
638        if is_nested_vec {
639            if optional {
640                return format!("{name}: val.{name}.as_ref().and_then(|v| serde_wasm_bindgen::to_value(v).ok())");
641            }
642            return format!("{name}: serde_wasm_bindgen::to_value(&val.{name}).unwrap_or(JsValue::NULL)");
643        }
644        if let TypeRef::Optional(inner) = ty {
645            let is_inner_nested = matches!(inner.as_ref(), TypeRef::Vec(vi) if matches!(vi.as_ref(), TypeRef::Vec(_)));
646            let is_inner_map = matches!(inner.as_ref(), TypeRef::Map(_, _));
647            if is_inner_map {
648                return format!(
649                    "{name}: val.{name}.as_ref().and_then(|v| serde_json::to_string(v).ok()).and_then(|s| js_sys::JSON::parse(&s).ok())"
650                );
651            }
652            if is_inner_nested {
653                return format!("{name}: val.{name}.as_ref().and_then(|v| serde_wasm_bindgen::to_value(v).ok())");
654            }
655        }
656    }
657
658    let prefix = config.type_name_prefix;
659    let is_enum_string = |n: &str| -> bool { config.enum_string_names.as_ref().is_some_and(|names| names.contains(n)) };
660
661    match ty {
662        // i64 casting for large int primitives
663        TypeRef::Primitive(p) if config.cast_large_ints_to_i64 && needs_i64_cast(p) => {
664            let cast_to = binding_prim_str(p);
665            if optional {
666                format!("{name}: val.{name}.map(|v| v as {cast_to})")
667            } else {
668                format!("{name}: val.{name} as {cast_to}")
669            }
670        }
671        // Optional(large_int) with i64 casting
672        TypeRef::Optional(inner)
673            if config.cast_large_ints_to_i64
674                && matches!(inner.as_ref(), TypeRef::Primitive(p) if needs_i64_cast(p)) =>
675        {
676            if let TypeRef::Primitive(p) = inner.as_ref() {
677                let cast_to = binding_prim_str(p);
678                format!("{name}: val.{name}.map(|v| v as {cast_to})")
679            } else {
680                field_conversion_from_core(name, ty, optional, sanitized, opaque_types)
681            }
682        }
683        // i32 casting for small uint primitives (extendr/R only)
684        TypeRef::Primitive(p) if config.cast_uints_to_i32 && needs_i32_cast(p) => {
685            if optional {
686                format!("{name}: val.{name}.map(|v| v as i32)")
687            } else {
688                format!("{name}: val.{name} as i32")
689            }
690        }
691        // Optional(small_uint) with i32 casting
692        TypeRef::Optional(inner)
693            if config.cast_uints_to_i32 && matches!(inner.as_ref(), TypeRef::Primitive(p) if needs_i32_cast(p)) =>
694        {
695            format!("{name}: val.{name}.map(|v| v as i32)")
696        }
697        // Vec<u8/u16/u32/i8/i16> needs element-wise core→i32 casting (extendr/R only)
698        TypeRef::Vec(inner)
699            if config.cast_uints_to_i32 && matches!(inner.as_ref(), TypeRef::Primitive(p) if needs_i32_cast(p)) =>
700        {
701            if let TypeRef::Primitive(_p) = inner.as_ref() {
702                if optional {
703                    format!("{name}: val.{name}.as_ref().map(|v| v.iter().map(|&x| x as i32).collect())")
704                } else {
705                    format!("{name}: val.{name}.iter().map(|&v| v as i32).collect()")
706                }
707            } else {
708                field_conversion_from_core(name, ty, optional, sanitized, opaque_types)
709            }
710        }
711        // f64 casting for large int primitives (extendr/R only)
712        TypeRef::Primitive(p) if config.cast_large_ints_to_f64 && needs_f64_cast(p) => {
713            if optional {
714                format!("{name}: val.{name}.map(|v| v as f64)")
715            } else {
716                format!("{name}: val.{name} as f64")
717            }
718        }
719        // Optional(large_int) with f64 casting
720        TypeRef::Optional(inner)
721            if config.cast_large_ints_to_f64
722                && matches!(inner.as_ref(), TypeRef::Primitive(p) if needs_f64_cast(p)) =>
723        {
724            format!("{name}: val.{name}.map(|v| v as f64)")
725        }
726        // Vec<usize/u64/i64/isize/f32> needs element-wise f64 cast for extendr/R backend
727        TypeRef::Vec(inner)
728            if config.cast_large_ints_to_f64
729                && matches!(inner.as_ref(), TypeRef::Primitive(p) if needs_f64_cast(p)) =>
730        {
731            if optional {
732                format!("{name}: val.{name}.as_ref().map(|v| v.iter().map(|&x| x as f64).collect())")
733            } else {
734                format!("{name}: val.{name}.iter().map(|&v| v as f64).collect()")
735            }
736        }
737        // Optional(Vec(usize/u64/i64/isize/f32)) needs element-wise f64 cast
738        TypeRef::Optional(inner)
739            if config.cast_large_ints_to_f64
740                && matches!(inner.as_ref(), TypeRef::Vec(vi) if matches!(vi.as_ref(), TypeRef::Primitive(p) if needs_f64_cast(p))) =>
741        {
742            format!("{name}: val.{name}.as_ref().map(|v| v.iter().map(|&x| x as f64).collect())")
743        }
744        // Vec<Vec<usize/u64/i64/isize/f32>> needs nested element-wise f64 cast (embeddings)
745        TypeRef::Vec(outer)
746            if config.cast_large_ints_to_f64
747                && matches!(outer.as_ref(), TypeRef::Vec(inner) if matches!(inner.as_ref(), TypeRef::Primitive(p) if needs_f64_cast(p))) =>
748        {
749            if optional {
750                format!(
751                    "{name}: val.{name}.as_ref().map(|v| v.iter().map(|inner| inner.iter().map(|&x| x as f64).collect()).collect())"
752                )
753            } else {
754                format!("{name}: val.{name}.iter().map(|inner| inner.iter().map(|&x| x as f64).collect()).collect()")
755            }
756        }
757        // Optional(Vec<Vec<usize/u64/i64/isize/f32>>) needs nested element-wise f64 cast
758        TypeRef::Optional(inner)
759            if config.cast_large_ints_to_f64
760                && matches!(inner.as_ref(), TypeRef::Vec(outer) if matches!(outer.as_ref(), TypeRef::Vec(prim) if matches!(prim.as_ref(), TypeRef::Primitive(p) if needs_f64_cast(p)))) =>
761        {
762            format!(
763                "{name}: val.{name}.as_ref().map(|v| v.iter().map(|inner| inner.iter().map(|&x| x as f64).collect()).collect())"
764            )
765        }
766        // Map values that are usize/u64/i64/isize/f32 stored as f64 in binding → cast when reading core
767        TypeRef::Map(_k, v)
768            if config.cast_large_ints_to_f64 && matches!(v.as_ref(), TypeRef::Primitive(p) if needs_f64_cast(p)) =>
769        {
770            if optional {
771                format!("{name}: val.{name}.as_ref().map(|m| m.iter().map(|(k, v)| (k.clone(), *v as f64)).collect())")
772            } else {
773                format!("{name}: val.{name}.iter().map(|(k, v)| (k.clone(), *v as f64)).collect()")
774            }
775        }
776        // Duration with f64 casting (R: no u64, use f64 millis)
777        TypeRef::Duration if config.cast_large_ints_to_f64 => {
778            if optional {
779                format!("{name}: val.{name}.map(|d| d.as_millis() as f64)")
780            } else {
781                format!("{name}: val.{name}.as_millis() as f64")
782            }
783        }
784        // f32→f64 casting (NAPI only)
785        TypeRef::Primitive(PrimitiveType::F32) if config.cast_f32_to_f64 => {
786            if optional {
787                format!("{name}: val.{name}.map(|v| v as f64)")
788            } else {
789                format!("{name}: val.{name} as f64")
790            }
791        }
792        // Duration with i64 casting
793        TypeRef::Duration if config.cast_large_ints_to_i64 => {
794            if optional {
795                format!("{name}: val.{name}.map(|d| d.as_millis() as u64 as i64)")
796            } else {
797                format!("{name}: val.{name}.as_millis() as u64 as i64")
798            }
799        }
800        // Opaque Named types with prefix: wrap in Arc with prefixed binding name
801        TypeRef::Named(n) if opaque_types.contains(n.as_str()) && !prefix.is_empty() => {
802            let prefixed = format!("{prefix}{n}");
803            if optional {
804                format!("{name}: val.{name}.map(|v| {prefixed} {{ inner: Arc::new(v) }})")
805            } else {
806                format!("{name}: {prefixed} {{ inner: Arc::new(val.{name}) }}")
807            }
808        }
809        // Enum-to-String Named types (PHP pattern)
810        TypeRef::Named(n) if is_enum_string(n) => {
811            // Use serde serialization to get the correct serde(rename) value, not Debug format.
812            // serde_json::to_value gives Value::String("auto") which we extract.
813            if optional {
814                format!(
815                    "{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())"
816                )
817            } else {
818                format!(
819                    "{name}: serde_json::to_value(val.{name}).ok().and_then(|s| s.as_str().map(String::from)).unwrap_or_default()"
820                )
821            }
822        }
823        // Vec<Enum-to-String> Named types: element-wise serde serialization
824        TypeRef::Vec(inner) if matches!(inner.as_ref(), TypeRef::Named(n) if is_enum_string(n)) => {
825            if optional {
826                format!(
827                    "{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())"
828                )
829            } else {
830                format!(
831                    "{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()"
832                )
833            }
834        }
835        // Optional(Vec<Enum-to-String>) Named types (PHP pattern)
836        TypeRef::Optional(inner) if matches!(inner.as_ref(), TypeRef::Vec(vi) if matches!(vi.as_ref(), TypeRef::Named(n) if is_enum_string(n))) =>
837        {
838            format!(
839                "{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())"
840            )
841        }
842        // Vec<f32> needs element-wise cast to f64 when f32→f64 mapping is active
843        TypeRef::Vec(inner)
844            if config.cast_f32_to_f64 && matches!(inner.as_ref(), TypeRef::Primitive(PrimitiveType::F32)) =>
845        {
846            if optional {
847                format!("{name}: val.{name}.as_ref().map(|v| v.iter().map(|&x| x as f64).collect())")
848            } else {
849                format!("{name}: val.{name}.iter().map(|&v| v as f64).collect()")
850            }
851        }
852        // Optional(Vec(f32)) needs element-wise cast to f64
853        TypeRef::Optional(inner)
854            if config.cast_f32_to_f64
855                && matches!(inner.as_ref(), TypeRef::Vec(vi) if matches!(vi.as_ref(), TypeRef::Primitive(PrimitiveType::F32))) =>
856        {
857            format!("{name}: val.{name}.as_ref().map(|v| v.iter().map(|&x| x as f64).collect())")
858        }
859        // Optional(Vec(u64/usize/isize)) needs element-wise i64 casting
860        TypeRef::Optional(inner)
861            if config.cast_large_ints_to_i64
862                && matches!(inner.as_ref(), TypeRef::Vec(vi) if matches!(vi.as_ref(), TypeRef::Primitive(p) if needs_i64_cast(p))) =>
863        {
864            if let TypeRef::Vec(vi) = inner.as_ref() {
865                if let TypeRef::Primitive(p) = vi.as_ref() {
866                    let cast_to = binding_prim_str(p);
867                    if sanitized {
868                        // Sanitized from Option<(T, T)> → Option<Vec<T>>: destructure tuple
869                        format!("{name}: val.{name}.map(|(a, b)| vec![a as {cast_to}, b as {cast_to}])")
870                    } else {
871                        format!("{name}: val.{name}.as_ref().map(|v| v.iter().map(|&x| x as {cast_to}).collect())")
872                    }
873                } else {
874                    field_conversion_from_core(name, ty, optional, sanitized, opaque_types)
875                }
876            } else {
877                field_conversion_from_core(name, ty, optional, sanitized, opaque_types)
878            }
879        }
880        // Vec<Vec<f32>> needs nested element-wise cast to f64 (for embeddings, etc.)
881        TypeRef::Vec(outer)
882            if config.cast_f32_to_f64
883                && matches!(outer.as_ref(), TypeRef::Vec(inner) if matches!(inner.as_ref(), TypeRef::Primitive(PrimitiveType::F32))) =>
884        {
885            if optional {
886                format!(
887                    "{name}: val.{name}.as_ref().map(|v| v.iter().map(|inner| inner.iter().map(|&x| x as f64).collect()).collect())"
888                )
889            } else {
890                format!("{name}: val.{name}.iter().map(|inner| inner.iter().map(|&x| x as f64).collect()).collect()")
891            }
892        }
893        // Optional(Vec<Vec<f32>>) needs nested element-wise cast to f64
894        TypeRef::Optional(inner)
895            if config.cast_f32_to_f64
896                && matches!(inner.as_ref(), TypeRef::Vec(outer) if matches!(outer.as_ref(), TypeRef::Vec(prim) if matches!(prim.as_ref(), TypeRef::Primitive(PrimitiveType::F32)))) =>
897        {
898            format!(
899                "{name}: val.{name}.as_ref().map(|v| v.iter().map(|inner| inner.iter().map(|&x| x as f64).collect()).collect())"
900            )
901        }
902        // Optional with i64-cast inner
903        TypeRef::Optional(inner)
904            if config.cast_large_ints_to_i64
905                && matches!(inner.as_ref(), TypeRef::Primitive(p) if needs_i64_cast(p)) =>
906        {
907            if let TypeRef::Primitive(p) = inner.as_ref() {
908                let cast_to = binding_prim_str(p);
909                format!("{name}: val.{name}.map(|v| v as {cast_to})")
910            } else {
911                field_conversion_from_core(name, ty, optional, sanitized, opaque_types)
912            }
913        }
914        // HashMap value type casting: when value type needs i64 casting
915        TypeRef::Map(_k, v)
916            if config.cast_large_ints_to_i64 && matches!(v.as_ref(), TypeRef::Primitive(p) if needs_i64_cast(p)) =>
917        {
918            if let TypeRef::Primitive(p) = v.as_ref() {
919                let cast_to = binding_prim_str(p);
920                if optional {
921                    format!(
922                        "{name}: val.{name}.as_ref().map(|m| m.iter().map(|(k, v)| (k.clone(), *v as {cast_to})).collect())"
923                    )
924                } else {
925                    format!("{name}: val.{name}.iter().map(|(k, v)| (k.clone(), *v as {cast_to})).collect()")
926                }
927            } else {
928                field_conversion_from_core(name, ty, optional, sanitized, opaque_types)
929            }
930        }
931        // Vec<u64/usize/isize> needs element-wise i64 casting (core→binding)
932        TypeRef::Vec(inner)
933            if config.cast_large_ints_to_i64
934                && matches!(inner.as_ref(), TypeRef::Primitive(p) if needs_i64_cast(p)) =>
935        {
936            if let TypeRef::Primitive(p) = inner.as_ref() {
937                let cast_to = binding_prim_str(p);
938                if sanitized {
939                    // Sanitized from tuple (T, T) → Vec<T>: destructure tuple into vec
940                    if optional {
941                        format!("{name}: val.{name}.map(|(a, b)| vec![a as {cast_to}, b as {cast_to}])")
942                    } else {
943                        format!("{name}: {{ let (a, b) = val.{name}; vec![a as {cast_to}, b as {cast_to}] }}")
944                    }
945                } else if optional {
946                    format!("{name}: val.{name}.as_ref().map(|v| v.iter().map(|&x| x as {cast_to}).collect())")
947                } else {
948                    format!("{name}: val.{name}.iter().map(|&v| v as {cast_to}).collect()")
949                }
950            } else {
951                field_conversion_from_core(name, ty, optional, sanitized, opaque_types)
952            }
953        }
954        // Vec<Vec<u64/usize/isize>> needs nested element-wise i64 casting (core→binding)
955        TypeRef::Vec(outer)
956            if config.cast_large_ints_to_i64
957                && matches!(outer.as_ref(), TypeRef::Vec(inner) if matches!(inner.as_ref(), TypeRef::Primitive(p) if needs_i64_cast(p))) =>
958        {
959            if let TypeRef::Vec(inner) = outer.as_ref() {
960                if let TypeRef::Primitive(p) = inner.as_ref() {
961                    let cast_to = binding_prim_str(p);
962                    if optional {
963                        format!(
964                            "{name}: val.{name}.as_ref().map(|v| v.iter().map(|inner| inner.iter().map(|&x| x as {cast_to}).collect()).collect())"
965                        )
966                    } else {
967                        format!(
968                            "{name}: val.{name}.iter().map(|inner| inner.iter().map(|&x| x as {cast_to}).collect()).collect()"
969                        )
970                    }
971                } else {
972                    field_conversion_from_core(name, ty, optional, sanitized, opaque_types)
973                }
974            } else {
975                field_conversion_from_core(name, ty, optional, sanitized, opaque_types)
976            }
977        }
978        // Json→String: core uses serde_json::Value, binding uses String (PHP)
979        TypeRef::Json if config.json_to_string => {
980            if optional {
981                format!("{name}: val.{name}.as_ref().map(ToString::to_string)")
982            } else {
983                format!("{name}: val.{name}.to_string()")
984            }
985        }
986        // Json stays as serde_json::Value: identity passthrough.
987        TypeRef::Json if config.json_as_value => {
988            format!("{name}: val.{name}")
989        }
990        TypeRef::Optional(inner) if config.json_as_value && matches!(inner.as_ref(), TypeRef::Json) => {
991            format!("{name}: val.{name}")
992        }
993        TypeRef::Vec(inner) if config.json_as_value && matches!(inner.as_ref(), TypeRef::Json) => {
994            if optional {
995                format!("{name}: Some(val.{name})")
996            } else {
997                format!("{name}: val.{name}")
998            }
999        }
1000        TypeRef::Map(_k, v) if config.json_as_value && matches!(v.as_ref(), TypeRef::Json) => {
1001            if optional {
1002                format!("{name}: val.{name}.map(|m| m.into_iter().map(|(k, v)| (k.into(), v)).collect())")
1003            } else {
1004                format!("{name}: val.{name}.into_iter().map(|(k, v)| (k.into(), v)).collect()")
1005            }
1006        }
1007        // Json→JsValue: core uses serde_json::Value, binding uses JsValue (WASM)
1008        TypeRef::Json if config.map_uses_jsvalue => {
1009            if optional {
1010                format!("{name}: val.{name}.as_ref().and_then(|v| serde_wasm_bindgen::to_value(v).ok())")
1011            } else {
1012                format!("{name}: serde_wasm_bindgen::to_value(&val.{name}).unwrap_or(JsValue::NULL)")
1013            }
1014        }
1015        // Vec<Json>→JsValue: core uses Vec<serde_json::Value>, binding uses JsValue (WASM)
1016        TypeRef::Vec(inner) if config.map_uses_jsvalue && matches!(inner.as_ref(), TypeRef::Json) => {
1017            if optional {
1018                format!("{name}: val.{name}.as_ref().and_then(|v| serde_wasm_bindgen::to_value(v).ok())")
1019            } else {
1020                format!("{name}: serde_wasm_bindgen::to_value(&val.{name}).unwrap_or(JsValue::NULL)")
1021            }
1022        }
1023        // Optional(Vec<Json>)→JsValue (WASM)
1024        TypeRef::Optional(inner)
1025            if config.map_uses_jsvalue
1026                && matches!(inner.as_ref(), TypeRef::Vec(vi) if matches!(vi.as_ref(), TypeRef::Json)) =>
1027        {
1028            format!("{name}: val.{name}.as_ref().and_then(|v| serde_wasm_bindgen::to_value(v).ok())")
1029        }
1030        // Fall through to default (handles paths, opaque without prefix, etc.)
1031        _ => field_conversion_from_core(name, ty, optional, sanitized, opaque_types),
1032    }
1033}
1034
1035/// Apply CoreWrapper transformations for core→binding direction.
1036/// Unwraps Arc, converts Cow→String, Bytes→Vec<u8>.
1037fn apply_core_wrapper_from_core(
1038    conversion: &str,
1039    name: &str,
1040    core_wrapper: &CoreWrapper,
1041    vec_inner_core_wrapper: &CoreWrapper,
1042    optional: bool,
1043) -> String {
1044    // Handle Vec<Arc<T>>: unwrap Arc elements
1045    if *vec_inner_core_wrapper == CoreWrapper::Arc {
1046        return conversion
1047            .replace(".map(Into::into).collect()", ".map(|v| (*v).clone().into()).collect()")
1048            .replace(
1049                "map(|v| v.into_iter().map(Into::into)",
1050                "map(|v| v.into_iter().map(|v| (*v).clone().into())",
1051            );
1052    }
1053
1054    match core_wrapper {
1055        CoreWrapper::None => conversion.to_string(),
1056        CoreWrapper::Cow => {
1057            // Cow<str> → String: core val.name is Cow<'static, str>, binding needs String.
1058            // Always emit val.{name}.into_owned() regardless of what the base conversion emits.
1059            // This handles both the normal path (base = "name: val.name") and the sanitized path
1060            // (base = "name: format!(\"{:?}\", val.name)") which produces debug-escaped strings.
1061            // When the binding has been optionalized (e.g. NAPI default-optional fields), the
1062            // upstream pass already wrapped the conversion in Some(...) — preserve that wrap.
1063            let prefix = format!("{name}: ");
1064            let already_some_wrapped = conversion
1065                .strip_prefix(&prefix)
1066                .is_some_and(|expr| expr.starts_with("Some("));
1067            if optional {
1068                format!("{name}: val.{name}.as_ref().map(|v| v.to_string())")
1069            } else if already_some_wrapped {
1070                format!("{name}: Some(val.{name}.to_string())")
1071            } else {
1072                format!("{name}: val.{name}.to_string()")
1073            }
1074        }
1075        CoreWrapper::Arc => {
1076            // Arc<T> → T: unwrap via clone.
1077            //
1078            // Special case: opaque Named types build the binding wrapper with
1079            // `{ inner: Arc::new(v) }` in the base conversion, but when the core
1080            // field is `Arc<T>`, `v` IS already the `Arc<T>` — wrapping it again
1081            // with `Arc::new` produces `Arc<Arc<T>>`.  Detect this pattern and
1082            // replace `Arc::new(v)` with `v`, and `Arc::new(val.{name})` with
1083            // `val.{name}`, then return without adding an extra unwrap chain.
1084            if conversion.contains("{ inner: Arc::new(") {
1085                return conversion.replace("{ inner: Arc::new(v) }", "{ inner: v }").replace(
1086                    &format!("{{ inner: Arc::new(val.{name}) }}"),
1087                    &format!("{{ inner: val.{name} }}"),
1088                );
1089            }
1090            if let Some(expr) = conversion.strip_prefix(&format!("{name}: ")) {
1091                if optional {
1092                    // When the base conversion is the simple passthrough `val.{name}`,
1093                    // the Option carries Arc<T> elements; deref-clone each.
1094                    // When the base is already a complex expression (e.g.
1095                    // `val.{name}.as_ref().map(ToString::to_string)` for Json fields),
1096                    // the Arc is transparently handled via Display/Deref coercion;
1097                    // chaining another `.map(|v| (*v).clone().into())` would operate
1098                    // on the already-converted value (e.g. String) and emit invalid
1099                    // codegen such as `(*String).clone()` (since str: !Clone).
1100                    let simple_passthrough = format!("val.{name}");
1101                    if expr == simple_passthrough {
1102                        format!("{name}: {expr}.map(|v| (*v).clone().into())")
1103                    } else {
1104                        format!("{name}: {expr}")
1105                    }
1106                } else {
1107                    let unwrapped = expr.replace(&format!("val.{name}"), &format!("(*val.{name}).clone()"));
1108                    format!("{name}: {unwrapped}")
1109                }
1110            } else {
1111                conversion.to_string()
1112            }
1113        }
1114        CoreWrapper::Bytes => {
1115            // Bytes → Vec<u8> (or napi Buffer via From<Vec<u8>>): .to_vec().into()
1116            // The TypeRef::Bytes field_conversion already emits the correct expression
1117            // (`.to_vec().into()` non-optional, `.map(|v| v.to_vec().into())` optional).
1118            // Detect those forms and pass through unchanged to avoid double conversion.
1119            if let Some(expr) = conversion.strip_prefix(&format!("{name}: ")) {
1120                let already_converted_non_opt = expr == format!("val.{name}.to_vec().into()");
1121                let already_converted_opt = expr == format!("val.{name}.map(|v| v.to_vec().into())");
1122                if already_converted_non_opt || already_converted_opt {
1123                    conversion.to_string()
1124                } else if optional {
1125                    format!("{name}: {expr}.map(|v| v.to_vec().into())")
1126                } else if expr == format!("val.{name}") {
1127                    format!("{name}: val.{name}.to_vec().into()")
1128                } else {
1129                    conversion.to_string()
1130                }
1131            } else {
1132                conversion.to_string()
1133            }
1134        }
1135        CoreWrapper::ArcMutex => {
1136            // Arc<Mutex<T>> → T: lock and clone
1137            if let Some(expr) = conversion.strip_prefix(&format!("{name}: ")) {
1138                if optional {
1139                    format!("{name}: {expr}.map(|v| v.lock().unwrap().clone().into())")
1140                } else if expr == format!("val.{name}") {
1141                    format!("{name}: val.{name}.lock().unwrap().clone().into()")
1142                } else {
1143                    conversion.to_string()
1144                }
1145            } else {
1146                conversion.to_string()
1147            }
1148        }
1149    }
1150}