Skip to main content

alef_codegen/generators/
binding_helpers.rs

1use crate::generators::{AsyncPattern, RustBindingConfig};
2use ahash::AHashSet;
3use alef_core::ir::{CoreWrapper, ParamDef, TypeDef, TypeRef};
4use std::fmt::Write;
5
6/// Helper: wrap an opaque inner value in the correct smart pointer expression.
7///
8/// - Plain opaque types use `Arc::new(val)`.
9/// - Mutex-wrapped opaque types use `Arc::new(std::sync::Mutex::new(val))`.
10fn arc_wrap(val: &str, name: &str, mutex_types: &AHashSet<String>) -> String {
11    if mutex_types.contains(name) {
12        format!("Arc::new(std::sync::Mutex::new({val}))")
13    } else {
14        format!("Arc::new({val})")
15    }
16}
17
18/// Wrap a core-call result for opaque delegation methods.
19///
20/// - `TypeRef::Named(n)` where `n == type_name` → re-wrap in `Self { inner: Arc::new(...) }`
21/// - `TypeRef::Named(n)` where `n` is another opaque type → wrap in `{n} { inner: Arc::new(...) }`
22/// - `TypeRef::Named(n)` where `n` is a non-opaque type → `todo!()` placeholder (From may not exist)
23/// - Everything else (primitives, String, Vec, etc.) → pass through unchanged
24/// - `TypeRef::Unit` → pass through unchanged
25///
26/// When `returns_cow` is true the core method returns `Cow<'_, T>`. `.into_owned()` is emitted
27/// before any further type conversion to obtain an owned `T`.
28///
29/// `mutex_types` identifies opaque types that use `Arc<Mutex<T>>` instead of `Arc<T>`, so
30/// constructor expressions use `Arc::new(Mutex::new(...))` where needed.
31#[allow(clippy::too_many_arguments)]
32pub fn wrap_return_with_mutex(
33    expr: &str,
34    return_type: &TypeRef,
35    type_name: &str,
36    opaque_types: &AHashSet<String>,
37    mutex_types: &AHashSet<String>,
38    self_is_opaque: bool,
39    returns_ref: bool,
40    returns_cow: bool,
41) -> String {
42    let self_arc = arc_wrap("", type_name, mutex_types); // used for pattern matching only
43    let _ = self_arc; // just to reference mutex_types in context
44    match return_type {
45        TypeRef::Named(n) if n == type_name && self_is_opaque => {
46            let inner = if returns_cow {
47                format!("{expr}.into_owned()")
48            } else if returns_ref {
49                format!("{expr}.clone()")
50            } else {
51                expr.to_string()
52            };
53            format!("Self {{ inner: {} }}", arc_wrap(&inner, type_name, mutex_types))
54        }
55        TypeRef::Named(n) if opaque_types.contains(n.as_str()) => {
56            let inner = if returns_cow {
57                format!("{expr}.into_owned()")
58            } else if returns_ref {
59                format!("{expr}.clone()")
60            } else {
61                expr.to_string()
62            };
63            format!("{n} {{ inner: {} }}", arc_wrap(&inner, n, mutex_types))
64        }
65        TypeRef::Named(_) => {
66            // Non-opaque Named return type — use .into() for core→binding From conversion.
67            // When the core returns a Cow, call .into_owned() first to get an owned T.
68            // When the core returns a reference, clone first since From<&T> typically doesn't exist.
69            // NOTE: If this type was sanitized to String in the binding, From won't exist.
70            // The calling backend should check method.sanitized before delegating.
71            // This code assumes non-sanitized Named types have From impls.
72            if returns_cow {
73                format!("{expr}.into_owned().into()")
74            } else if returns_ref {
75                format!("{expr}.clone().into()")
76            } else {
77                format!("{expr}.into()")
78            }
79        }
80        // String/Bytes: only convert when the core returns a reference (&str→String, &[u8]→Vec<u8>).
81        // When owned (returns_ref=false), both sides are already String/Vec<u8> — skip .into().
82        TypeRef::String | TypeRef::Bytes => {
83            if returns_ref {
84                format!("{expr}.into()")
85            } else {
86                expr.to_string()
87            }
88        }
89        // Path: PathBuf→String needs to_string_lossy, &Path→String too
90        TypeRef::Path => format!("{expr}.to_string_lossy().to_string()"),
91        // Duration: core returns std::time::Duration, binding uses u64 (millis)
92        TypeRef::Duration => format!("{expr}.as_millis() as u64"),
93        // Json: serde_json::Value needs serialization to string
94        TypeRef::Json => format!("{expr}.to_string()"),
95        // Optional: wrap inner conversion in .map(...)
96        TypeRef::Optional(inner) => match inner.as_ref() {
97            TypeRef::Named(n) if opaque_types.contains(n.as_str()) => {
98                let wrap = arc_wrap("v", n, mutex_types);
99                if returns_ref {
100                    format!(
101                        "{expr}.map(|v| {n} {{ inner: {} }})",
102                        arc_wrap("v.clone()", n, mutex_types)
103                    )
104                } else {
105                    format!("{expr}.map(|v| {n} {{ inner: {wrap} }})")
106                }
107            }
108            TypeRef::Named(_) => {
109                if returns_ref {
110                    format!("{expr}.map(|v| v.clone().into())")
111                } else {
112                    format!("{expr}.map(Into::into)")
113                }
114            }
115            TypeRef::Path => {
116                format!("{expr}.map(Into::into)")
117            }
118            TypeRef::String | TypeRef::Bytes => {
119                if returns_ref {
120                    format!("{expr}.map(Into::into)")
121                } else {
122                    expr.to_string()
123                }
124            }
125            TypeRef::Duration => format!("{expr}.map(|d| d.as_millis() as u64)"),
126            TypeRef::Json => format!("{expr}.map(ToString::to_string)"),
127            // Optional<Vec<Named>>: convert each element in the inner Vec
128            TypeRef::Vec(vec_inner) => match vec_inner.as_ref() {
129                TypeRef::Named(n) if opaque_types.contains(n.as_str()) => {
130                    if returns_ref {
131                        let wrap = arc_wrap("x.clone()", n, mutex_types);
132                        format!("{expr}.map(|v| v.into_iter().map(|x| {n} {{ inner: {wrap} }}).collect())")
133                    } else {
134                        let wrap = arc_wrap("x", n, mutex_types);
135                        format!("{expr}.map(|v| v.into_iter().map(|x| {n} {{ inner: {wrap} }}).collect())")
136                    }
137                }
138                TypeRef::Named(_) => {
139                    if returns_ref {
140                        format!("{expr}.map(|v| v.into_iter().map(|x| x.clone().into()).collect())")
141                    } else {
142                        format!("{expr}.map(|v| v.into_iter().map(Into::into).collect())")
143                    }
144                }
145                _ => expr.to_string(),
146            },
147            _ => expr.to_string(),
148        },
149        // Vec: map each element through the appropriate conversion
150        TypeRef::Vec(inner) => match inner.as_ref() {
151            TypeRef::Named(n) if opaque_types.contains(n.as_str()) => {
152                if returns_ref {
153                    let wrap = arc_wrap("v.clone()", n, mutex_types);
154                    format!("{expr}.into_iter().map(|v| {n} {{ inner: {wrap} }}).collect()")
155                } else {
156                    let wrap = arc_wrap("v", n, mutex_types);
157                    format!("{expr}.into_iter().map(|v| {n} {{ inner: {wrap} }}).collect()")
158                }
159            }
160            TypeRef::Named(_) => {
161                if returns_ref {
162                    format!("{expr}.into_iter().map(|v| v.clone().into()).collect()")
163                } else {
164                    format!("{expr}.into_iter().map(Into::into).collect()")
165                }
166            }
167            TypeRef::Path => {
168                format!("{expr}.into_iter().map(Into::into).collect()")
169            }
170            TypeRef::String | TypeRef::Bytes => {
171                if returns_ref {
172                    format!("{expr}.into_iter().map(Into::into).collect()")
173                } else {
174                    expr.to_string()
175                }
176            }
177            _ => expr.to_string(),
178        },
179        _ => expr.to_string(),
180    }
181}
182
183/// Wrap a core-call result for opaque delegation methods.
184///
185/// This is the backward-compatible wrapper that passes an empty `mutex_types` set.
186/// Use `wrap_return_with_mutex` when the type set contains mutex-wrapped opaque types.
187pub fn wrap_return(
188    expr: &str,
189    return_type: &TypeRef,
190    type_name: &str,
191    opaque_types: &AHashSet<String>,
192    self_is_opaque: bool,
193    returns_ref: bool,
194    returns_cow: bool,
195) -> String {
196    wrap_return_with_mutex(
197        expr,
198        return_type,
199        type_name,
200        opaque_types,
201        &AHashSet::new(),
202        self_is_opaque,
203        returns_ref,
204        returns_cow,
205    )
206}
207
208/// Unwrap a newtype return value when `return_newtype_wrapper` is set.
209///
210/// Core function returns a newtype (e.g. `NodeIndex(u32)`), but the binding return type
211/// is the inner type (e.g. `u32`). Access `.0` to unwrap the newtype.
212pub fn apply_return_newtype_unwrap(expr: &str, return_newtype_wrapper: &Option<String>) -> String {
213    match return_newtype_wrapper {
214        Some(_) => format!("({expr}).0"),
215        None => expr.to_string(),
216    }
217}
218
219/// Build call argument expressions from parameters.
220/// - Opaque Named types: unwrap Arc wrapper via `(*param.inner).clone()`
221/// - Non-opaque Named types: `.into()` for From conversion
222/// - String/Path/Bytes: `&param` since core functions typically take `&str`/`&Path`/`&[u8]`
223/// - Params with `newtype_wrapper` set: re-wrap the raw value in the newtype constructor
224///   (e.g., `NodeIndex(parent)`) since the binding resolved `NodeIndex(u32)` → `u32`.
225///
226/// NOTE: This function does not perform serde-based conversion. For Named params that lack
227/// From impls (e.g., due to sanitized fields), use `gen_serde_let_bindings` instead when
228/// `cfg.has_serde` is true, or fall back to `gen_unimplemented_body`.
229pub fn gen_call_args(params: &[ParamDef], opaque_types: &AHashSet<String>) -> String {
230    params
231        .iter()
232        .enumerate()
233        .map(|(idx, p)| {
234            let promoted = crate::shared::is_promoted_optional(params, idx);
235            // If a required param was promoted to optional, unwrap it before use.
236            // Note: promoted params that are not Optional<T> will NOT call .expect() because
237            // promoted refers to the PyO3 signature constraint, not the actual Rust type.
238            // The function_params logic wraps promoted params in Option<T>, making them truly optional.
239            let unwrap_suffix = if promoted && p.optional {
240                format!(".expect(\"'{}' is required\")", p.name)
241            } else {
242                String::new()
243            };
244            // If this param's type was resolved from a newtype (e.g. NodeIndex(u32) → u32),
245            // re-wrap the raw value back into the newtype when calling core.
246            if let Some(newtype_path) = &p.newtype_wrapper {
247                return if p.optional {
248                    format!("{}.map({newtype_path})", p.name)
249                } else if promoted {
250                    format!("{newtype_path}({}{})", p.name, unwrap_suffix)
251                } else {
252                    format!("{newtype_path}({})", p.name)
253                };
254            }
255            match &p.ty {
256                TypeRef::Named(name) if opaque_types.contains(name.as_str()) => {
257                    // Opaque type: borrow through Arc to get &CoreType
258                    if p.optional {
259                        format!("{}.as_ref().map(|v| &v.inner)", p.name)
260                    } else if promoted {
261                        format!("{}{}.inner.as_ref()", p.name, unwrap_suffix)
262                    } else {
263                        format!("&{}.inner", p.name)
264                    }
265                }
266                TypeRef::Named(_) => {
267                    if p.optional {
268                        if p.is_ref {
269                            // Option<T> (binding) -> Option<&CoreT>: use as_ref() only
270                            // The Into conversion must happen in a let binding to avoid E0716
271                            format!("{}.as_ref()", p.name)
272                        } else {
273                            format!("{}.map(Into::into)", p.name)
274                        }
275                    } else if promoted {
276                        format!("{}{}.into()", p.name, unwrap_suffix)
277                    } else {
278                        format!("{}.into()", p.name)
279                    }
280                }
281                // String → &str for core function calls when is_ref=true,
282                // or pass owned when is_ref=false (core takes String/impl Into<String>).
283                // For optional params: as_deref() when is_ref=true, pass owned when is_ref=false.
284                TypeRef::String | TypeRef::Char => {
285                    if p.optional {
286                        if p.is_ref {
287                            format!("{}.as_deref()", p.name)
288                        } else {
289                            p.name.clone()
290                        }
291                    } else if promoted {
292                        if p.is_ref {
293                            format!("&{}{}", p.name, unwrap_suffix)
294                        } else {
295                            format!("{}{}", p.name, unwrap_suffix)
296                        }
297                    } else if p.is_ref {
298                        format!("&{}", p.name)
299                    } else {
300                        p.name.clone()
301                    }
302                }
303                // Path → PathBuf/&Path for core function calls
304                TypeRef::Path => {
305                    if p.optional && p.is_ref {
306                        format!("{}.as_deref().map(std::path::Path::new)", p.name)
307                    } else if p.optional {
308                        format!("{}.map(std::path::PathBuf::from)", p.name)
309                    } else if promoted {
310                        format!("std::path::PathBuf::from({}{})", p.name, unwrap_suffix)
311                    } else if p.is_ref {
312                        format!("std::path::Path::new(&{})", p.name)
313                    } else {
314                        format!("std::path::PathBuf::from({})", p.name)
315                    }
316                }
317                TypeRef::Bytes => {
318                    if p.optional {
319                        if p.is_ref {
320                            format!("{}.as_deref()", p.name)
321                        } else {
322                            p.name.clone()
323                        }
324                    } else if promoted {
325                        // is_ref=true: pass &Vec<u8> (core takes &[u8])
326                        // is_ref=false: pass Vec<u8> (core takes owned Vec<u8>)
327                        if p.is_ref {
328                            format!("&{}{}", p.name, unwrap_suffix)
329                        } else {
330                            format!("{}{}", p.name, unwrap_suffix)
331                        }
332                    } else {
333                        // is_ref=true: pass &Vec<u8> (core takes &[u8])
334                        // is_ref=false: pass Vec<u8> (core takes owned Vec<u8>)
335                        if p.is_ref {
336                            format!("&{}", p.name)
337                        } else {
338                            p.name.clone()
339                        }
340                    }
341                }
342                // Duration: binding uses u64 (millis), core uses std::time::Duration
343                TypeRef::Duration => {
344                    if p.optional {
345                        format!("{}.map(std::time::Duration::from_millis)", p.name)
346                    } else if promoted {
347                        format!("std::time::Duration::from_millis({}{})", p.name, unwrap_suffix)
348                    } else {
349                        format!("std::time::Duration::from_millis({})", p.name)
350                    }
351                }
352                TypeRef::Json => {
353                    // JSON params: binding has String, core expects serde_json::Value
354                    if p.optional {
355                        format!("{}.as_ref().and_then(|s| serde_json::from_str(s).ok())", p.name)
356                    } else if promoted {
357                        format!("serde_json::from_str(&{}{}).unwrap_or_default()", p.name, unwrap_suffix)
358                    } else {
359                        format!("serde_json::from_str(&{}).unwrap_or_default()", p.name)
360                    }
361                }
362                TypeRef::Vec(inner) => {
363                    // Vec<Named>: convert each element via Into::into when used with let bindings
364                    if matches!(inner.as_ref(), TypeRef::Named(_)) {
365                        if p.optional {
366                            if p.is_ref {
367                                format!("{}.as_deref()", p.name)
368                            } else {
369                                p.name.clone()
370                            }
371                        } else if promoted {
372                            if p.is_ref {
373                                format!("&{}{}", p.name, unwrap_suffix)
374                            } else {
375                                format!("{}{}", p.name, unwrap_suffix)
376                            }
377                        } else if p.is_ref {
378                            format!("&{}", p.name)
379                        } else {
380                            p.name.clone()
381                        }
382                    } else if promoted {
383                        format!("{}{}", p.name, unwrap_suffix)
384                    } else if p.is_mut && p.optional {
385                        format!("{}.as_deref_mut()", p.name)
386                    } else if p.is_mut {
387                        format!("&mut {}", p.name)
388                    } else if p.is_ref && p.optional {
389                        format!("{}.as_deref()", p.name)
390                    } else if p.is_ref {
391                        format!("&{}", p.name)
392                    } else {
393                        p.name.clone()
394                    }
395                }
396                _ => {
397                    if promoted {
398                        format!("{}{}", p.name, unwrap_suffix)
399                    } else if p.is_mut && p.optional {
400                        format!("{}.as_deref_mut()", p.name)
401                    } else if p.is_mut {
402                        format!("&mut {}", p.name)
403                    } else if p.is_ref && p.optional {
404                        // Optional ref params: use as_deref() for slice/str coercion
405                        // Option<Vec<T>> -> Option<&[T]>, Option<String> -> Option<&str>
406                        format!("{}.as_deref()", p.name)
407                    } else if p.is_ref {
408                        format!("&{}", p.name)
409                    } else {
410                        p.name.clone()
411                    }
412                }
413            }
414        })
415        .collect::<Vec<_>>()
416        .join(", ")
417}
418
419/// Build call argument expressions using pre-bound let bindings for non-opaque Named params.
420/// Non-opaque Named params use `&{name}_core` references instead of `.into()`.
421pub fn gen_call_args_with_let_bindings(params: &[ParamDef], opaque_types: &AHashSet<String>) -> String {
422    params
423        .iter()
424        .enumerate()
425        .map(|(idx, p)| {
426            let promoted = crate::shared::is_promoted_optional(params, idx);
427            let unwrap_suffix = if promoted {
428                format!(".expect(\"'{}' is required\")", p.name)
429            } else {
430                String::new()
431            };
432            // If this param's type was resolved from a newtype, re-wrap when calling core.
433            if let Some(newtype_path) = &p.newtype_wrapper {
434                return if p.optional {
435                    format!("{}.map({newtype_path})", p.name)
436                } else if promoted {
437                    format!("{newtype_path}({}{})", p.name, unwrap_suffix)
438                } else {
439                    format!("{newtype_path}({})", p.name)
440                };
441            }
442            match &p.ty {
443                TypeRef::Named(name) if opaque_types.contains(name.as_str()) => {
444                    if p.optional {
445                        format!("{}.as_ref().map(|v| &v.inner)", p.name)
446                    } else if promoted {
447                        format!("{}{}.inner.as_ref()", p.name, unwrap_suffix)
448                    } else {
449                        format!("&{}.inner", p.name)
450                    }
451                }
452                TypeRef::Named(_) => {
453                    if p.optional && p.is_ref {
454                        // Let binding already created Option<&T> via .as_ref()
455                        format!("{}_core", p.name)
456                    } else if p.is_ref {
457                        // Let binding created T, need reference for call
458                        format!("&{}_core", p.name)
459                    } else {
460                        format!("{}_core", p.name)
461                    }
462                }
463                TypeRef::String | TypeRef::Char => {
464                    if p.optional {
465                        if p.is_ref {
466                            format!("{}.as_deref()", p.name)
467                        } else {
468                            p.name.clone()
469                        }
470                    } else if promoted {
471                        if p.is_ref {
472                            format!("&{}{}", p.name, unwrap_suffix)
473                        } else {
474                            format!("{}{}", p.name, unwrap_suffix)
475                        }
476                    } else if p.is_ref {
477                        format!("&{}", p.name)
478                    } else {
479                        p.name.clone()
480                    }
481                }
482                TypeRef::Path => {
483                    if promoted {
484                        format!("std::path::PathBuf::from({}{})", p.name, unwrap_suffix)
485                    } else if p.optional && p.is_ref {
486                        format!("{}.as_deref().map(std::path::Path::new)", p.name)
487                    } else if p.optional {
488                        format!("{}.map(std::path::PathBuf::from)", p.name)
489                    } else if p.is_ref {
490                        format!("std::path::Path::new(&{})", p.name)
491                    } else {
492                        format!("std::path::PathBuf::from({})", p.name)
493                    }
494                }
495                TypeRef::Bytes => {
496                    if p.optional {
497                        if p.is_ref {
498                            format!("{}.as_deref()", p.name)
499                        } else {
500                            p.name.clone()
501                        }
502                    } else if promoted {
503                        // is_ref=true: pass &Vec<u8> (core takes &[u8])
504                        // is_ref=false: pass Vec<u8> (core takes owned Vec<u8>)
505                        if p.is_ref {
506                            format!("&{}{}", p.name, unwrap_suffix)
507                        } else {
508                            format!("{}{}", p.name, unwrap_suffix)
509                        }
510                    } else {
511                        // is_ref=true: pass &Vec<u8> (core takes &[u8])
512                        // is_ref=false: pass Vec<u8> (core takes owned Vec<u8>)
513                        if p.is_ref {
514                            format!("&{}", p.name)
515                        } else {
516                            p.name.clone()
517                        }
518                    }
519                }
520                TypeRef::Duration => {
521                    if p.optional {
522                        format!("{}.map(std::time::Duration::from_millis)", p.name)
523                    } else if promoted {
524                        format!("std::time::Duration::from_millis({}{})", p.name, unwrap_suffix)
525                    } else {
526                        format!("std::time::Duration::from_millis({})", p.name)
527                    }
528                }
529                TypeRef::Vec(inner) => {
530                    // Vec<Named>: use let binding that converts each element
531                    if matches!(inner.as_ref(), TypeRef::Named(_)) {
532                        if p.optional && p.is_ref {
533                            // Let binding creates Option<Vec<CoreType>>, use as_deref() to get Option<&[CoreType]>
534                            format!("{}_core.as_deref()", p.name)
535                        } else if p.optional {
536                            // Let binding creates Option<Vec<CoreType>>, no ref needed
537                            format!("{}_core", p.name)
538                        } else if p.is_ref {
539                            format!("&{}_core", p.name)
540                        } else {
541                            format!("{}_core", p.name)
542                        }
543                    } else if matches!(inner.as_ref(), TypeRef::String | TypeRef::Char) && p.is_ref {
544                        // Vec<String> with is_ref=true: core expects &[&str].
545                        // Let binding created {name}_refs: Vec<&str> (or Option<Vec<&str>>).
546                        // Pass &{name}_refs to coerce Vec<&str> -> &[&str].
547                        if p.optional {
548                            format!("{}_refs.as_deref()", p.name)
549                        } else {
550                            format!("&{}_refs", p.name)
551                        }
552                    } else if promoted {
553                        format!("{}{}", p.name, unwrap_suffix)
554                    } else if p.is_ref && p.optional {
555                        format!("{}.as_deref()", p.name)
556                    } else if p.is_ref {
557                        format!("&{}", p.name)
558                    } else {
559                        p.name.clone()
560                    }
561                }
562                _ => {
563                    if promoted {
564                        format!("{}{}", p.name, unwrap_suffix)
565                    } else if p.is_ref && p.optional {
566                        format!("{}.as_deref()", p.name)
567                    } else if p.is_ref {
568                        format!("&{}", p.name)
569                    } else {
570                        p.name.clone()
571                    }
572                }
573            }
574        })
575        .collect::<Vec<_>>()
576        .join(", ")
577}
578
579/// Generate let bindings for non-opaque Named params, converting them to core types.
580pub fn gen_named_let_bindings_pub(params: &[ParamDef], opaque_types: &AHashSet<String>, core_import: &str) -> String {
581    gen_named_let_bindings(params, opaque_types, core_import)
582}
583
584/// Like `gen_named_let_bindings_pub` but without optional-promotion semantics.
585/// Use this for backends (e.g. WASM) that do not promote non-optional params to `Option<T>`.
586pub fn gen_named_let_bindings_no_promote(
587    params: &[ParamDef],
588    opaque_types: &AHashSet<String>,
589    core_import: &str,
590) -> String {
591    gen_named_let_bindings_inner(params, opaque_types, core_import, false)
592}
593
594pub(super) fn gen_named_let_bindings(
595    params: &[ParamDef],
596    opaque_types: &AHashSet<String>,
597    core_import: &str,
598) -> String {
599    gen_named_let_bindings_inner(params, opaque_types, core_import, true)
600}
601
602fn gen_named_let_bindings_inner(
603    params: &[ParamDef],
604    opaque_types: &AHashSet<String>,
605    core_import: &str,
606    promote: bool,
607) -> String {
608    let mut bindings = String::new();
609    for (idx, p) in params.iter().enumerate() {
610        match &p.ty {
611            TypeRef::Named(name) if !opaque_types.contains(name.as_str()) => {
612                let promoted = promote && crate::shared::is_promoted_optional(params, idx);
613                let core_type_path = format!("{}::{}", core_import, name);
614                if p.optional {
615                    if p.is_ref {
616                        // Option<T> (binding) -> Option<&CoreT> (core expects reference to core type)
617                        // Split into two bindings to avoid temporary value dropped while borrowed (E0716)
618                        write!(
619                            bindings,
620                            "let {name}_owned: Option<{core_type_path}> = {name}.map(Into::into);\n    let {name}_core = {name}_owned.as_ref();\n    ",
621                            name = p.name
622                        )
623                        .ok();
624                    } else {
625                        write!(
626                            bindings,
627                            "let {}_core: Option<{core_type_path}> = {}.map(Into::into);\n    ",
628                            p.name, p.name
629                        )
630                        .ok();
631                    }
632                } else if promoted {
633                    // Promoted-optional: unwrap then convert. Add explicit type annotation to help type inference.
634                    write!(
635                        bindings,
636                        "let {}_core: {core_type_path} = {}.expect(\"'{}' is required\").into();\n    ",
637                        p.name, p.name, p.name
638                    )
639                    .ok();
640                } else {
641                    // Non-optional: add explicit type annotation to help type inference
642                    write!(
643                        bindings,
644                        "let {}_core: {core_type_path} = {}.into();\n    ",
645                        p.name, p.name
646                    )
647                    .ok();
648                }
649            }
650            TypeRef::Vec(inner) if matches!(inner.as_ref(), TypeRef::Named(n) if !opaque_types.contains(n.as_str())) => {
651                let promoted = promote && crate::shared::is_promoted_optional(params, idx);
652                if p.optional && p.is_ref {
653                    // Option<Vec<Named>> with is_ref: convert to Option<Vec<CoreType>>, then use as_deref()
654                    // This ensures elements are converted from binding to core type.
655                    write!(
656                        bindings,
657                        "let {}_core: Option<Vec<_>> = {}.as_ref().map(|v| v.iter().map(|x| x.clone().into()).collect());\n    ",
658                        p.name, p.name
659                    )
660                    .ok();
661                } else if p.optional {
662                    // Option<Vec<Named>> without is_ref: convert to concrete Vec
663                    write!(
664                        bindings,
665                        "let {}_core = {}.as_ref().map(|v| v.iter().map(|x| x.clone().into()).collect()).unwrap_or_default();\n    ",
666                        p.name, p.name
667                    )
668                    .ok();
669                } else if promoted {
670                    // Promoted-optional: unwrap then convert
671                    write!(
672                        bindings,
673                        "let {}_core: Vec<_> = {}.expect(\"'{}' is required\").into_iter().map(Into::into).collect();\n    ",
674                        p.name, p.name, p.name
675                    )
676                    .ok();
677                } else if p.is_ref {
678                    // Non-optional Vec<Named> with is_ref=true: generate let binding for conversion
679                    write!(
680                        bindings,
681                        "let {}_core: Vec<_> = {}.into_iter().map(Into::into).collect();\n    ",
682                        p.name, p.name
683                    )
684                    .ok();
685                } else {
686                    // Vec<Named>: convert each element
687                    write!(
688                        bindings,
689                        "let {}_core: Vec<_> = {}.into_iter().map(Into::into).collect();\n    ",
690                        p.name, p.name
691                    )
692                    .ok();
693                }
694            }
695            // Vec<String> with is_ref=true: core expects &[&str] but binding holds Vec<String>.
696            // Generate a Vec<&str> intermediate so &{name}_refs coerces to &[&str].
697            // For Option<Vec<String>>, unwrap first then convert each element.
698            TypeRef::Vec(inner) if matches!(inner.as_ref(), TypeRef::String | TypeRef::Char) && p.is_ref => {
699                if p.optional {
700                    // Option<Vec<String>> -> unwrap_or_default() -> Vec<&str>
701                    write!(
702                        bindings,
703                        "let {}_core: Vec<String> = {}.clone().unwrap_or_default();\n    let {}_refs: Vec<&str> = {}_core.iter().map(|s| s.as_str()).collect();\n    ",
704                        p.name, p.name, p.name, p.name
705                    )
706                    .ok();
707                } else {
708                    write!(
709                        bindings,
710                        "let {}_refs: Vec<&str> = {}.iter().map(|s| s.as_str()).collect();\n    ",
711                        p.name, p.name
712                    )
713                    .ok();
714                }
715            }
716            _ => {}
717        }
718    }
719    bindings
720}
721
722/// Generate serde-based let bindings for non-opaque Named params.
723/// Serializes binding types to JSON and deserializes to core types.
724/// Used when From impls don't exist (e.g., types with sanitized fields).
725/// `indent` is the whitespace prefix for each generated line (e.g., "    " for functions, "        " for methods).
726/// NOTE: This function should only be called when `cfg.has_serde` is true.
727/// The caller (functions.rs, methods.rs) must gate the call behind a `has_serde` check.
728pub fn gen_serde_let_bindings(
729    params: &[ParamDef],
730    opaque_types: &AHashSet<String>,
731    core_import: &str,
732    err_conv: &str,
733    indent: &str,
734) -> String {
735    let mut bindings = String::new();
736    for p in params {
737        match &p.ty {
738            TypeRef::Named(name) if !opaque_types.contains(name.as_str()) => {
739                let core_path = format!("{}::{}", core_import, name);
740                if p.optional {
741                    write!(
742                        bindings,
743                        "let {name}_core: Option<{core_path}> = {name}.map(|v| {{\n\
744                         {indent}    let json = serde_json::to_string(&v){err_conv}?;\n\
745                         {indent}    serde_json::from_str(&json){err_conv}\n\
746                         {indent}}}).transpose()?;\n{indent}",
747                        name = p.name,
748                        core_path = core_path,
749                        err_conv = err_conv,
750                        indent = indent,
751                    )
752                    .ok();
753                } else {
754                    write!(
755                        bindings,
756                        "let {name}_json = serde_json::to_string(&{name}){err_conv}?;\n\
757                         {indent}let {name}_core: {core_path} = serde_json::from_str(&{name}_json){err_conv}?;\n{indent}",
758                        name = p.name,
759                        core_path = core_path,
760                        err_conv = err_conv,
761                        indent = indent,
762                    )
763                    .ok();
764                }
765            }
766            TypeRef::Vec(inner) => {
767                if let TypeRef::Named(name) = inner.as_ref() {
768                    if !opaque_types.contains(name.as_str()) {
769                        let core_path = format!("{}::{}", core_import, name);
770                        if p.optional {
771                            write!(
772                                bindings,
773                                "let {name}_core: Option<Vec<{core_path}>> = {name}.map(|v| {{\n\
774                                 {indent}    let json = serde_json::to_string(&v){err_conv}?;\n\
775                                 {indent}    serde_json::from_str(&json){err_conv}\n\
776                                 {indent}}}).transpose()?;\n{indent}",
777                                name = p.name,
778                                core_path = core_path,
779                                err_conv = err_conv,
780                                indent = indent,
781                            )
782                            .ok();
783                        } else {
784                            write!(
785                                bindings,
786                                "let {name}_json = serde_json::to_string(&{name}){err_conv}?;\n\
787                                 {indent}let {name}_core: Vec<{core_path}> = serde_json::from_str(&{name}_json){err_conv}?;\n{indent}",
788                                name = p.name,
789                                core_path = core_path,
790                                err_conv = err_conv,
791                                indent = indent,
792                            )
793                            .ok();
794                        }
795                    }
796                }
797            }
798            _ => {}
799        }
800    }
801    bindings
802}
803
804/// Check if params contain any non-opaque Named types that need let bindings.
805/// This includes direct Named types, Vec<Named> types, and Vec<String> params
806/// with is_ref=true (which need a Vec<&str> intermediate to pass as &[&str]).
807pub fn has_named_params(params: &[ParamDef], opaque_types: &AHashSet<String>) -> bool {
808    params.iter().any(|p| match &p.ty {
809        TypeRef::Named(name) if !opaque_types.contains(name.as_str()) => true,
810        TypeRef::Vec(inner) => {
811            // Vec<Named> always needs a conversion let binding.
812            // Vec<String> with is_ref=true needs a Vec<&str> intermediate for &[&str] coercion.
813            matches!(inner.as_ref(), TypeRef::Named(name) if !opaque_types.contains(name.as_str()))
814                || (matches!(inner.as_ref(), TypeRef::String | TypeRef::Char) && p.is_ref)
815        }
816        _ => false,
817    })
818}
819
820/// Check if a param type is safe for non-opaque delegation (no complex conversions needed).
821/// Vec and Map params can cause type mismatches (e.g. Vec<String> vs &[&str]).
822pub fn is_simple_non_opaque_param(ty: &TypeRef) -> bool {
823    match ty {
824        TypeRef::Primitive(_)
825        | TypeRef::String
826        | TypeRef::Char
827        | TypeRef::Bytes
828        | TypeRef::Path
829        | TypeRef::Unit
830        | TypeRef::Duration => true,
831        TypeRef::Optional(inner) => is_simple_non_opaque_param(inner),
832        _ => false,
833    }
834}
835
836/// Generate a lossy binding→core struct literal for non-opaque delegation.
837/// Sanitized fields use `Default::default()`, non-sanitized fields are cloned and converted.
838/// Fields are accessed via `self.` (behind &self), so all non-Copy types need `.clone()`.
839///
840/// NOTE: This assumes all binding struct fields implement Clone. If a field type does not
841/// implement Clone (e.g., `Mutex<T>`), it should be marked as `sanitized=true` so that
842/// `Default::default()` is used instead of calling `.clone()`. Backends that exclude types
843/// should mark such fields appropriately.
844pub fn gen_lossy_binding_to_core_fields(typ: &TypeDef, core_import: &str, option_duration_on_defaults: bool) -> String {
845    gen_lossy_binding_to_core_fields_inner(typ, core_import, false, option_duration_on_defaults)
846}
847
848/// Same as `gen_lossy_binding_to_core_fields` but declares `core_self` as mutable.
849pub fn gen_lossy_binding_to_core_fields_mut(
850    typ: &TypeDef,
851    core_import: &str,
852    option_duration_on_defaults: bool,
853) -> String {
854    gen_lossy_binding_to_core_fields_inner(typ, core_import, true, option_duration_on_defaults)
855}
856
857fn gen_lossy_binding_to_core_fields_inner(
858    typ: &TypeDef,
859    core_import: &str,
860    needs_mut: bool,
861    option_duration_on_defaults: bool,
862) -> String {
863    let core_path = crate::conversions::core_type_path(typ, core_import);
864    let mut_kw = if needs_mut { "mut " } else { "" };
865    // When has_stripped_cfg_fields is true we emit ..Default::default() at the end of the
866    // struct literal to fill cfg-gated fields that were stripped from the binding IR.
867    // Suppress clippy::needless_update because the fields only exist when the corresponding
868    // feature is enabled — without the feature, clippy thinks the spread is redundant.
869    let allow = if typ.has_stripped_cfg_fields {
870        "#[allow(clippy::needless_update)]\n        "
871    } else {
872        ""
873    };
874    let mut out = format!("{allow}let {mut_kw}core_self = {core_path} {{\n");
875    for field in &typ.fields {
876        let name = &field.name;
877        if field.sanitized {
878            writeln!(out, "            {name}: Default::default(),").ok();
879        } else {
880            let expr = match &field.ty {
881                TypeRef::Primitive(_) => format!("self.{name}"),
882                TypeRef::Duration => {
883                    if field.optional {
884                        format!("self.{name}.map(std::time::Duration::from_millis)")
885                    } else if option_duration_on_defaults && typ.has_default {
886                        // When option_duration_on_defaults is true, non-optional Duration fields
887                        // on has_default types are stored as Option<u64> in the binding struct.
888                        // Use .map(...).unwrap_or_default() so that None falls back to the core
889                        // type's Default (e.g. Duration::from_secs(30)) rather than Duration::ZERO.
890                        format!("self.{name}.map(std::time::Duration::from_millis).unwrap_or_default()")
891                    } else {
892                        format!("std::time::Duration::from_millis(self.{name})")
893                    }
894                }
895                TypeRef::String => format!("self.{name}.clone()"),
896                // Bytes: binding stores Vec<u8>. When core_wrapper == Bytes, core expects
897                // bytes::Bytes so we must call .into() to convert Vec<u8> → Bytes.
898                // When core_wrapper == None, the core field is also Vec<u8> (plain clone).
899                TypeRef::Bytes => {
900                    if field.core_wrapper == CoreWrapper::Bytes {
901                        format!("self.{name}.clone().into()")
902                    } else {
903                        format!("self.{name}.clone()")
904                    }
905                }
906                TypeRef::Char => {
907                    if field.optional {
908                        format!("self.{name}.as_ref().and_then(|s| s.chars().next())")
909                    } else {
910                        format!("self.{name}.chars().next().unwrap_or('*')")
911                    }
912                }
913                TypeRef::Path => {
914                    if field.optional {
915                        format!("self.{name}.clone().map(Into::into)")
916                    } else {
917                        format!("self.{name}.clone().into()")
918                    }
919                }
920                TypeRef::Named(_) => {
921                    if field.optional {
922                        format!("self.{name}.clone().map(Into::into)")
923                    } else {
924                        format!("self.{name}.clone().into()")
925                    }
926                }
927                TypeRef::Vec(inner) => match inner.as_ref() {
928                    TypeRef::Named(_) => {
929                        if field.optional {
930                            // Option<Vec<Named(T)>>: map over the Option, then convert each element
931                            format!("self.{name}.clone().map(|v| v.into_iter().map(Into::into).collect())")
932                        } else {
933                            format!("self.{name}.clone().into_iter().map(Into::into).collect()")
934                        }
935                    }
936                    _ => format!("self.{name}.clone()"),
937                },
938                TypeRef::Optional(inner) => {
939                    // When field.optional is also true, the binding field was flattened from
940                    // Option<Option<T>> to Option<T>. Core expects Option<Option<T>>, so wrap
941                    // with .map(Some) to reconstruct the double-optional.
942                    let base = match inner.as_ref() {
943                        TypeRef::Named(_) => {
944                            format!("self.{name}.clone().map(Into::into)")
945                        }
946                        TypeRef::Duration => {
947                            format!("self.{name}.map(|v| std::time::Duration::from_millis(v as u64))")
948                        }
949                        TypeRef::Vec(vi) if matches!(vi.as_ref(), TypeRef::Named(_)) => {
950                            format!("self.{name}.clone().map(|v| v.into_iter().map(Into::into).collect())")
951                        }
952                        _ => format!("self.{name}.clone()"),
953                    };
954                    if field.optional {
955                        format!("({base}).map(Some)")
956                    } else {
957                        base
958                    }
959                }
960                TypeRef::Map(_, v) => match v.as_ref() {
961                    TypeRef::Json => {
962                        // HashMap<String, String> (binding) → HashMap<String, Value> (core)
963                        if field.optional {
964                            format!(
965                                "self.{name}.clone().map(|m| m.into_iter().map(|(k, v)| \
966                                 (k, serde_json::from_str(&v).unwrap_or(serde_json::Value::String(v)))).collect())"
967                            )
968                        } else {
969                            format!(
970                                "self.{name}.clone().into_iter().map(|(k, v)| \
971                                 (k, serde_json::from_str(&v).unwrap_or(serde_json::Value::String(v)))).collect()"
972                            )
973                        }
974                    }
975                    // Collect to handle HashMap↔BTreeMap conversion
976                    _ => {
977                        if field.optional {
978                            format!("self.{name}.clone().map(|m| m.into_iter().collect())")
979                        } else {
980                            format!("self.{name}.clone().into_iter().collect()")
981                        }
982                    }
983                },
984                TypeRef::Unit => format!("self.{name}.clone()"),
985                TypeRef::Json => {
986                    // String (binding) → serde_json::Value (core)
987                    if field.optional {
988                        format!("self.{name}.as_ref().and_then(|s| serde_json::from_str(s).ok())")
989                    } else {
990                        format!("serde_json::from_str(&self.{name}).unwrap_or_default()")
991                    }
992                }
993            };
994            // Newtype wrapping: when the field was resolved from a newtype (e.g. NodeIndex → u32),
995            // re-wrap the binding value into the newtype for the core struct literal.
996            // When `optional=true` and `ty` is a plain Primitive (not TypeRef::Optional), the core
997            // field is actually `Option<NewtypeT>`, so we must use `.map(NewtypeT)` not `NewtypeT(...)`.
998            let expr = if let Some(newtype_path) = &field.newtype_wrapper {
999                match &field.ty {
1000                    TypeRef::Optional(_) => format!("({expr}).map({newtype_path})"),
1001                    TypeRef::Vec(_) => format!("({expr}).into_iter().map({newtype_path}).collect()"),
1002                    _ if field.optional => format!("({expr}).map({newtype_path})"),
1003                    _ => format!("{newtype_path}({expr})"),
1004                }
1005            } else {
1006                expr
1007            };
1008            writeln!(out, "            {name}: {expr},").ok();
1009        }
1010    }
1011    // Use ..Default::default() to fill cfg-gated fields stripped from the IR
1012    if typ.has_stripped_cfg_fields {
1013        out.push_str("            ..Default::default()\n");
1014    }
1015    out.push_str("        };\n        ");
1016    out
1017}
1018
1019/// Generate the body for an async call, unified across methods, static methods, and free functions.
1020///
1021/// - `core_call`: the expression to await, e.g. `inner.method(args)` or `CoreType::fn(args)`.
1022///   For Pyo3FutureIntoPy opaque methods this should reference `inner` (the Arc clone);
1023///   for all other patterns it may reference `self.inner` or a static call expression.
1024/// - `cfg`: binding configuration (determines which async pattern to emit)
1025/// - `has_error`: whether the core call returns a `Result`
1026/// - `return_wrap`: expression to produce the binding return value from `result`,
1027///   e.g. `"result"` or `"TypeName::from(result)"`
1028///
1029/// - `is_opaque`: whether the binding type is Arc-wrapped (affects TokioBlockOn wrapping)
1030/// - `inner_clone_line`: optional statement emitted before the pattern-specific body,
1031///   e.g. `"let inner = self.inner.clone();\n        "` for opaque instance methods, or `""`.
1032///   Required when `core_call` references `inner` (Pyo3FutureIntoPy opaque case).
1033#[allow(clippy::too_many_arguments)]
1034pub fn gen_async_body(
1035    core_call: &str,
1036    cfg: &RustBindingConfig,
1037    has_error: bool,
1038    return_wrap: &str,
1039    is_opaque: bool,
1040    inner_clone_line: &str,
1041    is_unit_return: bool,
1042    return_type: Option<&str>,
1043) -> String {
1044    let pattern_body = match cfg.async_pattern {
1045        AsyncPattern::Pyo3FutureIntoPy => {
1046            let result_handling = if has_error {
1047                format!(
1048                    "let result = {core_call}.await\n            \
1049                     .map_err(|e| PyErr::new::<PyRuntimeError, _>(e.to_string()))?;"
1050                )
1051            } else if is_unit_return {
1052                format!("{core_call}.await;")
1053            } else {
1054                format!("let result = {core_call}.await;")
1055            };
1056            let (ok_expr, extra_binding) = if is_unit_return && !has_error {
1057                ("()".to_string(), String::new())
1058            } else if return_wrap.contains(".into()") || return_wrap.contains("::from(") {
1059                // When return_wrap contains type conversions like .into() or ::from(),
1060                // bind to a variable to help type inference for the generic future_into_py.
1061                // This avoids E0283 "type annotations needed".
1062                let wrapped_var = "wrapped_result";
1063                let binding = if let Some(ret_type) = return_type {
1064                    // Add explicit type annotation to help type inference
1065                    format!("let {wrapped_var}: {ret_type} = {return_wrap};\n            ")
1066                } else {
1067                    format!("let {wrapped_var} = {return_wrap};\n            ")
1068                };
1069                (wrapped_var.to_string(), binding)
1070            } else {
1071                (return_wrap.to_string(), String::new())
1072            };
1073            format!(
1074                "pyo3_async_runtimes::tokio::future_into_py(py, async move {{\n            \
1075                 {result_handling}\n            \
1076                 {extra_binding}Ok({ok_expr})\n        }})"
1077            )
1078        }
1079        AsyncPattern::WasmNativeAsync => {
1080            let result_handling = if has_error {
1081                format!(
1082                    "let result = {core_call}.await\n        \
1083                     .map_err(|e| JsValue::from_str(&e.to_string()))?;"
1084                )
1085            } else if is_unit_return {
1086                format!("{core_call}.await;")
1087            } else {
1088                format!("let result = {core_call}.await;")
1089            };
1090            let ok_expr = if is_unit_return && !has_error {
1091                "()"
1092            } else {
1093                return_wrap
1094            };
1095            format!(
1096                "{result_handling}\n        \
1097                 Ok({ok_expr})"
1098            )
1099        }
1100        AsyncPattern::NapiNativeAsync => {
1101            let result_handling = if has_error {
1102                format!(
1103                    "let result = {core_call}.await\n            \
1104                     .map_err(|e| napi::Error::new(napi::Status::GenericFailure, e.to_string()))?;"
1105                )
1106            } else if is_unit_return {
1107                format!("{core_call}.await;")
1108            } else {
1109                format!("let result = {core_call}.await;")
1110            };
1111            if !has_error && !is_unit_return {
1112                // No error type: return value directly without Ok() wrapper
1113                format!(
1114                    "{result_handling}\n            \
1115                     {return_wrap}"
1116                )
1117            } else {
1118                let ok_expr = if is_unit_return && !has_error {
1119                    "()"
1120                } else {
1121                    return_wrap
1122                };
1123                format!(
1124                    "{result_handling}\n            \
1125                     Ok({ok_expr})"
1126                )
1127            }
1128        }
1129        AsyncPattern::TokioBlockOn => {
1130            if has_error {
1131                if is_opaque {
1132                    format!(
1133                        "let rt = tokio::runtime::Runtime::new()?;\n        \
1134                         let result = rt.block_on(async {{ {core_call}.await.map_err(|e| e.into()) }})?;\n        \
1135                         {return_wrap}"
1136                    )
1137                } else {
1138                    format!(
1139                        "let rt = tokio::runtime::Runtime::new()?;\n        \
1140                         rt.block_on(async {{ {core_call}.await.map_err(|e| e.into()) }})"
1141                    )
1142                }
1143            } else if is_opaque {
1144                if is_unit_return {
1145                    format!(
1146                        "let rt = tokio::runtime::Runtime::new()?;\n        \
1147                         rt.block_on(async {{ {core_call}.await }});"
1148                    )
1149                } else {
1150                    format!(
1151                        "let rt = tokio::runtime::Runtime::new()?;\n        \
1152                         let result = rt.block_on(async {{ {core_call}.await }});\n        \
1153                         {return_wrap}"
1154                    )
1155                }
1156            } else {
1157                format!(
1158                    "let rt = tokio::runtime::Runtime::new()?;\n        \
1159                     rt.block_on(async {{ {core_call}.await }})"
1160                )
1161            }
1162        }
1163        AsyncPattern::None => "todo!(\"async not supported by backend\")".to_string(),
1164    };
1165    if inner_clone_line.is_empty() {
1166        pattern_body
1167    } else {
1168        format!("{inner_clone_line}{pattern_body}")
1169    }
1170}
1171
1172/// Generate a compilable body for functions that can't be auto-delegated.
1173/// Returns a default value or error instead of `todo!()` which would panic.
1174///
1175/// `opaque_types` is the set of opaque type names (Arc-wrapped). Opaque types do not
1176/// implement `Default`, so returning `Default::default()` for their Named return types
1177/// would fail to compile. For those cases a `todo!()` body is emitted instead.
1178pub fn gen_unimplemented_body(
1179    return_type: &TypeRef,
1180    fn_name: &str,
1181    has_error: bool,
1182    cfg: &RustBindingConfig,
1183    params: &[ParamDef],
1184    opaque_types: &AHashSet<String>,
1185) -> String {
1186    // Suppress unused_variables by binding all params to `_`
1187    let suppress = if params.is_empty() {
1188        String::new()
1189    } else {
1190        let names: Vec<&str> = params.iter().map(|p| p.name.as_str()).collect();
1191        if names.len() == 1 {
1192            format!("let _ = {};\n        ", names[0])
1193        } else {
1194            format!("let _ = ({});\n        ", names.join(", "))
1195        }
1196    };
1197    let err_msg = format!("Not implemented: {fn_name}");
1198    let body = if has_error {
1199        // Backend-specific error return
1200        match cfg.async_pattern {
1201            AsyncPattern::Pyo3FutureIntoPy => {
1202                format!("Err(pyo3::exceptions::PyNotImplementedError::new_err(\"{err_msg}\"))")
1203            }
1204            AsyncPattern::NapiNativeAsync => {
1205                format!("Err(napi::Error::new(napi::Status::GenericFailure, \"{err_msg}\"))")
1206            }
1207            AsyncPattern::WasmNativeAsync => {
1208                format!("Err(JsValue::from_str(\"{err_msg}\"))")
1209            }
1210            _ => format!("Err(\"{err_msg}\".to_string())"),
1211        }
1212    } else {
1213        // Return type-appropriate default
1214        match return_type {
1215            TypeRef::Unit => "()".to_string(),
1216            TypeRef::String | TypeRef::Char | TypeRef::Path => format!("String::from(\"[unimplemented: {fn_name}]\")"),
1217            TypeRef::Bytes => "Vec::new()".to_string(),
1218            TypeRef::Primitive(p) => match p {
1219                alef_core::ir::PrimitiveType::Bool => "false".to_string(),
1220                alef_core::ir::PrimitiveType::F32 => "0.0f32".to_string(),
1221                alef_core::ir::PrimitiveType::F64 => "0.0f64".to_string(),
1222                _ => "0".to_string(),
1223            },
1224            TypeRef::Optional(_) => "None".to_string(),
1225            TypeRef::Vec(_) => "Vec::new()".to_string(),
1226            TypeRef::Map(_, _) => "Default::default()".to_string(),
1227            TypeRef::Duration => "0".to_string(),
1228            TypeRef::Named(name) => {
1229                // Opaque types (Arc-wrapped) do not implement Default — use todo!() to
1230                // produce a compilable placeholder that panics at runtime if called.
1231                // Non-opaque Named types (config structs) do derive Default, so use that.
1232                if opaque_types.contains(name.as_str()) {
1233                    format!("todo!(\"{err_msg}\")")
1234                } else {
1235                    "Default::default()".to_string()
1236                }
1237            }
1238            TypeRef::Json => {
1239                // Json return without error type: return Default::default()
1240                "Default::default()".to_string()
1241            }
1242        }
1243    };
1244    format!("{suppress}{body}")
1245}