Skip to main content

alef_codegen/generators/
functions.rs

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
12/// Generate a free function.
13pub 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    // When named_non_opaque_params_by_ref is true (extendr backend), Named non-opaque struct
22    // params must use references because extendr only generates TryFrom<&Robj> for &T.
23    // - Required params: `&T` (extendr generates TryFrom<&Robj> for &T)
24    // - Optional params: `Nullable<&T>` (extendr's Nullable<T: TryFrom<&Robj>>)
25    // - Promoted-optional (required following optional): `Nullable<&T>` (treated as optional)
26    // After the first optional/Nullable param, all subsequent params are also promoted.
27    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    // Use let-binding pattern for non-opaque Named params so core fns can take &CoreType.
64    // When named_non_opaque_params_by_ref is set (extendr), the binding signature uses &T,
65    // so we simulate is_ref=true for Named non-opaque params when generating call args.
66    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            // Params are `&T` in the signature — use .clone().into() for conversion.
102            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    // Use the function's rust_path for correct module path resolution
111    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    // Backend-specific error conversion string for serde bindings
124    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    // Generate the body based on async pattern
133    let body = if !can_delegate {
134        // Check if an adapter provides the body
135        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            // MARKER_SERDE_PATH
139            // Serde-based param conversion: serialize binding types to JSON, deserialize to core types.
140            // This handles Named params (e.g., ProcessConfig) that lack binding→core From impls.
141            // For async functions with Pyo3FutureIntoPy, serde bindings use indented format.
142            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            // Determine return wrapping strategy for serde async (uses explicit types to avoid E0283)
156            let returns_ref = func.returns_ref;
157            let wrap_return = |expr: &str| -> String {
158                match &func.return_type {
159                    TypeRef::Vec(inner) => {
160                        // Vec<T>: check if elements need conversion
161                        match inner.as_ref() {
162                            TypeRef::Named(_) => {
163                                // Vec<Named>: convert each element using Into::into
164                                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                        // Use explicit type with ::from() to avoid E0283 type inference issues in async context
178                        if returns_ref {
179                            format!("{return_type}::from({expr}.clone())")
180                        } else {
181                            format!("{return_type}::from({expr})")
182                        }
183                    }
184                    // String/Bytes are identity across all backends (String->String,
185                    // Vec<u8>->Vec<u8>) — no .into() needed for owned values.
186                    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                // Async serde path: wrap everything in future_into_py
195                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                    // When wrapped contains type conversions like .into() or ::from(),
204                    // bind to a variable to help type inference for the generic future_into_py.
205                    // This avoids E0283 "type annotations needed".
206                    if wrapped.contains(".into()") || wrapped.contains("::from(") || wrapped.contains("Into::into") {
207                        // Add explicit type annotation to help type inference
208                        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                // Async serde path for other backends (NAPI, etc.): use gen_async_body
218                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                // Unit return with error: avoid let_unit_value
233                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            // Async function that can't be auto-delegated — wrap unimplemented body in future_into_py
251            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            // Function can't be auto-delegated — return a default/error based on return type
263            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        // MARKER_DELEGATE_ASYNC
274        let core_call = format!("{core_fn_path}({call_args})");
275        // In async contexts (future_into_py, etc.), the compiler often can't infer the
276        // target type for .into(). Use explicit From::from() / collect::<Vec<T>>() instead.
277        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        // Determine return wrapping strategy
320        let returns_ref = func.returns_ref;
321        let wrap_return = |expr: &str| -> String {
322            match &func.return_type {
323                // Opaque type return: wrap in Arc
324                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                // Non-opaque Named: use .into() if From impl exists
332                TypeRef::Named(_name) => {
333                    if returns_ref {
334                        format!("{expr}.clone().into()")
335                    } else {
336                        format!("{expr}.into()")
337                    }
338                }
339                // String/Bytes: .into() handles &str→String, skip for owned
340                TypeRef::String | TypeRef::Bytes => {
341                    if returns_ref {
342                        format!("{expr}.into()")
343                    } else {
344                        expr.to_string()
345                    }
346                }
347                // Path: PathBuf→String needs to_string_lossy
348                TypeRef::Path => format!("{expr}.to_string_lossy().to_string()"),
349                // Json: serde_json::Value to string
350                TypeRef::Json => format!("{expr}.to_string()"),
351                // Optional with opaque inner
352                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                // Vec<Named>: map each element through Into
389                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            // Backend-specific error conversion
422            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    // Prepend let bindings for non-opaque Named params (sync delegate case).
449    // Only prepend when can_delegate is true — the !can_delegate serde path does its own bindings.
450    // However, always prepend Vec<String> ref bindings (names_refs) since serde path doesn't handle them.
451    let body = if !let_bindings.is_empty() && !func.is_async {
452        if can_delegate {
453            format!("{let_bindings}{body}")
454        } else {
455            // For the !can_delegate path, only prepend Vec<String>+is_ref bindings (names_refs)
456            // since serde bindings handle Named type conversions.
457            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                // Handle both Vec<String> and Option<Vec<String>> parameters.
461                // When p.optional=true, p.ty is the inner type (Vec<String>), so we need to unwrap first.
462                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    // Wrap long signature if necessary
479    // TokioBlockOn functions block synchronously inside the body — the generated function
480    // must NOT be `async fn` because extendr's `#[extendr]` cannot return a Future.
481    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    // For async PyO3 free functions, override return type and add lifetime generic.
489    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        // When formatting for long signatures, promote optional params like function_params() does
498        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        // For async PyO3, we need special signature handling
517        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    // Per-item clippy suppression: too_many_arguments when >7 params (including py)
552    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    // Per-item clippy suppression: missing_errors_doc for Result-returning functions
557    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
583/// Collect all unique trait import paths from types' methods.
584///
585/// Returns a deduplicated, sorted list of trait paths (e.g. `["liter_llm::LlmClient"]`)
586/// that need to be imported in generated binding code so that trait methods can be called.
587/// Both opaque and non-opaque types are scanned because non-opaque wrapper types also
588/// delegate trait method calls to their inner core type.
589pub fn collect_trait_imports(api: &ApiSurface) -> Vec<String> {
590    // Collect all trait paths, then deduplicate by last segment (trait name).
591    // When two paths resolve to the same trait name (e.g. `mylib_core::Dependency`
592    // and `mylib_core::di::Dependency`), only one import is needed. Keep the
593    // shorter (public re-export) path to avoid E0252 duplicate-import errors.
594    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    // Deduplicate by last path segment: keep the shortest path for each trait name.
604    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        // Prefer shorter paths (public re-exports are shorter than internal paths)
609        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
619/// Check if any type has methods from trait impls whose trait_source could not be resolved.
620///
621/// When true, the binding crate should add a glob import of the core crate (e.g.
622/// `use kreuzberg::*`) to bring all publicly exported traits into scope.
623/// This handles traits defined in private submodules that are re-exported.
624pub fn has_unresolved_trait_methods(api: &ApiSurface) -> bool {
625    // Count method names that appear on multiple non-trait types but lack trait_source.
626    // Such methods likely come from trait impls whose trait path could not be resolved
627    // (e.g. traits defined in private modules but re-exported via `pub use`).
628    let mut method_counts: AHashMap<&str, (usize, usize)> = AHashMap::new(); // (total, with_source)
629    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    // A method appearing on 3+ types without trait_source on any is almost certainly a trait method
642    method_counts
643        .values()
644        .any(|&(total, with_source)| total >= 3 && with_source == 0)
645}
646
647/// Collect explicit type and enum names from the API surface for named imports.
648///
649/// Returns a sorted, deduplicated list of type and enum names that should be
650/// imported from the core crate. This replaces glob imports (`use core::*`)
651/// which can cause name conflicts with local binding definitions (e.g. a
652/// `convert` function or `Result` type alias from the core crate shadowing
653/// the binding's own `convert` wrapper or `std::result::Result`).
654///
655/// Only struct/enum names are included — functions and type aliases are
656/// intentionally excluded because they are the source of conflicts.
657pub 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}