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