Skip to main content

alef_codegen/conversions/
binding_to_core.rs

1use alef_core::ir::{CoreWrapper, PrimitiveType, TypeDef, TypeRef};
2use std::fmt::Write;
3
4use super::ConversionConfig;
5use super::helpers::{core_prim_str, core_type_path, is_newtype, is_tuple_type_name, needs_i64_cast};
6
7/// Generate `impl From<BindingType> for core::Type` (binding -> core).
8/// Sanitized fields use `Default::default()` (lossy but functional).
9pub fn gen_from_binding_to_core(typ: &TypeDef, core_import: &str) -> String {
10    gen_from_binding_to_core_cfg(typ, core_import, &ConversionConfig::default())
11}
12
13/// Generate `impl From<BindingType> for core::Type` with backend-specific config.
14pub fn gen_from_binding_to_core_cfg(typ: &TypeDef, core_import: &str, config: &ConversionConfig) -> String {
15    let core_path = core_type_path(typ, core_import);
16    let binding_name = format!("{}{}", config.type_name_prefix, typ.name);
17    let mut out = String::with_capacity(256);
18    // When cfg-gated fields exist, ..Default::default() fills them when the feature is enabled.
19    // When disabled, all fields are already specified and the update has no effect — suppress lint.
20    if typ.has_stripped_cfg_fields {
21        writeln!(out, "#[allow(clippy::needless_update)]").ok();
22    }
23    // Suppress clippy when we use the builder pattern (Default + field reassignment)
24    let uses_builder_pattern = config.option_duration_on_defaults
25        && typ.has_default
26        && typ
27            .fields
28            .iter()
29            .any(|f| !f.optional && matches!(f.ty, TypeRef::Duration));
30    if uses_builder_pattern {
31        writeln!(out, "#[allow(clippy::field_reassign_with_default)]").ok();
32    }
33    writeln!(out, "impl From<{binding_name}> for {core_path} {{").ok();
34    writeln!(out, "    fn from(val: {binding_name}) -> Self {{").ok();
35
36    // Newtype structs: generate tuple constructor Self(val._0)
37    if is_newtype(typ) {
38        let field = &typ.fields[0];
39        let inner_expr = match &field.ty {
40            TypeRef::Named(_) => "val._0.into()".to_string(),
41            TypeRef::Path => "val._0.into()".to_string(),
42            TypeRef::Duration => "std::time::Duration::from_millis(val._0)".to_string(),
43            _ => "val._0".to_string(),
44        };
45        writeln!(out, "        Self({inner_expr})").ok();
46        writeln!(out, "    }}").ok();
47        write!(out, "}}").ok();
48        return out;
49    }
50
51    // When option_duration_on_defaults is set for a has_default type, non-optional Duration
52    // fields are stored as Option<u64> in the binding struct.  We use the builder pattern
53    // so that None falls back to the core type's Default (giving the real field default,
54    // e.g. Duration::from_millis(30000)) rather than Duration::ZERO.
55    let has_optionalized_duration = config.option_duration_on_defaults
56        && typ.has_default
57        && typ
58            .fields
59            .iter()
60            .any(|f| !f.optional && matches!(f.ty, TypeRef::Duration));
61
62    if has_optionalized_duration {
63        // Builder pattern: start from core default, override explicitly-set fields.
64        writeln!(out, "        let mut __result = {core_path}::default();").ok();
65        let optionalized = config.optionalize_defaults && typ.has_default;
66        for field in &typ.fields {
67            // Skip cfg-gated fields — they don't exist in the binding struct.
68            if field.cfg.is_some() {
69                continue;
70            }
71            if field.sanitized {
72                // sanitized fields keep the default value — skip
73                continue;
74            }
75            // Fields referencing excluded types keep their default value — skip
76            if !config.exclude_types.is_empty()
77                && super::helpers::field_references_excluded_type(&field.ty, config.exclude_types)
78            {
79                continue;
80            }
81            // Duration field stored as Option<u64/i64>: only override when Some
82            if !field.optional && matches!(field.ty, TypeRef::Duration) {
83                let cast = if config.cast_large_ints_to_i64 { " as u64" } else { "" };
84                writeln!(
85                    out,
86                    "        if let Some(__v) = val.{} {{ __result.{} = std::time::Duration::from_millis(__v{cast}); }}",
87                    field.name, field.name
88                )
89                .ok();
90                continue;
91            }
92            let conversion = if optionalized && !field.optional {
93                gen_optionalized_field_to_core(&field.name, &field.ty, config)
94            } else {
95                field_conversion_to_core_cfg(&field.name, &field.ty, field.optional, config)
96            };
97            // Strip the "name: " prefix to get just the expression, then assign
98            if let Some(expr) = conversion.strip_prefix(&format!("{}: ", field.name)) {
99                writeln!(out, "        __result.{} = {};", field.name, expr).ok();
100            }
101        }
102        writeln!(out, "        __result").ok();
103        writeln!(out, "    }}").ok();
104        write!(out, "}}").ok();
105        return out;
106    }
107
108    writeln!(out, "        Self {{").ok();
109    let optionalized = config.optionalize_defaults && typ.has_default;
110    for field in &typ.fields {
111        // Skip cfg-gated fields — they don't exist in the binding struct.
112        // When the binding is compiled, these fields are absent, and accessing them would fail.
113        // The ..Default::default() at the end fills in these fields when the core type is compiled
114        // with the required feature enabled.
115        if field.cfg.is_some() {
116            continue;
117        }
118        // Fields referencing excluded types don't exist in the binding struct.
119        // When the type has stripped cfg-gated fields, these fields may also be
120        // cfg-gated and absent from the core struct — skip them entirely and let
121        // ..Default::default() fill them in.
122        // Otherwise, use Default::default() to fill them in the core type.
123        // Sanitized fields also use Default::default() (lossy but functional).
124        let references_excluded = !config.exclude_types.is_empty()
125            && super::helpers::field_references_excluded_type(&field.ty, config.exclude_types);
126        if references_excluded && typ.has_stripped_cfg_fields {
127            continue;
128        }
129        let conversion = if field.sanitized || references_excluded {
130            format!("{}: Default::default()", field.name)
131        } else if optionalized && !field.optional {
132            // Field was wrapped in Option<T> for JS ergonomics but core expects T.
133            // Use unwrap_or_default() for simple types, unwrap_or_default() + into for Named.
134            gen_optionalized_field_to_core(&field.name, &field.ty, config)
135        } else {
136            field_conversion_to_core_cfg(&field.name, &field.ty, field.optional, config)
137        };
138        // Newtype wrapping: when the field was resolved from a newtype (e.g. NodeIndex → u32),
139        // wrap the binding value back into the newtype for the core struct.
140        // e.g. `source: val.source` → `source: kreuzberg::NodeIndex(val.source)`
141        //      `parent: val.parent` → `parent: val.parent.map(kreuzberg::NodeIndex)`
142        //      `children: val.children` → `children: val.children.into_iter().map(kreuzberg::NodeIndex).collect()`
143        let conversion = if let Some(newtype_path) = &field.newtype_wrapper {
144            if let Some(expr) = conversion.strip_prefix(&format!("{}: ", field.name)) {
145                // When `optional=true` and `ty` is a plain Primitive (not TypeRef::Optional), the core
146                // field is actually `Option<NewtypeT>`, so we must use `.map(NewtypeT)` not `NewtypeT(...)`.
147                match &field.ty {
148                    TypeRef::Optional(_) => format!("{}: ({expr}).map({newtype_path})", field.name),
149                    TypeRef::Vec(_) => {
150                        format!("{}: ({expr}).into_iter().map({newtype_path}).collect()", field.name)
151                    }
152                    _ if field.optional => format!("{}: ({expr}).map({newtype_path})", field.name),
153                    _ => format!("{}: {newtype_path}({expr})", field.name),
154                }
155            } else {
156                conversion
157            }
158        } else {
159            conversion
160        };
161        // Box<T> fields: wrap the converted value in Box::new()
162        let conversion = if field.is_boxed && matches!(&field.ty, TypeRef::Named(_)) {
163            if let Some(expr) = conversion.strip_prefix(&format!("{}: ", field.name)) {
164                if field.optional {
165                    // Option<Box<T>> field: map inside the Option
166                    format!("{}: {}.map(Box::new)", field.name, expr)
167                } else {
168                    format!("{}: Box::new({})", field.name, expr)
169                }
170            } else {
171                conversion
172            }
173        } else {
174            conversion
175        };
176        // CoreWrapper: apply Cow/Arc/Bytes wrapping for binding→core direction
177        let conversion = apply_core_wrapper_to_core(
178            &conversion,
179            &field.name,
180            &field.core_wrapper,
181            &field.vec_inner_core_wrapper,
182            field.optional,
183        );
184        writeln!(out, "            {conversion},").ok();
185    }
186    // Use ..Default::default() to fill cfg-gated fields stripped from the IR
187    if typ.has_stripped_cfg_fields {
188        writeln!(out, "            ..Default::default()").ok();
189    }
190    writeln!(out, "        }}").ok();
191    writeln!(out, "    }}").ok();
192    write!(out, "}}").ok();
193    out
194}
195
196/// Generate field conversion for a non-optional field that was optionalized
197/// (wrapped in Option<T>) in the binding struct for JS ergonomics.
198pub(super) fn gen_optionalized_field_to_core(name: &str, ty: &TypeRef, config: &ConversionConfig) -> String {
199    match ty {
200        TypeRef::Json => {
201            format!("{name}: val.{name}.as_ref().and_then(|s| serde_json::from_str(s).ok()).unwrap_or_default()")
202        }
203        TypeRef::Named(_) => {
204            // Named type: unwrap Option, convert via .into(), or use Default
205            format!("{name}: val.{name}.map(Into::into).unwrap_or_default()")
206        }
207        TypeRef::Primitive(PrimitiveType::F32) if config.cast_f32_to_f64 => {
208            format!("{name}: val.{name}.map(|v| v as f32).unwrap_or(0.0)")
209        }
210        TypeRef::Primitive(PrimitiveType::F32 | PrimitiveType::F64) => {
211            format!("{name}: val.{name}.unwrap_or(0.0)")
212        }
213        TypeRef::Primitive(p) if config.cast_large_ints_to_i64 && needs_i64_cast(p) => {
214            let core_ty = core_prim_str(p);
215            format!("{name}: val.{name}.map(|v| v as {core_ty}).unwrap_or_default()")
216        }
217        TypeRef::Optional(inner)
218            if config.cast_large_ints_to_i64
219                && matches!(inner.as_ref(), TypeRef::Primitive(p) if needs_i64_cast(p)) =>
220        {
221            if let TypeRef::Primitive(p) = inner.as_ref() {
222                let core_ty = core_prim_str(p);
223                format!("{name}: val.{name}.map(|v| v as {core_ty})")
224            } else {
225                field_conversion_to_core(name, ty, false)
226            }
227        }
228        TypeRef::Duration if config.cast_large_ints_to_i64 => {
229            format!("{name}: val.{name}.map(|v| std::time::Duration::from_millis(v as u64)).unwrap_or_default()")
230        }
231        TypeRef::Duration => {
232            format!("{name}: val.{name}.map(std::time::Duration::from_millis).unwrap_or_default()")
233        }
234        TypeRef::Path => {
235            format!("{name}: val.{name}.map(Into::into).unwrap_or_default()")
236        }
237        TypeRef::Optional(inner) if matches!(inner.as_ref(), TypeRef::Path) => {
238            // Binding has Option<String>, core has Option<PathBuf>
239            format!("{name}: val.{name}.map(|s| std::path::PathBuf::from(s))")
240        }
241        TypeRef::Optional(_) => {
242            // Field was flattened from Option<Option<T>> to Option<T> in the binding struct.
243            // Core expects Option<Option<T>>, so wrap with .map(Some) to reconstruct.
244            format!("{name}: val.{name}.map(Some)")
245        }
246        // Char: binding uses Option<String>, core uses char
247        TypeRef::Char => {
248            format!("{name}: val.{name}.and_then(|s| s.chars().next()).unwrap_or('*')")
249        }
250        TypeRef::Vec(inner) => match inner.as_ref() {
251            TypeRef::Json => {
252                format!(
253                    "{name}: val.{name}.map(|v| v.into_iter().filter_map(|s| serde_json::from_str(&s).ok()).collect()).unwrap_or_default()"
254                )
255            }
256            TypeRef::Named(_) => {
257                format!("{name}: val.{name}.map(|v| v.into_iter().map(Into::into).collect()).unwrap_or_default()")
258            }
259            TypeRef::Primitive(p) if config.cast_large_ints_to_i64 && needs_i64_cast(p) => {
260                let core_ty = core_prim_str(p);
261                format!(
262                    "{name}: val.{name}.map(|v| v.into_iter().map(|x| x as {core_ty}).collect()).unwrap_or_default()"
263                )
264            }
265            _ => format!("{name}: val.{name}.unwrap_or_default()"),
266        },
267        TypeRef::Map(k, v) if matches!(v.as_ref(), TypeRef::Json) => {
268            // Map with Json values: binding uses HashMap<K, String>, core uses HashMap<K, serde_json::Value>
269            let k_is_json = matches!(k.as_ref(), TypeRef::Json);
270            let k_expr = if k_is_json {
271                "serde_json::from_str(&k).unwrap_or_default()"
272            } else {
273                "k"
274            };
275            format!(
276                "{name}: val.{name}.unwrap_or_default().into_iter().map(|(k, v)| ({k_expr}, serde_json::from_str(&v).unwrap_or(serde_json::json!(v)))).collect()"
277            )
278        }
279        TypeRef::Map(k, _v) if matches!(k.as_ref(), TypeRef::Json) => {
280            // Map with Json keys: binding uses HashMap<String, V>, core uses HashMap<serde_json::Value, V>
281            format!(
282                "{name}: val.{name}.unwrap_or_default().into_iter().map(|(k, v)| (serde_json::from_str(&k).unwrap_or_default(), v)).collect()"
283            )
284        }
285        TypeRef::Map(_, _) => {
286            // Collect to handle HashMap↔BTreeMap conversion
287            format!("{name}: val.{name}.unwrap_or_default().into_iter().collect()")
288        }
289        _ => {
290            // Simple types (primitives, String, etc): unwrap_or_default()
291            format!("{name}: val.{name}.unwrap_or_default()")
292        }
293    }
294}
295
296/// Determine the field conversion expression for binding -> core.
297pub fn field_conversion_to_core(name: &str, ty: &TypeRef, optional: bool) -> String {
298    match ty {
299        // Primitives, String, Bytes, Unit -- direct assignment
300        TypeRef::Primitive(_) | TypeRef::String | TypeRef::Bytes | TypeRef::Unit => {
301            format!("{name}: val.{name}")
302        }
303        // Json: binding uses String, core uses serde_json::Value — parse or default
304        TypeRef::Json => {
305            if optional {
306                format!("{name}: val.{name}.as_ref().and_then(|s| serde_json::from_str(s).ok())")
307            } else {
308                format!("{name}: serde_json::from_str(&val.{name}).unwrap_or_default()")
309            }
310        }
311        // Char: binding uses String, core uses char — convert first character
312        TypeRef::Char => {
313            if optional {
314                format!("{name}: val.{name}.and_then(|s| s.chars().next())")
315            } else {
316                format!("{name}: val.{name}.chars().next().unwrap_or('*')")
317            }
318        }
319        // Duration: binding uses u64 (millis), core uses std::time::Duration
320        TypeRef::Duration => {
321            if optional {
322                format!("{name}: val.{name}.map(std::time::Duration::from_millis)")
323            } else {
324                format!("{name}: std::time::Duration::from_millis(val.{name})")
325            }
326        }
327        // Path needs .into() — binding uses String, core uses PathBuf
328        TypeRef::Path => {
329            if optional {
330                format!("{name}: val.{name}.map(Into::into)")
331            } else {
332                format!("{name}: val.{name}.into()")
333            }
334        }
335        // Named type -- needs .into() to convert between binding and core types
336        // Tuple types (e.g., "(String, String)") are passthrough — no conversion needed
337        TypeRef::Named(type_name) if is_tuple_type_name(type_name) => {
338            format!("{name}: val.{name}")
339        }
340        TypeRef::Named(_) => {
341            if optional {
342                format!("{name}: val.{name}.map(Into::into)")
343            } else {
344                format!("{name}: val.{name}.into()")
345            }
346        }
347        // Map with Json value type: binding uses HashMap<K, String>, core uses HashMap<K, Value>
348        TypeRef::Map(k, v) if matches!(v.as_ref(), TypeRef::Json) => {
349            let k_expr = if matches!(k.as_ref(), TypeRef::Json) {
350                "serde_json::from_str(&k).unwrap_or_default()"
351            } else {
352                "k"
353            };
354            if optional {
355                format!(
356                    "{name}: val.{name}.map(|m| m.into_iter().map(|(k, v)| ({k_expr}, serde_json::from_str(&v).unwrap_or_default())).collect())"
357                )
358            } else {
359                format!(
360                    "{name}: val.{name}.into_iter().map(|(k, v)| ({k_expr}, serde_json::from_str(&v).unwrap_or_default())).collect()"
361                )
362            }
363        }
364        // Optional with inner
365        TypeRef::Optional(inner) => match inner.as_ref() {
366            TypeRef::Json => format!("{name}: val.{name}.as_ref().and_then(|s| serde_json::from_str(s).ok())"),
367            TypeRef::Named(_) | TypeRef::Path => format!("{name}: val.{name}.map(Into::into)"),
368            TypeRef::Vec(vi) if matches!(vi.as_ref(), TypeRef::Named(_)) => {
369                format!("{name}: val.{name}.map(|v| v.into_iter().map(Into::into).collect())")
370            }
371            _ => format!("{name}: val.{name}"),
372        },
373        // Vec of named or Json types -- map each element
374        TypeRef::Vec(inner) => match inner.as_ref() {
375            TypeRef::Json => {
376                if optional {
377                    format!(
378                        "{name}: val.{name}.map(|v| v.into_iter().filter_map(|s| serde_json::from_str(&s).ok()).collect())"
379                    )
380                } else {
381                    format!("{name}: val.{name}.into_iter().filter_map(|s| serde_json::from_str(&s).ok()).collect()")
382                }
383            }
384            // Vec<(T1, T2)> — tuples are passthrough
385            TypeRef::Named(type_name) if is_tuple_type_name(type_name) => {
386                format!("{name}: val.{name}")
387            }
388            TypeRef::Named(_) => {
389                if optional {
390                    format!("{name}: val.{name}.map(|v| v.into_iter().map(Into::into).collect())")
391                } else {
392                    format!("{name}: val.{name}.into_iter().map(Into::into).collect()")
393                }
394            }
395            _ => format!("{name}: val.{name}"),
396        },
397        // Map -- collect to handle HashMap↔BTreeMap conversion;
398        // additionally convert Named keys/values via Into, Json values via serde.
399        TypeRef::Map(k, v) => {
400            let has_named_key = matches!(k.as_ref(), TypeRef::Named(n) if !is_tuple_type_name(n));
401            let has_named_val = matches!(v.as_ref(), TypeRef::Named(n) if !is_tuple_type_name(n));
402            let has_json_val = matches!(v.as_ref(), TypeRef::Json);
403            let has_json_key = matches!(k.as_ref(), TypeRef::Json);
404            // Vec<Named> values: each vector element needs Into conversion.
405            let has_vec_named_val = matches!(v.as_ref(), TypeRef::Vec(inner) if matches!(inner.as_ref(), TypeRef::Named(n) if !is_tuple_type_name(n)));
406            // Vec<Json> values: each element needs serde deserialization.
407            let has_vec_json_val = matches!(v.as_ref(), TypeRef::Vec(inner) if matches!(inner.as_ref(), TypeRef::Json));
408            if has_json_val || has_json_key || has_named_key || has_named_val || has_vec_named_val || has_vec_json_val {
409                let k_expr = if has_json_key {
410                    "serde_json::from_str(&k).unwrap_or(serde_json::Value::String(k))"
411                } else if has_named_key {
412                    "k.into()"
413                } else {
414                    "k"
415                };
416                let v_expr = if has_json_val {
417                    "serde_json::from_str(&v).unwrap_or(serde_json::Value::String(v))"
418                } else if has_named_val {
419                    "v.into()"
420                } else if has_vec_named_val {
421                    "v.into_iter().map(Into::into).collect()"
422                } else if has_vec_json_val {
423                    "v.into_iter().filter_map(|s| serde_json::from_str(&s).ok()).collect()"
424                } else {
425                    "v"
426                };
427                if optional {
428                    format!("{name}: val.{name}.map(|m| m.into_iter().map(|(k, v)| ({k_expr}, {v_expr})).collect())")
429                } else {
430                    format!("{name}: val.{name}.into_iter().map(|(k, v)| ({k_expr}, {v_expr})).collect()")
431                }
432            } else {
433                // No conversion needed — just collect for potential HashMap↔BTreeMap type change
434                if optional {
435                    format!("{name}: val.{name}.map(|m| m.into_iter().collect())")
436                } else {
437                    format!("{name}: val.{name}.into_iter().collect()")
438                }
439            }
440        }
441    }
442}
443
444/// Binding→core field conversion with backend-specific config (i64 casts, etc.).
445pub fn field_conversion_to_core_cfg(name: &str, ty: &TypeRef, optional: bool, config: &ConversionConfig) -> String {
446    // When optional=true and ty=Optional(T), the binding field was flattened from
447    // Option<Option<T>> to Option<T>. Core expects Option<Option<T>>, so wrap with .map(Some).
448    // This applies regardless of cast config; handle before any other dispatch.
449    if optional && matches!(ty, TypeRef::Optional(_)) {
450        // Delegate to get the inner Optional(T) → Option<T> conversion (with optional=false,
451        // since the outer Option is handled by the .map(Some) we add here).
452        let inner_expr = field_conversion_to_core_cfg(name, ty, false, config);
453        // inner_expr is "name: <expr-for-Option<T>>"; wrap it with .map(Some)
454        if let Some(expr) = inner_expr.strip_prefix(&format!("{name}: ")) {
455            return format!("{name}: ({expr}).map(Some)");
456        }
457        return inner_expr;
458    }
459
460    // WASM JsValue: use serde_wasm_bindgen for Map, nested Vec, and Vec<Json> types
461    if config.map_uses_jsvalue {
462        let is_nested_vec = matches!(ty, TypeRef::Vec(inner) if matches!(inner.as_ref(), TypeRef::Vec(_)));
463        let is_vec_json = matches!(ty, TypeRef::Vec(inner) if matches!(inner.as_ref(), TypeRef::Json));
464        let is_map = matches!(ty, TypeRef::Map(_, _));
465        if is_nested_vec || is_map || is_vec_json {
466            if optional {
467                return format!(
468                    "{name}: val.{name}.as_ref().and_then(|v| serde_wasm_bindgen::from_value(v.clone()).ok())"
469                );
470            }
471            return format!("{name}: serde_wasm_bindgen::from_value(val.{name}.clone()).unwrap_or_default()");
472        }
473        if let TypeRef::Optional(inner) = ty {
474            let is_inner_nested = matches!(inner.as_ref(), TypeRef::Vec(vi) if matches!(vi.as_ref(), TypeRef::Vec(_)));
475            let is_inner_vec_json = matches!(inner.as_ref(), TypeRef::Vec(vi) if matches!(vi.as_ref(), TypeRef::Json));
476            let is_inner_map = matches!(inner.as_ref(), TypeRef::Map(_, _));
477            if is_inner_nested || is_inner_map || is_inner_vec_json {
478                return format!(
479                    "{name}: val.{name}.as_ref().and_then(|v| serde_wasm_bindgen::from_value(v.clone()).ok())"
480                );
481            }
482        }
483    }
484
485    // Vec<T>→String binding→core: binding holds JSON string, core expects Vec<T>.
486    // field_type_for_serde collapses any Vec<T> not explicitly handled (including Vec<String>,
487    // Vec<Named>, etc.) to String. Apply serde round-trip for all Vec types.
488    if config.vec_named_to_string {
489        if let TypeRef::Vec(_) = ty {
490            if optional {
491                return format!("{name}: val.{name}.as_ref().and_then(|s| serde_json::from_str(s).ok())");
492            }
493            return format!("{name}: serde_json::from_str(&val.{name}).unwrap_or_default()");
494        }
495    }
496    // Json→String binding→core: use Default::default() (lossy — can't parse String back)
497    if config.json_to_string && matches!(ty, TypeRef::Json) {
498        return format!("{name}: Default::default()");
499    }
500    // Json→JsValue binding→core: use serde_wasm_bindgen to convert (WASM)
501    if config.map_uses_jsvalue && matches!(ty, TypeRef::Json) {
502        if optional {
503            return format!("{name}: val.{name}.as_ref().and_then(|v| serde_wasm_bindgen::from_value(v.clone()).ok())");
504        }
505        return format!("{name}: serde_wasm_bindgen::from_value(val.{name}.clone()).unwrap_or_default()");
506    }
507    if !config.cast_large_ints_to_i64
508        && !config.cast_f32_to_f64
509        && !config.json_to_string
510        && !config.vec_named_to_string
511    {
512        return field_conversion_to_core(name, ty, optional);
513    }
514    // Cast mode: handle primitives and Duration differently
515    match ty {
516        TypeRef::Primitive(p) if config.cast_large_ints_to_i64 && needs_i64_cast(p) => {
517            let core_ty = core_prim_str(p);
518            if optional {
519                format!("{name}: val.{name}.map(|v| v as {core_ty})")
520            } else {
521                format!("{name}: val.{name} as {core_ty}")
522            }
523        }
524        // f64→f32 cast (NAPI binding f64 → core f32)
525        TypeRef::Primitive(PrimitiveType::F32) if config.cast_f32_to_f64 => {
526            if optional {
527                format!("{name}: val.{name}.map(|v| v as f32)")
528            } else {
529                format!("{name}: val.{name} as f32")
530            }
531        }
532        TypeRef::Duration if config.cast_large_ints_to_i64 => {
533            if optional {
534                format!("{name}: val.{name}.map(|v| std::time::Duration::from_millis(v as u64))")
535            } else {
536                format!("{name}: std::time::Duration::from_millis(val.{name} as u64)")
537            }
538        }
539        TypeRef::Optional(inner) if matches!(inner.as_ref(), TypeRef::Primitive(p) if needs_i64_cast(p)) => {
540            if let TypeRef::Primitive(p) = inner.as_ref() {
541                let core_ty = core_prim_str(p);
542                format!("{name}: val.{name}.map(|v| v as {core_ty})")
543            } else {
544                field_conversion_to_core(name, ty, optional)
545            }
546        }
547        // Vec<u64/usize/isize> needs element-wise i64→core casting
548        TypeRef::Vec(inner)
549            if config.cast_large_ints_to_i64
550                && matches!(inner.as_ref(), TypeRef::Primitive(p) if needs_i64_cast(p)) =>
551        {
552            if let TypeRef::Primitive(p) = inner.as_ref() {
553                let core_ty = core_prim_str(p);
554                if optional {
555                    format!("{name}: val.{name}.map(|v| v.into_iter().map(|x| x as {core_ty}).collect())")
556                } else {
557                    format!("{name}: val.{name}.into_iter().map(|v| v as {core_ty}).collect()")
558                }
559            } else {
560                field_conversion_to_core(name, ty, optional)
561            }
562        }
563        // HashMap value type casting: when value type needs i64→core casting
564        TypeRef::Map(_k, v)
565            if config.cast_large_ints_to_i64 && matches!(v.as_ref(), TypeRef::Primitive(p) if needs_i64_cast(p)) =>
566        {
567            if let TypeRef::Primitive(p) = v.as_ref() {
568                let core_ty = core_prim_str(p);
569                if optional {
570                    format!("{name}: val.{name}.map(|m| m.into_iter().map(|(k, v)| (k, v as {core_ty})).collect())")
571                } else {
572                    format!("{name}: val.{name}.into_iter().map(|(k, v)| (k, v as {core_ty})).collect()")
573                }
574            } else {
575                field_conversion_to_core(name, ty, optional)
576            }
577        }
578        // Vec<f32> needs element-wise cast when f32→f64 mapping is active (NAPI)
579        TypeRef::Vec(inner)
580            if config.cast_f32_to_f64 && matches!(inner.as_ref(), TypeRef::Primitive(PrimitiveType::F32)) =>
581        {
582            if optional {
583                format!("{name}: val.{name}.map(|v| v.into_iter().map(|x| x as f32).collect())")
584            } else {
585                format!("{name}: val.{name}.into_iter().map(|v| v as f32).collect()")
586            }
587        }
588        // Optional(Vec(f32)) needs element-wise cast (NAPI only)
589        TypeRef::Optional(inner)
590            if config.cast_f32_to_f64
591                && matches!(inner.as_ref(), TypeRef::Vec(vi) if matches!(vi.as_ref(), TypeRef::Primitive(PrimitiveType::F32))) =>
592        {
593            format!("{name}: val.{name}.map(|v| v.into_iter().map(|x| x as f32).collect())")
594        }
595        // Fall through to default for everything else
596        _ => field_conversion_to_core(name, ty, optional),
597    }
598}
599
600/// Apply CoreWrapper transformations to a binding→core conversion expression.
601/// Wraps the value expression with Arc::new(), .into() for Cow, etc.
602fn apply_core_wrapper_to_core(
603    conversion: &str,
604    name: &str,
605    core_wrapper: &CoreWrapper,
606    vec_inner_core_wrapper: &CoreWrapper,
607    optional: bool,
608) -> String {
609    // Handle Vec<Arc<T>>: replace .map(Into::into) with .map(|v| std::sync::Arc::new(v.into()))
610    if *vec_inner_core_wrapper == CoreWrapper::Arc {
611        return conversion
612            .replace(
613                ".map(Into::into).collect()",
614                ".map(|v| std::sync::Arc::new(v.into())).collect()",
615            )
616            .replace(
617                "map(|v| v.into_iter().map(Into::into)",
618                "map(|v| v.into_iter().map(|v| std::sync::Arc::new(v.into()))",
619            );
620    }
621
622    match core_wrapper {
623        CoreWrapper::None => conversion.to_string(),
624        CoreWrapper::Cow => {
625            // Cow<str>: binding String → core Cow via .into()
626            // The field_conversion already emits "name: val.name" for strings,
627            // we need to add .into() to convert String → Cow<'static, str>
628            if let Some(expr) = conversion.strip_prefix(&format!("{name}: ")) {
629                if optional {
630                    format!("{name}: {expr}.map(Into::into)")
631                } else if expr == format!("val.{name}") {
632                    format!("{name}: val.{name}.into()")
633                } else if expr == "Default::default()" {
634                    // Sanitized field: Default::default() already resolves to the correct core type
635                    // (e.g. Cow<'static, str> — adding .into() breaks type inference).
636                    conversion.to_string()
637                } else {
638                    format!("{name}: ({expr}).into()")
639                }
640            } else {
641                conversion.to_string()
642            }
643        }
644        CoreWrapper::Arc => {
645            // Arc<T>: wrap with Arc::new()
646            if let Some(expr) = conversion.strip_prefix(&format!("{name}: ")) {
647                if expr == "Default::default()" {
648                    // Sanitized field: Default::default() resolves to the correct core type;
649                    // wrapping in Arc::new() would change the type.
650                    conversion.to_string()
651                } else if optional {
652                    format!("{name}: {expr}.map(|v| std::sync::Arc::new(v))")
653                } else {
654                    format!("{name}: std::sync::Arc::new({expr})")
655                }
656            } else {
657                conversion.to_string()
658            }
659        }
660        CoreWrapper::Bytes => {
661            // Bytes: binding Vec<u8> → core Bytes via .into()
662            if let Some(expr) = conversion.strip_prefix(&format!("{name}: ")) {
663                if optional {
664                    format!("{name}: {expr}.map(Into::into)")
665                } else if expr == format!("val.{name}") {
666                    format!("{name}: val.{name}.into()")
667                } else if expr == "Default::default()" {
668                    // Sanitized field: Default::default() already resolves to the correct core type
669                    // (e.g. bytes::Bytes — adding .into() breaks type inference).
670                    conversion.to_string()
671                } else {
672                    format!("{name}: ({expr}).into()")
673                }
674            } else {
675                conversion.to_string()
676            }
677        }
678        CoreWrapper::ArcMutex => {
679            // ArcMutex: binding T → core Arc<Mutex<T>> via Arc::new(Mutex::new())
680            if let Some(expr) = conversion.strip_prefix(&format!("{name}: ")) {
681                if optional {
682                    format!("{name}: {expr}.map(|v| std::sync::Arc::new(std::sync::Mutex::new(v.into())))")
683                } else if expr == format!("val.{name}") {
684                    format!("{name}: std::sync::Arc::new(std::sync::Mutex::new(val.{name}.into()))")
685                } else {
686                    format!("{name}: std::sync::Arc::new(std::sync::Mutex::new(({expr}).into()))")
687                }
688            } else {
689                conversion.to_string()
690            }
691        }
692    }
693}