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