Skip to main content

js2rust_bridge_macro/
lib.rs

1//! Proc-macro for generating Rust FFI bindings from js2rust C ABI export metadata.
2//!
3//! ## Usage
4//!
5//! ```rust,ignore
6//! js2rust_bridge!();
7//! ```
8//!
9//! The macro reads `js2rust.toml` from the crate root, transpiles JS to Zig,
10//! writes output to `.js2zig-cache/{group}/`, and generates Rust FFI bindings.
11//! The group name is derived from the file name (sanitized for Zig identifiers).
12//! A minimal `build.rs` only needs `js2rust_bridge::build(false)`.
13
14use indexmap::IndexMap;
15use proc_macro::TokenStream;
16use quote::{format_ident, quote};
17use serde::Deserialize;
18
19mod host_fn;
20
21/// `#[host_fn]` attribute macro — eliminates unsafe C ABI plumbing from host functions.
22///
23/// Write a normal Rust function using SDK types (`HostStr`, `JsStr`, `JsStrField`).
24/// The macro generates the `unsafe extern "C"` wrapper with correct C ABI signature.
25///
26/// ## Example
27///
28/// ```rust,ignore
29/// use js2rust_bridge::sdk::{HostStr, JsStr};
30///
31/// #[host_fn]
32/// fn host_concat(s1: HostStr, s2: HostStr) -> JsStr {
33///     JsStr::new(&format!("{}{}", &s1, &s2))
34/// }
35/// ```
36#[proc_macro_attribute]
37pub fn host_fn(attr: TokenStream, item: TokenStream) -> TokenStream {
38    host_fn::host_fn_impl(attr.into(), item.into()).into()
39}
40
41// ── js2rust.toml deserialization (minimal, shared format contract) ──
42
43#[derive(Debug, Deserialize)]
44struct TomlConfig {
45    project: TomlProject,
46    #[serde(default)]
47    host_functions: Vec<TomlHostFn>,
48}
49
50#[derive(Debug, Deserialize)]
51struct TomlProject {
52    js_file: String,
53    #[serde(default)]
54    additional_js_files: Vec<String>,
55}
56
57#[derive(Debug, Deserialize)]
58struct TomlHostFn {
59    name: String,
60    params: Vec<String>,
61    #[serde(default)]
62    returns: Option<String>,
63    #[serde(default)]
64    is_async: bool,
65    #[serde(default)]
66    async_returns: IndexMap<String, String>,
67}
68
69/// Load js2rust.toml from CARGO_MANIFEST_DIR.
70fn load_toml_config() -> TomlConfig {
71    let manifest_dir = std::env::var("CARGO_MANIFEST_DIR").unwrap_or_else(|_| ".".to_string());
72    let config_path = std::path::Path::new(&manifest_dir).join("js2rust.toml");
73
74    let content = std::fs::read_to_string(&config_path).unwrap_or_else(|e| {
75        panic!(
76            "js2rust_bridge: failed to read {}: {}\n\
77             Create a js2rust.toml in your crate root with:\n\
78             \n\
79             [project]\n\
80             js_file = \"js_src/main.js\"\n",
81            config_path.display(),
82            e
83        );
84    });
85
86    toml::from_str(&content).unwrap_or_else(|e| {
87        panic!(
88            "js2rust_bridge: failed to parse {}: {}",
89            config_path.display(),
90            e
91        );
92    })
93}
94
95// ── C ABI export metadata (mirrors the JSON schema) ───────────────
96
97#[derive(Debug, Deserialize)]
98struct CabiExport {
99    name: String,
100    params: Vec<CabiParam>,
101    ret_type: String,
102    #[serde(default)]
103    can_throw: bool,
104    /// Struct return: name of the returned struct (e.g. "FetchUserResult")
105    #[serde(default)]
106    ret_struct_name: Option<String>,
107    /// Struct return: fields of the returned struct (for generating #[repr(C)] struct)
108    #[serde(default)]
109    ret_struct_fields: Option<Vec<CabiStructField>>,
110}
111
112#[derive(Debug, Deserialize)]
113struct CabiStructField {
114    name: String,
115    /// C ABI type string (for FFI)
116    cabi_type: String,
117}
118
119#[derive(Debug, Deserialize)]
120struct CabiParam {
121    #[allow(dead_code)]
122    name: String,
123    zig_type: String,
124}
125
126// ── Main proc-macro entry point ───────────────────────────────────
127
128/// Function-like proc-macro: `js2rust_bridge!()`.
129///
130/// Reads `js2rust.toml` from the crate root, transpiles JS to Zig,
131/// and generates Rust FFI bindings.  Zero-argument — all configuration
132/// lives in the TOML file.
133#[proc_macro]
134pub fn js2rust_bridge(input: TokenStream) -> TokenStream {
135    // Accept empty input only
136    let _input: proc_macro2::TokenStream = input.into();
137
138    match generate() {
139        Ok(ts) => ts,
140        Err(e) => e.into(),
141    }
142}
143
144// ── Transpile + generate FFI ──────────────────────────────────────
145
146fn generate() -> Result<TokenStream, proc_macro2::TokenStream> {
147    let config = load_toml_config();
148    let manifest_dir = std::env::var("CARGO_MANIFEST_DIR").unwrap_or_else(|_| ".".to_string());
149
150    // Derive group name from js_file stem
151    let stem = std::path::Path::new(&config.project.js_file)
152        .file_stem()
153        .and_then(|s| s.to_str())
154        .unwrap_or("main");
155    let group = js2zig_core::analyzer::sanitize_module_name(stem);
156
157    // Resolve core JS file path
158    let js_file_path = std::path::Path::new(&manifest_dir).join(&config.project.js_file);
159
160    // Resolve additional JS file paths
161    let additional_js_paths: Vec<std::path::PathBuf> = config
162        .project
163        .additional_js_files
164        .iter()
165        .map(|f| std::path::Path::new(&manifest_dir).join(f))
166        .collect();
167
168    // Resolve cache directory
169    let cache_dir = std::path::Path::new(&manifest_dir).join(".js2zig-cache");
170
171    // Convert host function declarations to js2zig_core::HostFunction
172    let mut host_functions = Vec::new();
173    for hf in &config.host_functions {
174        let params: Vec<_> = hf
175            .params
176            .iter()
177            .map(|t| type_name_to_host_type(t))
178            .collect();
179
180        let return_type = hf.returns.as_deref().and_then(|t| {
181            if t == "void" {
182                None
183            } else {
184                Some(type_name_to_host_type(t))
185            }
186        });
187
188        let async_return_fields: Vec<(String, js2zig_core::HostType)> = hf
189            .async_returns
190            .iter()
191            .map(|(name, ty)| (name.clone(), type_name_to_host_type(ty)))
192            .collect();
193
194        host_functions.push(js2zig_core::HostFunction {
195            name: hf.name.clone(),
196            params,
197            return_type,
198            is_async: hf.is_async,
199            async_return_fields,
200        });
201    }
202
203    // Build ProjectConfig
204    let project_config = js2zig_core::ProjectConfig {
205        name: group.clone(),
206        js_file: js_file_path.clone(),
207        additional_js_files: additional_js_paths,
208        out_dir: cache_dir.clone(),
209        host_config: if host_functions.is_empty() {
210            None
211        } else {
212            Some(js2zig_core::HostConfig {
213                functions: host_functions,
214            })
215        },
216        force_rebuild: true,
217        run_zig_build: false,
218    };
219
220    // Transpile!
221    let project_result = js2zig_core::transpile_project(&project_config).map_err(|e| {
222        syn::Error::new(
223            proc_macro2::Span::call_site(),
224            format!(
225                "js2rust_bridge: transpilation failed for '{}': {}",
226                js_file_path.display(),
227                e
228            ),
229        )
230        .to_compile_error()
231    })?;
232
233    // Find the group result
234    let group_result = project_result.groups.first().ok_or_else(|| {
235        let mut msg = format!(
236            "js2rust_bridge: no groups found in transpilation result for '{}'.",
237            js_file_path.display()
238        );
239        if !project_result.diagnostics.is_empty() {
240            msg.push_str("\n\nTranspilation diagnostics:");
241            for diag in &project_result.diagnostics {
242                msg.push_str(&format!("\n  - {}", diag));
243            }
244        }
245        syn::Error::new(proc_macro2::Span::call_site(), msg).to_compile_error()
246    })?;
247
248    // Parse cabi_exports_json
249    let exports: Vec<CabiExport> =
250        serde_json::from_str(&group_result.cabi_exports_json).map_err(|e| {
251            syn::Error::new(
252                proc_macro2::Span::call_site(),
253                format!(
254                    "js2rust_bridge: failed to parse cabi_exports for group '{}': {}",
255                    group_result.name, e
256                ),
257            )
258            .to_compile_error()
259        })?;
260
261    // Optionally run zig build (side effect)
262    let zig_project_dir = cache_dir.join(&group);
263    let lib_path = zig_project_dir.join("zig-out").join("lib").join(format!(
264        "{}.lib",
265        if cfg!(target_os = "windows") {
266            &group
267        } else {
268            "lib"
269        }
270    ));
271    let lib_exists = lib_path.exists()
272        || zig_project_dir
273            .join("zig-out")
274            .join("lib")
275            .join(format!("lib{}.a", &group))
276            .exists();
277    if zig_project_dir.join("build.zig").exists() && !lib_exists {
278        let _ = std::process::Command::new("zig")
279            .arg("build")
280            .current_dir(&zig_project_dir)
281            .status();
282    }
283
284    // Generate Rust FFI bindings
285    let mut generated = generate_bindings(&exports, &group);
286
287    // Generate host function stub documentation
288    if !config.host_functions.is_empty() {
289        if let Some(host_stubs) = generate_host_stubs(&config.host_functions, &group) {
290            generated.push('\n');
291            generated.push_str(&host_stubs);
292        }
293    }
294
295    generated.parse::<TokenStream>().map_err(|e| {
296        syn::Error::new(
297            proc_macro2::Span::call_site(),
298            format!(
299                "js2rust_bridge: internal error generating bindings for '{}': {}",
300                js_file_path.display(),
301                e
302            ),
303        )
304        .to_compile_error()
305    })
306}
307
308// ── Type name conversion (shared) ─────────────────────────────────
309
310fn type_name_to_host_type(name: &str) -> js2zig_core::HostType {
311    match name {
312        "i64" => js2zig_core::HostType::I64,
313        "i32" => js2zig_core::HostType::I32,
314        "f64" => js2zig_core::HostType::F64,
315        "bool" => js2zig_core::HostType::Bool,
316        "str" => js2zig_core::HostType::Str,
317        "void" => js2zig_core::HostType::Void,
318        other => panic!(
319            "js2rust.toml: unknown host type '{}'. \
320            Valid types: i64, i32, f64, bool, str, void",
321            other
322        ),
323    }
324}
325
326// ── FFI bindings generation ───────────────────────────────────────
327
328fn generate_bindings(exports: &[CabiExport], group_suffix: &str) -> String {
329    let mut extern_fns = Vec::new();
330    let mut safe_wrappers = Vec::new();
331    let mut struct_defs = Vec::new();
332    let mut needs_jsstr = false;
333
334    let raw_mod = format_ident!("__js2rust_ffi_raw_{group_suffix}");
335    let safe_mod = format_ident!("__js2rust_ffi_safe_{group_suffix}");
336
337    // Collect struct definitions from ret_struct_name/ret_struct_fields
338    for exp in exports {
339        if let (Some(struct_name), Some(fields)) = (&exp.ret_struct_name, &exp.ret_struct_fields) {
340            if fields.is_empty() {
341                continue;
342            }
343            let struct_ident = format_ident!("{}", struct_name);
344            let mut field_defs = Vec::new();
345            for f in fields {
346                let field_name = format_ident!("{}", f.name);
347                let field_ty = cabi_type_to_rust_ffi(&f.cabi_type);
348                field_defs.push(quote! { pub #field_name: #field_ty });
349            }
350            struct_defs.push(quote! {
351                #[repr(C)]
352                #[derive(Debug, Copy, Clone)]
353                pub struct #struct_ident {
354                    #(#field_defs),*
355                }
356            });
357        }
358    }
359
360    for exp in exports {
361        let fn_name = format_ident!("{}", exp.name);
362
363        let mut extern_params = Vec::new();
364        for param in &exp.params {
365            let param_ident = format_ident!("{}", param.name);
366            let param_ty = zig_type_to_rust_ffi_type(&param.zig_type);
367            extern_params.push(quote! { #param_ident: #param_ty });
368        }
369
370        // Struct return: use out-pointer parameter
371        if let Some(ret_struct_name) = &exp.ret_struct_name {
372            let struct_name = format_ident!("{}", ret_struct_name);
373            extern_params.push(quote! { out: *mut #struct_name });
374            extern_fns.push(quote! {
375                pub fn #fn_name( #(#extern_params),* );
376            });
377        } else {
378            // Non-struct return: normal C ABI
379            let has_err_out = exp.can_throw && exp.ret_type != "StrRet";
380            if has_err_out {
381                extern_params.push(quote! { err_out: *mut *const std::ffi::c_char });
382            }
383            let ret_ty = zig_ret_type_to_rust_ffi(&exp.ret_type);
384            extern_fns.push(quote! {
385                pub fn #fn_name( #(#extern_params),* ) -> #ret_ty;
386            });
387            if exp.ret_type == "StrRet" {
388                needs_jsstr = true;
389            }
390        }
391
392        let safe_wrapper = generate_safe_wrapper(exp, &fn_name, &raw_mod, group_suffix);
393        safe_wrappers.push(safe_wrapper);
394    }
395
396    // Always provide js2rust_init/deinit safe wrappers
397    let runtime_init = quote! {
398        use std::sync::Once;
399
400        static INIT: Once = Once::new();
401
402        /// Initialize the Zig runtime (allocator + Io for async functions).
403        /// Call this before any async export function.
404        /// Safe to call multiple times (uses Once internally).
405        /// Panics if the Zig-side allocator initialization fails (OOM).
406        pub fn js2rust_init() {
407            extern "C" {
408                #[link_name = "js2rust_init"]
409                fn _js2rust_init();
410            }
411            INIT.call_once(|| {
412                unsafe { _js2rust_init() };
413            });
414        }
415
416        /// Ensure the Zig runtime is initialized (calls js2rust_init() exactly once).
417        /// Called automatically by all generated wrapper functions.
418        fn ensure_initialized() {
419            js2rust_init();
420        }
421
422        /// Release Zig runtime resources.
423        pub fn js2rust_deinit() {
424            extern "C" {
425                #[link_name = "js2rust_deinit"]
426                fn _js2rust_deinit();
427            }
428            unsafe { _js2rust_deinit() };
429        }
430    };
431    safe_wrappers.push(runtime_init);
432
433    // Conditionally define __JsStr in raw_mod for StrRet-returning functions.
434    let jsstr_def = if needs_jsstr {
435        quote! {
436            #[repr(C)]
437            #[derive(Debug, Copy, Clone)]
438            pub struct __JsStr { pub ptr: *const u8, pub len: isize }
439        }
440    } else {
441        quote! {}
442    };
443
444    let output = quote! {
445        #[allow(non_snake_case)]
446        #[allow(dead_code)]
447        #[allow(clippy::not_unsafe_ptr_arg_deref)]
448        mod #raw_mod {
449            #jsstr_def
450            #(#struct_defs)*
451            unsafe extern "C" {
452                #(#extern_fns)*
453            }
454        }
455
456        #[allow(non_snake_case)]
457        #[allow(dead_code)]
458        #[allow(clippy::not_unsafe_ptr_arg_deref)]
459        mod #safe_mod {
460            use super::#raw_mod;
461
462            #(#safe_wrappers)*
463        }
464
465        pub use #safe_mod::*;
466    };
467
468    output.to_string()
469}
470
471/// Generate host function stubs using SDK types (HostStr, JsStr, JsStrField).
472///
473/// Generated stubs call `HostStr::from_raw(ptr, len)` at the top and
474/// `JsStr::new(&result)` for string returns — no raw pointer manipulation
475/// needed in the user's business logic.
476///
477/// Async functions that return a struct get the struct definition with
478/// `JsStrField` fields, already `#[repr(C)]`-compatible.
479fn generate_host_stubs(host_fns: &[TomlHostFn], group_suffix: &str) -> Option<String> {
480    if host_fns.is_empty() {
481        return None;
482    }
483
484    let stub_mod = format_ident!("__js2rust_host_stubs_{group_suffix}");
485
486    let mut async_struct_defs = Vec::new();
487    let mut extern_fns = Vec::new();
488
489    for hf in host_fns {
490        let fn_sym = format_ident!("{}", hf.name);
491
492        // Build C ABI param types: string → ptr+len, others → native
493        let mut cabi_params = Vec::new();
494        let mut param_conversions = Vec::new();
495
496        for (i, param_ty) in hf.params.iter().enumerate() {
497            if param_ty == "str" {
498                let ptr_name = format_ident!("arg{}_ptr", i);
499                let len_name = format_ident!("arg{}_len", i);
500                let var_name = format_ident!("arg{}", i);
501                cabi_params.push(quote! { #ptr_name: *const u8, #len_name: usize });
502                param_conversions.push(quote! {
503                    let #var_name = js2rust_bridge::sdk::HostStr::from_raw(#ptr_name, #len_name);
504                });
505            } else {
506                let name = format_ident!("arg{}", i);
507                let rust_ty = host_type_to_rust_cabi_ffi(param_ty);
508                cabi_params.push(quote! { #name: #rust_ty });
509                // No conversion needed for primitives
510            }
511        }
512
513        // Return type
514        let ret_ty = if !hf.async_returns.is_empty() {
515            let struct_name = format_ident!("Host{}Result", pascal_case(&hf.name));
516            async_struct_defs.push(generate_async_struct(&struct_name, &hf.async_returns));
517            quote! { #struct_name }
518        } else if hf.returns.as_deref() == Some("str") {
519            quote! { js2rust_bridge::sdk::JsStr }
520        } else if hf.returns.as_deref() == Some("void") || hf.returns.is_none() {
521            quote! { () }
522        } else {
523            host_type_to_rust_cabi_ffi(hf.returns.as_deref().unwrap())
524        };
525
526        // Doc comment
527        let doc = build_host_stub_doc(hf);
528
529        // Build the body — param conversions + unimplemented placeholder
530        let body = if hf.returns.as_deref() == Some("str") {
531            // String return: show example of JsStr::new()
532            let arg_refs: Vec<_> = (0..hf.params.len())
533                .map(|i| {
534                    let name = format_ident!("arg{}", i);
535                    if hf.params[i] == "str" {
536                        quote! { &#name }
537                    } else {
538                        quote! { #name }
539                    }
540                })
541                .collect();
542            let todo_msg = format!(
543                "TODO: implement {} — replace with your logic, return sdk::JsStr::new(&result)",
544                hf.name
545            );
546            quote! {
547                #(#param_conversions)*
548                let _ = (#(#arg_refs),*); // suppress unused variable warnings
549                unimplemented!(#todo_msg);
550            }
551        } else if !hf.async_returns.is_empty() {
552            // Async struct return: show example of struct construction with JsStrField::new()
553            let todo_msg = format!(
554                "TODO: implement {} — replace with your async logic, use JsStrField::new(&name)",
555                hf.name
556            );
557            quote! {
558                #(#param_conversions)*
559                unimplemented!(#todo_msg);
560            }
561        } else {
562            // Plain return (i64, f64, etc.)
563            quote! {
564                #(#param_conversions)*
565                unimplemented!("TODO: implement {}", stringify!(#fn_sym));
566            }
567        };
568
569        extern_fns.push(quote! {
570            #[doc = #doc]
571            #[allow(dead_code)]
572            pub unsafe extern "C" fn #fn_sym( #(#cabi_params),* ) -> #ret_ty {
573                #body
574            }
575        });
576    }
577
578    let output = quote! {
579        /// Host function stubs generated by js2rust_bridge — uses `js2rust_bridge::sdk` types.
580        ///
581        /// Copy the function signatures below into your `host.rs` with `#[unsafe(no_mangle)]`
582        /// and replace the `unimplemented!()` bodies with your actual business logic.
583        ///
584        /// The SDK handles all C ABI conversion automatically:
585        /// - `HostStr::from_raw(ptr, len)` converts string params to `&str`
586        /// - `JsStr::new(&s)` allocates return strings in Zig Arena
587        /// - `JsStrField::new(&s)` for async struct string fields
588        #[allow(dead_code, non_snake_case, clippy::not_unsafe_ptr_arg_deref)]
589        mod #stub_mod {
590            // SDK types are accessed via crate path, no import needed
591
592            #(#async_struct_defs)*
593
594            #(#extern_fns)*
595        }
596    };
597
598    Some(output.to_string())
599}
600
601/// Generate an async return struct definition with SDK types.
602fn generate_async_struct(
603    struct_name: &syn::Ident,
604    fields: &IndexMap<String, String>,
605) -> proc_macro2::TokenStream {
606    let mut struct_fields = Vec::new();
607    for (name, ty) in fields {
608        let field_name = format_ident!("{}", name);
609        let field_type = if ty == "str" {
610            quote! { js2rust_bridge::sdk::JsStrField }
611        } else {
612            host_type_to_rust_cabi_ffi(ty)
613        };
614        struct_fields.push(quote! {
615            pub #field_name: #field_type,
616        });
617    }
618
619    let struct_doc = format!(
620        "C ABI return struct for `{}` (generated by js2rust_bridge).\n\
621         Uses `JsStrField` for string fields — allocated in Zig Arena.",
622        struct_name
623    );
624
625    quote! {
626        #[doc = #struct_doc]
627        #[repr(C)]
628        pub struct #struct_name {
629            #(#struct_fields)*
630        }
631    }
632}
633
634/// Build a doc string for the host function stub.
635fn build_host_stub_doc(hf: &TomlHostFn) -> String {
636    let js_params = hf.params.join(", ");
637    let js_ret = if !hf.async_returns.is_empty() {
638        format!(
639            "{{ {} }}",
640            hf.async_returns
641                .iter()
642                .map(|(k, v)| format!("{}: {}", k, v))
643                .collect::<Vec<_>>()
644                .join(", ")
645        )
646    } else {
647        hf.returns.as_deref().unwrap_or("void").to_string()
648    };
649
650    let cabi_sig = hf
651        .params
652        .iter()
653        .enumerate()
654        .map(|(i, t)| {
655            if t == "str" {
656                format!("arg{}_ptr: *const u8, arg{}_len: usize", i, i)
657            } else {
658                format!("arg{}: {}", i, t)
659            }
660        })
661        .collect::<Vec<_>>()
662        .join(", ");
663
664    let ret_sig = if hf.returns.as_deref() == Some("str") {
665        "JsStr".to_string()
666    } else if !hf.async_returns.is_empty() {
667        format!("Host{}Result", pascal_case(&hf.name))
668    } else if hf.returns.as_deref() == Some("void") || hf.returns.is_none() {
669        "void".to_string()
670    } else {
671        hf.returns.as_deref().unwrap().to_string()
672    };
673
674    let sdk_note = if hf.params.contains(&"str".to_string())
675        || hf.returns.as_deref() == Some("str")
676        || !hf.async_returns.is_empty()
677    {
678        "\nSDK types used: HostStr::from_raw(ptr,len) for params, JsStr::new(&result) / JsStrField::new(&field) for returns"
679    } else {
680        ""
681    };
682
683    format!(
684        "Host fn: {name}({js_params}) -> {js_ret}\
685         \nC ABI: fn({cabi_sig}) -> {ret_sig}\
686         {sdk_note}",
687        name = hf.name,
688        js_params = js_params,
689        js_ret = js_ret,
690        cabi_sig = cabi_sig,
691        ret_sig = ret_sig,
692        sdk_note = sdk_note,
693    )
694}
695
696/// Convert snake_case to PascalCase.
697fn pascal_case(name: &str) -> String {
698    let mut result = String::with_capacity(name.len());
699    let mut capitalize = true;
700    for ch in name.chars() {
701        if ch == '_' {
702            capitalize = true;
703        } else if capitalize {
704            result.push(ch.to_ascii_uppercase());
705            capitalize = false;
706        } else {
707            result.push(ch);
708        }
709    }
710    result
711}
712
713/// Convert type name to Rust C ABI FFI type.
714fn host_type_to_rust_cabi_ffi(type_name: &str) -> proc_macro2::TokenStream {
715    match type_name {
716        "i64" => quote! { i64 },
717        "i32" => quote! { i32 },
718        "f64" => quote! { f64 },
719        "bool" => quote! { bool },
720        "void" => quote! { () },
721        _ => quote! { *mut std::ffi::c_void },
722    }
723}
724
725fn generate_safe_wrapper(
726    exp: &CabiExport,
727    fn_name: &syn::Ident,
728    raw_mod: &syn::Ident,
729    group_suffix: &str,
730) -> proc_macro2::TokenStream {
731    let wrapper_name = format_ident!("{}_{}", exp.name, group_suffix);
732    let mut safe_params = Vec::new();
733    let mut ffi_args = Vec::new();
734
735    for param in &exp.params {
736        let param_ident = format_ident!("{}", param.name);
737        let safe_ty = zig_type_to_rust_safe_type(&param.zig_type);
738        safe_params.push(quote! { #param_ident: #safe_ty });
739        ffi_args.push(convert_safe_to_ffi(&param.zig_type, &param_ident));
740    }
741
742    // Struct return: use out-pointer
743    if let Some(ref struct_name) = exp.ret_struct_name {
744        let struct_ident = format_ident!("{}", struct_name);
745        let ret_ty = quote! { #raw_mod::#struct_ident };
746        let call_expr = quote! {
747            {
748                let mut result: #raw_mod::#struct_ident = unsafe { std::mem::zeroed() };
749                unsafe { super::#raw_mod::#fn_name(#(#ffi_args),* , &mut result) };
750                result
751            }
752        };
753        return quote! {
754            #[allow(non_snake_case)]
755            pub fn #wrapper_name( #(#safe_params),* ) -> #ret_ty {
756                ensure_initialized();
757                #call_expr
758            }
759        };
760    }
761
762    // Non-struct returns
763    let needs_jsstr = exp.ret_type == "StrRet";
764    let has_err_out = exp.can_throw && exp.ret_type != "StrRet" && exp.ret_struct_name.is_none();
765
766    let (ret_ty, call_expr) = if needs_jsstr {
767        (
768            quote! { Result<String, String> },
769            quote! {
770                {
771                    let ret: #raw_mod::__JsStr = unsafe { super::#raw_mod::#fn_name(#(#ffi_args),*) };
772                    if ret.len < 0 {
773                        let err_len = (-ret.len) as usize;
774                        let err_msg = if err_len > 0 && !ret.ptr.is_null() {
775                            let slice = unsafe { std::slice::from_raw_parts(ret.ptr, err_len) };
776                            String::from_utf8_lossy(slice).into_owned()
777                        } else {
778                            "unknown async error".to_string()
779                        };
780                        return Err(err_msg);
781                    }
782                    if ret.ptr.is_null() {
783                        Ok(String::new())
784                    } else {
785                        let len = ret.len as usize;
786                        let slice = unsafe { std::slice::from_raw_parts(ret.ptr, len) };
787                        Ok(String::from_utf8_lossy(slice).into_owned())
788                    }
789                }
790            },
791        )
792    } else if has_err_out {
793        let rust_ret = zig_ret_type_to_rust_safe(&exp.ret_type);
794        let rust_ret_wrapped = match exp.ret_type.as_str() {
795            "void" => quote! { Result<(), String> },
796            _ => quote! { Result<#rust_ret, String> },
797        };
798        let extract_result = match exp.ret_type.as_str() {
799            "void" => quote! { Ok(()) },
800            _ => quote! { Ok(result) },
801        };
802        let mut all_ffi_args: Vec<proc_macro2::TokenStream> = ffi_args.clone();
803        all_ffi_args.push(quote! { &mut err_ptr });
804        (
805            rust_ret_wrapped,
806            quote! {
807                {
808                    let mut err_ptr: *const std::ffi::c_char = std::ptr::null();
809                    let result = unsafe { super::#raw_mod::#fn_name(#(#all_ffi_args),*) };
810                    if !err_ptr.is_null() {
811                        let err_msg = unsafe { std::ffi::CStr::from_ptr(err_ptr).to_string_lossy().into_owned() };
812                        return Err(err_msg);
813                    }
814                    #extract_result
815                }
816            },
817        )
818    } else {
819        let rust_ret = zig_ret_type_to_rust_safe(&exp.ret_type);
820        (
821            rust_ret.clone(),
822            quote! {
823                unsafe { super::#raw_mod::#fn_name(#(#ffi_args),*) }
824            },
825        )
826    };
827
828    quote! {
829        #[allow(non_snake_case)]
830        pub fn #wrapper_name( #(#safe_params),* ) -> #ret_ty {
831            ensure_initialized();
832            #call_expr
833        }
834    }
835}
836
837// ── Type conversion helpers ───────────────────────────────────────
838
839fn zig_type_to_rust_ffi_type(zig_type: &str) -> proc_macro2::TokenStream {
840    match zig_type {
841        "[]const u8" => quote! { *const std::ffi::c_char },
842        "i32" => quote! { i32 },
843        "i64" => quote! { i64 },
844        "f64" => quote! { f64 },
845        "bool" => quote! { bool },
846        "void" => quote! { () },
847        "*usize" => quote! { *mut usize },
848        _ => quote! { *mut std::ffi::c_void },
849    }
850}
851
852fn zig_ret_type_to_rust_ffi(ret_type: &str) -> proc_macro2::TokenStream {
853    match ret_type {
854        "[]const u8" => quote! { *const std::ffi::c_char },
855        "StrRet" => quote! { __JsStr },
856        "i32" => quote! { i32 },
857        "i64" => quote! { i64 },
858        "f64" => quote! { f64 },
859        "bool" => quote! { bool },
860        "void" => quote! { () },
861        _ => quote! { *mut std::ffi::c_void },
862    }
863}
864
865fn zig_type_to_rust_safe_type(zig_type: &str) -> proc_macro2::TokenStream {
866    match zig_type {
867        "[]const u8" => quote! { &str },
868        "i32" => quote! { i32 },
869        "i64" => quote! { i64 },
870        "f64" => quote! { f64 },
871        "bool" => quote! { bool },
872        _ => quote! { *mut std::ffi::c_void },
873    }
874}
875
876fn convert_safe_to_ffi(zig_type: &str, ident: &syn::Ident) -> proc_macro2::TokenStream {
877    match zig_type {
878        "[]const u8" => quote! { std::ffi::CString::new(#ident).unwrap().into_raw() },
879        _ => quote! { #ident },
880    }
881}
882
883fn zig_ret_type_to_rust_safe(ret_type: &str) -> proc_macro2::TokenStream {
884    match ret_type {
885        "[]const u8" => quote! { String },
886        "i32" => quote! { i32 },
887        "i64" => quote! { i64 },
888        "f64" => quote! { f64 },
889        "bool" => quote! { bool },
890        "void" => quote! { () },
891        _ => quote! { *mut std::ffi::c_void },
892    }
893}
894
895/// Convert C ABI type string to Rust FFI type (for struct fields).
896fn cabi_type_to_rust_ffi(cabi_type: &str) -> proc_macro2::TokenStream {
897    match cabi_type {
898        "i64" => quote! { i64 },
899        "f64" => quote! { f64 },
900        "bool" => quote! { bool },
901        "str" => quote! { js2rust_bridge::sdk::JsStrField },
902        "StrRet" => quote! { __JsStr },
903        "struct" => quote! { *mut std::ffi::c_void }, // Should not happen for struct fields
904        // Handle [N]u8 as string type (JsStrField)
905        other if other.starts_with('[') && other.ends_with("]u8") => {
906            quote! { js2rust_bridge::sdk::JsStrField }
907        }
908        _ => {
909            // Debug: print unknown cabi_type
910            eprintln!("Unknown cabi_type: '{}'", cabi_type);
911            quote! { *mut std::ffi::c_void }
912        }
913    }
914}