1use crate::generators::binding_helpers::{
2 gen_async_body, gen_call_args, gen_call_args_cfg, gen_call_args_with_let_bindings, gen_named_let_bindings,
3 gen_named_let_bindings_by_ref, gen_serde_let_bindings, gen_unimplemented_body, has_named_params,
4};
5use crate::generators::{AdapterBodies, AsyncPattern, RustBindingConfig};
6use crate::shared::{function_params, function_sig_defaults};
7use crate::type_mapper::TypeMapper;
8use ahash::{AHashMap, AHashSet};
9use alef_core::ir::{ApiSurface, FunctionDef, TypeRef};
10use std::fmt::Write;
11
12pub fn gen_function(
14 func: &FunctionDef,
15 mapper: &dyn TypeMapper,
16 cfg: &RustBindingConfig,
17 adapter_bodies: &AdapterBodies,
18 opaque_types: &AHashSet<String>,
19) -> String {
20 let map_fn = |ty: &alef_core::ir::TypeRef| mapper.map_type(ty);
21 let params = if cfg.named_non_opaque_params_by_ref {
28 let mut seen_optional = false;
29 func.params
30 .iter()
31 .enumerate()
32 .map(|(idx, p)| {
33 if p.optional {
34 seen_optional = true;
35 }
36 let promoted = seen_optional && !p.optional && crate::shared::is_promoted_optional(&func.params, idx);
37 let ty = match &p.ty {
38 TypeRef::Named(n) if !opaque_types.contains(n.as_str()) => {
39 if p.optional || seen_optional || promoted {
40 format!("Nullable<&{}>", map_fn(&p.ty))
41 } else {
42 format!("&{}", map_fn(&p.ty))
43 }
44 }
45 _ => {
46 if p.optional || seen_optional {
47 format!("Option<{}>", map_fn(&p.ty))
48 } else {
49 map_fn(&p.ty)
50 }
51 }
52 };
53 format!("{}: {}", p.name, ty)
54 })
55 .collect::<Vec<_>>()
56 .join(", ")
57 } else {
58 function_params(&func.params, &map_fn)
59 };
60 let return_type = mapper.map_type(&func.return_type);
61 let ret = mapper.wrap_return(&return_type, func.error_type.is_some());
62
63 let effective_params: std::borrow::Cow<[alef_core::ir::ParamDef]> = if cfg.named_non_opaque_params_by_ref {
67 let modified: Vec<alef_core::ir::ParamDef> = func
68 .params
69 .iter()
70 .map(|p| {
71 if matches!(&p.ty, TypeRef::Named(n) if !opaque_types.contains(n.as_str())) {
72 alef_core::ir::ParamDef {
73 is_ref: true,
74 ..p.clone()
75 }
76 } else {
77 p.clone()
78 }
79 })
80 .collect();
81 std::borrow::Cow::Owned(modified)
82 } else {
83 std::borrow::Cow::Borrowed(&func.params)
84 };
85 let use_let_bindings = has_named_params(&effective_params, opaque_types);
86 let call_args = if use_let_bindings {
87 gen_call_args_with_let_bindings(&effective_params, opaque_types)
88 } else if cfg.cast_uints_to_i32 || cfg.cast_large_ints_to_f64 {
89 gen_call_args_cfg(
90 &effective_params,
91 opaque_types,
92 cfg.cast_uints_to_i32,
93 cfg.cast_large_ints_to_f64,
94 )
95 } else {
96 gen_call_args(&effective_params, opaque_types)
97 };
98 let core_import = cfg.core_import;
99 let let_bindings = if use_let_bindings {
100 if cfg.named_non_opaque_params_by_ref {
101 gen_named_let_bindings_by_ref(&func.params, opaque_types, core_import)
103 } else {
104 gen_named_let_bindings(&func.params, opaque_types, core_import)
105 }
106 } else {
107 String::new()
108 };
109
110 let core_fn_path = {
112 let path = func.rust_path.replace('-', "_");
113 if path.starts_with(core_import) {
114 path
115 } else {
116 format!("{core_import}::{}", func.name)
117 }
118 };
119
120 let can_delegate = crate::shared::can_auto_delegate_function(func, opaque_types)
121 || can_delegate_with_named_let_bindings(func, opaque_types);
122
123 let serde_err_conv = match cfg.async_pattern {
125 AsyncPattern::Pyo3FutureIntoPy => ".map_err(|e| pyo3::exceptions::PyRuntimeError::new_err(e.to_string()))",
126 AsyncPattern::NapiNativeAsync => ".map_err(|e| napi::Error::new(napi::Status::GenericFailure, e.to_string()))",
127 AsyncPattern::WasmNativeAsync => ".map_err(|e| JsValue::from_str(&e.to_string()))",
128 AsyncPattern::TokioBlockOn => ".map_err(|e| extendr_api::Error::Other(e.to_string()))",
129 _ => ".map_err(|e| e.to_string())",
130 };
131
132 let body = if !can_delegate {
134 if let Some(adapter_body) = adapter_bodies.get(&func.name) {
136 adapter_body.clone()
137 } else if cfg.has_serde && use_let_bindings && func.error_type.is_some() {
138 let is_async_pyo3 = func.is_async && cfg.async_pattern == AsyncPattern::Pyo3FutureIntoPy;
143 let (serde_indent, serde_err_async) = if is_async_pyo3 {
144 (
145 " ",
146 ".map_err(|e| pyo3::exceptions::PyRuntimeError::new_err(e.to_string()))",
147 )
148 } else {
149 (" ", serde_err_conv)
150 };
151 let serde_bindings =
152 gen_serde_let_bindings(&func.params, opaque_types, core_import, serde_err_async, serde_indent);
153 let core_call = format!("{core_fn_path}({call_args})");
154
155 let returns_ref = func.returns_ref;
157 let wrap_return = |expr: &str| -> String {
158 match &func.return_type {
159 TypeRef::Vec(inner) => {
160 match inner.as_ref() {
162 TypeRef::Named(_) => {
163 format!("{expr}.into_iter().map(Into::into).collect()")
165 }
166 _ => expr.to_string(),
167 }
168 }
169 TypeRef::Named(name) if opaque_types.contains(name.as_str()) => {
170 if returns_ref {
171 format!("{name} {{ inner: Arc::new({expr}.clone()) }}")
172 } else {
173 format!("{name} {{ inner: Arc::new({expr}) }}")
174 }
175 }
176 TypeRef::Named(_) => {
177 if returns_ref {
179 format!("{return_type}::from({expr}.clone())")
180 } else {
181 format!("{return_type}::from({expr})")
182 }
183 }
184 TypeRef::String | TypeRef::Bytes => expr.to_string(),
187 TypeRef::Path => format!("{expr}.to_string_lossy().to_string()"),
188 TypeRef::Json => format!("{expr}.to_string()"),
189 _ => expr.to_string(),
190 }
191 };
192
193 if is_async_pyo3 {
194 let is_unit = matches!(func.return_type, TypeRef::Unit);
196 let wrapped = wrap_return("result");
197 let core_await = format!(
198 "{core_call}.await\n .map_err(|e| PyErr::new::<PyRuntimeError, _>(e.to_string()))?"
199 );
200 let inner_body = if is_unit {
201 format!("{serde_bindings}{core_await};\n Ok(())")
202 } else {
203 if wrapped.contains(".into()") || wrapped.contains("::from(") || wrapped.contains("Into::into") {
207 format!(
209 "{serde_bindings}let result = {core_await};\n let wrapped_result: {return_type} = {wrapped};\n Ok(wrapped_result)"
210 )
211 } else {
212 format!("{serde_bindings}let result = {core_await};\n Ok({wrapped})")
213 }
214 };
215 format!("pyo3_async_runtimes::tokio::future_into_py(py, async move {{\n{inner_body}\n }})")
216 } else if func.is_async {
217 let is_unit = matches!(func.return_type, TypeRef::Unit);
219 let wrapped = wrap_return("result");
220 let async_body = gen_async_body(
221 &core_call,
222 cfg,
223 func.error_type.is_some(),
224 &wrapped,
225 false,
226 "",
227 is_unit,
228 Some(&return_type),
229 );
230 format!("{serde_bindings}{async_body}")
231 } else if matches!(func.return_type, TypeRef::Unit) {
232 let await_kw = if func.is_async { ".await" } else { "" };
234 let debug_marker = if func.is_async { "/*ASYNC_UNIT*/ " } else { "" };
235 format!("{serde_bindings}{debug_marker}{core_call}{await_kw}{serde_err_conv}?;\n Ok(())")
236 } else {
237 let wrapped = wrap_return("val");
238 let await_kw = if func.is_async { ".await" } else { "" };
239 if wrapped == "val" {
240 format!("{serde_bindings}{core_call}{await_kw}{serde_err_conv}")
241 } else if wrapped == "val.into()" {
242 format!("{serde_bindings}{core_call}{await_kw}.map(Into::into){serde_err_conv}")
243 } else if let Some(type_path) = wrapped.strip_suffix("::from(val)") {
244 format!("{serde_bindings}{core_call}{await_kw}.map({type_path}::from){serde_err_conv}")
245 } else {
246 format!("{serde_bindings}{core_call}{await_kw}.map(|val| {wrapped}){serde_err_conv}")
247 }
248 }
249 } else if func.is_async && cfg.async_pattern == AsyncPattern::Pyo3FutureIntoPy {
250 let suppress = if func.params.is_empty() {
252 String::new()
253 } else {
254 let names: Vec<&str> = func.params.iter().map(|p| p.name.as_str()).collect();
255 format!("let _ = ({});\n ", names.join(", "))
256 };
257 format!(
258 "{suppress}Err(pyo3::exceptions::PyNotImplementedError::new_err(\"not implemented: {}\"))",
259 func.name
260 )
261 } else {
262 gen_unimplemented_body(
264 &func.return_type,
265 &func.name,
266 func.error_type.is_some(),
267 cfg,
268 &func.params,
269 opaque_types,
270 )
271 }
272 } else if func.is_async {
273 let core_call = format!("{core_fn_path}({call_args})");
275 let return_wrap = match &func.return_type {
278 TypeRef::Named(n) if opaque_types.contains(n.as_str()) => {
279 format!("{n} {{ inner: Arc::new(result) }}")
280 }
281 TypeRef::Named(_) => {
282 format!("{return_type}::from(result)")
283 }
284 TypeRef::Vec(inner) => match inner.as_ref() {
285 TypeRef::Named(n) if opaque_types.contains(n.as_str()) => {
286 format!("result.into_iter().map(|v| {n} {{ inner: Arc::new(v) }}).collect::<Vec<_>>()")
287 }
288 TypeRef::Named(_) => {
289 let inner_mapped = mapper.map_type(inner);
290 format!("result.into_iter().map({inner_mapped}::from).collect::<Vec<_>>()")
291 }
292 _ => "result".to_string(),
293 },
294 TypeRef::Unit => "result".to_string(),
295 _ => super::binding_helpers::wrap_return(
296 "result",
297 &func.return_type,
298 "",
299 opaque_types,
300 false,
301 func.returns_ref,
302 false,
303 ),
304 };
305 let async_body = gen_async_body(
306 &core_call,
307 cfg,
308 func.error_type.is_some(),
309 &return_wrap,
310 false,
311 "",
312 matches!(func.return_type, TypeRef::Unit),
313 Some(&return_type),
314 );
315 format!("{let_bindings}{async_body}")
316 } else {
317 let core_call = format!("{core_fn_path}({call_args})");
318
319 let returns_ref = func.returns_ref;
321 let wrap_return = |expr: &str| -> String {
322 match &func.return_type {
323 TypeRef::Named(name) if opaque_types.contains(name.as_str()) => {
325 if returns_ref {
326 format!("{name} {{ inner: Arc::new({expr}.clone()) }}")
327 } else {
328 format!("{name} {{ inner: Arc::new({expr}) }}")
329 }
330 }
331 TypeRef::Named(_name) => {
333 if returns_ref {
334 format!("{expr}.clone().into()")
335 } else {
336 format!("{expr}.into()")
337 }
338 }
339 TypeRef::String | TypeRef::Bytes => {
341 if returns_ref {
342 format!("{expr}.into()")
343 } else {
344 expr.to_string()
345 }
346 }
347 TypeRef::Path => format!("{expr}.to_string_lossy().to_string()"),
349 TypeRef::Json => format!("{expr}.to_string()"),
351 TypeRef::Optional(inner) => match inner.as_ref() {
353 TypeRef::Named(name) if opaque_types.contains(name.as_str()) => {
354 if returns_ref {
355 format!("{expr}.map(|v| {name} {{ inner: Arc::new(v.clone()) }})")
356 } else {
357 format!("{expr}.map(|v| {name} {{ inner: Arc::new(v) }})")
358 }
359 }
360 TypeRef::Named(_) => {
361 if returns_ref {
362 format!("{expr}.map(|v| v.clone().into())")
363 } else {
364 format!("{expr}.map(Into::into)")
365 }
366 }
367 TypeRef::Path => {
368 format!("{expr}.map(|v| v.to_string_lossy().to_string())")
369 }
370 TypeRef::String | TypeRef::Bytes => {
371 if returns_ref {
372 format!("{expr}.map(Into::into)")
373 } else {
374 expr.to_string()
375 }
376 }
377 TypeRef::Vec(vi) => match vi.as_ref() {
378 TypeRef::Named(name) if opaque_types.contains(name.as_str()) => {
379 format!("{expr}.map(|v| v.into_iter().map(|x| {name} {{ inner: Arc::new(x) }}).collect())")
380 }
381 TypeRef::Named(_) => {
382 format!("{expr}.map(|v| v.into_iter().map(Into::into).collect())")
383 }
384 _ => expr.to_string(),
385 },
386 _ => expr.to_string(),
387 },
388 TypeRef::Vec(inner) => match inner.as_ref() {
390 TypeRef::Named(name) if opaque_types.contains(name.as_str()) => {
391 if returns_ref {
392 format!("{expr}.into_iter().map(|v| {name} {{ inner: Arc::new(v.clone()) }}).collect()")
393 } else {
394 format!("{expr}.into_iter().map(|v| {name} {{ inner: Arc::new(v) }}).collect()")
395 }
396 }
397 TypeRef::Named(_) => {
398 if returns_ref {
399 format!("{expr}.into_iter().map(|v| v.clone().into()).collect()")
400 } else {
401 format!("{expr}.into_iter().map(Into::into).collect()")
402 }
403 }
404 TypeRef::Path => {
405 format!("{expr}.into_iter().map(|v| v.to_string_lossy().to_string()).collect()")
406 }
407 TypeRef::String | TypeRef::Bytes => {
408 if returns_ref {
409 format!("{expr}.into_iter().map(Into::into).collect()")
410 } else {
411 expr.to_string()
412 }
413 }
414 _ => expr.to_string(),
415 },
416 _ => expr.to_string(),
417 }
418 };
419
420 if func.error_type.is_some() {
421 let err_conv = match cfg.async_pattern {
423 AsyncPattern::Pyo3FutureIntoPy => {
424 ".map_err(|e| pyo3::exceptions::PyRuntimeError::new_err(e.to_string()))"
425 }
426 AsyncPattern::NapiNativeAsync => {
427 ".map_err(|e| napi::Error::new(napi::Status::GenericFailure, e.to_string()))"
428 }
429 AsyncPattern::WasmNativeAsync => ".map_err(|e| JsValue::from_str(&e.to_string()))",
430 AsyncPattern::TokioBlockOn => ".map_err(|e| extendr_api::Error::Other(e.to_string()))",
431 _ => ".map_err(|e| e.to_string())",
432 };
433 let wrapped = wrap_return("val");
434 if wrapped == "val" {
435 format!("{core_call}{err_conv}")
436 } else if wrapped == "val.into()" {
437 format!("{core_call}.map(Into::into){err_conv}")
438 } else if let Some(type_path) = wrapped.strip_suffix("::from(val)") {
439 format!("{core_call}.map({type_path}::from){err_conv}")
440 } else {
441 format!("{core_call}.map(|val| {wrapped}){err_conv}")
442 }
443 } else {
444 wrap_return(&core_call)
445 }
446 };
447
448 let body = if !let_bindings.is_empty() && !func.is_async {
452 if can_delegate {
453 format!("{let_bindings}{body}")
454 } else {
455 let vec_str_bindings: String = func.params.iter().filter(|p| {
458 p.is_ref && matches!(&p.ty, TypeRef::Vec(inner) if matches!(inner.as_ref(), TypeRef::String | TypeRef::Char))
459 }).map(|p| {
460 if p.optional {
463 format!("let {}_refs: Vec<&str> = {}.as_ref().map(|v| v.iter().map(|s| s.as_str()).collect()).unwrap_or_default();\n ", p.name, p.name)
464 } else {
465 format!("let {}_refs: Vec<&str> = {}.iter().map(|s| s.as_str()).collect();\n ", p.name, p.name)
466 }
467 }).collect();
468 if !vec_str_bindings.is_empty() {
469 format!("{vec_str_bindings}{body}")
470 } else {
471 body
472 }
473 }
474 } else {
475 body
476 };
477
478 let async_kw = if func.is_async && cfg.async_pattern != AsyncPattern::TokioBlockOn {
482 "async "
483 } else {
484 ""
485 };
486 let func_needs_py = func.is_async && cfg.async_pattern == AsyncPattern::Pyo3FutureIntoPy;
487
488 let ret = if func_needs_py {
490 "PyResult<Bound<'py, PyAny>>".to_string()
491 } else {
492 ret
493 };
494 let func_lifetime = if func_needs_py { "<'py>" } else { "" };
495
496 let (func_sig, _params_formatted) = if params.len() > 100 {
497 let mut seen_optional = false;
499 let wrapped_params = func
500 .params
501 .iter()
502 .map(|p| {
503 if p.optional {
504 seen_optional = true;
505 }
506 let ty = if p.optional || seen_optional {
507 format!("Option<{}>", mapper.map_type(&p.ty))
508 } else {
509 mapper.map_type(&p.ty)
510 };
511 format!("{}: {}", p.name, ty)
512 })
513 .collect::<Vec<_>>()
514 .join(",\n ");
515
516 if func_needs_py {
518 (
519 format!(
520 "pub fn {}{func_lifetime}(py: Python<'py>,\n {}\n) -> {ret}",
521 func.name,
522 wrapped_params,
523 ret = ret
524 ),
525 "",
526 )
527 } else {
528 (
529 format!(
530 "pub {async_kw}fn {}(\n {}\n) -> {ret}",
531 func.name,
532 wrapped_params,
533 ret = ret
534 ),
535 "",
536 )
537 }
538 } else if func_needs_py {
539 (
540 format!(
541 "pub fn {}{func_lifetime}(py: Python<'py>, {params}) -> {ret}",
542 func.name
543 ),
544 "",
545 )
546 } else {
547 (format!("pub {async_kw}fn {}({params}) -> {ret}", func.name), "")
548 };
549
550 let mut out = String::with_capacity(1024);
551 let total_params = func.params.len() + if func_needs_py { 1 } else { 0 };
553 if total_params > 7 {
554 writeln!(out, "#[allow(clippy::too_many_arguments)]").ok();
555 }
556 if func.error_type.is_some() {
558 writeln!(out, "#[allow(clippy::missing_errors_doc)]").ok();
559 }
560 let attr_inner = cfg
561 .function_attr
562 .trim_start_matches('#')
563 .trim_start_matches('[')
564 .trim_end_matches(']');
565 writeln!(out, "#[{attr_inner}]").ok();
566 if cfg.needs_signature {
567 let sig = function_sig_defaults(&func.params);
568 writeln!(out, "{}{}{}", cfg.signature_prefix, sig, cfg.signature_suffix).ok();
569 }
570 write!(out, "{} {{\n {body}\n}}", func_sig,).ok();
571 out
572}
573
574fn can_delegate_with_named_let_bindings(func: &FunctionDef, opaque_types: &AHashSet<String>) -> bool {
575 !func.sanitized
576 && func
577 .params
578 .iter()
579 .all(|p| !p.sanitized && crate::shared::is_delegatable_param(&p.ty, opaque_types))
580 && crate::shared::is_delegatable_return(&func.return_type)
581}
582
583pub fn collect_trait_imports(api: &ApiSurface) -> Vec<String> {
590 let mut traits: AHashSet<String> = AHashSet::new();
595 for typ in api.types.iter().filter(|typ| !typ.is_trait) {
596 for method in &typ.methods {
597 if let Some(ref trait_path) = method.trait_source {
598 traits.insert(trait_path.clone());
599 }
600 }
601 }
602
603 let mut by_name: AHashMap<String, String> = AHashMap::new();
605 for path in traits {
606 let name = path.split("::").last().unwrap_or(&path).to_string();
607 let entry = by_name.entry(name).or_insert_with(|| path.clone());
608 if path.len() < entry.len() {
610 *entry = path;
611 }
612 }
613
614 let mut sorted: Vec<String> = by_name.into_values().collect();
615 sorted.sort();
616 sorted
617}
618
619pub fn has_unresolved_trait_methods(api: &ApiSurface) -> bool {
625 let mut method_counts: AHashMap<&str, (usize, usize)> = AHashMap::new(); for typ in api.types.iter().filter(|typ| !typ.is_trait) {
630 if typ.is_trait {
631 continue;
632 }
633 for method in &typ.methods {
634 let entry = method_counts.entry(&method.name).or_insert((0, 0));
635 entry.0 += 1;
636 if method.trait_source.is_some() {
637 entry.1 += 1;
638 }
639 }
640 }
641 method_counts
643 .values()
644 .any(|&(total, with_source)| total >= 3 && with_source == 0)
645}
646
647pub fn collect_explicit_core_imports(api: &ApiSurface) -> Vec<String> {
658 let mut names = std::collections::BTreeSet::new();
659 for typ in api.types.iter().filter(|typ| !typ.is_trait) {
660 names.insert(typ.name.clone());
661 }
662 for e in &api.enums {
663 names.insert(e.name.clone());
664 }
665 names.into_iter().collect()
666}