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: `¶m` 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 TypeRef::Vec(inner) if matches!(inner.as_ref(), TypeRef::String | TypeRef::Char) && p.is_ref => {
698 if p.optional {
699 write!(
700 bindings,
701 "let {}_refs: Option<Vec<&str>> = {}.as_ref().map(|v| v.iter().map(|s| s.as_str()).collect());\n ",
702 p.name, p.name
703 )
704 .ok();
705 } else {
706 write!(
707 bindings,
708 "let {}_refs: Vec<&str> = {}.iter().map(|s| s.as_str()).collect();\n ",
709 p.name, p.name
710 )
711 .ok();
712 }
713 }
714 _ => {}
715 }
716 }
717 bindings
718}
719
720/// Generate serde-based let bindings for non-opaque Named params.
721/// Serializes binding types to JSON and deserializes to core types.
722/// Used when From impls don't exist (e.g., types with sanitized fields).
723/// `indent` is the whitespace prefix for each generated line (e.g., " " for functions, " " for methods).
724/// NOTE: This function should only be called when `cfg.has_serde` is true.
725/// The caller (functions.rs, methods.rs) must gate the call behind a `has_serde` check.
726pub fn gen_serde_let_bindings(
727 params: &[ParamDef],
728 opaque_types: &AHashSet<String>,
729 core_import: &str,
730 err_conv: &str,
731 indent: &str,
732) -> String {
733 let mut bindings = String::new();
734 for p in params {
735 match &p.ty {
736 TypeRef::Named(name) if !opaque_types.contains(name.as_str()) => {
737 let core_path = format!("{}::{}", core_import, name);
738 if p.optional {
739 write!(
740 bindings,
741 "let {name}_core: Option<{core_path}> = {name}.map(|v| {{\n\
742 {indent} let json = serde_json::to_string(&v){err_conv}?;\n\
743 {indent} serde_json::from_str(&json){err_conv}\n\
744 {indent}}}).transpose()?;\n{indent}",
745 name = p.name,
746 core_path = core_path,
747 err_conv = err_conv,
748 indent = indent,
749 )
750 .ok();
751 } else {
752 write!(
753 bindings,
754 "let {name}_json = serde_json::to_string(&{name}){err_conv}?;\n\
755 {indent}let {name}_core: {core_path} = serde_json::from_str(&{name}_json){err_conv}?;\n{indent}",
756 name = p.name,
757 core_path = core_path,
758 err_conv = err_conv,
759 indent = indent,
760 )
761 .ok();
762 }
763 }
764 TypeRef::Vec(inner) => {
765 if let TypeRef::Named(name) = inner.as_ref() {
766 if !opaque_types.contains(name.as_str()) {
767 let core_path = format!("{}::{}", core_import, name);
768 if p.optional {
769 write!(
770 bindings,
771 "let {name}_core: Option<Vec<{core_path}>> = {name}.map(|v| {{\n\
772 {indent} let json = serde_json::to_string(&v){err_conv}?;\n\
773 {indent} serde_json::from_str(&json){err_conv}\n\
774 {indent}}}).transpose()?;\n{indent}",
775 name = p.name,
776 core_path = core_path,
777 err_conv = err_conv,
778 indent = indent,
779 )
780 .ok();
781 } else {
782 write!(
783 bindings,
784 "let {name}_json = serde_json::to_string(&{name}){err_conv}?;\n\
785 {indent}let {name}_core: Vec<{core_path}> = serde_json::from_str(&{name}_json){err_conv}?;\n{indent}",
786 name = p.name,
787 core_path = core_path,
788 err_conv = err_conv,
789 indent = indent,
790 )
791 .ok();
792 }
793 }
794 }
795 }
796 _ => {}
797 }
798 }
799 bindings
800}
801
802/// Check if params contain any non-opaque Named types that need let bindings.
803/// This includes direct Named types, Vec<Named> types, and Vec<String> params
804/// with is_ref=true (which need a Vec<&str> intermediate to pass as &[&str]).
805pub fn has_named_params(params: &[ParamDef], opaque_types: &AHashSet<String>) -> bool {
806 params.iter().any(|p| match &p.ty {
807 TypeRef::Named(name) if !opaque_types.contains(name.as_str()) => true,
808 TypeRef::Vec(inner) => {
809 // Vec<Named> always needs a conversion let binding.
810 // Vec<String> with is_ref=true needs a Vec<&str> intermediate for &[&str] coercion.
811 matches!(inner.as_ref(), TypeRef::Named(name) if !opaque_types.contains(name.as_str()))
812 || (matches!(inner.as_ref(), TypeRef::String | TypeRef::Char) && p.is_ref)
813 }
814 _ => false,
815 })
816}
817
818/// Check if a param type is safe for non-opaque delegation (no complex conversions needed).
819/// Vec and Map params can cause type mismatches (e.g. Vec<String> vs &[&str]).
820pub fn is_simple_non_opaque_param(ty: &TypeRef) -> bool {
821 match ty {
822 TypeRef::Primitive(_)
823 | TypeRef::String
824 | TypeRef::Char
825 | TypeRef::Bytes
826 | TypeRef::Path
827 | TypeRef::Unit
828 | TypeRef::Duration => true,
829 TypeRef::Optional(inner) => is_simple_non_opaque_param(inner),
830 _ => false,
831 }
832}
833
834/// Generate a lossy binding→core struct literal for non-opaque delegation.
835/// Sanitized fields use `Default::default()`, non-sanitized fields are cloned and converted.
836/// Fields are accessed via `self.` (behind &self), so all non-Copy types need `.clone()`.
837///
838/// NOTE: This assumes all binding struct fields implement Clone. If a field type does not
839/// implement Clone (e.g., `Mutex<T>`), it should be marked as `sanitized=true` so that
840/// `Default::default()` is used instead of calling `.clone()`. Backends that exclude types
841/// should mark such fields appropriately.
842pub fn gen_lossy_binding_to_core_fields(typ: &TypeDef, core_import: &str, option_duration_on_defaults: bool) -> String {
843 gen_lossy_binding_to_core_fields_inner(typ, core_import, false, option_duration_on_defaults)
844}
845
846/// Same as `gen_lossy_binding_to_core_fields` but declares `core_self` as mutable.
847pub fn gen_lossy_binding_to_core_fields_mut(
848 typ: &TypeDef,
849 core_import: &str,
850 option_duration_on_defaults: bool,
851) -> String {
852 gen_lossy_binding_to_core_fields_inner(typ, core_import, true, option_duration_on_defaults)
853}
854
855fn gen_lossy_binding_to_core_fields_inner(
856 typ: &TypeDef,
857 core_import: &str,
858 needs_mut: bool,
859 option_duration_on_defaults: bool,
860) -> String {
861 let core_path = crate::conversions::core_type_path(typ, core_import);
862 let mut_kw = if needs_mut { "mut " } else { "" };
863 // When has_stripped_cfg_fields is true we emit ..Default::default() at the end of the
864 // struct literal to fill cfg-gated fields that were stripped from the binding IR.
865 // Suppress clippy::needless_update because the fields only exist when the corresponding
866 // feature is enabled — without the feature, clippy thinks the spread is redundant.
867 let allow = if typ.has_stripped_cfg_fields {
868 "#[allow(clippy::needless_update)]\n "
869 } else {
870 ""
871 };
872 let mut out = format!("{allow}let {mut_kw}core_self = {core_path} {{\n");
873 for field in &typ.fields {
874 let name = &field.name;
875 if field.sanitized {
876 writeln!(out, " {name}: Default::default(),").ok();
877 } else {
878 let expr = match &field.ty {
879 TypeRef::Primitive(_) => format!("self.{name}"),
880 TypeRef::Duration => {
881 if field.optional {
882 format!("self.{name}.map(std::time::Duration::from_millis)")
883 } else if option_duration_on_defaults && typ.has_default {
884 // When option_duration_on_defaults is true, non-optional Duration fields
885 // on has_default types are stored as Option<u64> in the binding struct.
886 // Use .map(...).unwrap_or_default() so that None falls back to the core
887 // type's Default (e.g. Duration::from_secs(30)) rather than Duration::ZERO.
888 format!("self.{name}.map(std::time::Duration::from_millis).unwrap_or_default()")
889 } else {
890 format!("std::time::Duration::from_millis(self.{name})")
891 }
892 }
893 TypeRef::String => format!("self.{name}.clone()"),
894 // Bytes: binding stores Vec<u8>. When core_wrapper == Bytes, core expects
895 // bytes::Bytes so we must call .into() to convert Vec<u8> → Bytes.
896 // When core_wrapper == None, the core field is also Vec<u8> (plain clone).
897 TypeRef::Bytes => {
898 if field.core_wrapper == CoreWrapper::Bytes {
899 format!("self.{name}.clone().into()")
900 } else {
901 format!("self.{name}.clone()")
902 }
903 }
904 TypeRef::Char => {
905 if field.optional {
906 format!("self.{name}.as_ref().and_then(|s| s.chars().next())")
907 } else {
908 format!("self.{name}.chars().next().unwrap_or('*')")
909 }
910 }
911 TypeRef::Path => {
912 if field.optional {
913 format!("self.{name}.clone().map(Into::into)")
914 } else {
915 format!("self.{name}.clone().into()")
916 }
917 }
918 TypeRef::Named(_) => {
919 if field.optional {
920 format!("self.{name}.clone().map(Into::into)")
921 } else {
922 format!("self.{name}.clone().into()")
923 }
924 }
925 TypeRef::Vec(inner) => match inner.as_ref() {
926 TypeRef::Named(_) => {
927 if field.optional {
928 // Option<Vec<Named(T)>>: map over the Option, then convert each element
929 format!("self.{name}.clone().map(|v| v.into_iter().map(Into::into).collect())")
930 } else {
931 format!("self.{name}.clone().into_iter().map(Into::into).collect()")
932 }
933 }
934 _ => format!("self.{name}.clone()"),
935 },
936 TypeRef::Optional(inner) => {
937 // When field.optional is also true, the binding field was flattened from
938 // Option<Option<T>> to Option<T>. Core expects Option<Option<T>>, so wrap
939 // with .map(Some) to reconstruct the double-optional.
940 let base = match inner.as_ref() {
941 TypeRef::Named(_) => {
942 format!("self.{name}.clone().map(Into::into)")
943 }
944 TypeRef::Duration => {
945 format!("self.{name}.map(|v| std::time::Duration::from_millis(v as u64))")
946 }
947 TypeRef::Vec(vi) if matches!(vi.as_ref(), TypeRef::Named(_)) => {
948 format!("self.{name}.clone().map(|v| v.into_iter().map(Into::into).collect())")
949 }
950 _ => format!("self.{name}.clone()"),
951 };
952 if field.optional {
953 format!("({base}).map(Some)")
954 } else {
955 base
956 }
957 }
958 TypeRef::Map(_, v) => match v.as_ref() {
959 TypeRef::Json => {
960 // HashMap<String, String> (binding) → HashMap<String, Value> (core)
961 if field.optional {
962 format!(
963 "self.{name}.clone().map(|m| m.into_iter().map(|(k, v)| \
964 (k, serde_json::from_str(&v).unwrap_or(serde_json::Value::String(v)))).collect())"
965 )
966 } else {
967 format!(
968 "self.{name}.clone().into_iter().map(|(k, v)| \
969 (k, serde_json::from_str(&v).unwrap_or(serde_json::Value::String(v)))).collect()"
970 )
971 }
972 }
973 // Collect to handle HashMap↔BTreeMap conversion
974 _ => {
975 if field.optional {
976 format!("self.{name}.clone().map(|m| m.into_iter().collect())")
977 } else {
978 format!("self.{name}.clone().into_iter().collect()")
979 }
980 }
981 },
982 TypeRef::Unit => format!("self.{name}.clone()"),
983 TypeRef::Json => {
984 // String (binding) → serde_json::Value (core)
985 if field.optional {
986 format!("self.{name}.as_ref().and_then(|s| serde_json::from_str(s).ok())")
987 } else {
988 format!("serde_json::from_str(&self.{name}).unwrap_or_default()")
989 }
990 }
991 };
992 // Newtype wrapping: when the field was resolved from a newtype (e.g. NodeIndex → u32),
993 // re-wrap the binding value into the newtype for the core struct literal.
994 // When `optional=true` and `ty` is a plain Primitive (not TypeRef::Optional), the core
995 // field is actually `Option<NewtypeT>`, so we must use `.map(NewtypeT)` not `NewtypeT(...)`.
996 let expr = if let Some(newtype_path) = &field.newtype_wrapper {
997 match &field.ty {
998 TypeRef::Optional(_) => format!("({expr}).map({newtype_path})"),
999 TypeRef::Vec(_) => format!("({expr}).into_iter().map({newtype_path}).collect()"),
1000 _ if field.optional => format!("({expr}).map({newtype_path})"),
1001 _ => format!("{newtype_path}({expr})"),
1002 }
1003 } else {
1004 expr
1005 };
1006 writeln!(out, " {name}: {expr},").ok();
1007 }
1008 }
1009 // Use ..Default::default() to fill cfg-gated fields stripped from the IR
1010 if typ.has_stripped_cfg_fields {
1011 out.push_str(" ..Default::default()\n");
1012 }
1013 out.push_str(" };\n ");
1014 out
1015}
1016
1017/// Generate the body for an async call, unified across methods, static methods, and free functions.
1018///
1019/// - `core_call`: the expression to await, e.g. `inner.method(args)` or `CoreType::fn(args)`.
1020/// For Pyo3FutureIntoPy opaque methods this should reference `inner` (the Arc clone);
1021/// for all other patterns it may reference `self.inner` or a static call expression.
1022/// - `cfg`: binding configuration (determines which async pattern to emit)
1023/// - `has_error`: whether the core call returns a `Result`
1024/// - `return_wrap`: expression to produce the binding return value from `result`,
1025/// e.g. `"result"` or `"TypeName::from(result)"`
1026///
1027/// - `is_opaque`: whether the binding type is Arc-wrapped (affects TokioBlockOn wrapping)
1028/// - `inner_clone_line`: optional statement emitted before the pattern-specific body,
1029/// e.g. `"let inner = self.inner.clone();\n "` for opaque instance methods, or `""`.
1030/// Required when `core_call` references `inner` (Pyo3FutureIntoPy opaque case).
1031#[allow(clippy::too_many_arguments)]
1032pub fn gen_async_body(
1033 core_call: &str,
1034 cfg: &RustBindingConfig,
1035 has_error: bool,
1036 return_wrap: &str,
1037 is_opaque: bool,
1038 inner_clone_line: &str,
1039 is_unit_return: bool,
1040 return_type: Option<&str>,
1041) -> String {
1042 let pattern_body = match cfg.async_pattern {
1043 AsyncPattern::Pyo3FutureIntoPy => {
1044 let result_handling = if has_error {
1045 format!(
1046 "let result = {core_call}.await\n \
1047 .map_err(|e| PyErr::new::<PyRuntimeError, _>(e.to_string()))?;"
1048 )
1049 } else if is_unit_return {
1050 format!("{core_call}.await;")
1051 } else {
1052 format!("let result = {core_call}.await;")
1053 };
1054 let (ok_expr, extra_binding) = if is_unit_return && !has_error {
1055 ("()".to_string(), String::new())
1056 } else if return_wrap.contains(".into()") || return_wrap.contains("::from(") {
1057 // When return_wrap contains type conversions like .into() or ::from(),
1058 // bind to a variable to help type inference for the generic future_into_py.
1059 // This avoids E0283 "type annotations needed".
1060 let wrapped_var = "wrapped_result";
1061 let binding = if let Some(ret_type) = return_type {
1062 // Add explicit type annotation to help type inference
1063 format!("let {wrapped_var}: {ret_type} = {return_wrap};\n ")
1064 } else {
1065 format!("let {wrapped_var} = {return_wrap};\n ")
1066 };
1067 (wrapped_var.to_string(), binding)
1068 } else {
1069 (return_wrap.to_string(), String::new())
1070 };
1071 format!(
1072 "pyo3_async_runtimes::tokio::future_into_py(py, async move {{\n \
1073 {result_handling}\n \
1074 {extra_binding}Ok({ok_expr})\n }})"
1075 )
1076 }
1077 AsyncPattern::WasmNativeAsync => {
1078 let result_handling = if has_error {
1079 format!(
1080 "let result = {core_call}.await\n \
1081 .map_err(|e| JsValue::from_str(&e.to_string()))?;"
1082 )
1083 } else if is_unit_return {
1084 format!("{core_call}.await;")
1085 } else {
1086 format!("let result = {core_call}.await;")
1087 };
1088 let ok_expr = if is_unit_return && !has_error {
1089 "()"
1090 } else {
1091 return_wrap
1092 };
1093 format!(
1094 "{result_handling}\n \
1095 Ok({ok_expr})"
1096 )
1097 }
1098 AsyncPattern::NapiNativeAsync => {
1099 let result_handling = if has_error {
1100 format!(
1101 "let result = {core_call}.await\n \
1102 .map_err(|e| napi::Error::new(napi::Status::GenericFailure, e.to_string()))?;"
1103 )
1104 } else if is_unit_return {
1105 format!("{core_call}.await;")
1106 } else {
1107 format!("let result = {core_call}.await;")
1108 };
1109 if !has_error && !is_unit_return {
1110 // No error type: return value directly without Ok() wrapper
1111 format!(
1112 "{result_handling}\n \
1113 {return_wrap}"
1114 )
1115 } else {
1116 let ok_expr = if is_unit_return && !has_error {
1117 "()"
1118 } else {
1119 return_wrap
1120 };
1121 format!(
1122 "{result_handling}\n \
1123 Ok({ok_expr})"
1124 )
1125 }
1126 }
1127 AsyncPattern::TokioBlockOn => {
1128 if has_error {
1129 if is_opaque {
1130 format!(
1131 "let rt = tokio::runtime::Runtime::new()?;\n \
1132 let result = rt.block_on(async {{ {core_call}.await.map_err(|e| e.into()) }})?;\n \
1133 {return_wrap}"
1134 )
1135 } else {
1136 format!(
1137 "let rt = tokio::runtime::Runtime::new()?;\n \
1138 rt.block_on(async {{ {core_call}.await.map_err(|e| e.into()) }})"
1139 )
1140 }
1141 } else if is_opaque {
1142 if is_unit_return {
1143 format!(
1144 "let rt = tokio::runtime::Runtime::new()?;\n \
1145 rt.block_on(async {{ {core_call}.await }});"
1146 )
1147 } else {
1148 format!(
1149 "let rt = tokio::runtime::Runtime::new()?;\n \
1150 let result = rt.block_on(async {{ {core_call}.await }});\n \
1151 {return_wrap}"
1152 )
1153 }
1154 } else {
1155 format!(
1156 "let rt = tokio::runtime::Runtime::new()?;\n \
1157 rt.block_on(async {{ {core_call}.await }})"
1158 )
1159 }
1160 }
1161 AsyncPattern::None => "todo!(\"async not supported by backend\")".to_string(),
1162 };
1163 if inner_clone_line.is_empty() {
1164 pattern_body
1165 } else {
1166 format!("{inner_clone_line}{pattern_body}")
1167 }
1168}
1169
1170/// Generate a compilable body for functions that can't be auto-delegated.
1171/// Returns a default value or error instead of `todo!()` which would panic.
1172///
1173/// `opaque_types` is the set of opaque type names (Arc-wrapped). Opaque types do not
1174/// implement `Default`, so returning `Default::default()` for their Named return types
1175/// would fail to compile. For those cases a `todo!()` body is emitted instead.
1176pub fn gen_unimplemented_body(
1177 return_type: &TypeRef,
1178 fn_name: &str,
1179 has_error: bool,
1180 cfg: &RustBindingConfig,
1181 params: &[ParamDef],
1182 opaque_types: &AHashSet<String>,
1183) -> String {
1184 // Suppress unused_variables by binding all params to `_`
1185 let suppress = if params.is_empty() {
1186 String::new()
1187 } else {
1188 let names: Vec<&str> = params.iter().map(|p| p.name.as_str()).collect();
1189 if names.len() == 1 {
1190 format!("let _ = {};\n ", names[0])
1191 } else {
1192 format!("let _ = ({});\n ", names.join(", "))
1193 }
1194 };
1195 let err_msg = format!("Not implemented: {fn_name}");
1196 let body = if has_error {
1197 // Backend-specific error return
1198 match cfg.async_pattern {
1199 AsyncPattern::Pyo3FutureIntoPy => {
1200 format!("Err(pyo3::exceptions::PyNotImplementedError::new_err(\"{err_msg}\"))")
1201 }
1202 AsyncPattern::NapiNativeAsync => {
1203 format!("Err(napi::Error::new(napi::Status::GenericFailure, \"{err_msg}\"))")
1204 }
1205 AsyncPattern::WasmNativeAsync => {
1206 format!("Err(JsValue::from_str(\"{err_msg}\"))")
1207 }
1208 _ => format!("Err(\"{err_msg}\".to_string())"),
1209 }
1210 } else {
1211 // Return type-appropriate default
1212 match return_type {
1213 TypeRef::Unit => "()".to_string(),
1214 TypeRef::String | TypeRef::Char | TypeRef::Path => format!("String::from(\"[unimplemented: {fn_name}]\")"),
1215 TypeRef::Bytes => "Vec::new()".to_string(),
1216 TypeRef::Primitive(p) => match p {
1217 alef_core::ir::PrimitiveType::Bool => "false".to_string(),
1218 alef_core::ir::PrimitiveType::F32 => "0.0f32".to_string(),
1219 alef_core::ir::PrimitiveType::F64 => "0.0f64".to_string(),
1220 _ => "0".to_string(),
1221 },
1222 TypeRef::Optional(_) => "None".to_string(),
1223 TypeRef::Vec(_) => "Vec::new()".to_string(),
1224 TypeRef::Map(_, _) => "Default::default()".to_string(),
1225 TypeRef::Duration => "0".to_string(),
1226 TypeRef::Named(name) => {
1227 // Opaque types (Arc-wrapped) do not implement Default — use todo!() to
1228 // produce a compilable placeholder that panics at runtime if called.
1229 // Non-opaque Named types (config structs) do derive Default, so use that.
1230 if opaque_types.contains(name.as_str()) {
1231 format!("todo!(\"{err_msg}\")")
1232 } else {
1233 "Default::default()".to_string()
1234 }
1235 }
1236 TypeRef::Json => {
1237 // Json return without error type: return Default::default()
1238 "Default::default()".to_string()
1239 }
1240 }
1241 };
1242 format!("{suppress}{body}")
1243}