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, false)
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, false)
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 field that was optionalized (wrapped in `Option<T>`) in the
232/// binding struct for JS ergonomics (`optionalize_defaults`). When `field_is_ir_optional` is
233/// `true`, the field is genuinely `Option<T>` in the IR and the `Option` layer must be preserved
234/// in the output expression (use `.map(|m| …)` rather than `unwrap_or_default()`).
235pub(super) fn gen_optionalized_field_to_core(
236    name: &str,
237    ty: &TypeRef,
238    config: &ConversionConfig,
239    field_is_ir_optional: bool,
240) -> String {
241    match ty {
242        TypeRef::Json => {
243            format!("{name}: val.{name}.as_ref().and_then(|s| serde_json::from_str(s).ok()).unwrap_or_default()")
244        }
245        TypeRef::Named(_) => {
246            // Named type: unwrap Option, convert via .into(), or use Default
247            format!("{name}: val.{name}.map(Into::into).unwrap_or_default()")
248        }
249        TypeRef::Primitive(PrimitiveType::F32) if config.cast_f32_to_f64 => {
250            format!("{name}: val.{name}.map(|v| v as f32).unwrap_or(0.0)")
251        }
252        TypeRef::Primitive(PrimitiveType::F32 | PrimitiveType::F64) => {
253            format!("{name}: val.{name}.unwrap_or(0.0)")
254        }
255        TypeRef::Primitive(p) if config.cast_large_ints_to_i64 && needs_i64_cast(p) => {
256            let core_ty = core_prim_str(p);
257            format!("{name}: val.{name}.map(|v| v as {core_ty}).unwrap_or_default()")
258        }
259        TypeRef::Optional(inner)
260            if config.cast_large_ints_to_i64
261                && matches!(inner.as_ref(), TypeRef::Primitive(p) if needs_i64_cast(p)) =>
262        {
263            if let TypeRef::Primitive(p) = inner.as_ref() {
264                let core_ty = core_prim_str(p);
265                format!("{name}: val.{name}.map(|v| v as {core_ty})")
266            } else {
267                field_conversion_to_core(name, ty, false)
268            }
269        }
270        TypeRef::Duration if config.cast_large_ints_to_i64 => {
271            format!("{name}: val.{name}.map(|v| std::time::Duration::from_millis(v as u64)).unwrap_or_default()")
272        }
273        TypeRef::Duration => {
274            format!("{name}: val.{name}.map(std::time::Duration::from_millis).unwrap_or_default()")
275        }
276        TypeRef::Path => {
277            format!("{name}: val.{name}.map(Into::into).unwrap_or_default()")
278        }
279        TypeRef::Optional(inner) if matches!(inner.as_ref(), TypeRef::Path) => {
280            // Binding has Option<String>, core has Option<PathBuf>
281            format!("{name}: val.{name}.map(|s| std::path::PathBuf::from(s))")
282        }
283        TypeRef::Optional(_) => {
284            // Field was flattened from Option<Option<T>> to Option<T> in the binding struct.
285            // Core expects Option<Option<T>>, so wrap with .map(Some) to reconstruct.
286            format!("{name}: val.{name}.map(Some)")
287        }
288        // Char: binding uses Option<String>, core uses char
289        TypeRef::Char => {
290            format!("{name}: val.{name}.and_then(|s| s.chars().next()).unwrap_or('*')")
291        }
292        TypeRef::Vec(inner) => match inner.as_ref() {
293            TypeRef::Json => {
294                format!(
295                    "{name}: val.{name}.map(|v| v.into_iter().filter_map(|s| serde_json::from_str(&s).ok()).collect()).unwrap_or_default()"
296                )
297            }
298            TypeRef::Named(_) => {
299                format!("{name}: val.{name}.map(|v| v.into_iter().map(Into::into).collect()).unwrap_or_default()")
300            }
301            TypeRef::Primitive(p) if config.cast_large_ints_to_i64 && needs_i64_cast(p) => {
302                let core_ty = core_prim_str(p);
303                format!(
304                    "{name}: val.{name}.map(|v| v.into_iter().map(|x| x as {core_ty}).collect()).unwrap_or_default()"
305                )
306            }
307            _ => format!("{name}: val.{name}.unwrap_or_default()"),
308        },
309        TypeRef::Map(k, v) if matches!(v.as_ref(), TypeRef::Json) => {
310            // Map with Json values: binding uses HashMap<K, String>, core uses HashMap<K, serde_json::Value>
311            let k_is_json = matches!(k.as_ref(), TypeRef::Json);
312            let k_expr = if k_is_json {
313                "serde_json::from_str(&k).unwrap_or_default()"
314            } else {
315                "k"
316            };
317            format!(
318                "{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()"
319            )
320        }
321        TypeRef::Map(k, _v) if matches!(k.as_ref(), TypeRef::Json) => {
322            // Map with Json keys: binding uses HashMap<String, V>, core uses HashMap<serde_json::Value, V>
323            format!(
324                "{name}: val.{name}.unwrap_or_default().into_iter().map(|(k, v)| (serde_json::from_str(&k).unwrap_or_default(), v)).collect()"
325            )
326        }
327        TypeRef::Map(k, v) => {
328            // Map with Named values need .into() conversion on each value.
329            let has_named_val = matches!(v.as_ref(), TypeRef::Named(n) if !is_tuple_type_name(n));
330            let has_named_key = matches!(k.as_ref(), TypeRef::Named(n) if !is_tuple_type_name(n));
331            let val_is_string_enum = matches!(v.as_ref(), TypeRef::Named(n)
332                if config.enum_string_names.as_ref().is_some_and(|names| names.contains(n)));
333            if field_is_ir_optional {
334                // Genuinely optional field: preserve the Option layer using .map(|m| …).
335                if val_is_string_enum {
336                    format!(
337                        "{name}: val.{name}.map(|m| m.into_iter().map(|(k, v)| (k, serde_json::from_str(&v).unwrap_or_default())).collect())"
338                    )
339                } else if has_named_val {
340                    format!("{name}: val.{name}.map(|m| m.into_iter().map(|(k, v)| (k, v.into())).collect())")
341                } else if has_named_key {
342                    format!("{name}: val.{name}.map(|m| m.into_iter().map(|(k, v)| (k.into(), v)).collect())")
343                } else {
344                    format!("{name}: val.{name}.map(|m| m.into_iter().collect())")
345                }
346            } else if val_is_string_enum {
347                format!(
348                    "{name}: val.{name}.unwrap_or_default().into_iter().map(|(k, v)| (k, serde_json::from_str(&v).unwrap_or_default())).collect()"
349                )
350            } else if has_named_val {
351                format!("{name}: val.{name}.unwrap_or_default().into_iter().map(|(k, v)| (k, v.into())).collect()")
352            } else if has_named_key {
353                format!("{name}: val.{name}.unwrap_or_default().into_iter().map(|(k, v)| (k.into(), v)).collect()")
354            } else {
355                format!("{name}: val.{name}.unwrap_or_default().into_iter().collect()")
356            }
357        }
358        _ => {
359            // Simple types (primitives, String, etc): unwrap_or_default()
360            format!("{name}: val.{name}.unwrap_or_default()")
361        }
362    }
363}
364
365/// Determine the field conversion expression for binding -> core.
366pub fn field_conversion_to_core(name: &str, ty: &TypeRef, optional: bool) -> String {
367    match ty {
368        // Primitives, String, Unit -- direct assignment
369        TypeRef::Primitive(_) | TypeRef::String | TypeRef::Unit => {
370            format!("{name}: val.{name}")
371        }
372        // Bytes: binding uses Vec<u8>, core uses bytes::Bytes — convert via Into
373        TypeRef::Bytes => {
374            if optional {
375                format!("{name}: val.{name}.map(Into::into)")
376            } else {
377                format!("{name}: val.{name}.into()")
378            }
379        }
380        // Json: binding uses String, core uses serde_json::Value — parse or default
381        TypeRef::Json => {
382            if optional {
383                format!("{name}: val.{name}.as_ref().and_then(|s| serde_json::from_str(s).ok())")
384            } else {
385                format!("{name}: serde_json::from_str(&val.{name}).unwrap_or_default()")
386            }
387        }
388        // Char: binding uses String, core uses char — convert first character
389        TypeRef::Char => {
390            if optional {
391                format!("{name}: val.{name}.and_then(|s| s.chars().next())")
392            } else {
393                format!("{name}: val.{name}.chars().next().unwrap_or('*')")
394            }
395        }
396        // Duration: binding uses u64 (millis), core uses std::time::Duration
397        TypeRef::Duration => {
398            if optional {
399                format!("{name}: val.{name}.map(std::time::Duration::from_millis)")
400            } else {
401                format!("{name}: std::time::Duration::from_millis(val.{name})")
402            }
403        }
404        // Path needs .into() — binding uses String, core uses PathBuf
405        TypeRef::Path => {
406            if optional {
407                format!("{name}: val.{name}.map(Into::into)")
408            } else {
409                format!("{name}: val.{name}.into()")
410            }
411        }
412        // Named type -- needs .into() to convert between binding and core types
413        // Tuple types (e.g., "(String, String)") are passthrough — no conversion needed
414        TypeRef::Named(type_name) if is_tuple_type_name(type_name) => {
415            format!("{name}: val.{name}")
416        }
417        TypeRef::Named(_) => {
418            if optional {
419                format!("{name}: val.{name}.map(Into::into)")
420            } else {
421                format!("{name}: val.{name}.into()")
422            }
423        }
424        // Map with Json value type: binding uses HashMap<K, String>, core uses HashMap<K, Value>
425        TypeRef::Map(k, v) if matches!(v.as_ref(), TypeRef::Json) => {
426            let k_expr = if matches!(k.as_ref(), TypeRef::Json) {
427                "serde_json::from_str(&k).unwrap_or_default()"
428            } else {
429                "k"
430            };
431            if optional {
432                format!(
433                    "{name}: val.{name}.map(|m| m.into_iter().map(|(k, v)| ({k_expr}, serde_json::from_str(&v).unwrap_or_default())).collect())"
434                )
435            } else {
436                format!(
437                    "{name}: val.{name}.into_iter().map(|(k, v)| ({k_expr}, serde_json::from_str(&v).unwrap_or_default())).collect()"
438                )
439            }
440        }
441        // Optional with inner
442        TypeRef::Optional(inner) => match inner.as_ref() {
443            TypeRef::Json => format!("{name}: val.{name}.as_ref().and_then(|s| serde_json::from_str(s).ok())"),
444            TypeRef::Named(_) | TypeRef::Path => format!("{name}: val.{name}.map(Into::into)"),
445            TypeRef::Vec(vi) if matches!(vi.as_ref(), TypeRef::Named(_)) => {
446                format!("{name}: val.{name}.map(|v| v.into_iter().map(Into::into).collect())")
447            }
448            _ => format!("{name}: val.{name}"),
449        },
450        // Vec of named or Json types -- map each element
451        TypeRef::Vec(inner) => match inner.as_ref() {
452            TypeRef::Json => {
453                if optional {
454                    format!(
455                        "{name}: val.{name}.map(|v| v.into_iter().filter_map(|s| serde_json::from_str(&s).ok()).collect())"
456                    )
457                } else {
458                    format!("{name}: val.{name}.into_iter().filter_map(|s| serde_json::from_str(&s).ok()).collect()")
459                }
460            }
461            // Vec<(T1, T2)> — tuples are passthrough
462            TypeRef::Named(type_name) if is_tuple_type_name(type_name) => {
463                format!("{name}: val.{name}")
464            }
465            TypeRef::Named(_) => {
466                if optional {
467                    format!("{name}: val.{name}.map(|v| v.into_iter().map(Into::into).collect())")
468                } else {
469                    format!("{name}: val.{name}.into_iter().map(Into::into).collect()")
470                }
471            }
472            _ => format!("{name}: val.{name}"),
473        },
474        // Map -- collect to handle HashMap↔BTreeMap conversion;
475        // additionally convert Named keys/values via Into, Json values via serde.
476        TypeRef::Map(k, v) => {
477            let has_named_key = matches!(k.as_ref(), TypeRef::Named(n) if !is_tuple_type_name(n));
478            let has_named_val = matches!(v.as_ref(), TypeRef::Named(n) if !is_tuple_type_name(n));
479            let has_json_val = matches!(v.as_ref(), TypeRef::Json);
480            let has_json_key = matches!(k.as_ref(), TypeRef::Json);
481            // Vec<Named> values: each vector element needs Into conversion.
482            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)));
483            // Vec<Json> values: each element needs serde deserialization.
484            let has_vec_json_val = matches!(v.as_ref(), TypeRef::Vec(inner) if matches!(inner.as_ref(), TypeRef::Json));
485            if has_json_val || has_json_key || has_named_key || has_named_val || has_vec_named_val || has_vec_json_val {
486                let k_expr = if has_json_key {
487                    "serde_json::from_str(&k).unwrap_or(serde_json::Value::String(k))"
488                } else if has_named_key {
489                    "k.into()"
490                } else {
491                    "k"
492                };
493                let v_expr = if has_json_val {
494                    "serde_json::from_str(&v).unwrap_or(serde_json::Value::String(v))"
495                } else if has_named_val {
496                    "v.into()"
497                } else if has_vec_named_val {
498                    "v.into_iter().map(Into::into).collect()"
499                } else if has_vec_json_val {
500                    "v.into_iter().filter_map(|s| serde_json::from_str(&s).ok()).collect()"
501                } else {
502                    "v"
503                };
504                if optional {
505                    format!("{name}: val.{name}.map(|m| m.into_iter().map(|(k, v)| ({k_expr}, {v_expr})).collect())")
506                } else {
507                    format!("{name}: val.{name}.into_iter().map(|(k, v)| ({k_expr}, {v_expr})).collect()")
508                }
509            } else {
510                // No conversion needed for keys/values — just collect for potential
511                // HashMap↔BTreeMap type change. Still apply per-value .into() when the value
512                // type is a Named wrapper that requires conversion (e.g. a binding-side newtype).
513                if optional {
514                    if has_named_val {
515                        format!("{name}: val.{name}.map(|m| m.into_iter().map(|(k, v)| (k, v.into())).collect())")
516                    } else {
517                        format!("{name}: val.{name}.map(|m| m.into_iter().collect())")
518                    }
519                } else {
520                    format!("{name}: val.{name}.into_iter().collect()")
521                }
522            }
523        }
524    }
525}
526
527/// Binding→core field conversion with backend-specific config (i64 casts, etc.).
528pub fn field_conversion_to_core_cfg(name: &str, ty: &TypeRef, optional: bool, config: &ConversionConfig) -> String {
529    // When optional=true and ty=Optional(T), the binding field was flattened from
530    // Option<Option<T>> to Option<T>. Core expects Option<Option<T>>, so wrap with .map(Some).
531    // This applies regardless of cast config; handle before any other dispatch.
532    if optional && matches!(ty, TypeRef::Optional(_)) {
533        // Delegate to get the inner Optional(T) → Option<T> conversion (with optional=false,
534        // since the outer Option is handled by the .map(Some) we add here).
535        let inner_expr = field_conversion_to_core_cfg(name, ty, false, config);
536        // inner_expr is "name: <expr-for-Option<T>>"; wrap it with .map(Some)
537        if let Some(expr) = inner_expr.strip_prefix(&format!("{name}: ")) {
538            return format!("{name}: ({expr}).map(Some)");
539        }
540        return inner_expr;
541    }
542
543    // WASM JsValue: use serde_wasm_bindgen for Map, nested Vec, and Vec<Json> types
544    if config.map_uses_jsvalue {
545        let is_nested_vec = matches!(ty, TypeRef::Vec(inner) if matches!(inner.as_ref(), TypeRef::Vec(_)));
546        let is_vec_json = matches!(ty, TypeRef::Vec(inner) if matches!(inner.as_ref(), TypeRef::Json));
547        let is_map = matches!(ty, TypeRef::Map(_, _));
548        if is_nested_vec || is_map || is_vec_json {
549            if optional {
550                return format!(
551                    "{name}: val.{name}.as_ref().and_then(|v| serde_wasm_bindgen::from_value(v.clone()).ok())"
552                );
553            }
554            return format!("{name}: serde_wasm_bindgen::from_value(val.{name}.clone()).unwrap_or_default()");
555        }
556        if let TypeRef::Optional(inner) = ty {
557            let is_inner_nested = matches!(inner.as_ref(), TypeRef::Vec(vi) if matches!(vi.as_ref(), TypeRef::Vec(_)));
558            let is_inner_vec_json = matches!(inner.as_ref(), TypeRef::Vec(vi) if matches!(vi.as_ref(), TypeRef::Json));
559            let is_inner_map = matches!(inner.as_ref(), TypeRef::Map(_, _));
560            if is_inner_nested || is_inner_map || is_inner_vec_json {
561                return format!(
562                    "{name}: val.{name}.as_ref().and_then(|v| serde_wasm_bindgen::from_value(v.clone()).ok())"
563                );
564            }
565        }
566    }
567
568    // Vec<Named>→String binding→core: binding holds JSON string, core expects Vec<Named>.
569    // Only apply serde round-trip for Vec<Named> types (complex structs that can't cross FFI).
570    // Vec<String>, Vec<Primitive>, etc. stay as-is since they map directly.
571    if config.vec_named_to_string {
572        if let TypeRef::Vec(inner) = ty {
573            if matches!(inner.as_ref(), TypeRef::Named(_)) {
574                if optional {
575                    return format!("{name}: val.{name}.as_ref().and_then(|s| serde_json::from_str(s).ok())");
576                }
577                return format!("{name}: serde_json::from_str(&val.{name}).unwrap_or_default()");
578            }
579        }
580    }
581    // Json→String binding→core: use Default::default() (lossy — can't parse String back)
582    if config.json_to_string && matches!(ty, TypeRef::Json) {
583        return format!("{name}: Default::default()");
584    }
585    // Json→JsValue binding→core: use serde_wasm_bindgen to convert (WASM)
586    if config.map_uses_jsvalue && matches!(ty, TypeRef::Json) {
587        if optional {
588            return format!("{name}: val.{name}.as_ref().and_then(|v| serde_wasm_bindgen::from_value(v.clone()).ok())");
589        }
590        return format!("{name}: serde_wasm_bindgen::from_value(val.{name}.clone()).unwrap_or_default()");
591    }
592    if !config.cast_large_ints_to_i64
593        && !config.cast_f32_to_f64
594        && !config.json_to_string
595        && !config.vec_named_to_string
596    {
597        return field_conversion_to_core(name, ty, optional);
598    }
599    // Cast mode: handle primitives and Duration differently
600    match ty {
601        TypeRef::Primitive(p) if config.cast_large_ints_to_i64 && needs_i64_cast(p) => {
602            let core_ty = core_prim_str(p);
603            if optional {
604                format!("{name}: val.{name}.map(|v| v as {core_ty})")
605            } else {
606                format!("{name}: val.{name} as {core_ty}")
607            }
608        }
609        // f64→f32 cast (NAPI binding f64 → core f32)
610        TypeRef::Primitive(PrimitiveType::F32) if config.cast_f32_to_f64 => {
611            if optional {
612                format!("{name}: val.{name}.map(|v| v as f32)")
613            } else {
614                format!("{name}: val.{name} as f32")
615            }
616        }
617        TypeRef::Duration if config.cast_large_ints_to_i64 => {
618            if optional {
619                format!("{name}: val.{name}.map(|v| std::time::Duration::from_millis(v as u64))")
620            } else {
621                format!("{name}: std::time::Duration::from_millis(val.{name} as u64)")
622            }
623        }
624        TypeRef::Optional(inner) if matches!(inner.as_ref(), TypeRef::Primitive(p) if needs_i64_cast(p)) => {
625            if let TypeRef::Primitive(p) = inner.as_ref() {
626                let core_ty = core_prim_str(p);
627                format!("{name}: val.{name}.map(|v| v as {core_ty})")
628            } else {
629                field_conversion_to_core(name, ty, optional)
630            }
631        }
632        // Vec<u64/usize/isize> needs element-wise i64→core casting
633        TypeRef::Vec(inner)
634            if config.cast_large_ints_to_i64
635                && matches!(inner.as_ref(), TypeRef::Primitive(p) if needs_i64_cast(p)) =>
636        {
637            if let TypeRef::Primitive(p) = inner.as_ref() {
638                let core_ty = core_prim_str(p);
639                if optional {
640                    format!("{name}: val.{name}.map(|v| v.into_iter().map(|x| x as {core_ty}).collect())")
641                } else {
642                    format!("{name}: val.{name}.into_iter().map(|v| v as {core_ty}).collect()")
643                }
644            } else {
645                field_conversion_to_core(name, ty, optional)
646            }
647        }
648        // HashMap value type casting: when value type needs i64→core casting
649        TypeRef::Map(_k, v)
650            if config.cast_large_ints_to_i64 && matches!(v.as_ref(), TypeRef::Primitive(p) if needs_i64_cast(p)) =>
651        {
652            if let TypeRef::Primitive(p) = v.as_ref() {
653                let core_ty = core_prim_str(p);
654                if optional {
655                    format!("{name}: val.{name}.map(|m| m.into_iter().map(|(k, v)| (k, v as {core_ty})).collect())")
656                } else {
657                    format!("{name}: val.{name}.into_iter().map(|(k, v)| (k, v as {core_ty})).collect()")
658                }
659            } else {
660                field_conversion_to_core(name, ty, optional)
661            }
662        }
663        // Vec<f32> needs element-wise cast when f32→f64 mapping is active (NAPI)
664        TypeRef::Vec(inner)
665            if config.cast_f32_to_f64 && matches!(inner.as_ref(), TypeRef::Primitive(PrimitiveType::F32)) =>
666        {
667            if optional {
668                format!("{name}: val.{name}.map(|v| v.into_iter().map(|x| x as f32).collect())")
669            } else {
670                format!("{name}: val.{name}.into_iter().map(|v| v as f32).collect()")
671            }
672        }
673        // Optional(Vec(f32)) needs element-wise cast (NAPI only)
674        TypeRef::Optional(inner)
675            if config.cast_f32_to_f64
676                && matches!(inner.as_ref(), TypeRef::Vec(vi) if matches!(vi.as_ref(), TypeRef::Primitive(PrimitiveType::F32))) =>
677        {
678            format!("{name}: val.{name}.map(|v| v.into_iter().map(|x| x as f32).collect())")
679        }
680        // Fall through to default for everything else
681        _ => field_conversion_to_core(name, ty, optional),
682    }
683}
684
685/// Apply CoreWrapper transformations to a binding→core conversion expression.
686/// Wraps the value expression with Arc::new(), .into() for Cow, etc.
687fn apply_core_wrapper_to_core(
688    conversion: &str,
689    name: &str,
690    core_wrapper: &CoreWrapper,
691    vec_inner_core_wrapper: &CoreWrapper,
692    optional: bool,
693) -> String {
694    // Handle Vec<Arc<T>>: replace .map(Into::into) with .map(|v| std::sync::Arc::new(v.into()))
695    if *vec_inner_core_wrapper == CoreWrapper::Arc {
696        return conversion
697            .replace(
698                ".map(Into::into).collect()",
699                ".map(|v| std::sync::Arc::new(v.into())).collect()",
700            )
701            .replace(
702                "map(|v| v.into_iter().map(Into::into)",
703                "map(|v| v.into_iter().map(|v| std::sync::Arc::new(v.into()))",
704            );
705    }
706
707    match core_wrapper {
708        CoreWrapper::None => conversion.to_string(),
709        CoreWrapper::Cow => {
710            // Cow<str>: binding String → core Cow via .into()
711            // The field_conversion already emits "name: val.name" for strings,
712            // we need to add .into() to convert String → Cow<'static, str>
713            if let Some(expr) = conversion.strip_prefix(&format!("{name}: ")) {
714                if optional {
715                    format!("{name}: {expr}.map(Into::into)")
716                } else if expr == format!("val.{name}") {
717                    format!("{name}: val.{name}.into()")
718                } else if expr == "Default::default()" {
719                    // Sanitized field: Default::default() already resolves to the correct core type
720                    // (e.g. Cow<'static, str> — adding .into() breaks type inference).
721                    conversion.to_string()
722                } else {
723                    format!("{name}: ({expr}).into()")
724                }
725            } else {
726                conversion.to_string()
727            }
728        }
729        CoreWrapper::Arc => {
730            // Arc<T>: wrap with Arc::new()
731            if let Some(expr) = conversion.strip_prefix(&format!("{name}: ")) {
732                if expr == "Default::default()" {
733                    // Sanitized field: Default::default() resolves to the correct core type;
734                    // wrapping in Arc::new() would change the type.
735                    conversion.to_string()
736                } else if optional {
737                    format!("{name}: {expr}.map(|v| std::sync::Arc::new(v))")
738                } else {
739                    format!("{name}: std::sync::Arc::new({expr})")
740                }
741            } else {
742                conversion.to_string()
743            }
744        }
745        CoreWrapper::Bytes => {
746            // Bytes: binding Vec<u8> → core bytes::Bytes via .into().
747            // When TypeRef::Bytes already emitted a conversion (e.g. `val.{name}.into()` or
748            // `val.{name}.map(Into::into)`), applying another .into() creates an ambiguous
749            // double-into chain. Detect and dedup: use the already-generated expression as-is
750            // when it fully covers the conversion, or emit a fresh single .into() for bare fields.
751            if let Some(expr) = conversion.strip_prefix(&format!("{name}: ")) {
752                let already_converted_non_opt = expr == format!("val.{name}.into()");
753                let already_converted_opt = expr
754                    .strip_prefix(&format!("val.{name}"))
755                    .map(|s| s == ".map(Into::into)")
756                    .unwrap_or(false);
757                if already_converted_non_opt || already_converted_opt {
758                    // The base conversion already handles Bytes — pass through unchanged.
759                    conversion.to_string()
760                } else if optional {
761                    format!("{name}: {expr}.map(Into::into)")
762                } else if expr == format!("val.{name}") {
763                    format!("{name}: val.{name}.into()")
764                } else if expr == "Default::default()" {
765                    // Sanitized field: Default::default() already resolves to the correct core type
766                    // (e.g. bytes::Bytes — adding .into() breaks type inference).
767                    conversion.to_string()
768                } else {
769                    format!("{name}: ({expr}).into()")
770                }
771            } else {
772                conversion.to_string()
773            }
774        }
775        CoreWrapper::ArcMutex => {
776            // ArcMutex: binding T → core Arc<Mutex<T>> via Arc::new(Mutex::new())
777            if let Some(expr) = conversion.strip_prefix(&format!("{name}: ")) {
778                if optional {
779                    format!("{name}: {expr}.map(|v| std::sync::Arc::new(std::sync::Mutex::new(v.into())))")
780                } else if expr == format!("val.{name}") {
781                    format!("{name}: std::sync::Arc::new(std::sync::Mutex::new(val.{name}.into()))")
782                } else {
783                    format!("{name}: std::sync::Arc::new(std::sync::Mutex::new(({expr}).into()))")
784                }
785            } else {
786                conversion.to_string()
787            }
788        }
789    }
790}