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            original_type: None,
1051        }
1052    }
1053
1054    fn make_param(name: &str, ty: TypeRef, is_ref: bool) -> ParamDef {
1055        ParamDef {
1056            name: name.to_string(),
1057            ty,
1058            optional: false,
1059            default: None,
1060            sanitized: false,
1061            typed_default: None,
1062            is_ref,
1063            is_mut: false,
1064            newtype_wrapper: None,
1065            original_type: None,
1066        }
1067    }
1068
1069    fn make_spec<'a>(
1070        trait_def: &'a TypeDef,
1071        bridge_config: &'a TraitBridgeConfig,
1072        wrapper_prefix: &'a str,
1073        type_paths: HashMap<String, String>,
1074    ) -> TraitBridgeSpec<'a> {
1075        TraitBridgeSpec {
1076            trait_def,
1077            bridge_config,
1078            core_import: "mylib",
1079            wrapper_prefix,
1080            type_paths,
1081            error_type: "MyError".to_string(),
1082            error_constructor: "MyError::from({msg})".to_string(),
1083        }
1084    }
1085
1086    // ---------------------------------------------------------------------------
1087    // Mock backend
1088    // ---------------------------------------------------------------------------
1089
1090    struct MockBridgeGenerator;
1091
1092    impl TraitBridgeGenerator for MockBridgeGenerator {
1093        fn foreign_object_type(&self) -> &str {
1094            "Py<PyAny>"
1095        }
1096
1097        fn bridge_imports(&self) -> Vec<String> {
1098            vec!["pyo3::prelude::*".to_string(), "pyo3::types::PyString".to_string()]
1099        }
1100
1101        fn gen_sync_method_body(&self, method: &MethodDef, _spec: &TraitBridgeSpec) -> String {
1102            format!("// sync body for {}", method.name)
1103        }
1104
1105        fn gen_async_method_body(&self, method: &MethodDef, _spec: &TraitBridgeSpec) -> String {
1106            format!("// async body for {}", method.name)
1107        }
1108
1109        fn gen_constructor(&self, spec: &TraitBridgeSpec) -> String {
1110            format!(
1111                "impl {} {{\n    pub fn new(obj: Py<PyAny>) -> Self {{ Self {{ inner: obj, cached_name: String::new() }} }}\n}}",
1112                spec.wrapper_name()
1113            )
1114        }
1115
1116        fn gen_registration_fn(&self, spec: &TraitBridgeSpec) -> String {
1117            let fn_name = spec.bridge_config.register_fn.as_deref().unwrap_or("register");
1118            format!("pub fn {fn_name}(obj: Py<PyAny>) {{ /* register */ }}")
1119        }
1120    }
1121
1122    // ---------------------------------------------------------------------------
1123    // TraitBridgeSpec helpers
1124    // ---------------------------------------------------------------------------
1125
1126    #[test]
1127    fn test_wrapper_name() {
1128        let trait_def = make_type_def("OcrBackend", "mylib::OcrBackend", vec![]);
1129        let config = make_trait_bridge_config(None, None);
1130        let spec = make_spec(&trait_def, &config, "Py", HashMap::new());
1131        assert_eq!(spec.wrapper_name(), "PyOcrBackendBridge");
1132    }
1133
1134    #[test]
1135    fn test_trait_snake() {
1136        let trait_def = make_type_def("OcrBackend", "mylib::OcrBackend", vec![]);
1137        let config = make_trait_bridge_config(None, None);
1138        let spec = make_spec(&trait_def, &config, "Py", HashMap::new());
1139        assert_eq!(spec.trait_snake(), "ocr_backend");
1140    }
1141
1142    #[test]
1143    fn test_trait_path_replaces_hyphens() {
1144        let trait_def = make_type_def("OcrBackend", "my-lib::OcrBackend", vec![]);
1145        let config = make_trait_bridge_config(None, None);
1146        let spec = make_spec(&trait_def, &config, "Py", HashMap::new());
1147        assert_eq!(spec.trait_path(), "my_lib::OcrBackend");
1148    }
1149
1150    #[test]
1151    fn test_required_methods_filters_no_default_impl() {
1152        let methods = vec![
1153            make_method("process", vec![], TypeRef::String, false, false, None, None),
1154            make_method("initialize", vec![], TypeRef::Unit, false, true, None, None),
1155            make_method("detect", vec![], TypeRef::String, false, false, None, None),
1156        ];
1157        let trait_def = make_type_def("OcrBackend", "mylib::OcrBackend", methods);
1158        let config = make_trait_bridge_config(None, None);
1159        let spec = make_spec(&trait_def, &config, "Py", HashMap::new());
1160        let required = spec.required_methods();
1161        assert_eq!(required.len(), 2);
1162        assert!(required.iter().any(|m| m.name == "process"));
1163        assert!(required.iter().any(|m| m.name == "detect"));
1164    }
1165
1166    #[test]
1167    fn test_optional_methods_filters_has_default_impl() {
1168        let methods = vec![
1169            make_method("process", vec![], TypeRef::String, false, false, None, None),
1170            make_method("initialize", vec![], TypeRef::Unit, false, true, None, None),
1171            make_method("shutdown", vec![], TypeRef::Unit, false, true, None, None),
1172        ];
1173        let trait_def = make_type_def("OcrBackend", "mylib::OcrBackend", methods);
1174        let config = make_trait_bridge_config(None, None);
1175        let spec = make_spec(&trait_def, &config, "Py", HashMap::new());
1176        let optional = spec.optional_methods();
1177        assert_eq!(optional.len(), 2);
1178        assert!(optional.iter().any(|m| m.name == "initialize"));
1179        assert!(optional.iter().any(|m| m.name == "shutdown"));
1180    }
1181
1182    #[test]
1183    fn test_error_path() {
1184        let trait_def = make_type_def("OcrBackend", "mylib::OcrBackend", vec![]);
1185        let config = make_trait_bridge_config(None, None);
1186        let spec = make_spec(&trait_def, &config, "Py", HashMap::new());
1187        assert_eq!(spec.error_path(), "mylib::MyError");
1188    }
1189
1190    // ---------------------------------------------------------------------------
1191    // format_type_ref
1192    // ---------------------------------------------------------------------------
1193
1194    #[test]
1195    fn test_format_type_ref_primitives() {
1196        let paths = HashMap::new();
1197        let cases: Vec<(TypeRef, &str)> = vec![
1198            (TypeRef::Primitive(PrimitiveType::Bool), "bool"),
1199            (TypeRef::Primitive(PrimitiveType::U8), "u8"),
1200            (TypeRef::Primitive(PrimitiveType::U16), "u16"),
1201            (TypeRef::Primitive(PrimitiveType::U32), "u32"),
1202            (TypeRef::Primitive(PrimitiveType::U64), "u64"),
1203            (TypeRef::Primitive(PrimitiveType::I8), "i8"),
1204            (TypeRef::Primitive(PrimitiveType::I16), "i16"),
1205            (TypeRef::Primitive(PrimitiveType::I32), "i32"),
1206            (TypeRef::Primitive(PrimitiveType::I64), "i64"),
1207            (TypeRef::Primitive(PrimitiveType::F32), "f32"),
1208            (TypeRef::Primitive(PrimitiveType::F64), "f64"),
1209            (TypeRef::Primitive(PrimitiveType::Usize), "usize"),
1210            (TypeRef::Primitive(PrimitiveType::Isize), "isize"),
1211        ];
1212        for (ty, expected) in cases {
1213            assert_eq!(format_type_ref(&ty, &paths), expected, "mismatch for {expected}");
1214        }
1215    }
1216
1217    #[test]
1218    fn test_format_type_ref_string() {
1219        assert_eq!(format_type_ref(&TypeRef::String, &HashMap::new()), "String");
1220    }
1221
1222    #[test]
1223    fn test_format_type_ref_char() {
1224        assert_eq!(format_type_ref(&TypeRef::Char, &HashMap::new()), "char");
1225    }
1226
1227    #[test]
1228    fn test_format_type_ref_bytes() {
1229        assert_eq!(format_type_ref(&TypeRef::Bytes, &HashMap::new()), "Vec<u8>");
1230    }
1231
1232    #[test]
1233    fn test_format_type_ref_path() {
1234        assert_eq!(format_type_ref(&TypeRef::Path, &HashMap::new()), "std::path::PathBuf");
1235    }
1236
1237    #[test]
1238    fn test_format_type_ref_unit() {
1239        assert_eq!(format_type_ref(&TypeRef::Unit, &HashMap::new()), "()");
1240    }
1241
1242    #[test]
1243    fn test_format_type_ref_json() {
1244        assert_eq!(format_type_ref(&TypeRef::Json, &HashMap::new()), "serde_json::Value");
1245    }
1246
1247    #[test]
1248    fn test_format_type_ref_duration() {
1249        assert_eq!(
1250            format_type_ref(&TypeRef::Duration, &HashMap::new()),
1251            "std::time::Duration"
1252        );
1253    }
1254
1255    #[test]
1256    fn test_format_type_ref_optional() {
1257        let ty = TypeRef::Optional(Box::new(TypeRef::String));
1258        assert_eq!(format_type_ref(&ty, &HashMap::new()), "Option<String>");
1259    }
1260
1261    #[test]
1262    fn test_format_type_ref_optional_nested() {
1263        let ty = TypeRef::Optional(Box::new(TypeRef::Optional(Box::new(TypeRef::Primitive(
1264            PrimitiveType::U32,
1265        )))));
1266        assert_eq!(format_type_ref(&ty, &HashMap::new()), "Option<Option<u32>>");
1267    }
1268
1269    #[test]
1270    fn test_format_type_ref_vec() {
1271        let ty = TypeRef::Vec(Box::new(TypeRef::Primitive(PrimitiveType::U8)));
1272        assert_eq!(format_type_ref(&ty, &HashMap::new()), "Vec<u8>");
1273    }
1274
1275    #[test]
1276    fn test_format_type_ref_vec_nested() {
1277        let ty = TypeRef::Vec(Box::new(TypeRef::Vec(Box::new(TypeRef::String))));
1278        assert_eq!(format_type_ref(&ty, &HashMap::new()), "Vec<Vec<String>>");
1279    }
1280
1281    #[test]
1282    fn test_format_type_ref_map() {
1283        let ty = TypeRef::Map(
1284            Box::new(TypeRef::String),
1285            Box::new(TypeRef::Primitive(PrimitiveType::I64)),
1286        );
1287        assert_eq!(
1288            format_type_ref(&ty, &HashMap::new()),
1289            "std::collections::HashMap<String, i64>"
1290        );
1291    }
1292
1293    #[test]
1294    fn test_format_type_ref_map_nested_value() {
1295        let ty = TypeRef::Map(
1296            Box::new(TypeRef::String),
1297            Box::new(TypeRef::Vec(Box::new(TypeRef::String))),
1298        );
1299        assert_eq!(
1300            format_type_ref(&ty, &HashMap::new()),
1301            "std::collections::HashMap<String, Vec<String>>"
1302        );
1303    }
1304
1305    #[test]
1306    fn test_format_type_ref_named_without_type_paths() {
1307        let ty = TypeRef::Named("Config".to_string());
1308        assert_eq!(format_type_ref(&ty, &HashMap::new()), "Config");
1309    }
1310
1311    #[test]
1312    fn test_format_type_ref_named_with_type_paths() {
1313        let ty = TypeRef::Named("Config".to_string());
1314        let mut paths = HashMap::new();
1315        paths.insert("Config".to_string(), "mylib::Config".to_string());
1316        assert_eq!(format_type_ref(&ty, &paths), "mylib::Config");
1317    }
1318
1319    #[test]
1320    fn test_format_type_ref_named_not_in_type_paths_falls_back_to_name() {
1321        let ty = TypeRef::Named("Unknown".to_string());
1322        let mut paths = HashMap::new();
1323        paths.insert("Other".to_string(), "mylib::Other".to_string());
1324        assert_eq!(format_type_ref(&ty, &paths), "Unknown");
1325    }
1326
1327    // ---------------------------------------------------------------------------
1328    // format_param_type
1329    // ---------------------------------------------------------------------------
1330
1331    #[test]
1332    fn test_format_param_type_string_ref() {
1333        let param = make_param("input", TypeRef::String, true);
1334        assert_eq!(format_param_type(&param, &HashMap::new()), "&str");
1335    }
1336
1337    #[test]
1338    fn test_format_param_type_string_owned() {
1339        let param = make_param("input", TypeRef::String, false);
1340        assert_eq!(format_param_type(&param, &HashMap::new()), "String");
1341    }
1342
1343    #[test]
1344    fn test_format_param_type_bytes_ref() {
1345        let param = make_param("data", TypeRef::Bytes, true);
1346        assert_eq!(format_param_type(&param, &HashMap::new()), "&[u8]");
1347    }
1348
1349    #[test]
1350    fn test_format_param_type_bytes_owned() {
1351        let param = make_param("data", TypeRef::Bytes, false);
1352        assert_eq!(format_param_type(&param, &HashMap::new()), "Vec<u8>");
1353    }
1354
1355    #[test]
1356    fn test_format_param_type_path_ref() {
1357        let param = make_param("path", TypeRef::Path, true);
1358        assert_eq!(format_param_type(&param, &HashMap::new()), "&std::path::Path");
1359    }
1360
1361    #[test]
1362    fn test_format_param_type_path_owned() {
1363        let param = make_param("path", TypeRef::Path, false);
1364        assert_eq!(format_param_type(&param, &HashMap::new()), "std::path::PathBuf");
1365    }
1366
1367    #[test]
1368    fn test_format_param_type_vec_ref() {
1369        let param = make_param("items", TypeRef::Vec(Box::new(TypeRef::String)), true);
1370        assert_eq!(format_param_type(&param, &HashMap::new()), "&[String]");
1371    }
1372
1373    #[test]
1374    fn test_format_param_type_vec_owned() {
1375        let param = make_param("items", TypeRef::Vec(Box::new(TypeRef::String)), false);
1376        assert_eq!(format_param_type(&param, &HashMap::new()), "Vec<String>");
1377    }
1378
1379    #[test]
1380    fn test_format_param_type_named_ref_with_type_paths() {
1381        let mut paths = HashMap::new();
1382        paths.insert("Config".to_string(), "mylib::Config".to_string());
1383        let param = make_param("cfg", TypeRef::Named("Config".to_string()), true);
1384        assert_eq!(format_param_type(&param, &paths), "&mylib::Config");
1385    }
1386
1387    #[test]
1388    fn test_format_param_type_named_ref_without_type_paths() {
1389        let param = make_param("cfg", TypeRef::Named("Config".to_string()), true);
1390        assert_eq!(format_param_type(&param, &HashMap::new()), "&Config");
1391    }
1392
1393    #[test]
1394    fn test_format_param_type_primitive_ref_passes_by_value() {
1395        // Copy types like u32 are passed by value even when is_ref is set
1396        let param = make_param("count", TypeRef::Primitive(PrimitiveType::U32), true);
1397        assert_eq!(format_param_type(&param, &HashMap::new()), "u32");
1398    }
1399
1400    #[test]
1401    fn test_format_param_type_unit_ref_passes_by_value() {
1402        let param = make_param("nothing", TypeRef::Unit, true);
1403        assert_eq!(format_param_type(&param, &HashMap::new()), "()");
1404    }
1405
1406    // ---------------------------------------------------------------------------
1407    // format_return_type
1408    // ---------------------------------------------------------------------------
1409
1410    #[test]
1411    fn test_format_return_type_without_error() {
1412        let result = format_return_type(&TypeRef::String, None, &HashMap::new(), false);
1413        assert_eq!(result, "String");
1414    }
1415
1416    #[test]
1417    fn test_format_return_type_with_error() {
1418        let result = format_return_type(&TypeRef::String, Some("MyError"), &HashMap::new(), false);
1419        assert_eq!(result, "std::result::Result<String, MyError>");
1420    }
1421
1422    #[test]
1423    fn test_format_return_type_unit_with_error() {
1424        let result = format_return_type(
1425            &TypeRef::Unit,
1426            Some("Box<dyn std::error::Error>"),
1427            &HashMap::new(),
1428            false,
1429        );
1430        assert_eq!(result, "std::result::Result<(), Box<dyn std::error::Error>>");
1431    }
1432
1433    #[test]
1434    fn test_format_return_type_named_with_type_paths_and_error() {
1435        let mut paths = HashMap::new();
1436        paths.insert("Output".to_string(), "mylib::Output".to_string());
1437        let result = format_return_type(
1438            &TypeRef::Named("Output".to_string()),
1439            Some("mylib::MyError"),
1440            &paths,
1441            false,
1442        );
1443        assert_eq!(result, "std::result::Result<mylib::Output, mylib::MyError>");
1444    }
1445
1446    #[test]
1447    fn test_format_return_type_vec_string_with_returns_ref() {
1448        // `fn supported_mime_types(&self) -> &[&str]` is extracted as
1449        // `return_type = Vec(String), returns_ref = true`.
1450        // The generated impl signature must emit `&[&str]`, not `Vec<String>`.
1451        let result = format_return_type(&TypeRef::Vec(Box::new(TypeRef::String)), None, &HashMap::new(), true);
1452        assert_eq!(result, "&[&str]", "Vec<String> + returns_ref must yield &[&str]");
1453    }
1454
1455    #[test]
1456    fn test_format_return_type_vec_no_returns_ref_unchanged() {
1457        // Without returns_ref the type is unchanged.
1458        let result = format_return_type(&TypeRef::Vec(Box::new(TypeRef::String)), None, &HashMap::new(), false);
1459        assert_eq!(
1460            result, "Vec<String>",
1461            "Vec<String> without returns_ref must stay Vec<String>"
1462        );
1463    }
1464
1465    // ---------------------------------------------------------------------------
1466    // gen_bridge_wrapper_struct
1467    // ---------------------------------------------------------------------------
1468
1469    #[test]
1470    fn test_gen_bridge_wrapper_struct_contains_struct_name() {
1471        let trait_def = make_type_def("OcrBackend", "mylib::OcrBackend", vec![]);
1472        let config = make_trait_bridge_config(None, None);
1473        let spec = make_spec(&trait_def, &config, "Py", HashMap::new());
1474        let generator = MockBridgeGenerator;
1475        let result = gen_bridge_wrapper_struct(&spec, &generator);
1476        assert!(
1477            result.contains("pub struct PyOcrBackendBridge"),
1478            "missing struct declaration in:\n{result}"
1479        );
1480    }
1481
1482    #[test]
1483    fn test_gen_bridge_wrapper_struct_contains_inner_field() {
1484        let trait_def = make_type_def("OcrBackend", "mylib::OcrBackend", vec![]);
1485        let config = make_trait_bridge_config(None, None);
1486        let spec = make_spec(&trait_def, &config, "Py", HashMap::new());
1487        let generator = MockBridgeGenerator;
1488        let result = gen_bridge_wrapper_struct(&spec, &generator);
1489        assert!(result.contains("inner: Py<PyAny>"), "missing inner field in:\n{result}");
1490    }
1491
1492    #[test]
1493    fn test_gen_bridge_wrapper_struct_contains_cached_name() {
1494        let trait_def = make_type_def("OcrBackend", "mylib::OcrBackend", vec![]);
1495        let config = make_trait_bridge_config(None, None);
1496        let spec = make_spec(&trait_def, &config, "Py", HashMap::new());
1497        let generator = MockBridgeGenerator;
1498        let result = gen_bridge_wrapper_struct(&spec, &generator);
1499        assert!(
1500            result.contains("cached_name: String"),
1501            "missing cached_name field in:\n{result}"
1502        );
1503    }
1504
1505    // ---------------------------------------------------------------------------
1506    // gen_bridge_plugin_impl
1507    // ---------------------------------------------------------------------------
1508
1509    #[test]
1510    fn test_gen_bridge_plugin_impl_returns_none_when_no_super_trait() {
1511        let trait_def = make_type_def("OcrBackend", "mylib::OcrBackend", vec![]);
1512        let config = make_trait_bridge_config(None, None);
1513        let spec = make_spec(&trait_def, &config, "Py", HashMap::new());
1514        let generator = MockBridgeGenerator;
1515        assert!(gen_bridge_plugin_impl(&spec, &generator).is_none());
1516    }
1517
1518    #[test]
1519    fn test_gen_bridge_plugin_impl_returns_some_when_super_trait_configured() {
1520        let trait_def = make_type_def("OcrBackend", "mylib::OcrBackend", vec![]);
1521        let config = make_trait_bridge_config(Some("Plugin"), None);
1522        let spec = make_spec(&trait_def, &config, "Py", HashMap::new());
1523        let generator = MockBridgeGenerator;
1524        assert!(gen_bridge_plugin_impl(&spec, &generator).is_some());
1525    }
1526
1527    #[test]
1528    fn test_gen_bridge_plugin_impl_uses_qualified_super_trait_path() {
1529        let trait_def = make_type_def("OcrBackend", "mylib::OcrBackend", vec![]);
1530        let config = make_trait_bridge_config(Some("Plugin"), None);
1531        let spec = make_spec(&trait_def, &config, "Py", HashMap::new());
1532        let generator = MockBridgeGenerator;
1533        let result = gen_bridge_plugin_impl(&spec, &generator).unwrap();
1534        assert!(
1535            result.contains("impl mylib::Plugin for PyOcrBackendBridge"),
1536            "missing qualified super-trait path in:\n{result}"
1537        );
1538    }
1539
1540    #[test]
1541    fn test_gen_bridge_plugin_impl_uses_already_qualified_super_trait_path() {
1542        let trait_def = make_type_def("OcrBackend", "mylib::OcrBackend", vec![]);
1543        let config = make_trait_bridge_config(Some("other_crate::Plugin"), None);
1544        let spec = make_spec(&trait_def, &config, "Py", HashMap::new());
1545        let generator = MockBridgeGenerator;
1546        let result = gen_bridge_plugin_impl(&spec, &generator).unwrap();
1547        assert!(
1548            result.contains("impl other_crate::Plugin for PyOcrBackendBridge"),
1549            "wrong super-trait path in:\n{result}"
1550        );
1551    }
1552
1553    #[test]
1554    fn test_gen_bridge_plugin_impl_contains_name_fn() {
1555        let trait_def = make_type_def("OcrBackend", "mylib::OcrBackend", vec![]);
1556        let config = make_trait_bridge_config(Some("Plugin"), None);
1557        let spec = make_spec(&trait_def, &config, "Py", HashMap::new());
1558        let generator = MockBridgeGenerator;
1559        let result = gen_bridge_plugin_impl(&spec, &generator).unwrap();
1560        assert!(
1561            result.contains("fn name(") && result.contains("cached_name"),
1562            "missing name() using cached_name in:\n{result}"
1563        );
1564    }
1565
1566    #[test]
1567    fn test_gen_bridge_plugin_impl_contains_version_fn() {
1568        let trait_def = make_type_def("OcrBackend", "mylib::OcrBackend", vec![]);
1569        let config = make_trait_bridge_config(Some("Plugin"), None);
1570        let spec = make_spec(&trait_def, &config, "Py", HashMap::new());
1571        let generator = MockBridgeGenerator;
1572        let result = gen_bridge_plugin_impl(&spec, &generator).unwrap();
1573        assert!(result.contains("fn version("), "missing version() in:\n{result}");
1574    }
1575
1576    #[test]
1577    fn test_gen_bridge_plugin_impl_contains_initialize_fn() {
1578        let trait_def = make_type_def("OcrBackend", "mylib::OcrBackend", vec![]);
1579        let config = make_trait_bridge_config(Some("Plugin"), None);
1580        let spec = make_spec(&trait_def, &config, "Py", HashMap::new());
1581        let generator = MockBridgeGenerator;
1582        let result = gen_bridge_plugin_impl(&spec, &generator).unwrap();
1583        assert!(result.contains("fn initialize("), "missing initialize() in:\n{result}");
1584    }
1585
1586    #[test]
1587    fn test_gen_bridge_plugin_impl_contains_shutdown_fn() {
1588        let trait_def = make_type_def("OcrBackend", "mylib::OcrBackend", vec![]);
1589        let config = make_trait_bridge_config(Some("Plugin"), None);
1590        let spec = make_spec(&trait_def, &config, "Py", HashMap::new());
1591        let generator = MockBridgeGenerator;
1592        let result = gen_bridge_plugin_impl(&spec, &generator).unwrap();
1593        assert!(result.contains("fn shutdown("), "missing shutdown() in:\n{result}");
1594    }
1595
1596    // ---------------------------------------------------------------------------
1597    // gen_bridge_trait_impl
1598    // ---------------------------------------------------------------------------
1599
1600    #[test]
1601    fn test_gen_bridge_trait_impl_includes_impl_header() {
1602        let trait_def = make_type_def("OcrBackend", "mylib::OcrBackend", vec![]);
1603        let config = make_trait_bridge_config(None, None);
1604        let spec = make_spec(&trait_def, &config, "Py", HashMap::new());
1605        let generator = MockBridgeGenerator;
1606        let result = gen_bridge_trait_impl(&spec, &generator);
1607        assert!(
1608            result.contains("impl mylib::OcrBackend for PyOcrBackendBridge"),
1609            "missing impl header in:\n{result}"
1610        );
1611    }
1612
1613    #[test]
1614    fn test_gen_bridge_trait_impl_includes_method_signatures() {
1615        let methods = vec![make_method(
1616            "process",
1617            vec![],
1618            TypeRef::String,
1619            false,
1620            false,
1621            None,
1622            None,
1623        )];
1624        let trait_def = make_type_def("OcrBackend", "mylib::OcrBackend", methods);
1625        let config = make_trait_bridge_config(None, None);
1626        let spec = make_spec(&trait_def, &config, "Py", HashMap::new());
1627        let generator = MockBridgeGenerator;
1628        let result = gen_bridge_trait_impl(&spec, &generator);
1629        assert!(result.contains("fn process("), "missing method signature in:\n{result}");
1630    }
1631
1632    #[test]
1633    fn test_gen_bridge_trait_impl_includes_method_body_from_generator() {
1634        let methods = vec![make_method(
1635            "process",
1636            vec![],
1637            TypeRef::String,
1638            false,
1639            false,
1640            None,
1641            None,
1642        )];
1643        let trait_def = make_type_def("OcrBackend", "mylib::OcrBackend", methods);
1644        let config = make_trait_bridge_config(None, None);
1645        let spec = make_spec(&trait_def, &config, "Py", HashMap::new());
1646        let generator = MockBridgeGenerator;
1647        let result = gen_bridge_trait_impl(&spec, &generator);
1648        assert!(
1649            result.contains("// sync body for process"),
1650            "missing sync method body in:\n{result}"
1651        );
1652    }
1653
1654    #[test]
1655    fn test_gen_bridge_trait_impl_async_method_uses_async_body() {
1656        let methods = vec![make_method(
1657            "process_async",
1658            vec![],
1659            TypeRef::String,
1660            true,
1661            false,
1662            None,
1663            None,
1664        )];
1665        let trait_def = make_type_def("OcrBackend", "mylib::OcrBackend", methods);
1666        let config = make_trait_bridge_config(None, None);
1667        let spec = make_spec(&trait_def, &config, "Py", HashMap::new());
1668        let generator = MockBridgeGenerator;
1669        let result = gen_bridge_trait_impl(&spec, &generator);
1670        assert!(
1671            result.contains("// async body for process_async"),
1672            "missing async method body in:\n{result}"
1673        );
1674        assert!(
1675            result.contains("async fn process_async("),
1676            "missing async keyword in method signature in:\n{result}"
1677        );
1678    }
1679
1680    #[test]
1681    fn test_gen_bridge_trait_impl_filters_trait_source_methods() {
1682        // Methods with trait_source set come from super-traits and should be excluded
1683        let methods = vec![
1684            make_method("own_method", vec![], TypeRef::String, false, false, None, None),
1685            make_method(
1686                "inherited_method",
1687                vec![],
1688                TypeRef::String,
1689                false,
1690                false,
1691                Some("other_crate::OtherTrait"),
1692                None,
1693            ),
1694        ];
1695        let trait_def = make_type_def("OcrBackend", "mylib::OcrBackend", methods);
1696        let config = make_trait_bridge_config(None, None);
1697        let spec = make_spec(&trait_def, &config, "Py", HashMap::new());
1698        let generator = MockBridgeGenerator;
1699        let result = gen_bridge_trait_impl(&spec, &generator);
1700        assert!(
1701            result.contains("fn own_method("),
1702            "own method should be present in:\n{result}"
1703        );
1704        assert!(
1705            !result.contains("fn inherited_method("),
1706            "inherited method should be filtered out in:\n{result}"
1707        );
1708    }
1709
1710    #[test]
1711    fn test_gen_bridge_trait_impl_method_with_params() {
1712        let params = vec![
1713            make_param("input", TypeRef::String, true),
1714            make_param("count", TypeRef::Primitive(PrimitiveType::U32), false),
1715        ];
1716        let methods = vec![make_method(
1717            "process",
1718            params,
1719            TypeRef::String,
1720            false,
1721            false,
1722            None,
1723            None,
1724        )];
1725        let trait_def = make_type_def("OcrBackend", "mylib::OcrBackend", methods);
1726        let config = make_trait_bridge_config(None, None);
1727        let spec = make_spec(&trait_def, &config, "Py", HashMap::new());
1728        let generator = MockBridgeGenerator;
1729        let result = gen_bridge_trait_impl(&spec, &generator);
1730        assert!(result.contains("input: &str"), "missing &str param in:\n{result}");
1731        assert!(result.contains("count: u32"), "missing u32 param in:\n{result}");
1732    }
1733
1734    #[test]
1735    fn test_gen_bridge_trait_impl_return_type_with_error() {
1736        let methods = vec![make_method(
1737            "process",
1738            vec![],
1739            TypeRef::String,
1740            false,
1741            false,
1742            None,
1743            Some("MyError"),
1744        )];
1745        let trait_def = make_type_def("OcrBackend", "mylib::OcrBackend", methods);
1746        let config = make_trait_bridge_config(None, None);
1747        let spec = make_spec(&trait_def, &config, "Py", HashMap::new());
1748        let generator = MockBridgeGenerator;
1749        let result = gen_bridge_trait_impl(&spec, &generator);
1750        assert!(
1751            result.contains("-> std::result::Result<String, mylib::MyError>"),
1752            "missing std::result::Result return type in:\n{result}"
1753        );
1754    }
1755
1756    // ---------------------------------------------------------------------------
1757    // gen_bridge_registration_fn
1758    // ---------------------------------------------------------------------------
1759
1760    #[test]
1761    fn test_gen_bridge_registration_fn_returns_none_without_register_fn() {
1762        let trait_def = make_type_def("OcrBackend", "mylib::OcrBackend", vec![]);
1763        let config = make_trait_bridge_config(None, None);
1764        let spec = make_spec(&trait_def, &config, "Py", HashMap::new());
1765        let generator = MockBridgeGenerator;
1766        assert!(gen_bridge_registration_fn(&spec, &generator).is_none());
1767    }
1768
1769    #[test]
1770    fn test_gen_bridge_registration_fn_returns_some_with_register_fn() {
1771        let trait_def = make_type_def("OcrBackend", "mylib::OcrBackend", vec![]);
1772        let config = make_trait_bridge_config(None, Some("register_ocr_backend"));
1773        let spec = make_spec(&trait_def, &config, "Py", HashMap::new());
1774        let generator = MockBridgeGenerator;
1775        let result = gen_bridge_registration_fn(&spec, &generator);
1776        assert!(result.is_some());
1777        let code = result.unwrap();
1778        assert!(
1779            code.contains("register_ocr_backend"),
1780            "missing register fn name in:\n{code}"
1781        );
1782    }
1783
1784    // ---------------------------------------------------------------------------
1785    // gen_bridge_all
1786    // ---------------------------------------------------------------------------
1787
1788    #[test]
1789    fn test_gen_bridge_all_includes_imports() {
1790        let trait_def = make_type_def("OcrBackend", "mylib::OcrBackend", vec![]);
1791        let config = make_trait_bridge_config(None, None);
1792        let spec = make_spec(&trait_def, &config, "Py", HashMap::new());
1793        let generator = MockBridgeGenerator;
1794        let output = gen_bridge_all(&spec, &generator);
1795        assert!(output.imports.contains(&"pyo3::prelude::*".to_string()));
1796        assert!(output.imports.contains(&"pyo3::types::PyString".to_string()));
1797    }
1798
1799    #[test]
1800    fn test_gen_bridge_all_includes_wrapper_struct() {
1801        let trait_def = make_type_def("OcrBackend", "mylib::OcrBackend", vec![]);
1802        let config = make_trait_bridge_config(None, None);
1803        let spec = make_spec(&trait_def, &config, "Py", HashMap::new());
1804        let generator = MockBridgeGenerator;
1805        let output = gen_bridge_all(&spec, &generator);
1806        assert!(
1807            output.code.contains("pub struct PyOcrBackendBridge"),
1808            "missing struct in:\n{}",
1809            output.code
1810        );
1811    }
1812
1813    #[test]
1814    fn test_gen_bridge_all_includes_constructor() {
1815        let trait_def = make_type_def("OcrBackend", "mylib::OcrBackend", vec![]);
1816        let config = make_trait_bridge_config(None, None);
1817        let spec = make_spec(&trait_def, &config, "Py", HashMap::new());
1818        let generator = MockBridgeGenerator;
1819        let output = gen_bridge_all(&spec, &generator);
1820        assert!(
1821            output.code.contains("pub fn new("),
1822            "missing constructor in:\n{}",
1823            output.code
1824        );
1825    }
1826
1827    #[test]
1828    fn test_gen_bridge_all_includes_trait_impl() {
1829        let methods = vec![make_method(
1830            "process",
1831            vec![],
1832            TypeRef::String,
1833            false,
1834            false,
1835            None,
1836            None,
1837        )];
1838        let trait_def = make_type_def("OcrBackend", "mylib::OcrBackend", methods);
1839        let config = make_trait_bridge_config(None, None);
1840        let spec = make_spec(&trait_def, &config, "Py", HashMap::new());
1841        let generator = MockBridgeGenerator;
1842        let output = gen_bridge_all(&spec, &generator);
1843        assert!(
1844            output.code.contains("impl mylib::OcrBackend for PyOcrBackendBridge"),
1845            "missing trait impl in:\n{}",
1846            output.code
1847        );
1848    }
1849
1850    #[test]
1851    fn test_gen_bridge_all_includes_plugin_impl_when_super_trait_set() {
1852        let trait_def = make_type_def("OcrBackend", "mylib::OcrBackend", vec![]);
1853        let config = make_trait_bridge_config(Some("Plugin"), None);
1854        let spec = make_spec(&trait_def, &config, "Py", HashMap::new());
1855        let generator = MockBridgeGenerator;
1856        let output = gen_bridge_all(&spec, &generator);
1857        assert!(
1858            output.code.contains("impl mylib::Plugin for PyOcrBackendBridge"),
1859            "missing plugin impl in:\n{}",
1860            output.code
1861        );
1862    }
1863
1864    #[test]
1865    fn test_gen_bridge_all_no_plugin_impl_when_no_super_trait() {
1866        let trait_def = make_type_def("OcrBackend", "mylib::OcrBackend", vec![]);
1867        let config = make_trait_bridge_config(None, None);
1868        let spec = make_spec(&trait_def, &config, "Py", HashMap::new());
1869        let generator = MockBridgeGenerator;
1870        let output = gen_bridge_all(&spec, &generator);
1871        assert!(
1872            !output.code.contains("fn name(") || !output.code.contains("cached_name"),
1873            "unexpected plugin impl present without super_trait"
1874        );
1875    }
1876
1877    #[test]
1878    fn test_gen_bridge_all_includes_registration_fn_when_configured() {
1879        let trait_def = make_type_def("OcrBackend", "mylib::OcrBackend", vec![]);
1880        let config = make_trait_bridge_config(None, Some("register_ocr_backend"));
1881        let spec = make_spec(&trait_def, &config, "Py", HashMap::new());
1882        let generator = MockBridgeGenerator;
1883        let output = gen_bridge_all(&spec, &generator);
1884        assert!(
1885            output.code.contains("register_ocr_backend"),
1886            "missing registration fn in:\n{}",
1887            output.code
1888        );
1889    }
1890
1891    #[test]
1892    fn test_gen_bridge_all_no_registration_fn_when_absent() {
1893        let trait_def = make_type_def("OcrBackend", "mylib::OcrBackend", vec![]);
1894        let config = make_trait_bridge_config(None, None);
1895        let spec = make_spec(&trait_def, &config, "Py", HashMap::new());
1896        let generator = MockBridgeGenerator;
1897        let output = gen_bridge_all(&spec, &generator);
1898        assert!(
1899            !output.code.contains("register_ocr_backend"),
1900            "unexpected registration fn present:\n{}",
1901            output.code
1902        );
1903    }
1904
1905    #[test]
1906    fn test_gen_bridge_all_ordering_struct_before_trait_impl() {
1907        let trait_def = make_type_def("OcrBackend", "mylib::OcrBackend", vec![]);
1908        let config = make_trait_bridge_config(None, None);
1909        let spec = make_spec(&trait_def, &config, "Py", HashMap::new());
1910        let generator = MockBridgeGenerator;
1911        let output = gen_bridge_all(&spec, &generator);
1912        let struct_pos = output.code.find("pub struct PyOcrBackendBridge").unwrap();
1913        let impl_pos = output
1914            .code
1915            .find("impl mylib::OcrBackend for PyOcrBackendBridge")
1916            .unwrap();
1917        assert!(struct_pos < impl_pos, "struct should appear before trait impl");
1918    }
1919
1920    // ---------------------------------------------------------------------------
1921    // find_bridge_param / find_bridge_field
1922    // ---------------------------------------------------------------------------
1923
1924    fn make_bridge(
1925        type_alias: Option<&str>,
1926        param_name: Option<&str>,
1927        bind_via: BridgeBinding,
1928        options_type: Option<&str>,
1929        options_field: Option<&str>,
1930        context_type: Option<&str>,
1931        result_type: Option<&str>,
1932    ) -> TraitBridgeConfig {
1933        TraitBridgeConfig {
1934            trait_name: "HtmlVisitor".to_string(),
1935            super_trait: None,
1936            registry_getter: None,
1937            register_fn: None,
1938            unregister_fn: None,
1939            clear_fn: None,
1940            type_alias: type_alias.map(str::to_string),
1941            param_name: param_name.map(str::to_string),
1942            register_extra_args: None,
1943            exclude_languages: vec![],
1944            ffi_skip_methods: Vec::new(),
1945            bind_via,
1946            options_type: options_type.map(str::to_string),
1947            options_field: options_field.map(str::to_string),
1948            context_type: context_type.map(str::to_string),
1949            result_type: result_type.map(str::to_string),
1950        }
1951    }
1952
1953    #[test]
1954    fn find_bridge_param_returns_first_param_match_in_function_param_mode() {
1955        let func = make_func(
1956            "convert",
1957            vec![
1958                make_param("html", TypeRef::String, true),
1959                make_param("visitor", TypeRef::Named("VisitorHandle".to_string()), false),
1960            ],
1961        );
1962        let bridges = vec![make_bridge(
1963            Some("VisitorHandle"),
1964            Some("visitor"),
1965            BridgeBinding::FunctionParam,
1966            None,
1967            None,
1968            None,
1969            None,
1970        )];
1971        let result = find_bridge_param(&func, &bridges).expect("bridge match");
1972        assert_eq!(result.0, 1);
1973    }
1974
1975    #[test]
1976    fn find_bridge_param_skips_options_field_bridges() {
1977        let func = make_func(
1978            "convert",
1979            vec![
1980                make_param("html", TypeRef::String, true),
1981                make_param("visitor", TypeRef::Named("VisitorHandle".to_string()), false),
1982            ],
1983        );
1984        let bridges = vec![make_bridge(
1985            Some("VisitorHandle"),
1986            Some("visitor"),
1987            BridgeBinding::OptionsField,
1988            Some("ConversionOptions"),
1989            Some("visitor"),
1990            None,
1991            None,
1992        )];
1993        assert!(
1994            find_bridge_param(&func, &bridges).is_none(),
1995            "bridges configured with bind_via=options_field must not be returned by find_bridge_param"
1996        );
1997    }
1998
1999    #[test]
2000    fn find_bridge_field_detects_field_via_alias() {
2001        let opts_type = TypeDef {
2002            name: "ConversionOptions".to_string(),
2003            rust_path: "mylib::ConversionOptions".to_string(),
2004            original_rust_path: String::new(),
2005            fields: vec![
2006                make_field("debug", TypeRef::Primitive(PrimitiveType::Bool)),
2007                make_field(
2008                    "visitor",
2009                    TypeRef::Optional(Box::new(TypeRef::Named("VisitorHandle".to_string()))),
2010                ),
2011            ],
2012            methods: vec![],
2013            is_opaque: false,
2014            is_clone: true,
2015            is_copy: false,
2016            doc: String::new(),
2017            cfg: None,
2018            is_trait: false,
2019            has_default: true,
2020            has_stripped_cfg_fields: false,
2021            is_return_type: false,
2022            serde_rename_all: None,
2023            has_serde: false,
2024            super_traits: vec![],
2025            binding_excluded: false,
2026            binding_exclusion_reason: None,
2027        };
2028        let func = make_func(
2029            "convert",
2030            vec![
2031                make_param("html", TypeRef::String, true),
2032                make_param(
2033                    "options",
2034                    TypeRef::Optional(Box::new(TypeRef::Named("ConversionOptions".to_string()))),
2035                    false,
2036                ),
2037            ],
2038        );
2039        let bridges = vec![make_bridge(
2040            Some("VisitorHandle"),
2041            Some("visitor"),
2042            BridgeBinding::OptionsField,
2043            Some("ConversionOptions"),
2044            None,
2045            None,
2046            None,
2047        )];
2048        let m = find_bridge_field(&func, std::slice::from_ref(&opts_type), &bridges).expect("bridge field match");
2049        assert_eq!(m.param_index, 1);
2050        assert_eq!(m.param_name, "options");
2051        assert_eq!(m.options_type, "ConversionOptions");
2052        assert!(m.param_is_optional);
2053        assert_eq!(m.field_name, "visitor");
2054    }
2055
2056    #[test]
2057    fn find_bridge_field_returns_none_for_function_param_bridge() {
2058        let opts_type = TypeDef {
2059            name: "ConversionOptions".to_string(),
2060            rust_path: "mylib::ConversionOptions".to_string(),
2061            original_rust_path: String::new(),
2062            fields: vec![make_field(
2063                "visitor",
2064                TypeRef::Optional(Box::new(TypeRef::Named("VisitorHandle".to_string()))),
2065            )],
2066            methods: vec![],
2067            is_opaque: false,
2068            is_clone: true,
2069            is_copy: false,
2070            doc: String::new(),
2071            cfg: None,
2072            is_trait: false,
2073            has_default: true,
2074            has_stripped_cfg_fields: false,
2075            is_return_type: false,
2076            serde_rename_all: None,
2077            has_serde: false,
2078            super_traits: vec![],
2079            binding_excluded: false,
2080            binding_exclusion_reason: None,
2081        };
2082        let func = make_func(
2083            "convert",
2084            vec![make_param(
2085                "options",
2086                TypeRef::Named("ConversionOptions".to_string()),
2087                false,
2088            )],
2089        );
2090        let bridges = vec![make_bridge(
2091            Some("VisitorHandle"),
2092            Some("visitor"),
2093            BridgeBinding::FunctionParam,
2094            None,
2095            None,
2096            None,
2097            None,
2098        )];
2099        assert!(find_bridge_field(&func, std::slice::from_ref(&opts_type), &bridges).is_none());
2100    }
2101}