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