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, Named>: each value needs .into() to convert core→binding
404        TypeRef::Map(_k, v) if matches!(v.as_ref(), TypeRef::Named(_)) => {
405            if optional {
406                format!("{name}: val.{name}.map(|m| m.into_iter().map(|(k, v)| (k, v.into())).collect())")
407            } else {
408                format!("{name}: val.{name}.into_iter().map(|(k, v)| (k, v.into())).collect()")
409            }
410        }
411        // Optional(Map<K, Named>): same but wrapped in Option
412        TypeRef::Optional(inner) if matches!(inner.as_ref(), TypeRef::Map(_k, v) if matches!(v.as_ref(), TypeRef::Named(_))) =>
413        {
414            format!("{name}: val.{name}.map(|m| m.into_iter().map(|(k, v)| (k, v.into())).collect())")
415        }
416        // Vec<Named>: each element needs .into() to convert core→binding
417        TypeRef::Vec(inner) if matches!(inner.as_ref(), TypeRef::Named(_)) => {
418            if optional {
419                format!("{name}: val.{name}.map(|v| v.into_iter().map(Into::into).collect())")
420            } else {
421                format!("{name}: val.{name}.into_iter().map(Into::into).collect()")
422            }
423        }
424        // Optional(Vec<Named>): same but wrapped in Option
425        TypeRef::Optional(inner) if matches!(inner.as_ref(), TypeRef::Vec(vi) if matches!(vi.as_ref(), TypeRef::Named(_))) =>
426        {
427            format!("{name}: val.{name}.map(|v| v.into_iter().map(Into::into).collect())")
428        }
429        // Everything else is symmetric
430        _ => field_conversion_to_core(name, ty, optional),
431    }
432}
433
434/// Core→binding field conversion with backend-specific config.
435pub fn field_conversion_from_core_cfg(
436    name: &str,
437    ty: &TypeRef,
438    optional: bool,
439    sanitized: bool,
440    opaque_types: &AHashSet<String>,
441    config: &ConversionConfig,
442) -> String {
443    // Sanitized fields: for WASM (map_uses_jsvalue), Map and Vec<Json> fields target JsValue
444    // and need serde_wasm_bindgen::to_value() instead of iterator-based .collect().
445    // Note: Vec<String> sanitized does NOT use the JsValue path because Vec<String> maps to
446    // Vec<String> in WASM (not JsValue) — use the normal sanitized iterator path instead.
447    if sanitized {
448        if config.map_uses_jsvalue {
449            // Map(String, String) sanitized → JsValue (HashMap maps to JsValue in WASM)
450            // Use js_sys::JSON::parse(json_str) to get a plain JS object (not ES6 Map).
451            if let TypeRef::Map(k, v) = ty {
452                if matches!(k.as_ref(), TypeRef::String) && matches!(v.as_ref(), TypeRef::String) {
453                    if optional {
454                        return format!(
455                            "{name}: val.{name}.as_ref().and_then(|v| serde_json::to_string(v).ok()).and_then(|s| js_sys::JSON::parse(&s).ok())"
456                        );
457                    }
458                    return format!(
459                        "{name}: js_sys::JSON::parse(&serde_json::to_string(&val.{name}).unwrap_or_default()).unwrap_or(JsValue::NULL)"
460                    );
461                }
462            }
463            // Vec<Json> sanitized → JsValue (Vec<Json> maps to JsValue in WASM via nested-vec path)
464            if let TypeRef::Vec(inner) = ty {
465                if matches!(inner.as_ref(), TypeRef::Json) {
466                    if optional {
467                        return format!(
468                            "{name}: val.{name}.as_ref().and_then(|v| serde_wasm_bindgen::to_value(v).ok())"
469                        );
470                    }
471                    return format!("{name}: serde_wasm_bindgen::to_value(&val.{name}).unwrap_or(JsValue::NULL)");
472                }
473            }
474        }
475        return field_conversion_from_core(name, ty, optional, sanitized, opaque_types);
476    }
477
478    // Untagged data enum field (core holds the typed enum, binding holds serde_json::Value):
479    // serialize via serde_json::to_value.  Handles direct, Optional, and Vec wrappings.
480    if let Some(untagged_names) = config.untagged_data_enum_names {
481        let direct_named = matches!(ty, TypeRef::Named(n) if untagged_names.contains(n));
482        let optional_named = matches!(ty, TypeRef::Optional(inner)
483            if matches!(inner.as_ref(), TypeRef::Named(n) if untagged_names.contains(n)));
484        let vec_named = matches!(ty, TypeRef::Vec(inner)
485            if matches!(inner.as_ref(), TypeRef::Named(n) if untagged_names.contains(n)));
486        let optional_vec_named = matches!(ty, TypeRef::Optional(outer)
487            if matches!(outer.as_ref(), TypeRef::Vec(inner)
488                if matches!(inner.as_ref(), TypeRef::Named(n) if untagged_names.contains(n))));
489        if direct_named {
490            if optional {
491                return format!("{name}: val.{name}.as_ref().and_then(|v| serde_json::to_value(v).ok())");
492            }
493            return format!("{name}: serde_json::to_value(&val.{name}).unwrap_or(serde_json::Value::Null)");
494        }
495        if optional_named {
496            return format!("{name}: val.{name}.as_ref().and_then(|v| serde_json::to_value(v).ok())");
497        }
498        if vec_named {
499            if optional {
500                return format!(
501                    "{name}: val.{name}.as_ref().map(|v| v.iter().filter_map(|x| serde_json::to_value(x).ok()).collect())"
502                );
503            }
504            return format!("{name}: val.{name}.iter().filter_map(|x| serde_json::to_value(x).ok()).collect()");
505        }
506        if optional_vec_named {
507            return format!(
508                "{name}: val.{name}.as_ref().map(|v| v.iter().filter_map(|x| serde_json::to_value(x).ok()).collect())"
509            );
510        }
511    }
512
513    // Vec<Named>→String core→binding: binding holds JSON string, core has Vec<Named>.
514    // Only apply serde round-trip for Vec<Named> types (complex structs that can't cross FFI).
515    // Vec<String>, Vec<Primitive>, etc. stay as-is since they map directly.
516    if config.vec_named_to_string {
517        if let TypeRef::Vec(inner) = ty {
518            if matches!(inner.as_ref(), TypeRef::Named(_)) {
519                if optional {
520                    return format!("{name}: val.{name}.as_ref().and_then(|v| serde_json::to_string(v).ok())");
521                }
522                return format!("{name}: serde_json::to_string(&val.{name}).unwrap_or_default()");
523            }
524        }
525    }
526
527    // Map→String core→binding: binding holds Debug-formatted string, core has HashMap.
528    // Used by Rustler (Elixir NIFs) where HashMap cannot cross the NIF boundary directly.
529    if config.map_as_string && matches!(ty, TypeRef::Map(_, _)) {
530        if optional {
531            return format!("{name}: val.{name}.as_ref().map(|m| format!(\"{{m:?}}\"))");
532        }
533        return format!("{name}: format!(\"{{:?}}\", val.{name})");
534    }
535    if config.map_as_string {
536        if let TypeRef::Optional(inner) = ty {
537            if matches!(inner.as_ref(), TypeRef::Map(_, _)) {
538                return format!("{name}: val.{name}.as_ref().map(|m| format!(\"{{m:?}}\"))");
539            }
540        }
541    }
542
543    // WASM JsValue: use js_sys::JSON::parse for Map types (produces plain JS objects, not ES6
544    // Maps which serde_wasm_bindgen would produce for serialize_map calls). Use
545    // serde_wasm_bindgen for nested Vec types.
546    if config.map_uses_jsvalue {
547        let is_nested_vec = matches!(ty, TypeRef::Vec(inner) if matches!(inner.as_ref(), TypeRef::Vec(_)));
548        let is_map = matches!(ty, TypeRef::Map(_, _));
549        if is_map {
550            if optional {
551                return format!(
552                    "{name}: val.{name}.as_ref().and_then(|v| serde_json::to_string(v).ok()).and_then(|s| js_sys::JSON::parse(&s).ok())"
553                );
554            }
555            return format!(
556                "{name}: js_sys::JSON::parse(&serde_json::to_string(&val.{name}).unwrap_or_default()).unwrap_or(JsValue::NULL)"
557            );
558        }
559        if is_nested_vec {
560            if optional {
561                return format!("{name}: val.{name}.as_ref().and_then(|v| serde_wasm_bindgen::to_value(v).ok())");
562            }
563            return format!("{name}: serde_wasm_bindgen::to_value(&val.{name}).unwrap_or(JsValue::NULL)");
564        }
565        if let TypeRef::Optional(inner) = ty {
566            let is_inner_nested = matches!(inner.as_ref(), TypeRef::Vec(vi) if matches!(vi.as_ref(), TypeRef::Vec(_)));
567            let is_inner_map = matches!(inner.as_ref(), TypeRef::Map(_, _));
568            if is_inner_map {
569                return format!(
570                    "{name}: val.{name}.as_ref().and_then(|v| serde_json::to_string(v).ok()).and_then(|s| js_sys::JSON::parse(&s).ok())"
571                );
572            }
573            if is_inner_nested {
574                return format!("{name}: val.{name}.as_ref().and_then(|v| serde_wasm_bindgen::to_value(v).ok())");
575            }
576        }
577    }
578
579    let prefix = config.type_name_prefix;
580    let is_enum_string = |n: &str| -> bool { config.enum_string_names.as_ref().is_some_and(|names| names.contains(n)) };
581
582    match ty {
583        // i64 casting for large int primitives
584        TypeRef::Primitive(p) if config.cast_large_ints_to_i64 && needs_i64_cast(p) => {
585            let cast_to = binding_prim_str(p);
586            if optional {
587                format!("{name}: val.{name}.map(|v| v as {cast_to})")
588            } else {
589                format!("{name}: val.{name} as {cast_to}")
590            }
591        }
592        // Optional(large_int) with i64 casting
593        TypeRef::Optional(inner)
594            if config.cast_large_ints_to_i64
595                && matches!(inner.as_ref(), TypeRef::Primitive(p) if needs_i64_cast(p)) =>
596        {
597            if let TypeRef::Primitive(p) = inner.as_ref() {
598                let cast_to = binding_prim_str(p);
599                format!("{name}: val.{name}.map(|v| v as {cast_to})")
600            } else {
601                field_conversion_from_core(name, ty, optional, sanitized, opaque_types)
602            }
603        }
604        // i32 casting for small uint primitives (extendr/R only)
605        TypeRef::Primitive(p) if config.cast_uints_to_i32 && needs_i32_cast(p) => {
606            if optional {
607                format!("{name}: val.{name}.map(|v| v as i32)")
608            } else {
609                format!("{name}: val.{name} as i32")
610            }
611        }
612        // Optional(small_uint) with i32 casting
613        TypeRef::Optional(inner)
614            if config.cast_uints_to_i32 && matches!(inner.as_ref(), TypeRef::Primitive(p) if needs_i32_cast(p)) =>
615        {
616            format!("{name}: val.{name}.map(|v| v as i32)")
617        }
618        // Vec<u8/u16/u32/i8/i16> needs element-wise core→i32 casting (extendr/R only)
619        TypeRef::Vec(inner)
620            if config.cast_uints_to_i32 && matches!(inner.as_ref(), TypeRef::Primitive(p) if needs_i32_cast(p)) =>
621        {
622            if let TypeRef::Primitive(_p) = inner.as_ref() {
623                if optional {
624                    format!("{name}: val.{name}.as_ref().map(|v| v.iter().map(|&x| x as i32).collect())")
625                } else {
626                    format!("{name}: val.{name}.iter().map(|&v| v as i32).collect()")
627                }
628            } else {
629                field_conversion_from_core(name, ty, optional, sanitized, opaque_types)
630            }
631        }
632        // f64 casting for large int primitives (extendr/R only)
633        TypeRef::Primitive(p) if config.cast_large_ints_to_f64 && needs_f64_cast(p) => {
634            if optional {
635                format!("{name}: val.{name}.map(|v| v as f64)")
636            } else {
637                format!("{name}: val.{name} as f64")
638            }
639        }
640        // Optional(large_int) with f64 casting
641        TypeRef::Optional(inner)
642            if config.cast_large_ints_to_f64
643                && matches!(inner.as_ref(), TypeRef::Primitive(p) if needs_f64_cast(p)) =>
644        {
645            format!("{name}: val.{name}.map(|v| v as f64)")
646        }
647        // Vec<usize/u64/i64/isize/f32> needs element-wise f64 cast for extendr/R backend
648        TypeRef::Vec(inner)
649            if config.cast_large_ints_to_f64
650                && matches!(inner.as_ref(), TypeRef::Primitive(p) if needs_f64_cast(p)) =>
651        {
652            if optional {
653                format!("{name}: val.{name}.as_ref().map(|v| v.iter().map(|&x| x as f64).collect())")
654            } else {
655                format!("{name}: val.{name}.iter().map(|&v| v as f64).collect()")
656            }
657        }
658        // Optional(Vec(usize/u64/i64/isize/f32)) needs element-wise f64 cast
659        TypeRef::Optional(inner)
660            if config.cast_large_ints_to_f64
661                && matches!(inner.as_ref(), TypeRef::Vec(vi) if matches!(vi.as_ref(), TypeRef::Primitive(p) if needs_f64_cast(p))) =>
662        {
663            format!("{name}: val.{name}.as_ref().map(|v| v.iter().map(|&x| x as f64).collect())")
664        }
665        // Vec<Vec<usize/u64/i64/isize/f32>> needs nested element-wise f64 cast (embeddings)
666        TypeRef::Vec(outer)
667            if config.cast_large_ints_to_f64
668                && matches!(outer.as_ref(), TypeRef::Vec(inner) if matches!(inner.as_ref(), TypeRef::Primitive(p) if needs_f64_cast(p))) =>
669        {
670            if optional {
671                format!(
672                    "{name}: val.{name}.as_ref().map(|v| v.iter().map(|inner| inner.iter().map(|&x| x as f64).collect()).collect())"
673                )
674            } else {
675                format!("{name}: val.{name}.iter().map(|inner| inner.iter().map(|&x| x as f64).collect()).collect()")
676            }
677        }
678        // Optional(Vec<Vec<usize/u64/i64/isize/f32>>) needs nested element-wise f64 cast
679        TypeRef::Optional(inner)
680            if config.cast_large_ints_to_f64
681                && 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)))) =>
682        {
683            format!(
684                "{name}: val.{name}.as_ref().map(|v| v.iter().map(|inner| inner.iter().map(|&x| x as f64).collect()).collect())"
685            )
686        }
687        // Map values that are usize/u64/i64/isize/f32 stored as f64 in binding → cast when reading core
688        TypeRef::Map(_k, v)
689            if config.cast_large_ints_to_f64 && matches!(v.as_ref(), TypeRef::Primitive(p) if needs_f64_cast(p)) =>
690        {
691            if optional {
692                format!("{name}: val.{name}.as_ref().map(|m| m.iter().map(|(k, v)| (k.clone(), *v as f64)).collect())")
693            } else {
694                format!("{name}: val.{name}.iter().map(|(k, v)| (k.clone(), *v as f64)).collect()")
695            }
696        }
697        // Duration with f64 casting (R: no u64, use f64 millis)
698        TypeRef::Duration if config.cast_large_ints_to_f64 => {
699            if optional {
700                format!("{name}: val.{name}.map(|d| d.as_millis() as f64)")
701            } else {
702                format!("{name}: val.{name}.as_millis() as f64")
703            }
704        }
705        // f32→f64 casting (NAPI only)
706        TypeRef::Primitive(PrimitiveType::F32) if config.cast_f32_to_f64 => {
707            if optional {
708                format!("{name}: val.{name}.map(|v| v as f64)")
709            } else {
710                format!("{name}: val.{name} as f64")
711            }
712        }
713        // Duration with i64 casting
714        TypeRef::Duration if config.cast_large_ints_to_i64 => {
715            if optional {
716                format!("{name}: val.{name}.map(|d| d.as_millis() as u64 as i64)")
717            } else {
718                format!("{name}: val.{name}.as_millis() as u64 as i64")
719            }
720        }
721        // Opaque Named types with prefix: wrap in Arc with prefixed binding name
722        TypeRef::Named(n) if opaque_types.contains(n.as_str()) && !prefix.is_empty() => {
723            let prefixed = format!("{prefix}{n}");
724            if optional {
725                format!("{name}: val.{name}.map(|v| {prefixed} {{ inner: Arc::new(v) }})")
726            } else {
727                format!("{name}: {prefixed} {{ inner: Arc::new(val.{name}) }}")
728            }
729        }
730        // Enum-to-String Named types (PHP pattern)
731        TypeRef::Named(n) if is_enum_string(n) => {
732            // Use serde serialization to get the correct serde(rename) value, not Debug format.
733            // serde_json::to_value gives Value::String("auto") which we extract.
734            if optional {
735                format!(
736                    "{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())"
737                )
738            } else {
739                format!(
740                    "{name}: serde_json::to_value(val.{name}).ok().and_then(|s| s.as_str().map(String::from)).unwrap_or_default()"
741                )
742            }
743        }
744        // Vec<Enum-to-String> Named types: element-wise serde serialization
745        TypeRef::Vec(inner) if matches!(inner.as_ref(), TypeRef::Named(n) if is_enum_string(n)) => {
746            if optional {
747                format!(
748                    "{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())"
749                )
750            } else {
751                format!(
752                    "{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()"
753                )
754            }
755        }
756        // Optional(Vec<Enum-to-String>) Named types (PHP pattern)
757        TypeRef::Optional(inner) if matches!(inner.as_ref(), TypeRef::Vec(vi) if matches!(vi.as_ref(), TypeRef::Named(n) if is_enum_string(n))) =>
758        {
759            format!(
760                "{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())"
761            )
762        }
763        // Vec<f32> needs element-wise cast to f64 when f32→f64 mapping is active
764        TypeRef::Vec(inner)
765            if config.cast_f32_to_f64 && matches!(inner.as_ref(), TypeRef::Primitive(PrimitiveType::F32)) =>
766        {
767            if optional {
768                format!("{name}: val.{name}.as_ref().map(|v| v.iter().map(|&x| x as f64).collect())")
769            } else {
770                format!("{name}: val.{name}.iter().map(|&v| v as f64).collect()")
771            }
772        }
773        // Optional(Vec(f32)) needs element-wise cast to f64
774        TypeRef::Optional(inner)
775            if config.cast_f32_to_f64
776                && matches!(inner.as_ref(), TypeRef::Vec(vi) if matches!(vi.as_ref(), TypeRef::Primitive(PrimitiveType::F32))) =>
777        {
778            format!("{name}: val.{name}.as_ref().map(|v| v.iter().map(|&x| x as f64).collect())")
779        }
780        // Optional(Vec(u64/usize/isize)) needs element-wise i64 casting
781        TypeRef::Optional(inner)
782            if config.cast_large_ints_to_i64
783                && matches!(inner.as_ref(), TypeRef::Vec(vi) if matches!(vi.as_ref(), TypeRef::Primitive(p) if needs_i64_cast(p))) =>
784        {
785            if let TypeRef::Vec(vi) = inner.as_ref() {
786                if let TypeRef::Primitive(p) = vi.as_ref() {
787                    let cast_to = binding_prim_str(p);
788                    if sanitized {
789                        // Sanitized from Option<(T, T)> → Option<Vec<T>>: destructure tuple
790                        format!("{name}: val.{name}.map(|(a, b)| vec![a as {cast_to}, b as {cast_to}])")
791                    } else {
792                        format!("{name}: val.{name}.as_ref().map(|v| v.iter().map(|&x| x as {cast_to}).collect())")
793                    }
794                } else {
795                    field_conversion_from_core(name, ty, optional, sanitized, opaque_types)
796                }
797            } else {
798                field_conversion_from_core(name, ty, optional, sanitized, opaque_types)
799            }
800        }
801        // Vec<Vec<f32>> needs nested element-wise cast to f64 (for embeddings, etc.)
802        TypeRef::Vec(outer)
803            if config.cast_f32_to_f64
804                && matches!(outer.as_ref(), TypeRef::Vec(inner) if matches!(inner.as_ref(), TypeRef::Primitive(PrimitiveType::F32))) =>
805        {
806            if optional {
807                format!(
808                    "{name}: val.{name}.as_ref().map(|v| v.iter().map(|inner| inner.iter().map(|&x| x as f64).collect()).collect())"
809                )
810            } else {
811                format!("{name}: val.{name}.iter().map(|inner| inner.iter().map(|&x| x as f64).collect()).collect()")
812            }
813        }
814        // Optional(Vec<Vec<f32>>) needs nested element-wise cast to f64
815        TypeRef::Optional(inner)
816            if config.cast_f32_to_f64
817                && matches!(inner.as_ref(), TypeRef::Vec(outer) if matches!(outer.as_ref(), TypeRef::Vec(prim) if matches!(prim.as_ref(), TypeRef::Primitive(PrimitiveType::F32)))) =>
818        {
819            format!(
820                "{name}: val.{name}.as_ref().map(|v| v.iter().map(|inner| inner.iter().map(|&x| x as f64).collect()).collect())"
821            )
822        }
823        // Optional with i64-cast inner
824        TypeRef::Optional(inner)
825            if config.cast_large_ints_to_i64
826                && matches!(inner.as_ref(), TypeRef::Primitive(p) if needs_i64_cast(p)) =>
827        {
828            if let TypeRef::Primitive(p) = inner.as_ref() {
829                let cast_to = binding_prim_str(p);
830                format!("{name}: val.{name}.map(|v| v as {cast_to})")
831            } else {
832                field_conversion_from_core(name, ty, optional, sanitized, opaque_types)
833            }
834        }
835        // HashMap value type casting: when value type needs i64 casting
836        TypeRef::Map(_k, v)
837            if config.cast_large_ints_to_i64 && matches!(v.as_ref(), TypeRef::Primitive(p) if needs_i64_cast(p)) =>
838        {
839            if let TypeRef::Primitive(p) = v.as_ref() {
840                let cast_to = binding_prim_str(p);
841                if optional {
842                    format!(
843                        "{name}: val.{name}.as_ref().map(|m| m.iter().map(|(k, v)| (k.clone(), *v as {cast_to})).collect())"
844                    )
845                } else {
846                    format!("{name}: val.{name}.iter().map(|(k, v)| (k.clone(), *v as {cast_to})).collect()")
847                }
848            } else {
849                field_conversion_from_core(name, ty, optional, sanitized, opaque_types)
850            }
851        }
852        // Vec<u64/usize/isize> needs element-wise i64 casting (core→binding)
853        TypeRef::Vec(inner)
854            if config.cast_large_ints_to_i64
855                && matches!(inner.as_ref(), TypeRef::Primitive(p) if needs_i64_cast(p)) =>
856        {
857            if let TypeRef::Primitive(p) = inner.as_ref() {
858                let cast_to = binding_prim_str(p);
859                if sanitized {
860                    // Sanitized from tuple (T, T) → Vec<T>: destructure tuple into vec
861                    if optional {
862                        format!("{name}: val.{name}.map(|(a, b)| vec![a as {cast_to}, b as {cast_to}])")
863                    } else {
864                        format!("{name}: {{ let (a, b) = val.{name}; vec![a as {cast_to}, b as {cast_to}] }}")
865                    }
866                } else if optional {
867                    format!("{name}: val.{name}.as_ref().map(|v| v.iter().map(|&x| x as {cast_to}).collect())")
868                } else {
869                    format!("{name}: val.{name}.iter().map(|&v| v as {cast_to}).collect()")
870                }
871            } else {
872                field_conversion_from_core(name, ty, optional, sanitized, opaque_types)
873            }
874        }
875        // Vec<Vec<u64/usize/isize>> needs nested element-wise i64 casting (core→binding)
876        TypeRef::Vec(outer)
877            if config.cast_large_ints_to_i64
878                && matches!(outer.as_ref(), TypeRef::Vec(inner) if matches!(inner.as_ref(), TypeRef::Primitive(p) if needs_i64_cast(p))) =>
879        {
880            if let TypeRef::Vec(inner) = outer.as_ref() {
881                if let TypeRef::Primitive(p) = inner.as_ref() {
882                    let cast_to = binding_prim_str(p);
883                    if optional {
884                        format!(
885                            "{name}: val.{name}.as_ref().map(|v| v.iter().map(|inner| inner.iter().map(|&x| x as {cast_to}).collect()).collect())"
886                        )
887                    } else {
888                        format!(
889                            "{name}: val.{name}.iter().map(|inner| inner.iter().map(|&x| x as {cast_to}).collect()).collect()"
890                        )
891                    }
892                } else {
893                    field_conversion_from_core(name, ty, optional, sanitized, opaque_types)
894                }
895            } else {
896                field_conversion_from_core(name, ty, optional, sanitized, opaque_types)
897            }
898        }
899        // Json→String: core uses serde_json::Value, binding uses String (PHP)
900        TypeRef::Json if config.json_to_string => {
901            if optional {
902                format!("{name}: val.{name}.as_ref().map(ToString::to_string)")
903            } else {
904                format!("{name}: val.{name}.to_string()")
905            }
906        }
907        // Json stays as serde_json::Value: identity passthrough.
908        TypeRef::Json if config.json_as_value => {
909            format!("{name}: val.{name}")
910        }
911        TypeRef::Optional(inner) if config.json_as_value && matches!(inner.as_ref(), TypeRef::Json) => {
912            format!("{name}: val.{name}")
913        }
914        TypeRef::Vec(inner) if config.json_as_value && matches!(inner.as_ref(), TypeRef::Json) => {
915            if optional {
916                format!("{name}: Some(val.{name})")
917            } else {
918                format!("{name}: val.{name}")
919            }
920        }
921        TypeRef::Map(_k, v) if config.json_as_value && matches!(v.as_ref(), TypeRef::Json) => {
922            if optional {
923                format!("{name}: val.{name}.map(|m| m.into_iter().map(|(k, v)| (k.into(), v)).collect())")
924            } else {
925                format!("{name}: val.{name}.into_iter().map(|(k, v)| (k.into(), v)).collect()")
926            }
927        }
928        // Json→JsValue: core uses serde_json::Value, binding uses JsValue (WASM)
929        TypeRef::Json if config.map_uses_jsvalue => {
930            if optional {
931                format!("{name}: val.{name}.as_ref().and_then(|v| serde_wasm_bindgen::to_value(v).ok())")
932            } else {
933                format!("{name}: serde_wasm_bindgen::to_value(&val.{name}).unwrap_or(JsValue::NULL)")
934            }
935        }
936        // Vec<Json>→JsValue: core uses Vec<serde_json::Value>, binding uses JsValue (WASM)
937        TypeRef::Vec(inner) if config.map_uses_jsvalue && matches!(inner.as_ref(), TypeRef::Json) => {
938            if optional {
939                format!("{name}: val.{name}.as_ref().and_then(|v| serde_wasm_bindgen::to_value(v).ok())")
940            } else {
941                format!("{name}: serde_wasm_bindgen::to_value(&val.{name}).unwrap_or(JsValue::NULL)")
942            }
943        }
944        // Optional(Vec<Json>)→JsValue (WASM)
945        TypeRef::Optional(inner)
946            if config.map_uses_jsvalue
947                && matches!(inner.as_ref(), TypeRef::Vec(vi) if matches!(vi.as_ref(), TypeRef::Json)) =>
948        {
949            format!("{name}: val.{name}.as_ref().and_then(|v| serde_wasm_bindgen::to_value(v).ok())")
950        }
951        // Fall through to default (handles paths, opaque without prefix, etc.)
952        _ => field_conversion_from_core(name, ty, optional, sanitized, opaque_types),
953    }
954}
955
956/// Apply CoreWrapper transformations for core→binding direction.
957/// Unwraps Arc, converts Cow→String, Bytes→Vec<u8>.
958fn apply_core_wrapper_from_core(
959    conversion: &str,
960    name: &str,
961    core_wrapper: &CoreWrapper,
962    vec_inner_core_wrapper: &CoreWrapper,
963    optional: bool,
964) -> String {
965    // Handle Vec<Arc<T>>: unwrap Arc elements
966    if *vec_inner_core_wrapper == CoreWrapper::Arc {
967        return conversion
968            .replace(".map(Into::into).collect()", ".map(|v| (*v).clone().into()).collect()")
969            .replace(
970                "map(|v| v.into_iter().map(Into::into)",
971                "map(|v| v.into_iter().map(|v| (*v).clone().into())",
972            );
973    }
974
975    match core_wrapper {
976        CoreWrapper::None => conversion.to_string(),
977        CoreWrapper::Cow => {
978            // Cow<str> → String: core val.name is Cow<'static, str>, binding needs String.
979            // Always emit val.{name}.into_owned() regardless of what the base conversion emits.
980            // This handles both the normal path (base = "name: val.name") and the sanitized path
981            // (base = "name: format!(\"{:?}\", val.name)") which produces debug-escaped strings.
982            // When the binding has been optionalized (e.g. NAPI default-optional fields), the
983            // upstream pass already wrapped the conversion in Some(...) — preserve that wrap.
984            let prefix = format!("{name}: ");
985            let already_some_wrapped = conversion
986                .strip_prefix(&prefix)
987                .is_some_and(|expr| expr.starts_with("Some("));
988            if optional {
989                format!("{name}: val.{name}.as_ref().map(|v| v.to_string())")
990            } else if already_some_wrapped {
991                format!("{name}: Some(val.{name}.to_string())")
992            } else {
993                format!("{name}: val.{name}.to_string()")
994            }
995        }
996        CoreWrapper::Arc => {
997            // Arc<T> → T: unwrap via clone.
998            //
999            // Special case: opaque Named types build the binding wrapper with
1000            // `{ inner: Arc::new(v) }` in the base conversion, but when the core
1001            // field is `Arc<T>`, `v` IS already the `Arc<T>` — wrapping it again
1002            // with `Arc::new` produces `Arc<Arc<T>>`.  Detect this pattern and
1003            // replace `Arc::new(v)` with `v`, and `Arc::new(val.{name})` with
1004            // `val.{name}`, then return without adding an extra unwrap chain.
1005            if conversion.contains("{ inner: Arc::new(") {
1006                return conversion.replace("{ inner: Arc::new(v) }", "{ inner: v }").replace(
1007                    &format!("{{ inner: Arc::new(val.{name}) }}"),
1008                    &format!("{{ inner: val.{name} }}"),
1009                );
1010            }
1011            if let Some(expr) = conversion.strip_prefix(&format!("{name}: ")) {
1012                if optional {
1013                    // When the base conversion is the simple passthrough `val.{name}`,
1014                    // the Option carries Arc<T> elements; deref-clone each.
1015                    // When the base is already a complex expression (e.g.
1016                    // `val.{name}.as_ref().map(ToString::to_string)` for Json fields),
1017                    // the Arc is transparently handled via Display/Deref coercion;
1018                    // chaining another `.map(|v| (*v).clone().into())` would operate
1019                    // on the already-converted value (e.g. String) and emit invalid
1020                    // codegen such as `(*String).clone()` (since str: !Clone).
1021                    let simple_passthrough = format!("val.{name}");
1022                    if expr == simple_passthrough {
1023                        format!("{name}: {expr}.map(|v| (*v).clone().into())")
1024                    } else {
1025                        format!("{name}: {expr}")
1026                    }
1027                } else {
1028                    let unwrapped = expr.replace(&format!("val.{name}"), &format!("(*val.{name}).clone()"));
1029                    format!("{name}: {unwrapped}")
1030                }
1031            } else {
1032                conversion.to_string()
1033            }
1034        }
1035        CoreWrapper::Bytes => {
1036            // Bytes → Vec<u8> (or napi Buffer via From<Vec<u8>>): .to_vec().into()
1037            // The TypeRef::Bytes field_conversion already emits the correct expression
1038            // (`.to_vec().into()` non-optional, `.map(|v| v.to_vec().into())` optional).
1039            // Detect those forms and pass through unchanged to avoid double conversion.
1040            if let Some(expr) = conversion.strip_prefix(&format!("{name}: ")) {
1041                let already_converted_non_opt = expr == format!("val.{name}.to_vec().into()");
1042                let already_converted_opt = expr == format!("val.{name}.map(|v| v.to_vec().into())");
1043                if already_converted_non_opt || already_converted_opt {
1044                    conversion.to_string()
1045                } else if optional {
1046                    format!("{name}: {expr}.map(|v| v.to_vec().into())")
1047                } else if expr == format!("val.{name}") {
1048                    format!("{name}: val.{name}.to_vec().into()")
1049                } else {
1050                    conversion.to_string()
1051                }
1052            } else {
1053                conversion.to_string()
1054            }
1055        }
1056        CoreWrapper::ArcMutex => {
1057            // Arc<Mutex<T>> → T: lock and clone
1058            if let Some(expr) = conversion.strip_prefix(&format!("{name}: ")) {
1059                if optional {
1060                    format!("{name}: {expr}.map(|v| v.lock().unwrap().clone().into())")
1061                } else if expr == format!("val.{name}") {
1062                    format!("{name}: val.{name}.lock().unwrap().clone().into()")
1063                } else {
1064                    conversion.to_string()
1065                }
1066            } else {
1067                conversion.to_string()
1068            }
1069        }
1070    }
1071}