Skip to main content

alef_codegen/generators/
trait_bridge.rs

1//! Shared trait bridge code generation.
2//!
3//! Generates wrapper structs that allow foreign language objects (Python, JS, etc.)
4//! to implement Rust traits via FFI. Each backend implements [`TraitBridgeGenerator`]
5//! to provide language-specific dispatch logic; the shared functions in this module
6//! handle the structural boilerplate.
7
8use alef_core::config::{BridgeBinding, TraitBridgeConfig};
9use alef_core::ir::{FieldDef, FunctionDef, MethodDef, ParamDef, PrimitiveType, TypeDef, TypeRef};
10use heck::ToSnakeCase;
11use std::collections::HashMap;
12
13/// Everything needed to generate a trait bridge for one trait.
14pub struct TraitBridgeSpec<'a> {
15    /// The trait definition from the IR.
16    pub trait_def: &'a TypeDef,
17    /// Bridge configuration from `alef.toml`.
18    pub bridge_config: &'a TraitBridgeConfig,
19    /// Core crate import path (e.g., `"kreuzberg"`).
20    pub core_import: &'a str,
21    /// Language-specific prefix for the wrapper type (e.g., `"Python"`, `"Js"`, `"Wasm"`).
22    pub wrapper_prefix: &'a str,
23    /// Map of type name → fully-qualified Rust path for qualifying `Named` types.
24    pub type_paths: HashMap<String, String>,
25    /// The crate's error type name (e.g., `"KreuzbergError"`). Defaults to `"Error"`.
26    pub error_type: String,
27    /// Error constructor pattern. `{msg}` is replaced with the message expression.
28    pub error_constructor: String,
29}
30
31impl<'a> TraitBridgeSpec<'a> {
32    /// Fully qualified error type path (e.g., `"kreuzberg::KreuzbergError"`).
33    ///
34    /// If `error_type` already looks fully-qualified (contains `::`) or is a generic
35    /// type expression (contains `<`), it is returned as-is without prefixing
36    /// `core_import`. This lets backends specify rich error types like
37    /// `"Box<dyn std::error::Error + Send + Sync>"` directly.
38    pub fn error_path(&self) -> String {
39        if self.error_type.contains("::") || self.error_type.contains('<') {
40            self.error_type.clone()
41        } else {
42            format!("{}::{}", self.core_import, self.error_type)
43        }
44    }
45
46    /// Generate an error construction expression from a message expression.
47    pub fn make_error(&self, msg_expr: &str) -> String {
48        self.error_constructor.replace("{msg}", msg_expr)
49    }
50
51    /// Wrapper struct name: `{prefix}{TraitName}Bridge` (e.g., `PythonOcrBackendBridge`).
52    pub fn wrapper_name(&self) -> String {
53        format!("{}{}Bridge", self.wrapper_prefix, self.trait_def.name)
54    }
55
56    /// Snake-case version of the trait name (e.g., `"ocr_backend"`).
57    pub fn trait_snake(&self) -> String {
58        self.trait_def.name.to_snake_case()
59    }
60
61    /// Full Rust path to the trait (e.g., `kreuzberg::OcrBackend`).
62    pub fn trait_path(&self) -> String {
63        self.trait_def.rust_path.replace('-', "_")
64    }
65
66    /// Methods that are required (no default impl) — must be provided by the foreign object.
67    pub fn required_methods(&self) -> Vec<&'a MethodDef> {
68        self.trait_def.methods.iter().filter(|m| !m.has_default_impl).collect()
69    }
70
71    /// Methods that have a default impl — optional on the foreign object.
72    pub fn optional_methods(&self) -> Vec<&'a MethodDef> {
73        self.trait_def.methods.iter().filter(|m| m.has_default_impl).collect()
74    }
75}
76
77/// Backend-specific trait bridge generation.
78///
79/// Each binding backend (PyO3, NAPI-RS, wasm-bindgen, etc.) implements this trait
80/// to provide the language-specific parts of bridge codegen. The shared functions
81/// in this module call these methods to fill in the backend-dependent pieces.
82pub trait TraitBridgeGenerator {
83    /// The type of the wrapped foreign object (e.g., `"Py<PyAny>"`, `"ThreadsafeFunction"`).
84    fn foreign_object_type(&self) -> &str;
85
86    /// Additional `use` imports needed for the bridge code.
87    fn bridge_imports(&self) -> Vec<String>;
88
89    /// Generate the body of a synchronous method bridge.
90    ///
91    /// The returned string is inserted inside the trait impl method. It should
92    /// call through to the foreign object and convert the result.
93    fn gen_sync_method_body(&self, method: &MethodDef, spec: &TraitBridgeSpec) -> String;
94
95    /// Generate the body of an async method bridge.
96    ///
97    /// The returned string is the body of a `Box::pin(async move { ... })` block.
98    fn gen_async_method_body(&self, method: &MethodDef, spec: &TraitBridgeSpec) -> String;
99
100    /// Generate the constructor body that validates and wraps the foreign object.
101    ///
102    /// Should check that the foreign object provides all required methods and
103    /// return `Self { ... }` on success.
104    fn gen_constructor(&self, spec: &TraitBridgeSpec) -> String;
105
106    /// Generate the complete registration function including attributes, signature, and body.
107    ///
108    /// Each backend needs different function signatures (PyO3 takes `py: Python`,
109    /// NAPI takes `#[napi]` with JS params, FFI takes `extern "C"` with raw pointers),
110    /// so the generator owns the full function.
111    fn gen_registration_fn(&self, spec: &TraitBridgeSpec) -> String;
112
113    /// Generate an unregistration function for the bridge.
114    ///
115    /// Default implementation returns an empty string — backends opt in by
116    /// emitting a function whose name is `spec.bridge_config.unregister_fn`
117    /// (when set) and whose body calls into the host crate's
118    /// `unregister_*(name)` plugin entry point.
119    fn gen_unregistration_fn(&self, _spec: &TraitBridgeSpec) -> String {
120        String::new()
121    }
122
123    /// Generate a clear-all-plugins function for the bridge.
124    ///
125    /// Default implementation returns an empty string — backends opt in by
126    /// emitting a function whose name is `spec.bridge_config.clear_fn`
127    /// (when set) and whose body calls into the host crate's `clear_*()`
128    /// plugin entry point. Typically used in test teardown.
129    fn gen_clear_fn(&self, _spec: &TraitBridgeSpec) -> String {
130        String::new()
131    }
132
133    /// Whether the `#[async_trait]` macro should require `Send` on its futures.
134    ///
135    /// Returns `true` (default) for most targets. WASM is single-threaded so its
136    /// trait bounds don't include `Send`; implementors should return `false` there.
137    fn async_trait_is_send(&self) -> bool {
138        true
139    }
140}
141
142// ---------------------------------------------------------------------------
143// Shared generation functions
144// ---------------------------------------------------------------------------
145
146/// Generate the wrapper struct holding the foreign object and cached fields.
147///
148/// Produces a struct like:
149/// ```ignore
150/// pub struct PythonOcrBackendBridge {
151///     inner: Py<PyAny>,
152///     cached_name: String,
153/// }
154/// ```
155pub fn gen_bridge_wrapper_struct(spec: &TraitBridgeSpec, generator: &dyn TraitBridgeGenerator) -> String {
156    let wrapper = spec.wrapper_name();
157    let foreign_type = generator.foreign_object_type();
158
159    crate::template_env::render(
160        "generators/trait_bridge/wrapper_struct.jinja",
161        minijinja::context! {
162            wrapper_prefix => spec.wrapper_prefix,
163            trait_name => &spec.trait_def.name,
164            wrapper_name => wrapper,
165            foreign_type => foreign_type,
166        },
167    )
168}
169
170/// Generate `impl std::fmt::Debug for Wrapper`.
171///
172/// Required by trait bounds on `Plugin` super-trait (and many others) that
173/// extend `Debug`. Without this, generic plugin-pattern bridges fail to
174/// compile when the user's trait has a `Debug` super-trait bound.
175fn gen_bridge_debug_impl(spec: &TraitBridgeSpec) -> String {
176    let wrapper = spec.wrapper_name();
177    crate::template_env::render(
178        "generators/trait_bridge/debug_impl.jinja",
179        minijinja::context! {
180            wrapper_name => wrapper,
181        },
182    )
183}
184
185/// Generate `impl SuperTrait for Wrapper` when the bridge config specifies a super-trait.
186///
187/// Forwards `name()`, `version()`, `initialize()`, and `shutdown()` to the
188/// foreign object, using `cached_name` for `name()`.
189///
190/// The super-trait path is derived from the config's `super_trait` field. If it
191/// contains `::`, it's used as-is; otherwise it's qualified as `{core_import}::{super_trait}`.
192pub fn gen_bridge_plugin_impl(spec: &TraitBridgeSpec, generator: &dyn TraitBridgeGenerator) -> Option<String> {
193    let super_trait_name = spec.bridge_config.super_trait.as_deref()?;
194
195    let wrapper = spec.wrapper_name();
196    let core_import = spec.core_import;
197
198    // Derive the fully-qualified super-trait path
199    let super_trait_path = if super_trait_name.contains("::") {
200        super_trait_name.to_string()
201    } else {
202        format!("{core_import}::{super_trait_name}")
203    };
204
205    // Build synthetic MethodDefs for the Plugin methods and delegate to the generator
206    // for the actual call bodies. The Plugin trait interface is well-known: name(),
207    // version(), initialize(), shutdown().
208    let error_path = spec.error_path();
209
210    // version() -> String — delegate to foreign object
211    let version_method = MethodDef {
212        name: "version".to_string(),
213        params: vec![],
214        return_type: alef_core::ir::TypeRef::String,
215        is_async: false,
216        is_static: false,
217        error_type: None,
218        doc: String::new(),
219        receiver: Some(alef_core::ir::ReceiverKind::Ref),
220        sanitized: false,
221        trait_source: None,
222        returns_ref: false,
223        returns_cow: false,
224        return_newtype_wrapper: None,
225        has_default_impl: false,
226        binding_excluded: false,
227        binding_exclusion_reason: None,
228    };
229    let version_body = generator.gen_sync_method_body(&version_method, spec);
230
231    // initialize() -> Result<(), ErrorType>
232    let init_method = MethodDef {
233        name: "initialize".to_string(),
234        params: vec![],
235        return_type: alef_core::ir::TypeRef::Unit,
236        is_async: false,
237        is_static: false,
238        error_type: Some(error_path.clone()),
239        doc: String::new(),
240        receiver: Some(alef_core::ir::ReceiverKind::Ref),
241        sanitized: false,
242        trait_source: None,
243        returns_ref: false,
244        returns_cow: false,
245        return_newtype_wrapper: None,
246        has_default_impl: true,
247        binding_excluded: false,
248        binding_exclusion_reason: None,
249    };
250    let init_body = generator.gen_sync_method_body(&init_method, spec);
251
252    // shutdown() -> Result<(), ErrorType>
253    let shutdown_method = MethodDef {
254        name: "shutdown".to_string(),
255        params: vec![],
256        return_type: alef_core::ir::TypeRef::Unit,
257        is_async: false,
258        is_static: false,
259        error_type: Some(error_path.clone()),
260        doc: String::new(),
261        receiver: Some(alef_core::ir::ReceiverKind::Ref),
262        sanitized: false,
263        trait_source: None,
264        returns_ref: false,
265        returns_cow: false,
266        return_newtype_wrapper: None,
267        has_default_impl: true,
268        binding_excluded: false,
269        binding_exclusion_reason: None,
270    };
271    let shutdown_body = generator.gen_sync_method_body(&shutdown_method, spec);
272
273    // Split method bodies into lines for template iteration
274    let version_lines: Vec<&str> = version_body.lines().collect();
275    let init_lines: Vec<&str> = init_body.lines().collect();
276    let shutdown_lines: Vec<&str> = shutdown_body.lines().collect();
277
278    Some(crate::template_env::render(
279        "generators/trait_bridge/plugin_impl.jinja",
280        minijinja::context! {
281            super_trait_path => super_trait_path,
282            wrapper_name => wrapper,
283            error_path => error_path,
284            version_lines => version_lines,
285            init_lines => init_lines,
286            shutdown_lines => shutdown_lines,
287        },
288    ))
289}
290
291/// Generate `impl Trait for Wrapper` dispatching each method through the generator.
292///
293/// Methods with `has_default_impl = true` are NOT emitted — the trait's own default
294/// implementation is used instead.  Only required (non-defaulted) own methods get a
295/// generated vtable-forwarding body.
296pub fn gen_bridge_trait_impl(spec: &TraitBridgeSpec, generator: &dyn TraitBridgeGenerator) -> String {
297    let wrapper = spec.wrapper_name();
298    let trait_path = spec.trait_path();
299
300    // Check if the trait has async methods (needed for async_trait macro compatibility).
301    // Only own, required (non-default) methods need this check — those are the ones we emit.
302    let has_async_methods = spec
303        .trait_def
304        .methods
305        .iter()
306        .any(|m| m.is_async && m.trait_source.is_none() && !m.has_default_impl);
307    let async_trait_is_send = generator.async_trait_is_send();
308
309    // Filter out:
310    // - Methods inherited from super-traits (handled by gen_bridge_plugin_impl)
311    // - Methods with a default impl (let the trait's own default take effect)
312    let own_methods: Vec<_> = spec
313        .trait_def
314        .methods
315        .iter()
316        .filter(|m| m.trait_source.is_none() && !m.has_default_impl)
317        .collect();
318
319    // Build method code with proper indentation
320    let mut methods_code = String::with_capacity(1024);
321    for (i, method) in own_methods.iter().enumerate() {
322        if i > 0 {
323            methods_code.push_str("\n\n");
324        }
325
326        // Build the method signature
327        let async_kw = if method.is_async { "async " } else { "" };
328        let receiver = match &method.receiver {
329            Some(alef_core::ir::ReceiverKind::Ref) => "&self",
330            Some(alef_core::ir::ReceiverKind::RefMut) => "&mut self",
331            Some(alef_core::ir::ReceiverKind::Owned) => "self",
332            None => "",
333        };
334
335        // Build params (excluding self), using format_param_type to respect is_ref/is_mut
336        let params: Vec<String> = method
337            .params
338            .iter()
339            .map(|p| format!("{}: {}", p.name, format_param_type(p, &spec.type_paths)))
340            .collect();
341
342        let all_params = if receiver.is_empty() {
343            params.join(", ")
344        } else if params.is_empty() {
345            receiver.to_string()
346        } else {
347            format!("{}, {}", receiver, params.join(", "))
348        };
349
350        // Return type — override the IR's error type with the configured crate error type
351        // so the impl matches the actual trait definition (the IR may extract a different
352        // error type like anyhow::Error from re-exports or type alias resolution).
353        // Pass `returns_ref` so Vec<T> is emitted as `&[elem]` when the trait returns a slice.
354        let error_override = method.error_type.as_ref().map(|_| spec.error_path());
355        let ret = format_return_type(
356            &method.return_type,
357            error_override.as_deref(),
358            &spec.type_paths,
359            method.returns_ref,
360        );
361
362        // Generate body: async methods use Box::pin, sync methods call directly
363        let raw_body = if method.is_async {
364            generator.gen_async_method_body(method, spec)
365        } else {
366            generator.gen_sync_method_body(method, spec)
367        };
368
369        // When the trait method returns `&[&str]` (i.e. Vec<String> + returns_ref), the
370        // foreign bridge body returns an owned Vec<String> (via unwrap_or_default or similar).
371        // Wrap it with Box::leak so the &'static str slice satisfies the return type.
372        // This is correct for the plugin registration pattern: supported_mime_types() is
373        // called once per registration and the data is process-global.
374        //
375        // Exception: when the raw_body is already a reference to a cached
376        // `&'static [&'static str]` field (e.g. FFI's `self.{name}_strs` fast-path),
377        // there is nothing to leak — return it directly.
378        let raw_body_trimmed = raw_body.trim();
379        let body_is_static_slice = raw_body_trimmed.starts_with("self.") && raw_body_trimmed.ends_with("_strs");
380        let body = if method.returns_ref
381            && matches!(&method.return_type, alef_core::ir::TypeRef::Vec(inner) if matches!(inner.as_ref(), alef_core::ir::TypeRef::String))
382        {
383            if body_is_static_slice {
384                raw_body
385            } else {
386                format!(
387                    "let __types: Vec<String> = {{ {raw_body} }};\n\
388                     let __strs: Vec<&'static str> = __types.into_iter()\n\
389                         .map(|s| -> &'static str {{ Box::leak(s.into_boxed_str()) }})\n\
390                         .collect();\n\
391                     Box::leak(__strs.into_boxed_slice())"
392                )
393            }
394        } else {
395            raw_body
396        };
397
398        // Indent body lines
399        let indented_body = body
400            .lines()
401            .map(|line| format!("        {line}"))
402            .collect::<Vec<_>>()
403            .join("\n");
404
405        methods_code.push_str(&crate::template_env::render(
406            "generators/trait_bridge/trait_method.jinja",
407            minijinja::context! {
408                async_kw => async_kw,
409                method_name => &method.name,
410                all_params => all_params,
411                ret => ret,
412                indented_body => &indented_body,
413            },
414        ));
415    }
416
417    crate::template_env::render(
418        "generators/trait_bridge/trait_impl.jinja",
419        minijinja::context! {
420            has_async_methods => has_async_methods,
421            async_trait_is_send => async_trait_is_send,
422            trait_path => trait_path,
423            wrapper_name => wrapper,
424            methods_code => methods_code,
425        },
426    )
427}
428
429/// Generate the `register_xxx()` function that wraps a foreign object and
430/// inserts it into the plugin registry.
431///
432/// Returns `None` when `bridge_config.register_fn` is absent (per-call bridge pattern).
433/// The generator owns the full function (attributes, signature, body) because each
434/// backend needs different signatures.
435pub fn gen_bridge_registration_fn(spec: &TraitBridgeSpec, generator: &dyn TraitBridgeGenerator) -> Option<String> {
436    spec.bridge_config.register_fn.as_deref()?;
437    Some(generator.gen_registration_fn(spec))
438}
439
440/// Generate the `unregister_xxx(name)` function that removes a previously
441/// registered plugin from the registry.
442///
443/// Returns `None` when `bridge_config.unregister_fn` is absent or when the
444/// backend hasn't opted in (returns the empty string from
445/// [`TraitBridgeGenerator::gen_unregistration_fn`]).
446pub fn gen_bridge_unregistration_fn(spec: &TraitBridgeSpec, generator: &dyn TraitBridgeGenerator) -> Option<String> {
447    spec.bridge_config.unregister_fn.as_deref()?;
448    let body = generator.gen_unregistration_fn(spec);
449    if body.is_empty() { None } else { Some(body) }
450}
451
452/// Generate the `clear_xxx()` function that removes all registered plugins
453/// of this type.
454///
455/// Returns `None` when `bridge_config.clear_fn` is absent or when the
456/// backend hasn't opted in (returns the empty string from
457/// [`TraitBridgeGenerator::gen_clear_fn`]).
458pub fn gen_bridge_clear_fn(spec: &TraitBridgeSpec, generator: &dyn TraitBridgeGenerator) -> Option<String> {
459    spec.bridge_config.clear_fn.as_deref()?;
460    let body = generator.gen_clear_fn(spec);
461    if body.is_empty() { None } else { Some(body) }
462}
463
464/// Resolve the FQN of a host-crate plugin function (e.g.
465/// `kreuzberg::plugins::ocr::unregister_ocr_backend`) given the bridge's
466/// `registry_getter` path. The convention used by host crates is:
467///
468/// - `registry_getter = "kreuzberg::plugins::registry::get_ocr_backend_registry"`
469/// - top-level fn      = `kreuzberg::plugins::ocr::unregister_ocr_backend`
470///
471/// We rewrite `::registry::get_*_registry` to `::<sub>::<fn_name>` where
472/// `<sub>` is the trait submodule name (extracted from `_*_registry`).
473/// When the heuristic fails (no `registry_getter`, unexpected shape), we
474/// fall back to `{core_import}::plugins::{fn_name}` so the user can rely on
475/// a re-export.
476///
477/// Shared by every backend that opts in to `unregister_*`/`clear_*` codegen
478/// (pyo3, napi, magnus, php, rustler, gleam, extendr, dart, swift, kotlin,
479/// wasm). Replaces the duplicated `<lang>_host_function_path` helpers that
480/// each backend used to define.
481pub fn host_function_path(spec: &TraitBridgeSpec, fn_name: &str) -> String {
482    if let Some(getter) = spec.bridge_config.registry_getter.as_deref() {
483        let last = getter.rsplit("::").next().unwrap_or("");
484        if let Some(sub) = last.strip_prefix("get_").and_then(|s| s.strip_suffix("_registry")) {
485            let prefix_end = getter.len() - last.len();
486            let prefix = &getter[..prefix_end];
487            let prefix = prefix.trim_end_matches("registry::");
488            return format!("{prefix}{sub}::{fn_name}");
489        }
490    }
491    format!("{}::plugins::{}", spec.core_import, fn_name)
492}
493
494/// Result of trait bridge generation: imports (to be added via `builder.add_import`)
495/// and the code body (to be added via `builder.add_item`).
496pub struct BridgeOutput {
497    /// Import paths (e.g., `"std::sync::Arc"`) — callers should add via `builder.add_import()`.
498    pub imports: Vec<String>,
499    /// The generated code (struct, impls, registration fn).
500    pub code: String,
501}
502
503/// Generate the complete trait bridge code block: struct, impls, and
504/// optionally a registration function.
505///
506/// Returns [`BridgeOutput`] with imports separated from code so callers can
507/// route imports through `builder.add_import()` (which deduplicates).
508pub fn gen_bridge_all(spec: &TraitBridgeSpec, generator: &dyn TraitBridgeGenerator) -> BridgeOutput {
509    let imports = generator.bridge_imports();
510    let mut out = String::with_capacity(4096);
511
512    // Wrapper struct
513    out.push_str(&gen_bridge_wrapper_struct(spec, generator));
514    out.push_str("\n\n");
515
516    // Debug impl (required by Plugin super-trait Debug bound)
517    out.push_str(&gen_bridge_debug_impl(spec));
518    out.push_str("\n\n");
519
520    // Constructor (impl block with new())
521    out.push_str(&generator.gen_constructor(spec));
522    out.push_str("\n\n");
523
524    // Plugin super-trait impl (if applicable)
525    if let Some(plugin_impl) = gen_bridge_plugin_impl(spec, generator) {
526        out.push_str(&plugin_impl);
527        out.push_str("\n\n");
528    }
529
530    // Trait impl
531    out.push_str(&gen_bridge_trait_impl(spec, generator));
532
533    // Registration function — only when register_fn is configured
534    if let Some(reg_fn_code) = gen_bridge_registration_fn(spec, generator) {
535        out.push_str("\n\n");
536        out.push_str(&reg_fn_code);
537    }
538
539    // Unregistration function — only when unregister_fn is configured AND
540    // the backend has opted in (non-empty body).
541    if let Some(unreg_fn_code) = gen_bridge_unregistration_fn(spec, generator) {
542        out.push_str("\n\n");
543        out.push_str(&unreg_fn_code);
544    }
545
546    // Clear-all function — only when clear_fn is configured AND the backend
547    // has opted in (non-empty body).
548    if let Some(clear_fn_code) = gen_bridge_clear_fn(spec, generator) {
549        out.push_str("\n\n");
550        out.push_str(&clear_fn_code);
551    }
552
553    BridgeOutput { imports, code: out }
554}
555
556// ---------------------------------------------------------------------------
557// Helpers
558// ---------------------------------------------------------------------------
559
560/// Format a `TypeRef` as a Rust type string for use in trait method signatures.
561///
562/// `type_paths` qualifies `Named` types with their full Rust path (e.g., `"Config"` →
563/// `"kreuzberg::Config"`). If a name isn't in `type_paths`, it's used as-is.
564pub fn format_type_ref(ty: &alef_core::ir::TypeRef, type_paths: &HashMap<String, String>) -> String {
565    use alef_core::ir::{PrimitiveType, TypeRef};
566    match ty {
567        TypeRef::Primitive(p) => match p {
568            PrimitiveType::Bool => "bool",
569            PrimitiveType::U8 => "u8",
570            PrimitiveType::U16 => "u16",
571            PrimitiveType::U32 => "u32",
572            PrimitiveType::U64 => "u64",
573            PrimitiveType::I8 => "i8",
574            PrimitiveType::I16 => "i16",
575            PrimitiveType::I32 => "i32",
576            PrimitiveType::I64 => "i64",
577            PrimitiveType::F32 => "f32",
578            PrimitiveType::F64 => "f64",
579            PrimitiveType::Usize => "usize",
580            PrimitiveType::Isize => "isize",
581        }
582        .to_string(),
583        TypeRef::String => "String".to_string(),
584        TypeRef::Char => "char".to_string(),
585        TypeRef::Bytes => "Vec<u8>".to_string(),
586        TypeRef::Optional(inner) => format!("Option<{}>", format_type_ref(inner, type_paths)),
587        TypeRef::Vec(inner) => format!("Vec<{}>", format_type_ref(inner, type_paths)),
588        TypeRef::Map(k, v) => format!(
589            "std::collections::HashMap<{}, {}>",
590            format_type_ref(k, type_paths),
591            format_type_ref(v, type_paths)
592        ),
593        TypeRef::Named(name) => type_paths.get(name.as_str()).cloned().unwrap_or_else(|| name.clone()),
594        TypeRef::Path => "std::path::PathBuf".to_string(),
595        TypeRef::Unit => "()".to_string(),
596        TypeRef::Json => "serde_json::Value".to_string(),
597        TypeRef::Duration => "std::time::Duration".to_string(),
598    }
599}
600
601/// Format a return type, wrapping in `Result` when an error type is present.
602///
603/// When `returns_ref` is `true` and the IR type is `Vec(T)`, the trait method
604/// actually returns `&[T]` (the IR collapses `&[T]` into `Vec<T>` + `returns_ref`
605/// flag). This function emits the correct reference slice type in that case so the
606/// generated bridge impl signature matches the actual trait definition.
607///
608/// For the FFI bridge the concrete element type of a `Vec<String>` with `returns_ref`
609/// is `&str`, yielding a return type of `&[&str]`.
610pub fn format_return_type(
611    ty: &alef_core::ir::TypeRef,
612    error_type: Option<&str>,
613    type_paths: &HashMap<String, String>,
614    returns_ref: bool,
615) -> String {
616    let inner = if returns_ref {
617        // Rewrite Vec<T> → &[elem_type] where elem_type is the ref-form of T.
618        if let alef_core::ir::TypeRef::Vec(elem) = ty {
619            let elem_str = match elem.as_ref() {
620                alef_core::ir::TypeRef::String => "&str".to_string(),
621                alef_core::ir::TypeRef::Bytes => "&[u8]".to_string(),
622                alef_core::ir::TypeRef::Named(name) => {
623                    let qualified = type_paths.get(name.as_str()).cloned().unwrap_or_else(|| name.clone());
624                    format!("&{qualified}")
625                }
626                other => format_type_ref(other, type_paths),
627            };
628            format!("&[{elem_str}]")
629        } else {
630            format_type_ref(ty, type_paths)
631        }
632    } else {
633        format_type_ref(ty, type_paths)
634    };
635    match error_type {
636        Some(err) => format!("std::result::Result<{inner}, {err}>"),
637        None => inner,
638    }
639}
640
641/// Format a parameter type, respecting `is_ref`, `is_mut`, and `optional` from the IR.
642///
643/// Unlike [`format_type_ref`], this function produces reference types when the
644/// original Rust parameter was a `&T` or `&mut T`, and wraps in `Option<>` when
645/// `param.optional` is true:
646/// - `String + is_ref` → `&str`
647/// - `String + is_ref + optional` → `Option<&str>`
648/// - `Bytes + is_ref` → `&[u8]`
649/// - `Path + is_ref` → `&std::path::Path`
650/// - `Vec<T> + is_ref` → `&[T]`
651/// - `Named(n) + is_ref` → `&{qualified_name}`
652pub fn format_param_type(param: &ParamDef, type_paths: &HashMap<String, String>) -> String {
653    use alef_core::ir::TypeRef;
654    let base = if param.is_ref {
655        let mutability = if param.is_mut { "mut " } else { "" };
656        match &param.ty {
657            TypeRef::String => format!("&{mutability}str"),
658            TypeRef::Bytes => format!("&{mutability}[u8]"),
659            TypeRef::Path => format!("&{mutability}std::path::Path"),
660            TypeRef::Vec(inner) => format!("&{mutability}[{}]", format_type_ref(inner, type_paths)),
661            TypeRef::Named(name) => {
662                let qualified = type_paths.get(name.as_str()).cloned().unwrap_or_else(|| name.clone());
663                format!("&{mutability}{qualified}")
664            }
665            TypeRef::Optional(inner) => {
666                // Preserve the Option wrapper but apply the ref transformation to the inner type.
667                // e.g. Option<String> + is_ref → Option<&str>
668                //      Option<Vec<T>> + is_ref → Option<&[T]>
669                let inner_type_str = match inner.as_ref() {
670                    TypeRef::String => format!("&{mutability}str"),
671                    TypeRef::Bytes => format!("&{mutability}[u8]"),
672                    TypeRef::Path => format!("&{mutability}std::path::Path"),
673                    TypeRef::Vec(v) => format!("&{mutability}[{}]", format_type_ref(v, type_paths)),
674                    TypeRef::Named(name) => {
675                        let qualified = type_paths.get(name.as_str()).cloned().unwrap_or_else(|| name.clone());
676                        format!("&{mutability}{qualified}")
677                    }
678                    // Primitives and other Copy types: pass by value inside Option
679                    other => format_type_ref(other, type_paths),
680                };
681                // Already wrapped in Option — return directly to avoid double-wrapping below.
682                return format!("Option<{inner_type_str}>");
683            }
684            // All other types are Copy/small — pass by value even when is_ref is set
685            other => format_type_ref(other, type_paths),
686        }
687    } else {
688        format_type_ref(&param.ty, type_paths)
689    };
690
691    // Wrap in Option<> when the parameter is optional (e.g. `title: Option<&str>`).
692    // The TypeRef::Optional arm above returns early, so this only fires for the
693    // `optional: true` IR flag pattern where ty is the unwrapped inner type.
694    if param.optional {
695        format!("Option<{base}>")
696    } else {
697        base
698    }
699}
700
701// ---------------------------------------------------------------------------
702// Shared helpers — used by all backend trait_bridge modules.
703// ---------------------------------------------------------------------------
704
705/// Map a Rust primitive to its type string.
706pub fn prim(p: &PrimitiveType) -> &'static str {
707    use PrimitiveType::*;
708    match p {
709        Bool => "bool",
710        U8 => "u8",
711        U16 => "u16",
712        U32 => "u32",
713        U64 => "u64",
714        I8 => "i8",
715        I16 => "i16",
716        I32 => "i32",
717        I64 => "i64",
718        F32 => "f32",
719        F64 => "f64",
720        Usize => "usize",
721        Isize => "isize",
722    }
723}
724
725/// Map a `TypeRef` to its Rust source type string for use in trait bridge method
726/// signatures. `ci` is the core import path (e.g. `"kreuzberg"`), `tp` maps
727/// type names to fully-qualified paths.
728pub fn bridge_param_type(ty: &TypeRef, ci: &str, is_ref: bool, tp: &HashMap<String, String>) -> String {
729    match ty {
730        TypeRef::Bytes if is_ref => "&[u8]".into(),
731        TypeRef::Bytes => "Vec<u8>".into(),
732        TypeRef::String if is_ref => "&str".into(),
733        TypeRef::String => "String".into(),
734        TypeRef::Path if is_ref => "&std::path::Path".into(),
735        TypeRef::Path => "std::path::PathBuf".into(),
736        TypeRef::Named(n) => {
737            let qualified = tp.get(n).cloned().unwrap_or_else(|| format!("{ci}::{n}"));
738            if is_ref { format!("&{qualified}") } else { qualified }
739        }
740        TypeRef::Vec(inner) => format!("Vec<{}>", bridge_param_type(inner, ci, false, tp)),
741        TypeRef::Optional(inner) => format!("Option<{}>", bridge_param_type(inner, ci, false, tp)),
742        TypeRef::Primitive(p) => prim(p).into(),
743        TypeRef::Unit => "()".into(),
744        TypeRef::Char => "char".into(),
745        TypeRef::Map(k, v) => format!(
746            "std::collections::HashMap<{}, {}>",
747            bridge_param_type(k, ci, false, tp),
748            bridge_param_type(v, ci, false, tp)
749        ),
750        TypeRef::Json => "serde_json::Value".into(),
751        TypeRef::Duration => "std::time::Duration".into(),
752    }
753}
754
755/// Map a visitor method parameter type to the correct Rust type string, handling
756/// IR quirks:
757/// - `ty=String, optional=true, is_ref=true` → `Option<&str>` (IR collapses `Option<&str>`)
758/// - `ty=Vec<T>, is_ref=true` → `&[T]` (IR collapses `&[T]`)
759/// - Everything else delegates to [`bridge_param_type`].
760pub fn visitor_param_type(ty: &TypeRef, is_ref: bool, optional: bool, tp: &HashMap<String, String>) -> String {
761    if optional && matches!(ty, TypeRef::String) && is_ref {
762        return "Option<&str>".to_string();
763    }
764    if is_ref {
765        if let TypeRef::Vec(inner) = ty {
766            let inner_str = bridge_param_type(inner, "", false, tp);
767            return format!("&[{inner_str}]");
768        }
769    }
770    bridge_param_type(ty, "", is_ref, tp)
771}
772
773/// Find the first function parameter that matches a trait bridge configuration
774/// (by type alias or parameter name).
775///
776/// Bridges configured with `bind_via = "options_field"` are skipped — they live on a
777/// struct field rather than directly as a parameter, and are returned by
778/// [`find_bridge_field`] instead.
779pub fn find_bridge_param<'a>(
780    func: &FunctionDef,
781    bridges: &'a [TraitBridgeConfig],
782) -> Option<(usize, &'a TraitBridgeConfig)> {
783    for (idx, param) in func.params.iter().enumerate() {
784        let named = match &param.ty {
785            TypeRef::Named(n) => Some(n.as_str()),
786            TypeRef::Optional(inner) => {
787                if let TypeRef::Named(n) = inner.as_ref() {
788                    Some(n.as_str())
789                } else {
790                    None
791                }
792            }
793            _ => None,
794        };
795        for bridge in bridges {
796            if bridge.bind_via != BridgeBinding::FunctionParam {
797                continue;
798            }
799            if let Some(type_name) = named {
800                if bridge.type_alias.as_deref() == Some(type_name) {
801                    return Some((idx, bridge));
802                }
803            }
804            if bridge.param_name.as_deref() == Some(param.name.as_str()) {
805                return Some((idx, bridge));
806            }
807        }
808    }
809    None
810}
811
812/// Match info for a trait bridge whose handle lives as a struct field
813/// (`bind_via = "options_field"`).
814#[derive(Debug, Clone)]
815pub struct BridgeFieldMatch<'a> {
816    /// Index of the function parameter that carries the owning struct.
817    pub param_index: usize,
818    /// Name of the parameter (e.g., `"options"`).
819    pub param_name: String,
820    /// IR type name of the parameter, with any `Option<>` wrapper unwrapped.
821    pub options_type: String,
822    /// True if the param is `Option<TypeName>` rather than `TypeName`.
823    pub param_is_optional: bool,
824    /// Name of the field on `options_type` that holds the bridge handle.
825    pub field_name: String,
826    /// The matching field definition (carries the field's `TypeRef`).
827    pub field: &'a FieldDef,
828    /// The bridge configuration that produced the match.
829    pub bridge: &'a TraitBridgeConfig,
830}
831
832/// Find the first function parameter whose IR type carries a bridge field
833/// (`bind_via = "options_field"`).
834///
835/// For each function parameter whose IR type is `Named(N)` or `Optional<Named(N)>`,
836/// look up `N` in `types`. If `N` matches any bridge's `options_type`, search its
837/// fields for one whose name matches the bridge's resolved options field (or whose
838/// type's `Named` alias matches the bridge's `type_alias`). Returns the first match.
839///
840/// Bridges configured with `bind_via = "function_param"` are skipped — those go
841/// through [`find_bridge_param`] instead.
842pub fn find_bridge_field<'a>(
843    func: &FunctionDef,
844    types: &'a [TypeDef],
845    bridges: &'a [TraitBridgeConfig],
846) -> Option<BridgeFieldMatch<'a>> {
847    fn unwrap_named(ty: &TypeRef) -> Option<(&str, bool)> {
848        match ty {
849            TypeRef::Named(n) => Some((n.as_str(), false)),
850            TypeRef::Optional(inner) => {
851                if let TypeRef::Named(n) = inner.as_ref() {
852                    Some((n.as_str(), true))
853                } else {
854                    None
855                }
856            }
857            _ => None,
858        }
859    }
860
861    for (idx, param) in func.params.iter().enumerate() {
862        let Some((type_name, is_optional)) = unwrap_named(&param.ty) else {
863            continue;
864        };
865        let Some(type_def) = types.iter().find(|t| t.name == type_name) else {
866            continue;
867        };
868        for bridge in bridges {
869            if bridge.bind_via != BridgeBinding::OptionsField {
870                continue;
871            }
872            if bridge.options_type.as_deref() != Some(type_name) {
873                continue;
874            }
875            let field_name = bridge.resolved_options_field();
876            for field in &type_def.fields {
877                let matches_name = field_name.is_some_and(|n| field.name == n);
878                let matches_alias = bridge
879                    .type_alias
880                    .as_deref()
881                    .is_some_and(|alias| field_type_matches_alias(&field.ty, alias));
882                if matches_name || matches_alias {
883                    return Some(BridgeFieldMatch {
884                        param_index: idx,
885                        param_name: param.name.clone(),
886                        options_type: type_name.to_string(),
887                        param_is_optional: is_optional,
888                        field_name: field.name.clone(),
889                        field,
890                        bridge,
891                    });
892                }
893            }
894        }
895    }
896    None
897}
898
899/// True if `field_ty` references a `Named` type whose name equals `alias`,
900/// allowing for `Option<>` and `Vec<>` wrappers.
901fn field_type_matches_alias(field_ty: &TypeRef, alias: &str) -> bool {
902    match field_ty {
903        TypeRef::Named(n) => n == alias,
904        TypeRef::Optional(inner) | TypeRef::Vec(inner) => field_type_matches_alias(inner, alias),
905        _ => false,
906    }
907}
908
909/// Convert a snake_case string to camelCase.
910pub fn to_camel_case(s: &str) -> String {
911    let mut result = String::new();
912    let mut capitalize_next = false;
913    for ch in s.chars() {
914        if ch == '_' {
915            capitalize_next = true;
916        } else if capitalize_next {
917            result.push(ch.to_ascii_uppercase());
918            capitalize_next = false;
919        } else {
920            result.push(ch);
921        }
922    }
923    result
924}
925
926#[cfg(test)]
927mod tests {
928    use super::*;
929    use alef_core::config::TraitBridgeConfig;
930    use alef_core::ir::{MethodDef, ParamDef, PrimitiveType, ReceiverKind, TypeDef, TypeRef};
931
932    // ---------------------------------------------------------------------------
933    // Test helpers
934    // ---------------------------------------------------------------------------
935
936    fn make_trait_bridge_config(super_trait: Option<&str>, register_fn: Option<&str>) -> TraitBridgeConfig {
937        TraitBridgeConfig {
938            trait_name: "OcrBackend".to_string(),
939            super_trait: super_trait.map(str::to_string),
940            registry_getter: None,
941            register_fn: register_fn.map(str::to_string),
942            unregister_fn: None,
943            clear_fn: None,
944            type_alias: None,
945            param_name: None,
946            register_extra_args: None,
947            exclude_languages: Vec::new(),
948            ffi_skip_methods: Vec::new(),
949            bind_via: BridgeBinding::FunctionParam,
950            options_type: None,
951            options_field: None,
952            context_type: None,
953            result_type: None,
954        }
955    }
956
957    fn make_type_def(name: &str, rust_path: &str, methods: Vec<MethodDef>) -> TypeDef {
958        TypeDef {
959            name: name.to_string(),
960            rust_path: rust_path.to_string(),
961            original_rust_path: rust_path.to_string(),
962            fields: vec![],
963            methods,
964            is_opaque: true,
965            is_clone: false,
966            is_copy: false,
967            doc: String::new(),
968            cfg: None,
969            is_trait: true,
970            has_default: false,
971            has_stripped_cfg_fields: false,
972            is_return_type: false,
973            serde_rename_all: None,
974            has_serde: false,
975            super_traits: vec![],
976            binding_excluded: false,
977            binding_exclusion_reason: None,
978        }
979    }
980
981    fn make_method(
982        name: &str,
983        params: Vec<ParamDef>,
984        return_type: TypeRef,
985        is_async: bool,
986        has_default_impl: bool,
987        trait_source: Option<&str>,
988        error_type: Option<&str>,
989    ) -> MethodDef {
990        MethodDef {
991            name: name.to_string(),
992            params,
993            return_type,
994            is_async,
995            is_static: false,
996            error_type: error_type.map(str::to_string),
997            doc: String::new(),
998            receiver: Some(ReceiverKind::Ref),
999            sanitized: false,
1000            trait_source: trait_source.map(str::to_string),
1001            returns_ref: false,
1002            returns_cow: false,
1003            return_newtype_wrapper: None,
1004            has_default_impl,
1005            binding_excluded: false,
1006            binding_exclusion_reason: None,
1007        }
1008    }
1009
1010    fn make_func(name: &str, params: Vec<ParamDef>) -> FunctionDef {
1011        FunctionDef {
1012            name: name.to_string(),
1013            rust_path: format!("mylib::{name}"),
1014            original_rust_path: String::new(),
1015            params,
1016            return_type: TypeRef::Unit,
1017            is_async: false,
1018            error_type: None,
1019            doc: String::new(),
1020            cfg: None,
1021            sanitized: false,
1022            return_sanitized: false,
1023            returns_ref: false,
1024            returns_cow: false,
1025            return_newtype_wrapper: None,
1026            binding_excluded: false,
1027            binding_exclusion_reason: None,
1028        }
1029    }
1030
1031    fn make_field(name: &str, ty: TypeRef) -> FieldDef {
1032        FieldDef {
1033            name: name.to_string(),
1034            ty,
1035            optional: false,
1036            default: None,
1037            doc: String::new(),
1038            sanitized: false,
1039            is_boxed: false,
1040            type_rust_path: None,
1041            cfg: None,
1042            typed_default: None,
1043            core_wrapper: Default::default(),
1044            vec_inner_core_wrapper: Default::default(),
1045            newtype_wrapper: None,
1046            serde_rename: None,
1047            serde_flatten: false,
1048            binding_excluded: false,
1049            binding_exclusion_reason: None,
1050        }
1051    }
1052
1053    fn make_param(name: &str, ty: TypeRef, is_ref: bool) -> ParamDef {
1054        ParamDef {
1055            name: name.to_string(),
1056            ty,
1057            optional: false,
1058            default: None,
1059            sanitized: false,
1060            typed_default: None,
1061            is_ref,
1062            is_mut: false,
1063            newtype_wrapper: None,
1064            original_type: None,
1065        }
1066    }
1067
1068    fn make_spec<'a>(
1069        trait_def: &'a TypeDef,
1070        bridge_config: &'a TraitBridgeConfig,
1071        wrapper_prefix: &'a str,
1072        type_paths: HashMap<String, String>,
1073    ) -> TraitBridgeSpec<'a> {
1074        TraitBridgeSpec {
1075            trait_def,
1076            bridge_config,
1077            core_import: "mylib",
1078            wrapper_prefix,
1079            type_paths,
1080            error_type: "MyError".to_string(),
1081            error_constructor: "MyError::from({msg})".to_string(),
1082        }
1083    }
1084
1085    // ---------------------------------------------------------------------------
1086    // Mock backend
1087    // ---------------------------------------------------------------------------
1088
1089    struct MockBridgeGenerator;
1090
1091    impl TraitBridgeGenerator for MockBridgeGenerator {
1092        fn foreign_object_type(&self) -> &str {
1093            "Py<PyAny>"
1094        }
1095
1096        fn bridge_imports(&self) -> Vec<String> {
1097            vec!["pyo3::prelude::*".to_string(), "pyo3::types::PyString".to_string()]
1098        }
1099
1100        fn gen_sync_method_body(&self, method: &MethodDef, _spec: &TraitBridgeSpec) -> String {
1101            format!("// sync body for {}", method.name)
1102        }
1103
1104        fn gen_async_method_body(&self, method: &MethodDef, _spec: &TraitBridgeSpec) -> String {
1105            format!("// async body for {}", method.name)
1106        }
1107
1108        fn gen_constructor(&self, spec: &TraitBridgeSpec) -> String {
1109            format!(
1110                "impl {} {{\n    pub fn new(obj: Py<PyAny>) -> Self {{ Self {{ inner: obj, cached_name: String::new() }} }}\n}}",
1111                spec.wrapper_name()
1112            )
1113        }
1114
1115        fn gen_registration_fn(&self, spec: &TraitBridgeSpec) -> String {
1116            let fn_name = spec.bridge_config.register_fn.as_deref().unwrap_or("register");
1117            format!("pub fn {fn_name}(obj: Py<PyAny>) {{ /* register */ }}")
1118        }
1119    }
1120
1121    // ---------------------------------------------------------------------------
1122    // TraitBridgeSpec helpers
1123    // ---------------------------------------------------------------------------
1124
1125    #[test]
1126    fn test_wrapper_name() {
1127        let trait_def = make_type_def("OcrBackend", "mylib::OcrBackend", vec![]);
1128        let config = make_trait_bridge_config(None, None);
1129        let spec = make_spec(&trait_def, &config, "Py", HashMap::new());
1130        assert_eq!(spec.wrapper_name(), "PyOcrBackendBridge");
1131    }
1132
1133    #[test]
1134    fn test_trait_snake() {
1135        let trait_def = make_type_def("OcrBackend", "mylib::OcrBackend", vec![]);
1136        let config = make_trait_bridge_config(None, None);
1137        let spec = make_spec(&trait_def, &config, "Py", HashMap::new());
1138        assert_eq!(spec.trait_snake(), "ocr_backend");
1139    }
1140
1141    #[test]
1142    fn test_trait_path_replaces_hyphens() {
1143        let trait_def = make_type_def("OcrBackend", "my-lib::OcrBackend", vec![]);
1144        let config = make_trait_bridge_config(None, None);
1145        let spec = make_spec(&trait_def, &config, "Py", HashMap::new());
1146        assert_eq!(spec.trait_path(), "my_lib::OcrBackend");
1147    }
1148
1149    #[test]
1150    fn test_required_methods_filters_no_default_impl() {
1151        let methods = vec![
1152            make_method("process", vec![], TypeRef::String, false, false, None, None),
1153            make_method("initialize", vec![], TypeRef::Unit, false, true, None, None),
1154            make_method("detect", vec![], TypeRef::String, false, false, None, None),
1155        ];
1156        let trait_def = make_type_def("OcrBackend", "mylib::OcrBackend", methods);
1157        let config = make_trait_bridge_config(None, None);
1158        let spec = make_spec(&trait_def, &config, "Py", HashMap::new());
1159        let required = spec.required_methods();
1160        assert_eq!(required.len(), 2);
1161        assert!(required.iter().any(|m| m.name == "process"));
1162        assert!(required.iter().any(|m| m.name == "detect"));
1163    }
1164
1165    #[test]
1166    fn test_optional_methods_filters_has_default_impl() {
1167        let methods = vec![
1168            make_method("process", vec![], TypeRef::String, false, false, None, None),
1169            make_method("initialize", vec![], TypeRef::Unit, false, true, None, None),
1170            make_method("shutdown", vec![], TypeRef::Unit, false, true, None, None),
1171        ];
1172        let trait_def = make_type_def("OcrBackend", "mylib::OcrBackend", methods);
1173        let config = make_trait_bridge_config(None, None);
1174        let spec = make_spec(&trait_def, &config, "Py", HashMap::new());
1175        let optional = spec.optional_methods();
1176        assert_eq!(optional.len(), 2);
1177        assert!(optional.iter().any(|m| m.name == "initialize"));
1178        assert!(optional.iter().any(|m| m.name == "shutdown"));
1179    }
1180
1181    #[test]
1182    fn test_error_path() {
1183        let trait_def = make_type_def("OcrBackend", "mylib::OcrBackend", vec![]);
1184        let config = make_trait_bridge_config(None, None);
1185        let spec = make_spec(&trait_def, &config, "Py", HashMap::new());
1186        assert_eq!(spec.error_path(), "mylib::MyError");
1187    }
1188
1189    // ---------------------------------------------------------------------------
1190    // format_type_ref
1191    // ---------------------------------------------------------------------------
1192
1193    #[test]
1194    fn test_format_type_ref_primitives() {
1195        let paths = HashMap::new();
1196        let cases: Vec<(TypeRef, &str)> = vec![
1197            (TypeRef::Primitive(PrimitiveType::Bool), "bool"),
1198            (TypeRef::Primitive(PrimitiveType::U8), "u8"),
1199            (TypeRef::Primitive(PrimitiveType::U16), "u16"),
1200            (TypeRef::Primitive(PrimitiveType::U32), "u32"),
1201            (TypeRef::Primitive(PrimitiveType::U64), "u64"),
1202            (TypeRef::Primitive(PrimitiveType::I8), "i8"),
1203            (TypeRef::Primitive(PrimitiveType::I16), "i16"),
1204            (TypeRef::Primitive(PrimitiveType::I32), "i32"),
1205            (TypeRef::Primitive(PrimitiveType::I64), "i64"),
1206            (TypeRef::Primitive(PrimitiveType::F32), "f32"),
1207            (TypeRef::Primitive(PrimitiveType::F64), "f64"),
1208            (TypeRef::Primitive(PrimitiveType::Usize), "usize"),
1209            (TypeRef::Primitive(PrimitiveType::Isize), "isize"),
1210        ];
1211        for (ty, expected) in cases {
1212            assert_eq!(format_type_ref(&ty, &paths), expected, "mismatch for {expected}");
1213        }
1214    }
1215
1216    #[test]
1217    fn test_format_type_ref_string() {
1218        assert_eq!(format_type_ref(&TypeRef::String, &HashMap::new()), "String");
1219    }
1220
1221    #[test]
1222    fn test_format_type_ref_char() {
1223        assert_eq!(format_type_ref(&TypeRef::Char, &HashMap::new()), "char");
1224    }
1225
1226    #[test]
1227    fn test_format_type_ref_bytes() {
1228        assert_eq!(format_type_ref(&TypeRef::Bytes, &HashMap::new()), "Vec<u8>");
1229    }
1230
1231    #[test]
1232    fn test_format_type_ref_path() {
1233        assert_eq!(format_type_ref(&TypeRef::Path, &HashMap::new()), "std::path::PathBuf");
1234    }
1235
1236    #[test]
1237    fn test_format_type_ref_unit() {
1238        assert_eq!(format_type_ref(&TypeRef::Unit, &HashMap::new()), "()");
1239    }
1240
1241    #[test]
1242    fn test_format_type_ref_json() {
1243        assert_eq!(format_type_ref(&TypeRef::Json, &HashMap::new()), "serde_json::Value");
1244    }
1245
1246    #[test]
1247    fn test_format_type_ref_duration() {
1248        assert_eq!(
1249            format_type_ref(&TypeRef::Duration, &HashMap::new()),
1250            "std::time::Duration"
1251        );
1252    }
1253
1254    #[test]
1255    fn test_format_type_ref_optional() {
1256        let ty = TypeRef::Optional(Box::new(TypeRef::String));
1257        assert_eq!(format_type_ref(&ty, &HashMap::new()), "Option<String>");
1258    }
1259
1260    #[test]
1261    fn test_format_type_ref_optional_nested() {
1262        let ty = TypeRef::Optional(Box::new(TypeRef::Optional(Box::new(TypeRef::Primitive(
1263            PrimitiveType::U32,
1264        )))));
1265        assert_eq!(format_type_ref(&ty, &HashMap::new()), "Option<Option<u32>>");
1266    }
1267
1268    #[test]
1269    fn test_format_type_ref_vec() {
1270        let ty = TypeRef::Vec(Box::new(TypeRef::Primitive(PrimitiveType::U8)));
1271        assert_eq!(format_type_ref(&ty, &HashMap::new()), "Vec<u8>");
1272    }
1273
1274    #[test]
1275    fn test_format_type_ref_vec_nested() {
1276        let ty = TypeRef::Vec(Box::new(TypeRef::Vec(Box::new(TypeRef::String))));
1277        assert_eq!(format_type_ref(&ty, &HashMap::new()), "Vec<Vec<String>>");
1278    }
1279
1280    #[test]
1281    fn test_format_type_ref_map() {
1282        let ty = TypeRef::Map(
1283            Box::new(TypeRef::String),
1284            Box::new(TypeRef::Primitive(PrimitiveType::I64)),
1285        );
1286        assert_eq!(
1287            format_type_ref(&ty, &HashMap::new()),
1288            "std::collections::HashMap<String, i64>"
1289        );
1290    }
1291
1292    #[test]
1293    fn test_format_type_ref_map_nested_value() {
1294        let ty = TypeRef::Map(
1295            Box::new(TypeRef::String),
1296            Box::new(TypeRef::Vec(Box::new(TypeRef::String))),
1297        );
1298        assert_eq!(
1299            format_type_ref(&ty, &HashMap::new()),
1300            "std::collections::HashMap<String, Vec<String>>"
1301        );
1302    }
1303
1304    #[test]
1305    fn test_format_type_ref_named_without_type_paths() {
1306        let ty = TypeRef::Named("Config".to_string());
1307        assert_eq!(format_type_ref(&ty, &HashMap::new()), "Config");
1308    }
1309
1310    #[test]
1311    fn test_format_type_ref_named_with_type_paths() {
1312        let ty = TypeRef::Named("Config".to_string());
1313        let mut paths = HashMap::new();
1314        paths.insert("Config".to_string(), "mylib::Config".to_string());
1315        assert_eq!(format_type_ref(&ty, &paths), "mylib::Config");
1316    }
1317
1318    #[test]
1319    fn test_format_type_ref_named_not_in_type_paths_falls_back_to_name() {
1320        let ty = TypeRef::Named("Unknown".to_string());
1321        let mut paths = HashMap::new();
1322        paths.insert("Other".to_string(), "mylib::Other".to_string());
1323        assert_eq!(format_type_ref(&ty, &paths), "Unknown");
1324    }
1325
1326    // ---------------------------------------------------------------------------
1327    // format_param_type
1328    // ---------------------------------------------------------------------------
1329
1330    #[test]
1331    fn test_format_param_type_string_ref() {
1332        let param = make_param("input", TypeRef::String, true);
1333        assert_eq!(format_param_type(&param, &HashMap::new()), "&str");
1334    }
1335
1336    #[test]
1337    fn test_format_param_type_string_owned() {
1338        let param = make_param("input", TypeRef::String, false);
1339        assert_eq!(format_param_type(&param, &HashMap::new()), "String");
1340    }
1341
1342    #[test]
1343    fn test_format_param_type_bytes_ref() {
1344        let param = make_param("data", TypeRef::Bytes, true);
1345        assert_eq!(format_param_type(&param, &HashMap::new()), "&[u8]");
1346    }
1347
1348    #[test]
1349    fn test_format_param_type_bytes_owned() {
1350        let param = make_param("data", TypeRef::Bytes, false);
1351        assert_eq!(format_param_type(&param, &HashMap::new()), "Vec<u8>");
1352    }
1353
1354    #[test]
1355    fn test_format_param_type_path_ref() {
1356        let param = make_param("path", TypeRef::Path, true);
1357        assert_eq!(format_param_type(&param, &HashMap::new()), "&std::path::Path");
1358    }
1359
1360    #[test]
1361    fn test_format_param_type_path_owned() {
1362        let param = make_param("path", TypeRef::Path, false);
1363        assert_eq!(format_param_type(&param, &HashMap::new()), "std::path::PathBuf");
1364    }
1365
1366    #[test]
1367    fn test_format_param_type_vec_ref() {
1368        let param = make_param("items", TypeRef::Vec(Box::new(TypeRef::String)), true);
1369        assert_eq!(format_param_type(&param, &HashMap::new()), "&[String]");
1370    }
1371
1372    #[test]
1373    fn test_format_param_type_vec_owned() {
1374        let param = make_param("items", TypeRef::Vec(Box::new(TypeRef::String)), false);
1375        assert_eq!(format_param_type(&param, &HashMap::new()), "Vec<String>");
1376    }
1377
1378    #[test]
1379    fn test_format_param_type_named_ref_with_type_paths() {
1380        let mut paths = HashMap::new();
1381        paths.insert("Config".to_string(), "mylib::Config".to_string());
1382        let param = make_param("cfg", TypeRef::Named("Config".to_string()), true);
1383        assert_eq!(format_param_type(&param, &paths), "&mylib::Config");
1384    }
1385
1386    #[test]
1387    fn test_format_param_type_named_ref_without_type_paths() {
1388        let param = make_param("cfg", TypeRef::Named("Config".to_string()), true);
1389        assert_eq!(format_param_type(&param, &HashMap::new()), "&Config");
1390    }
1391
1392    #[test]
1393    fn test_format_param_type_primitive_ref_passes_by_value() {
1394        // Copy types like u32 are passed by value even when is_ref is set
1395        let param = make_param("count", TypeRef::Primitive(PrimitiveType::U32), true);
1396        assert_eq!(format_param_type(&param, &HashMap::new()), "u32");
1397    }
1398
1399    #[test]
1400    fn test_format_param_type_unit_ref_passes_by_value() {
1401        let param = make_param("nothing", TypeRef::Unit, true);
1402        assert_eq!(format_param_type(&param, &HashMap::new()), "()");
1403    }
1404
1405    // ---------------------------------------------------------------------------
1406    // format_return_type
1407    // ---------------------------------------------------------------------------
1408
1409    #[test]
1410    fn test_format_return_type_without_error() {
1411        let result = format_return_type(&TypeRef::String, None, &HashMap::new(), false);
1412        assert_eq!(result, "String");
1413    }
1414
1415    #[test]
1416    fn test_format_return_type_with_error() {
1417        let result = format_return_type(&TypeRef::String, Some("MyError"), &HashMap::new(), false);
1418        assert_eq!(result, "std::result::Result<String, MyError>");
1419    }
1420
1421    #[test]
1422    fn test_format_return_type_unit_with_error() {
1423        let result = format_return_type(
1424            &TypeRef::Unit,
1425            Some("Box<dyn std::error::Error>"),
1426            &HashMap::new(),
1427            false,
1428        );
1429        assert_eq!(result, "std::result::Result<(), Box<dyn std::error::Error>>");
1430    }
1431
1432    #[test]
1433    fn test_format_return_type_named_with_type_paths_and_error() {
1434        let mut paths = HashMap::new();
1435        paths.insert("Output".to_string(), "mylib::Output".to_string());
1436        let result = format_return_type(
1437            &TypeRef::Named("Output".to_string()),
1438            Some("mylib::MyError"),
1439            &paths,
1440            false,
1441        );
1442        assert_eq!(result, "std::result::Result<mylib::Output, mylib::MyError>");
1443    }
1444
1445    #[test]
1446    fn test_format_return_type_vec_string_with_returns_ref() {
1447        // `fn supported_mime_types(&self) -> &[&str]` is extracted as
1448        // `return_type = Vec(String), returns_ref = true`.
1449        // The generated impl signature must emit `&[&str]`, not `Vec<String>`.
1450        let result = format_return_type(&TypeRef::Vec(Box::new(TypeRef::String)), None, &HashMap::new(), true);
1451        assert_eq!(result, "&[&str]", "Vec<String> + returns_ref must yield &[&str]");
1452    }
1453
1454    #[test]
1455    fn test_format_return_type_vec_no_returns_ref_unchanged() {
1456        // Without returns_ref the type is unchanged.
1457        let result = format_return_type(&TypeRef::Vec(Box::new(TypeRef::String)), None, &HashMap::new(), false);
1458        assert_eq!(
1459            result, "Vec<String>",
1460            "Vec<String> without returns_ref must stay Vec<String>"
1461        );
1462    }
1463
1464    // ---------------------------------------------------------------------------
1465    // gen_bridge_wrapper_struct
1466    // ---------------------------------------------------------------------------
1467
1468    #[test]
1469    fn test_gen_bridge_wrapper_struct_contains_struct_name() {
1470        let trait_def = make_type_def("OcrBackend", "mylib::OcrBackend", vec![]);
1471        let config = make_trait_bridge_config(None, None);
1472        let spec = make_spec(&trait_def, &config, "Py", HashMap::new());
1473        let generator = MockBridgeGenerator;
1474        let result = gen_bridge_wrapper_struct(&spec, &generator);
1475        assert!(
1476            result.contains("pub struct PyOcrBackendBridge"),
1477            "missing struct declaration in:\n{result}"
1478        );
1479    }
1480
1481    #[test]
1482    fn test_gen_bridge_wrapper_struct_contains_inner_field() {
1483        let trait_def = make_type_def("OcrBackend", "mylib::OcrBackend", vec![]);
1484        let config = make_trait_bridge_config(None, None);
1485        let spec = make_spec(&trait_def, &config, "Py", HashMap::new());
1486        let generator = MockBridgeGenerator;
1487        let result = gen_bridge_wrapper_struct(&spec, &generator);
1488        assert!(result.contains("inner: Py<PyAny>"), "missing inner field in:\n{result}");
1489    }
1490
1491    #[test]
1492    fn test_gen_bridge_wrapper_struct_contains_cached_name() {
1493        let trait_def = make_type_def("OcrBackend", "mylib::OcrBackend", vec![]);
1494        let config = make_trait_bridge_config(None, None);
1495        let spec = make_spec(&trait_def, &config, "Py", HashMap::new());
1496        let generator = MockBridgeGenerator;
1497        let result = gen_bridge_wrapper_struct(&spec, &generator);
1498        assert!(
1499            result.contains("cached_name: String"),
1500            "missing cached_name field in:\n{result}"
1501        );
1502    }
1503
1504    // ---------------------------------------------------------------------------
1505    // gen_bridge_plugin_impl
1506    // ---------------------------------------------------------------------------
1507
1508    #[test]
1509    fn test_gen_bridge_plugin_impl_returns_none_when_no_super_trait() {
1510        let trait_def = make_type_def("OcrBackend", "mylib::OcrBackend", vec![]);
1511        let config = make_trait_bridge_config(None, None);
1512        let spec = make_spec(&trait_def, &config, "Py", HashMap::new());
1513        let generator = MockBridgeGenerator;
1514        assert!(gen_bridge_plugin_impl(&spec, &generator).is_none());
1515    }
1516
1517    #[test]
1518    fn test_gen_bridge_plugin_impl_returns_some_when_super_trait_configured() {
1519        let trait_def = make_type_def("OcrBackend", "mylib::OcrBackend", vec![]);
1520        let config = make_trait_bridge_config(Some("Plugin"), None);
1521        let spec = make_spec(&trait_def, &config, "Py", HashMap::new());
1522        let generator = MockBridgeGenerator;
1523        assert!(gen_bridge_plugin_impl(&spec, &generator).is_some());
1524    }
1525
1526    #[test]
1527    fn test_gen_bridge_plugin_impl_uses_qualified_super_trait_path() {
1528        let trait_def = make_type_def("OcrBackend", "mylib::OcrBackend", vec![]);
1529        let config = make_trait_bridge_config(Some("Plugin"), None);
1530        let spec = make_spec(&trait_def, &config, "Py", HashMap::new());
1531        let generator = MockBridgeGenerator;
1532        let result = gen_bridge_plugin_impl(&spec, &generator).unwrap();
1533        assert!(
1534            result.contains("impl mylib::Plugin for PyOcrBackendBridge"),
1535            "missing qualified super-trait path in:\n{result}"
1536        );
1537    }
1538
1539    #[test]
1540    fn test_gen_bridge_plugin_impl_uses_already_qualified_super_trait_path() {
1541        let trait_def = make_type_def("OcrBackend", "mylib::OcrBackend", vec![]);
1542        let config = make_trait_bridge_config(Some("other_crate::Plugin"), None);
1543        let spec = make_spec(&trait_def, &config, "Py", HashMap::new());
1544        let generator = MockBridgeGenerator;
1545        let result = gen_bridge_plugin_impl(&spec, &generator).unwrap();
1546        assert!(
1547            result.contains("impl other_crate::Plugin for PyOcrBackendBridge"),
1548            "wrong super-trait path in:\n{result}"
1549        );
1550    }
1551
1552    #[test]
1553    fn test_gen_bridge_plugin_impl_contains_name_fn() {
1554        let trait_def = make_type_def("OcrBackend", "mylib::OcrBackend", vec![]);
1555        let config = make_trait_bridge_config(Some("Plugin"), None);
1556        let spec = make_spec(&trait_def, &config, "Py", HashMap::new());
1557        let generator = MockBridgeGenerator;
1558        let result = gen_bridge_plugin_impl(&spec, &generator).unwrap();
1559        assert!(
1560            result.contains("fn name(") && result.contains("cached_name"),
1561            "missing name() using cached_name in:\n{result}"
1562        );
1563    }
1564
1565    #[test]
1566    fn test_gen_bridge_plugin_impl_contains_version_fn() {
1567        let trait_def = make_type_def("OcrBackend", "mylib::OcrBackend", vec![]);
1568        let config = make_trait_bridge_config(Some("Plugin"), None);
1569        let spec = make_spec(&trait_def, &config, "Py", HashMap::new());
1570        let generator = MockBridgeGenerator;
1571        let result = gen_bridge_plugin_impl(&spec, &generator).unwrap();
1572        assert!(result.contains("fn version("), "missing version() in:\n{result}");
1573    }
1574
1575    #[test]
1576    fn test_gen_bridge_plugin_impl_contains_initialize_fn() {
1577        let trait_def = make_type_def("OcrBackend", "mylib::OcrBackend", vec![]);
1578        let config = make_trait_bridge_config(Some("Plugin"), None);
1579        let spec = make_spec(&trait_def, &config, "Py", HashMap::new());
1580        let generator = MockBridgeGenerator;
1581        let result = gen_bridge_plugin_impl(&spec, &generator).unwrap();
1582        assert!(result.contains("fn initialize("), "missing initialize() in:\n{result}");
1583    }
1584
1585    #[test]
1586    fn test_gen_bridge_plugin_impl_contains_shutdown_fn() {
1587        let trait_def = make_type_def("OcrBackend", "mylib::OcrBackend", vec![]);
1588        let config = make_trait_bridge_config(Some("Plugin"), None);
1589        let spec = make_spec(&trait_def, &config, "Py", HashMap::new());
1590        let generator = MockBridgeGenerator;
1591        let result = gen_bridge_plugin_impl(&spec, &generator).unwrap();
1592        assert!(result.contains("fn shutdown("), "missing shutdown() in:\n{result}");
1593    }
1594
1595    // ---------------------------------------------------------------------------
1596    // gen_bridge_trait_impl
1597    // ---------------------------------------------------------------------------
1598
1599    #[test]
1600    fn test_gen_bridge_trait_impl_includes_impl_header() {
1601        let trait_def = make_type_def("OcrBackend", "mylib::OcrBackend", vec![]);
1602        let config = make_trait_bridge_config(None, None);
1603        let spec = make_spec(&trait_def, &config, "Py", HashMap::new());
1604        let generator = MockBridgeGenerator;
1605        let result = gen_bridge_trait_impl(&spec, &generator);
1606        assert!(
1607            result.contains("impl mylib::OcrBackend for PyOcrBackendBridge"),
1608            "missing impl header in:\n{result}"
1609        );
1610    }
1611
1612    #[test]
1613    fn test_gen_bridge_trait_impl_includes_method_signatures() {
1614        let methods = vec![make_method(
1615            "process",
1616            vec![],
1617            TypeRef::String,
1618            false,
1619            false,
1620            None,
1621            None,
1622        )];
1623        let trait_def = make_type_def("OcrBackend", "mylib::OcrBackend", methods);
1624        let config = make_trait_bridge_config(None, None);
1625        let spec = make_spec(&trait_def, &config, "Py", HashMap::new());
1626        let generator = MockBridgeGenerator;
1627        let result = gen_bridge_trait_impl(&spec, &generator);
1628        assert!(result.contains("fn process("), "missing method signature in:\n{result}");
1629    }
1630
1631    #[test]
1632    fn test_gen_bridge_trait_impl_includes_method_body_from_generator() {
1633        let methods = vec![make_method(
1634            "process",
1635            vec![],
1636            TypeRef::String,
1637            false,
1638            false,
1639            None,
1640            None,
1641        )];
1642        let trait_def = make_type_def("OcrBackend", "mylib::OcrBackend", methods);
1643        let config = make_trait_bridge_config(None, None);
1644        let spec = make_spec(&trait_def, &config, "Py", HashMap::new());
1645        let generator = MockBridgeGenerator;
1646        let result = gen_bridge_trait_impl(&spec, &generator);
1647        assert!(
1648            result.contains("// sync body for process"),
1649            "missing sync method body in:\n{result}"
1650        );
1651    }
1652
1653    #[test]
1654    fn test_gen_bridge_trait_impl_async_method_uses_async_body() {
1655        let methods = vec![make_method(
1656            "process_async",
1657            vec![],
1658            TypeRef::String,
1659            true,
1660            false,
1661            None,
1662            None,
1663        )];
1664        let trait_def = make_type_def("OcrBackend", "mylib::OcrBackend", methods);
1665        let config = make_trait_bridge_config(None, None);
1666        let spec = make_spec(&trait_def, &config, "Py", HashMap::new());
1667        let generator = MockBridgeGenerator;
1668        let result = gen_bridge_trait_impl(&spec, &generator);
1669        assert!(
1670            result.contains("// async body for process_async"),
1671            "missing async method body in:\n{result}"
1672        );
1673        assert!(
1674            result.contains("async fn process_async("),
1675            "missing async keyword in method signature in:\n{result}"
1676        );
1677    }
1678
1679    #[test]
1680    fn test_gen_bridge_trait_impl_filters_trait_source_methods() {
1681        // Methods with trait_source set come from super-traits and should be excluded
1682        let methods = vec![
1683            make_method("own_method", vec![], TypeRef::String, false, false, None, None),
1684            make_method(
1685                "inherited_method",
1686                vec![],
1687                TypeRef::String,
1688                false,
1689                false,
1690                Some("other_crate::OtherTrait"),
1691                None,
1692            ),
1693        ];
1694        let trait_def = make_type_def("OcrBackend", "mylib::OcrBackend", methods);
1695        let config = make_trait_bridge_config(None, None);
1696        let spec = make_spec(&trait_def, &config, "Py", HashMap::new());
1697        let generator = MockBridgeGenerator;
1698        let result = gen_bridge_trait_impl(&spec, &generator);
1699        assert!(
1700            result.contains("fn own_method("),
1701            "own method should be present in:\n{result}"
1702        );
1703        assert!(
1704            !result.contains("fn inherited_method("),
1705            "inherited method should be filtered out in:\n{result}"
1706        );
1707    }
1708
1709    #[test]
1710    fn test_gen_bridge_trait_impl_method_with_params() {
1711        let params = vec![
1712            make_param("input", TypeRef::String, true),
1713            make_param("count", TypeRef::Primitive(PrimitiveType::U32), false),
1714        ];
1715        let methods = vec![make_method(
1716            "process",
1717            params,
1718            TypeRef::String,
1719            false,
1720            false,
1721            None,
1722            None,
1723        )];
1724        let trait_def = make_type_def("OcrBackend", "mylib::OcrBackend", methods);
1725        let config = make_trait_bridge_config(None, None);
1726        let spec = make_spec(&trait_def, &config, "Py", HashMap::new());
1727        let generator = MockBridgeGenerator;
1728        let result = gen_bridge_trait_impl(&spec, &generator);
1729        assert!(result.contains("input: &str"), "missing &str param in:\n{result}");
1730        assert!(result.contains("count: u32"), "missing u32 param in:\n{result}");
1731    }
1732
1733    #[test]
1734    fn test_gen_bridge_trait_impl_return_type_with_error() {
1735        let methods = vec![make_method(
1736            "process",
1737            vec![],
1738            TypeRef::String,
1739            false,
1740            false,
1741            None,
1742            Some("MyError"),
1743        )];
1744        let trait_def = make_type_def("OcrBackend", "mylib::OcrBackend", methods);
1745        let config = make_trait_bridge_config(None, None);
1746        let spec = make_spec(&trait_def, &config, "Py", HashMap::new());
1747        let generator = MockBridgeGenerator;
1748        let result = gen_bridge_trait_impl(&spec, &generator);
1749        assert!(
1750            result.contains("-> std::result::Result<String, mylib::MyError>"),
1751            "missing std::result::Result return type in:\n{result}"
1752        );
1753    }
1754
1755    // ---------------------------------------------------------------------------
1756    // gen_bridge_registration_fn
1757    // ---------------------------------------------------------------------------
1758
1759    #[test]
1760    fn test_gen_bridge_registration_fn_returns_none_without_register_fn() {
1761        let trait_def = make_type_def("OcrBackend", "mylib::OcrBackend", vec![]);
1762        let config = make_trait_bridge_config(None, None);
1763        let spec = make_spec(&trait_def, &config, "Py", HashMap::new());
1764        let generator = MockBridgeGenerator;
1765        assert!(gen_bridge_registration_fn(&spec, &generator).is_none());
1766    }
1767
1768    #[test]
1769    fn test_gen_bridge_registration_fn_returns_some_with_register_fn() {
1770        let trait_def = make_type_def("OcrBackend", "mylib::OcrBackend", vec![]);
1771        let config = make_trait_bridge_config(None, Some("register_ocr_backend"));
1772        let spec = make_spec(&trait_def, &config, "Py", HashMap::new());
1773        let generator = MockBridgeGenerator;
1774        let result = gen_bridge_registration_fn(&spec, &generator);
1775        assert!(result.is_some());
1776        let code = result.unwrap();
1777        assert!(
1778            code.contains("register_ocr_backend"),
1779            "missing register fn name in:\n{code}"
1780        );
1781    }
1782
1783    // ---------------------------------------------------------------------------
1784    // gen_bridge_all
1785    // ---------------------------------------------------------------------------
1786
1787    #[test]
1788    fn test_gen_bridge_all_includes_imports() {
1789        let trait_def = make_type_def("OcrBackend", "mylib::OcrBackend", vec![]);
1790        let config = make_trait_bridge_config(None, None);
1791        let spec = make_spec(&trait_def, &config, "Py", HashMap::new());
1792        let generator = MockBridgeGenerator;
1793        let output = gen_bridge_all(&spec, &generator);
1794        assert!(output.imports.contains(&"pyo3::prelude::*".to_string()));
1795        assert!(output.imports.contains(&"pyo3::types::PyString".to_string()));
1796    }
1797
1798    #[test]
1799    fn test_gen_bridge_all_includes_wrapper_struct() {
1800        let trait_def = make_type_def("OcrBackend", "mylib::OcrBackend", vec![]);
1801        let config = make_trait_bridge_config(None, None);
1802        let spec = make_spec(&trait_def, &config, "Py", HashMap::new());
1803        let generator = MockBridgeGenerator;
1804        let output = gen_bridge_all(&spec, &generator);
1805        assert!(
1806            output.code.contains("pub struct PyOcrBackendBridge"),
1807            "missing struct in:\n{}",
1808            output.code
1809        );
1810    }
1811
1812    #[test]
1813    fn test_gen_bridge_all_includes_constructor() {
1814        let trait_def = make_type_def("OcrBackend", "mylib::OcrBackend", vec![]);
1815        let config = make_trait_bridge_config(None, None);
1816        let spec = make_spec(&trait_def, &config, "Py", HashMap::new());
1817        let generator = MockBridgeGenerator;
1818        let output = gen_bridge_all(&spec, &generator);
1819        assert!(
1820            output.code.contains("pub fn new("),
1821            "missing constructor in:\n{}",
1822            output.code
1823        );
1824    }
1825
1826    #[test]
1827    fn test_gen_bridge_all_includes_trait_impl() {
1828        let methods = vec![make_method(
1829            "process",
1830            vec![],
1831            TypeRef::String,
1832            false,
1833            false,
1834            None,
1835            None,
1836        )];
1837        let trait_def = make_type_def("OcrBackend", "mylib::OcrBackend", methods);
1838        let config = make_trait_bridge_config(None, None);
1839        let spec = make_spec(&trait_def, &config, "Py", HashMap::new());
1840        let generator = MockBridgeGenerator;
1841        let output = gen_bridge_all(&spec, &generator);
1842        assert!(
1843            output.code.contains("impl mylib::OcrBackend for PyOcrBackendBridge"),
1844            "missing trait impl in:\n{}",
1845            output.code
1846        );
1847    }
1848
1849    #[test]
1850    fn test_gen_bridge_all_includes_plugin_impl_when_super_trait_set() {
1851        let trait_def = make_type_def("OcrBackend", "mylib::OcrBackend", vec![]);
1852        let config = make_trait_bridge_config(Some("Plugin"), None);
1853        let spec = make_spec(&trait_def, &config, "Py", HashMap::new());
1854        let generator = MockBridgeGenerator;
1855        let output = gen_bridge_all(&spec, &generator);
1856        assert!(
1857            output.code.contains("impl mylib::Plugin for PyOcrBackendBridge"),
1858            "missing plugin impl in:\n{}",
1859            output.code
1860        );
1861    }
1862
1863    #[test]
1864    fn test_gen_bridge_all_no_plugin_impl_when_no_super_trait() {
1865        let trait_def = make_type_def("OcrBackend", "mylib::OcrBackend", vec![]);
1866        let config = make_trait_bridge_config(None, None);
1867        let spec = make_spec(&trait_def, &config, "Py", HashMap::new());
1868        let generator = MockBridgeGenerator;
1869        let output = gen_bridge_all(&spec, &generator);
1870        assert!(
1871            !output.code.contains("fn name(") || !output.code.contains("cached_name"),
1872            "unexpected plugin impl present without super_trait"
1873        );
1874    }
1875
1876    #[test]
1877    fn test_gen_bridge_all_includes_registration_fn_when_configured() {
1878        let trait_def = make_type_def("OcrBackend", "mylib::OcrBackend", vec![]);
1879        let config = make_trait_bridge_config(None, Some("register_ocr_backend"));
1880        let spec = make_spec(&trait_def, &config, "Py", HashMap::new());
1881        let generator = MockBridgeGenerator;
1882        let output = gen_bridge_all(&spec, &generator);
1883        assert!(
1884            output.code.contains("register_ocr_backend"),
1885            "missing registration fn in:\n{}",
1886            output.code
1887        );
1888    }
1889
1890    #[test]
1891    fn test_gen_bridge_all_no_registration_fn_when_absent() {
1892        let trait_def = make_type_def("OcrBackend", "mylib::OcrBackend", vec![]);
1893        let config = make_trait_bridge_config(None, None);
1894        let spec = make_spec(&trait_def, &config, "Py", HashMap::new());
1895        let generator = MockBridgeGenerator;
1896        let output = gen_bridge_all(&spec, &generator);
1897        assert!(
1898            !output.code.contains("register_ocr_backend"),
1899            "unexpected registration fn present:\n{}",
1900            output.code
1901        );
1902    }
1903
1904    #[test]
1905    fn test_gen_bridge_all_ordering_struct_before_trait_impl() {
1906        let trait_def = make_type_def("OcrBackend", "mylib::OcrBackend", vec![]);
1907        let config = make_trait_bridge_config(None, None);
1908        let spec = make_spec(&trait_def, &config, "Py", HashMap::new());
1909        let generator = MockBridgeGenerator;
1910        let output = gen_bridge_all(&spec, &generator);
1911        let struct_pos = output.code.find("pub struct PyOcrBackendBridge").unwrap();
1912        let impl_pos = output
1913            .code
1914            .find("impl mylib::OcrBackend for PyOcrBackendBridge")
1915            .unwrap();
1916        assert!(struct_pos < impl_pos, "struct should appear before trait impl");
1917    }
1918
1919    // ---------------------------------------------------------------------------
1920    // find_bridge_param / find_bridge_field
1921    // ---------------------------------------------------------------------------
1922
1923    fn make_bridge(
1924        type_alias: Option<&str>,
1925        param_name: Option<&str>,
1926        bind_via: BridgeBinding,
1927        options_type: Option<&str>,
1928        options_field: Option<&str>,
1929        context_type: Option<&str>,
1930        result_type: Option<&str>,
1931    ) -> TraitBridgeConfig {
1932        TraitBridgeConfig {
1933            trait_name: "HtmlVisitor".to_string(),
1934            super_trait: None,
1935            registry_getter: None,
1936            register_fn: None,
1937            unregister_fn: None,
1938            clear_fn: None,
1939            type_alias: type_alias.map(str::to_string),
1940            param_name: param_name.map(str::to_string),
1941            register_extra_args: None,
1942            exclude_languages: vec![],
1943            ffi_skip_methods: Vec::new(),
1944            bind_via,
1945            options_type: options_type.map(str::to_string),
1946            options_field: options_field.map(str::to_string),
1947            context_type: context_type.map(str::to_string),
1948            result_type: result_type.map(str::to_string),
1949        }
1950    }
1951
1952    #[test]
1953    fn find_bridge_param_returns_first_param_match_in_function_param_mode() {
1954        let func = make_func(
1955            "convert",
1956            vec![
1957                make_param("html", TypeRef::String, true),
1958                make_param("visitor", TypeRef::Named("VisitorHandle".to_string()), false),
1959            ],
1960        );
1961        let bridges = vec![make_bridge(
1962            Some("VisitorHandle"),
1963            Some("visitor"),
1964            BridgeBinding::FunctionParam,
1965            None,
1966            None,
1967            None,
1968            None,
1969        )];
1970        let result = find_bridge_param(&func, &bridges).expect("bridge match");
1971        assert_eq!(result.0, 1);
1972    }
1973
1974    #[test]
1975    fn find_bridge_param_skips_options_field_bridges() {
1976        let func = make_func(
1977            "convert",
1978            vec![
1979                make_param("html", TypeRef::String, true),
1980                make_param("visitor", TypeRef::Named("VisitorHandle".to_string()), false),
1981            ],
1982        );
1983        let bridges = vec![make_bridge(
1984            Some("VisitorHandle"),
1985            Some("visitor"),
1986            BridgeBinding::OptionsField,
1987            Some("ConversionOptions"),
1988            Some("visitor"),
1989            None,
1990            None,
1991        )];
1992        assert!(
1993            find_bridge_param(&func, &bridges).is_none(),
1994            "bridges configured with bind_via=options_field must not be returned by find_bridge_param"
1995        );
1996    }
1997
1998    #[test]
1999    fn find_bridge_field_detects_field_via_alias() {
2000        let opts_type = TypeDef {
2001            name: "ConversionOptions".to_string(),
2002            rust_path: "mylib::ConversionOptions".to_string(),
2003            original_rust_path: String::new(),
2004            fields: vec![
2005                make_field("debug", TypeRef::Primitive(PrimitiveType::Bool)),
2006                make_field(
2007                    "visitor",
2008                    TypeRef::Optional(Box::new(TypeRef::Named("VisitorHandle".to_string()))),
2009                ),
2010            ],
2011            methods: vec![],
2012            is_opaque: false,
2013            is_clone: true,
2014            is_copy: false,
2015            doc: String::new(),
2016            cfg: None,
2017            is_trait: false,
2018            has_default: true,
2019            has_stripped_cfg_fields: false,
2020            is_return_type: false,
2021            serde_rename_all: None,
2022            has_serde: false,
2023            super_traits: vec![],
2024            binding_excluded: false,
2025            binding_exclusion_reason: None,
2026        };
2027        let func = make_func(
2028            "convert",
2029            vec![
2030                make_param("html", TypeRef::String, true),
2031                make_param(
2032                    "options",
2033                    TypeRef::Optional(Box::new(TypeRef::Named("ConversionOptions".to_string()))),
2034                    false,
2035                ),
2036            ],
2037        );
2038        let bridges = vec![make_bridge(
2039            Some("VisitorHandle"),
2040            Some("visitor"),
2041            BridgeBinding::OptionsField,
2042            Some("ConversionOptions"),
2043            None,
2044            None,
2045            None,
2046        )];
2047        let m = find_bridge_field(&func, std::slice::from_ref(&opts_type), &bridges).expect("bridge field match");
2048        assert_eq!(m.param_index, 1);
2049        assert_eq!(m.param_name, "options");
2050        assert_eq!(m.options_type, "ConversionOptions");
2051        assert!(m.param_is_optional);
2052        assert_eq!(m.field_name, "visitor");
2053    }
2054
2055    #[test]
2056    fn find_bridge_field_returns_none_for_function_param_bridge() {
2057        let opts_type = TypeDef {
2058            name: "ConversionOptions".to_string(),
2059            rust_path: "mylib::ConversionOptions".to_string(),
2060            original_rust_path: String::new(),
2061            fields: vec![make_field(
2062                "visitor",
2063                TypeRef::Optional(Box::new(TypeRef::Named("VisitorHandle".to_string()))),
2064            )],
2065            methods: vec![],
2066            is_opaque: false,
2067            is_clone: true,
2068            is_copy: false,
2069            doc: String::new(),
2070            cfg: None,
2071            is_trait: false,
2072            has_default: true,
2073            has_stripped_cfg_fields: false,
2074            is_return_type: false,
2075            serde_rename_all: None,
2076            has_serde: false,
2077            super_traits: vec![],
2078            binding_excluded: false,
2079            binding_exclusion_reason: None,
2080        };
2081        let func = make_func(
2082            "convert",
2083            vec![make_param(
2084                "options",
2085                TypeRef::Named("ConversionOptions".to_string()),
2086                false,
2087            )],
2088        );
2089        let bridges = vec![make_bridge(
2090            Some("VisitorHandle"),
2091            Some("visitor"),
2092            BridgeBinding::FunctionParam,
2093            None,
2094            None,
2095            None,
2096            None,
2097        )];
2098        assert!(find_bridge_field(&func, std::slice::from_ref(&opts_type), &bridges).is_none());
2099    }
2100}