Skip to main content

alef_backend_php/
trait_bridge.rs

1//! PHP (ext-php-rs) specific trait bridge code generation.
2//!
3//! Generates Rust wrapper structs that implement Rust traits by delegating
4//! to PHP objects via ext-php-rs Zval method calls.
5
6use minijinja::context;
7use std::fmt::Write;
8
9use alef_codegen::generators::trait_bridge::{
10    BridgeOutput, TraitBridgeGenerator, TraitBridgeSpec, bridge_param_type as param_type, gen_bridge_all,
11    visitor_param_type,
12};
13use alef_core::config::TraitBridgeConfig;
14use alef_core::ir::{ApiSurface, MethodDef, TypeDef, TypeRef};
15use std::collections::HashMap;
16
17/// Find the first parameter index and bridge config where the parameter's named type
18/// matches a trait bridge's `type_alias`.
19///
20/// Returns `None` when no bridge applies.
21pub use alef_codegen::generators::trait_bridge::find_bridge_param;
22
23/// PHP-specific trait bridge generator.
24/// Implements code generation for bridging PHP objects to Rust traits.
25pub struct PhpBridgeGenerator {
26    /// Core crate import path (e.g., `"kreuzberg"`).
27    pub core_import: String,
28    /// Map of type name → fully-qualified Rust path for type references.
29    pub type_paths: HashMap<String, String>,
30    /// Error type name (e.g., `"KreuzbergError"`).
31    pub error_type: String,
32}
33
34impl TraitBridgeGenerator for PhpBridgeGenerator {
35    fn foreign_object_type(&self) -> &str {
36        "*mut ext_php_rs::types::ZendObject"
37    }
38
39    fn bridge_imports(&self) -> Vec<String> {
40        vec!["std::sync::Arc".to_string()]
41    }
42
43    fn gen_sync_method_body(&self, method: &MethodDef, _spec: &TraitBridgeSpec) -> String {
44        let name = &method.name;
45
46        let has_args = !method.params.is_empty();
47        let args_expr = if has_args {
48            let mut args_parts = Vec::new();
49            for p in &method.params {
50                let arg_expr = match &p.ty {
51                    TypeRef::String => format!("ext_php_rs::types::Zval::try_from({}).unwrap_or_default()", p.name),
52                    TypeRef::Path => format!(
53                        "ext_php_rs::types::Zval::try_from({}.to_string_lossy().to_string()).unwrap_or_default()",
54                        p.name
55                    ),
56                    TypeRef::Bytes => format!(
57                        "ext_php_rs::types::Zval::try_from(format!(\"{{:?}}\", {})).unwrap_or_default()",
58                        p.name
59                    ),
60                    TypeRef::Named(_) => {
61                        format!(
62                            "ext_php_rs::types::Zval::try_from(serde_json::to_string(&{}).unwrap_or_default()).unwrap_or_default()",
63                            p.name
64                        )
65                    }
66                    TypeRef::Primitive(_) => {
67                        format!("ext_php_rs::types::Zval::try_from({}).unwrap_or_default()", p.name)
68                    }
69                    _ => format!(
70                        "ext_php_rs::types::Zval::try_from(format!(\"{{:?}}\", {})).unwrap_or_default()",
71                        p.name
72                    ),
73                };
74                args_parts.push(arg_expr);
75            }
76            let args_array = format!("[{}]", args_parts.join(", "));
77            format!(
78                "{}.iter().map(|z| z as &dyn ext_php_rs::convert::IntoZvalDyn).collect()",
79                args_array
80            )
81        } else {
82            "vec![]".to_string()
83        };
84
85        let is_result_type = method.error_type.is_some();
86        let is_unit_return = matches!(method.return_type, TypeRef::Unit);
87
88        crate::template_env::render(
89            "sync_method_body.jinja",
90            context! {
91                method_name => name,
92                args_expr => args_expr,
93                is_result_type => is_result_type,
94                is_unit_return => is_unit_return,
95                core_import => &self.core_import,
96            },
97        )
98    }
99
100    fn gen_async_method_body(&self, method: &MethodDef, spec: &TraitBridgeSpec) -> String {
101        let name = &method.name;
102
103        let string_params: Vec<String> = method
104            .params
105            .iter()
106            .filter(|p| matches!(&p.ty, TypeRef::String))
107            .map(|p| p.name.clone())
108            .collect();
109
110        let has_args = !method.params.is_empty();
111        let args_expr = if has_args {
112            let mut args_parts = Vec::new();
113            for p in &method.params {
114                let arg_expr = match &p.ty {
115                    TypeRef::String => format!("ext_php_rs::types::Zval::try_from({}).unwrap_or_default()", p.name),
116                    TypeRef::Path => format!(
117                        "ext_php_rs::types::Zval::try_from({}.to_string_lossy().to_string()).unwrap_or_default()",
118                        p.name
119                    ),
120                    TypeRef::Bytes => format!(
121                        "ext_php_rs::types::Zval::try_from(format!(\"{{:?}}\", {})).unwrap_or_default()",
122                        p.name
123                    ),
124                    TypeRef::Named(_) => {
125                        format!(
126                            "ext_php_rs::types::Zval::try_from(serde_json::to_string(&{}).unwrap_or_default()).unwrap_or_default()",
127                            p.name
128                        )
129                    }
130                    TypeRef::Primitive(_) => {
131                        format!("ext_php_rs::types::Zval::try_from({}).unwrap_or_default()", p.name)
132                    }
133                    _ => format!(
134                        "ext_php_rs::types::Zval::try_from(format!(\"{{:?}}\", {})).unwrap_or_default()",
135                        p.name
136                    ),
137                };
138                args_parts.push(arg_expr);
139            }
140            let args_array = format!("[{}]", args_parts.join(", "));
141            format!(
142                "{}.iter().map(|z| z as &dyn ext_php_rs::convert::IntoZvalDyn).collect()",
143                args_array
144            )
145        } else {
146            "vec![]".to_string()
147        };
148
149        let is_result_type = method.error_type.is_some();
150
151        crate::template_env::render(
152            "async_method_body.jinja",
153            context! {
154                method_name => name,
155                args_expr => args_expr,
156                string_params => string_params,
157                is_result_type => is_result_type,
158                core_import => &spec.core_import,
159            },
160        )
161    }
162
163    fn gen_constructor(&self, spec: &TraitBridgeSpec) -> String {
164        let wrapper = spec.wrapper_name();
165
166        crate::template_env::render(
167            "bridge_constructor.jinja",
168            context! {
169                wrapper => &wrapper,
170            },
171        )
172    }
173
174    fn gen_unregistration_fn(&self, spec: &TraitBridgeSpec) -> String {
175        let Some(unregister_fn) = spec.bridge_config.unregister_fn.as_deref() else {
176            return String::new();
177        };
178        let host_path = alef_codegen::generators::trait_bridge::host_function_path(spec, unregister_fn);
179
180        crate::template_env::render(
181            "bridge_unregister_fn.jinja",
182            context! {
183                unregister_fn => unregister_fn,
184                host_path => &host_path,
185            },
186        )
187    }
188
189    fn gen_clear_fn(&self, spec: &TraitBridgeSpec) -> String {
190        let Some(clear_fn) = spec.bridge_config.clear_fn.as_deref() else {
191            return String::new();
192        };
193        let host_path = alef_codegen::generators::trait_bridge::host_function_path(spec, clear_fn);
194
195        crate::template_env::render(
196            "bridge_clear_fn.jinja",
197            context! {
198                clear_fn => clear_fn,
199                host_path => &host_path,
200            },
201        )
202    }
203
204    fn gen_registration_fn(&self, spec: &TraitBridgeSpec) -> String {
205        let Some(register_fn) = spec.bridge_config.register_fn.as_deref() else {
206            return String::new();
207        };
208        let Some(registry_getter) = spec.bridge_config.registry_getter.as_deref() else {
209            return String::new();
210        };
211        let wrapper = spec.wrapper_name();
212        let trait_path = spec.trait_path();
213
214        let req_methods: Vec<&MethodDef> = spec.required_methods();
215        let required_methods: Vec<minijinja::Value> = req_methods
216            .iter()
217            .map(|m| {
218                minijinja::context! {
219                    name => m.name.as_str(),
220                }
221            })
222            .collect();
223
224        let extra_args = spec
225            .bridge_config
226            .register_extra_args
227            .as_deref()
228            .map(|a| format!(", {a}"))
229            .unwrap_or_default();
230
231        crate::template_env::render(
232            "bridge_registration_fn.jinja",
233            context! {
234                register_fn => register_fn,
235                required_methods => required_methods,
236                wrapper => &wrapper,
237                trait_path => &trait_path,
238                registry_getter => registry_getter,
239                extra_args => &extra_args,
240            },
241        )
242    }
243}
244
245/// Generate all trait bridge code for a given trait type and bridge config.
246pub fn gen_trait_bridge(
247    trait_type: &TypeDef,
248    bridge_cfg: &TraitBridgeConfig,
249    core_import: &str,
250    error_type: &str,
251    error_constructor: &str,
252    api: &ApiSurface,
253) -> BridgeOutput {
254    // Build type name → rust_path lookup as owned HashMap
255    let type_paths: HashMap<String, String> = api
256        .types
257        .iter()
258        .map(|t| (t.name.clone(), t.rust_path.replace('-', "_")))
259        .chain(
260            api.enums
261                .iter()
262                .map(|e| (e.name.clone(), e.rust_path.replace('-', "_"))),
263        )
264        .collect();
265
266    // Visitor-style bridge: all methods have defaults, no registry, no super-trait.
267    let is_visitor_bridge = bridge_cfg.type_alias.is_some()
268        && bridge_cfg.register_fn.is_none()
269        && bridge_cfg.super_trait.is_none()
270        && trait_type.methods.iter().all(|m| m.has_default_impl);
271
272    if is_visitor_bridge {
273        let struct_name = format!("Php{}Bridge", bridge_cfg.trait_name);
274        let trait_path = trait_type.rust_path.replace('-', "_");
275        let code = gen_visitor_bridge(trait_type, bridge_cfg, &struct_name, &trait_path, &type_paths);
276        BridgeOutput { imports: vec![], code }
277    } else {
278        // Use the IR-driven TraitBridgeGenerator infrastructure
279        let generator = PhpBridgeGenerator {
280            core_import: core_import.to_string(),
281            type_paths: type_paths.clone(),
282            error_type: error_type.to_string(),
283        };
284        let spec = TraitBridgeSpec {
285            trait_def: trait_type,
286            bridge_config: bridge_cfg,
287            core_import,
288            wrapper_prefix: "Php",
289            type_paths,
290            error_type: error_type.to_string(),
291            error_constructor: error_constructor.to_string(),
292        };
293        gen_bridge_all(&spec, &generator)
294    }
295}
296
297/// Generate a visitor-style bridge wrapping a PHP `Zval` object reference.
298///
299/// Every trait method checks if the PHP object has a matching camelCase method,
300/// then calls it and maps the PHP return value to `VisitResult`.
301fn gen_visitor_bridge(
302    trait_type: &TypeDef,
303    _bridge_cfg: &TraitBridgeConfig,
304    struct_name: &str,
305    trait_path: &str,
306    type_paths: &HashMap<String, String>,
307) -> String {
308    let mut out = String::with_capacity(4096);
309    let core_crate = trait_path
310        .split("::")
311        .next()
312        .unwrap_or("html_to_markdown_rs")
313        .to_string();
314
315    // Helper: convert NodeContext to a PHP array (Zval)
316    out.push_str(&crate::template_env::render(
317        "visitor_nodecontext_helper.jinja",
318        context! {
319            core_crate => &core_crate,
320        },
321    ));
322    out.push('\n');
323
324    // Helper: map a PHP return Zval to VisitResult.
325    out.push_str(&crate::template_env::render(
326        "visitor_zval_to_visitresult.jinja",
327        context! {
328            core_crate => &core_crate,
329        },
330    ));
331    out.push('\n');
332
333    // Helper: apply {param_name} template substitution to Custom visit results.
334    // Use push_str to avoid writeln! format-string interpretation of braces.
335    out.push_str(&format!(
336        "fn php_visit_result_with_template(val: &ext_php_rs::types::Zval, tmpl_vars: &[(&str, &str)]) -> {core_crate}::VisitResult {{\n"
337    ));
338    out.push_str("    let base = php_zval_to_visit_result(val);\n");
339    out.push_str(&format!(
340        "    if let {core_crate}::VisitResult::Custom(tmpl) = base {{\n"
341    ));
342    out.push_str("        let mut s = tmpl;\n");
343    out.push_str("        for (k, v) in tmpl_vars {\n");
344    // Generates: s = s.replace(&format!("{{{}}}", k), v);
345    // where "{{{}}}" is a format literal: {{ → {, {} → k, }} → } giving "{k}"
346    out.push_str("            s = s.replace(&format!(\"{{{}}}\", k), v);\n");
347    out.push_str("        }\n");
348    out.push_str(&format!("        {core_crate}::VisitResult::Custom(s)\n"));
349    out.push_str("    } else {\n");
350    out.push_str("        base\n");
351    out.push_str("    }\n");
352    out.push_str("}\n\n");
353
354    // Bridge struct — stores a reference to the PHP object.
355    out.push_str(&crate::template_env::render(
356        "visitor_bridge_struct.jinja",
357        context! {
358            struct_name => struct_name,
359        },
360    ));
361    out.push('\n');
362
363    // Trait impl
364    out.push_str(&format!("impl {trait_path} for {struct_name} {{\n"));
365    for method in &trait_type.methods {
366        if method.trait_source.is_some() {
367            continue;
368        }
369        gen_visitor_method_php(&mut out, method, type_paths);
370    }
371    out.push_str("}\n");
372    out.push('\n');
373
374    out
375}
376
377/// Generate a single visitor method that checks for a snake_case PHP method and calls it.
378fn gen_visitor_method_php(out: &mut String, method: &MethodDef, type_paths: &HashMap<String, String>) {
379    let name = &method.name;
380
381    let mut sig_parts = vec!["&mut self".to_string()];
382    for p in &method.params {
383        let ty_str = visitor_param_type(&p.ty, p.is_ref, p.optional, type_paths);
384        sig_parts.push(format!("{}: {}", p.name, ty_str));
385    }
386    let sig = sig_parts.join(", ");
387
388    let ret_ty = match &method.return_type {
389        TypeRef::Named(n) => type_paths.get(n).cloned().unwrap_or_else(|| n.clone()),
390        other => param_type(other, "", false, type_paths),
391    };
392
393    out.push_str(&format!("    fn {name}({sig}) -> {ret_ty} {{\n"));
394
395    // SAFETY: php_obj pointer is valid for the lifetime of the PHP call frame.
396    out.push_str("        // SAFETY: php_obj is a valid ZendObject pointer for the duration of this call.\n");
397    out.push_str("        let php_obj_ref = unsafe { &mut *self.php_obj };\n");
398
399    // Build args array
400    let has_args = !method.params.is_empty();
401    if has_args {
402        out.push_str("        let mut args: Vec<ext_php_rs::types::Zval> = Vec::new();\n");
403        for p in &method.params {
404            if let TypeRef::Named(n) = &p.ty {
405                if n == "NodeContext" {
406                    out.push_str(&format!(
407                        "        let ctx_arr = nodecontext_to_php_array({}{});\n",
408                        if p.is_ref { "" } else { "&" },
409                        p.name
410                    ));
411                    out.push_str("        args.push(ext_php_rs::convert::IntoZval::into_zval(ctx_arr, false).unwrap_or_default());\n");
412                    continue;
413                }
414            }
415            // Check optional string ref BEFORE non-optional string, since visitor_param_type
416            // returns Option<&str> for optional string ref params.
417            if p.optional && matches!(&p.ty, TypeRef::String) && p.is_ref {
418                out.push_str(&format!(
419                    "        args.push(match {0} {{ Some(s) => ext_php_rs::types::Zval::try_from(s.to_string()).unwrap_or_default(), None => ext_php_rs::types::Zval::new() }});\n",
420                    p.name
421                ));
422                continue;
423            }
424            if matches!(&p.ty, TypeRef::String) {
425                if p.is_ref {
426                    out.push_str(&format!(
427                        "        args.push(ext_php_rs::types::Zval::try_from({}.to_string()).unwrap_or_default());\n",
428                        p.name
429                    ));
430                } else {
431                    out.push_str(&format!(
432                        "        args.push(ext_php_rs::types::Zval::try_from({}.clone()).unwrap_or_default());\n",
433                        p.name
434                    ));
435                }
436                continue;
437            }
438            if matches!(&p.ty, TypeRef::Primitive(alef_core::ir::PrimitiveType::Bool)) {
439                out.push_str(&format!(
440                    "        {{ let mut _zv = ext_php_rs::types::Zval::new(); _zv.set_bool({}); args.push(_zv); }}\n",
441                    p.name
442                ));
443                continue;
444            }
445            // Default: format as string
446            out.push_str(&format!(
447                "        args.push(ext_php_rs::types::Zval::try_from(format!(\"{{:?}}\", {})).unwrap_or_default());\n",
448                p.name
449            ));
450        }
451    }
452
453    // Call the PHP method via try_call_method which takes Vec<&dyn IntoZvalDyn>.
454    // If the method does not exist, try_call_method returns Err(Error::Callable),
455    // which we treat as a "no-op, return Continue" (same as the default impl).
456    if has_args {
457        out.push_str("        let dyn_args: Vec<&dyn ext_php_rs::convert::IntoZvalDyn> = args.iter().map(|z| z as &dyn ext_php_rs::convert::IntoZvalDyn).collect();\n");
458    }
459    let args_expr = if has_args { "dyn_args" } else { "vec![]" };
460    out.push_str(&format!(
461        "        let result = php_obj_ref.try_call_method(\"{name}\", {args_expr});\n"
462    ));
463
464    // Build template vars for {param_name} → value substitution in Custom results.
465    // Each non-ctx param gets an owned String so we can take &str references.
466    let mut tmpl_var_names: Vec<String> = Vec::new();
467    for p in &method.params {
468        if let TypeRef::Named(n) = &p.ty {
469            if n == "NodeContext" {
470                continue;
471            }
472        }
473        // Skip Vec/slice params — no Display impl; not useful in templates.
474        if matches!(&p.ty, TypeRef::Vec(_)) {
475            continue;
476        }
477        // Strip leading underscore from param name for the template key (e.g. _src → src)
478        let key = p.name.strip_prefix('_').unwrap_or(&p.name);
479        let owned_var = format!("_{key}_s");
480        let expr: String = if p.optional && matches!(&p.ty, TypeRef::String) && p.is_ref {
481            format!("{}.map(|s| s.to_string()).unwrap_or_default()", p.name)
482        } else if matches!(&p.ty, TypeRef::String) && p.is_ref {
483            format!("{}.to_string()", p.name)
484        } else if matches!(&p.ty, TypeRef::String) {
485            format!("{}.clone()", p.name)
486        } else if matches!(&p.ty, TypeRef::Optional(_)) {
487            format!("{}.map(|v| v.to_string()).unwrap_or_default()", p.name)
488        } else {
489            format!("{}.to_string()", p.name)
490        };
491        writeln!(out, "        let {owned_var}: String = {expr};").unwrap();
492        tmpl_var_names.push(format!("(\"{key}\", {owned_var}.as_str())"));
493    }
494    let tmpl_vars_expr = if tmpl_var_names.is_empty() {
495        "&[]".to_string()
496    } else {
497        format!("&[{}]", tmpl_var_names.join(", "))
498    };
499
500    // Parse result — try_call_method returns Result<Zval> (not Result<Option<Zval>>)
501    out.push_str("        match result {\n");
502    out.push_str(&format!("            Err(_) => {ret_ty}::Continue,\n"));
503    out.push_str(&format!(
504        "            Ok(val) => php_visit_result_with_template(&val, {tmpl_vars_expr}),\n"
505    ));
506    out.push_str("        }\n");
507    out.push_str("    }\n");
508    out.push('\n');
509}
510
511/// Generate a PHP static method that has one parameter replaced by
512/// `Option<ext_php_rs::boxed::ZBox<ext_php_rs::types::ZendObject>>` (a trait bridge).
513#[allow(clippy::too_many_arguments)]
514pub fn gen_bridge_function(
515    func: &alef_core::ir::FunctionDef,
516    bridge_param_idx: usize,
517    bridge_cfg: &TraitBridgeConfig,
518    mapper: &dyn alef_codegen::type_mapper::TypeMapper,
519    opaque_types: &ahash::AHashSet<String>,
520    core_import: &str,
521) -> String {
522    use alef_core::ir::TypeRef;
523
524    let struct_name = format!("Php{}Bridge", bridge_cfg.trait_name);
525    let handle_path = format!("{core_import}::visitor::VisitorHandle");
526    let param_name = &func.params[bridge_param_idx].name;
527    let bridge_param = &func.params[bridge_param_idx];
528    let is_optional = bridge_param.optional || matches!(&bridge_param.ty, TypeRef::Optional(_));
529
530    // Build parameter list, hiding bridge params from signature
531    let mut sig_parts = Vec::new();
532    for (idx, p) in func.params.iter().enumerate() {
533        if idx == bridge_param_idx {
534            // Bridge param: &mut ZendObject implements FromZvalMut in ext-php-rs 0.15,
535            // allowing PHP to pass any object. ZBox<ZendObject> does NOT implement
536            // FromZvalMut, so we must use the reference form here.
537            let php_obj_ty = "&mut ext_php_rs::types::ZendObject";
538            if is_optional {
539                sig_parts.push(format!("{}: Option<{php_obj_ty}>", p.name));
540            } else {
541                sig_parts.push(format!("{}: {php_obj_ty}", p.name));
542            }
543        } else {
544            let promoted = idx > bridge_param_idx || func.params[..idx].iter().any(|pp| pp.optional);
545            let base = mapper.map_type(&p.ty);
546            // #[php_class] types (non-opaque Named) only implement FromZvalMut for &mut T,
547            // not for owned T — so we must use &mut T in the function signature.
548            let ty = match &p.ty {
549                TypeRef::Named(n) if !opaque_types.contains(n.as_str()) => {
550                    if p.optional || promoted {
551                        format!("Option<&mut {base}>")
552                    } else {
553                        format!("&mut {base}")
554                    }
555                }
556                TypeRef::Optional(inner) => {
557                    if let TypeRef::Named(n) = inner.as_ref() {
558                        if !opaque_types.contains(n.as_str()) {
559                            format!("Option<&mut {base}>")
560                        } else if p.optional || promoted {
561                            format!("Option<{base}>")
562                        } else {
563                            base
564                        }
565                    } else if p.optional || promoted {
566                        format!("Option<{base}>")
567                    } else {
568                        base
569                    }
570                }
571                _ => {
572                    if p.optional || promoted {
573                        format!("Option<{base}>")
574                    } else {
575                        base
576                    }
577                }
578            };
579            sig_parts.push(format!("{}: {}", p.name, ty));
580        }
581    }
582
583    let params_str = sig_parts.join(", ");
584    let return_type = mapper.map_type(&func.return_type);
585    let ret = mapper.wrap_return(&return_type, func.error_type.is_some());
586
587    let err_conv = ".map_err(|e| ext_php_rs::exception::PhpException::default(e.to_string()))";
588
589    // Bridge wrapping code
590    let bridge_wrap = if is_optional {
591        format!(
592            "let {param_name} = {param_name}.map(|v| {{\n        \
593             let bridge = {struct_name}::new(v);\n        \
594             std::rc::Rc::new(std::cell::RefCell::new(bridge)) as {handle_path}\n    \
595             }});"
596        )
597    } else {
598        format!(
599            "let {param_name} = {{\n        \
600             let bridge = {struct_name}::new({param_name});\n        \
601             std::rc::Rc::new(std::cell::RefCell::new(bridge)) as {handle_path}\n    \
602             }};"
603        )
604    };
605
606    // Serde let bindings for non-bridge Named params
607    let serde_bindings: String = func
608        .params
609        .iter()
610        .enumerate()
611        .filter(|(idx, p)| {
612            if *idx == bridge_param_idx {
613                return false;
614            }
615            let named = match &p.ty {
616                TypeRef::Named(n) => Some(n.as_str()),
617                TypeRef::Optional(inner) => {
618                    if let TypeRef::Named(n) = inner.as_ref() {
619                        Some(n.as_str())
620                    } else {
621                        None
622                    }
623                }
624                _ => None,
625            };
626            named.is_some_and(|n| !opaque_types.contains(n))
627        })
628        .map(|(_, p)| {
629            let name = &p.name;
630            let core_path = format!(
631                "{core_import}::{}",
632                match &p.ty {
633                    TypeRef::Named(n) => n.clone(),
634                    TypeRef::Optional(inner) =>
635                        if let TypeRef::Named(n) = inner.as_ref() {
636                            n.clone()
637                        } else {
638                            String::new()
639                        },
640                    _ => String::new(),
641                }
642            );
643            if p.optional || matches!(&p.ty, TypeRef::Optional(_)) {
644                format!(
645                    "let {name}_core: Option<{core_path}> = {name}.map(|v| {{\n        \
646                     let json = serde_json::to_string(&v){err_conv}?;\n        \
647                     serde_json::from_str(&json){err_conv}\n    \
648                     }}).transpose()?;\n    "
649                )
650            } else {
651                format!(
652                    "let {name}_json = serde_json::to_string(&{name}){err_conv}?;\n    \
653                     let {name}_core: {core_path} = serde_json::from_str(&{name}_json){err_conv}?;\n    "
654                )
655            }
656        })
657        .collect();
658
659    // Build call args
660    let call_args: Vec<String> = func
661        .params
662        .iter()
663        .enumerate()
664        .map(|(idx, p)| {
665            if idx == bridge_param_idx {
666                return p.name.clone();
667            }
668            match &p.ty {
669                TypeRef::Named(n) if opaque_types.contains(n.as_str()) => {
670                    if p.optional {
671                        format!("{}.as_ref().map(|v| &v.inner)", p.name)
672                    } else {
673                        format!("&{}.inner", p.name)
674                    }
675                }
676                TypeRef::Named(_) => format!("{}_core", p.name),
677                TypeRef::Optional(inner) => {
678                    if let TypeRef::Named(n) = inner.as_ref() {
679                        if opaque_types.contains(n.as_str()) {
680                            format!("{}.as_ref().map(|v| &v.inner)", p.name)
681                        } else {
682                            format!("{}_core", p.name)
683                        }
684                    } else {
685                        p.name.clone()
686                    }
687                }
688                TypeRef::String | TypeRef::Char => {
689                    if p.is_ref {
690                        format!("&{}", p.name)
691                    } else {
692                        p.name.clone()
693                    }
694                }
695                _ => p.name.clone(),
696            }
697        })
698        .collect();
699    let call_args_str = call_args.join(", ");
700
701    let core_fn_path = {
702        let path = func.rust_path.replace('-', "_");
703        if path.starts_with(core_import) {
704            path
705        } else {
706            format!("{core_import}::{}", func.name)
707        }
708    };
709    let core_call = format!("{core_fn_path}({call_args_str})");
710
711    let return_wrap = match &func.return_type {
712        TypeRef::Named(name) if opaque_types.contains(name.as_str()) => {
713            format!("{name} {{ inner: std::sync::Arc::new(val) }}")
714        }
715        TypeRef::Named(_) => "val.into()".to_string(),
716        TypeRef::String | TypeRef::Bytes => "val.into()".to_string(),
717        _ => "val".to_string(),
718    };
719
720    let body = if func.error_type.is_some() {
721        if return_wrap == "val" {
722            format!("{bridge_wrap}\n    {serde_bindings}{core_call}{err_conv}")
723        } else {
724            format!("{bridge_wrap}\n    {serde_bindings}{core_call}.map(|val| {return_wrap}){err_conv}")
725        }
726    } else {
727        format!("{bridge_wrap}\n    {serde_bindings}{core_call}")
728    };
729
730    let func_name = &func.name;
731    let mut out = String::with_capacity(1024);
732    if func.error_type.is_some() {
733        out.push_str("#[allow(clippy::missing_errors_doc)]\n");
734    }
735    out.push_str(&format!("pub fn {func_name}({params_str}) -> {ret} {{\n"));
736    out.push_str(&format!("    {body}\n"));
737    out.push_str("}\n");
738
739    out
740}