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//!     "js_src/main.js",    // core JS file path (relative to CARGO_MANIFEST_DIR)
8//!     // Sync host functions (optional, comma-separated):
9//!     host_add(i64, i64) -> i64,
10//!     host_concat(str, str) -> str,
11//!     // Async host functions (called with `await` from JS):
12//!     async fetch_user(str) -> { id: i64, name: str },
13//! }
14//! ```
15//!
16//! The macro transpiles JS to Zig inline, writes output to
17//! `.js2zig-cache/{group}/`, and generates Rust FFI bindings.
18//! The group name is derived from the file name (sanitized for Zig identifiers).
19//! A minimal `build.rs` is only needed to link the compiled static library.
20
21use proc_macro::TokenStream;
22use quote::{format_ident, quote};
23use serde::Deserialize;
24use syn::{
25    braced, parenthesized,
26    parse::{Parse, ParseStream},
27    Ident, LitStr, Token,
28};
29
30// ── C ABI export metadata (mirrors the JSON schema) ───────────────
31
32#[derive(Debug, Deserialize)]
33struct CabiExport {
34    name: String,
35    params: Vec<CabiParam>,
36    ret_type: String,
37    #[serde(default)]
38    can_throw: bool,
39}
40
41#[derive(Debug, Deserialize)]
42struct CabiParam {
43    #[allow(dead_code)]
44    name: String,
45    zig_type: String,
46}
47
48// ── Macro input parsing ───────────────────────────────────────────
49
50/// Parsed host function declaration: `[async] name(type1, type2) -> ret_type`
51struct HostFnDecl {
52    name: String,
53    params: Vec<String>,
54    return_type: String,
55    is_async: bool,
56    /// For async functions with struct return: Vec<(field_name, field_type)>
57    async_return_fields: Vec<(String, String)>,
58}
59
60/// Full macro input.
61struct MacroInput {
62    /// Core JS file path (e.g. "js_src/main.js").
63    js_file: String,
64    /// Additional JS file paths (multi-root mode).
65    additional_js_files: Vec<String>,
66    /// Group name derived from the file stem (sanitized).
67    group: String,
68    host_fns: Vec<HostFnDecl>,
69}
70
71impl Parse for MacroInput {
72    fn parse(input: ParseStream) -> syn::Result<Self> {
73        // Core JS file path (string literal)
74        let js_file_lit: LitStr = input.parse()?;
75        let js_file = js_file_lit.value();
76
77        // Derive group name from file stem, sanitized for Zig identifiers.
78        let stem = std::path::Path::new(&js_file)
79            .file_stem()
80            .and_then(|s| s.to_str())
81            .unwrap_or("main");
82        let group = js2zig_core::analyzer::sanitize_module_name(stem);
83
84        // After the primary JS file: additional JS files or host functions
85        // (all comma-separated).  Additional JS files are LitStr; host functions
86        // start with an optional `async` keyword followed by an Ident.
87        let mut additional_js_files = Vec::new();
88        let mut host_fns = Vec::new();
89        loop {
90            if !input.peek(Token![,]) {
91                break;
92            }
93            input.parse::<Token![,]>()?;
94            if input.is_empty() {
95                break;
96            }
97            // Decide: LitStr → additional JS file; async/Ident → host function
98            if input.peek(LitStr) {
99                let additional: LitStr = input.parse()?;
100                additional_js_files.push(additional.value());
101                continue;
102            }
103            // Must be a host function declaration
104
105            // Parse first — could be `async` keyword or function name
106            let is_async = input.peek(Token![async]);
107            if is_async {
108                input.parse::<Token![async]>()?;
109            }
110            let name: Ident = input.parse()?;
111            let name_str = name.to_string();
112
113            // parameter types in parentheses
114            let paren_content;
115            parenthesized!(paren_content in input);
116            let mut params = Vec::new();
117            while !paren_content.is_empty() {
118                let ty: Ident = paren_content.parse()?;
119                params.push(ty.to_string());
120                if paren_content.peek(Token![,]) {
121                    paren_content.parse::<Token![,]>()?;
122                }
123            }
124
125            // return type after `->`
126            input.parse::<Token![->]>()?;
127
128            // Check for struct return type `{ field: type, ... }` or simple Ident
129            let (return_type, async_fields) = if input.peek(syn::token::Brace) {
130                let struct_content;
131                braced!(struct_content in input);
132                let mut fields = Vec::new();
133                while !struct_content.is_empty() {
134                    let field_name: Ident = struct_content.parse()?;
135                    struct_content.parse::<Token![:]>()?;
136                    let field_type: Ident = struct_content.parse()?;
137                    fields.push((field_name.to_string(), field_type.to_string()));
138                    if struct_content.peek(Token![,]) {
139                        struct_content.parse::<Token![,]>()?;
140                    }
141                }
142                // For struct returns, return_type is "void" (actual type is in async_fields)
143                ("void".to_string(), fields)
144            } else {
145                let ret: Ident = input.parse()?;
146                (ret.to_string(), Vec::new())
147            };
148
149            host_fns.push(HostFnDecl {
150                name: name_str,
151                params,
152                return_type,
153                is_async,
154                async_return_fields: async_fields,
155            });
156        }
157
158        Ok(MacroInput {
159            js_file,
160            additional_js_files,
161            group,
162            host_fns,
163        })
164    }
165}
166
167// ── Type name conversion ──────────────────────────────────────────
168
169/// Convert macro-level type name to `js2zig_core::HostType`.
170fn type_name_to_host_type(name: &str) -> Result<js2zig_core::HostType, String> {
171    match name {
172        "i64" => Ok(js2zig_core::HostType::I64),
173        "i32" => Ok(js2zig_core::HostType::I32),
174        "f64" => Ok(js2zig_core::HostType::F64),
175        "bool" => Ok(js2zig_core::HostType::Bool),
176        "str" => Ok(js2zig_core::HostType::Str),
177        "void" => Ok(js2zig_core::HostType::Void),
178        other => Err(format!(
179            "js2rust_bridge: unknown host type '{}'. \
180            Valid types: i64, i32, f64, bool, str, void",
181            other
182        )),
183    }
184}
185
186// ── Main proc-macro entry point ───────────────────────────────────
187
188/// Function-like proc-macro: `js2rust_bridge!("js_src/main.js", host_fns...)`.
189///
190/// Transpiles JS to Zig, generates Rust FFI bindings, and optionally
191/// runs `zig build` to compile the static library.
192#[proc_macro]
193pub fn js2rust_bridge(input: TokenStream) -> TokenStream {
194    let input_tokens: proc_macro2::TokenStream = input.into();
195
196    match syn::parse2::<MacroInput>(input_tokens) {
197        Ok(parsed) => generate(&parsed),
198        Err(e) => e.to_compile_error().into(),
199    }
200}
201
202// ── Transpile + generate FFI ──────────────────────────────────────
203
204fn generate(input: &MacroInput) -> TokenStream {
205    let manifest_dir = std::env::var("CARGO_MANIFEST_DIR").unwrap_or_else(|_| ".".to_string());
206
207    // Resolve core JS file path
208    let js_file_path = std::path::Path::new(&manifest_dir).join(&input.js_file);
209
210    // Resolve cache directory for Zig output
211    let cache_dir = std::path::Path::new(&manifest_dir).join(".js2zig-cache");
212
213    // Convert host function declarations to js2zig_core::HostFunction
214    let mut host_functions = Vec::new();
215    for hf in &input.host_fns {
216        let params: Result<Vec<_>, _> = hf
217            .params
218            .iter()
219            .map(|t| type_name_to_host_type(t))
220            .collect();
221        let params = match params {
222            Ok(p) => p,
223            Err(e) => {
224                return syn::Error::new(proc_macro2::Span::call_site(), e)
225                    .to_compile_error()
226                    .into()
227            }
228        };
229
230        let return_type = match type_name_to_host_type(&hf.return_type) {
231            Ok(js2zig_core::HostType::Void) => None,
232            Ok(t) => Some(t),
233            Err(e) => {
234                return syn::Error::new(proc_macro2::Span::call_site(), e)
235                    .to_compile_error()
236                    .into()
237            }
238        };
239
240        // Convert async return fields
241        let async_return_fields: Result<Vec<_>, _> = hf
242            .async_return_fields
243            .iter()
244            .map(|(name, ty)| type_name_to_host_type(ty).map(|t| (name.clone(), t)))
245            .collect();
246        let async_return_fields = match async_return_fields {
247            Ok(v) => v,
248            Err(e) => {
249                return syn::Error::new(proc_macro2::Span::call_site(), e)
250                    .to_compile_error()
251                    .into()
252            }
253        };
254
255        host_functions.push(js2zig_core::HostFunction {
256            name: hf.name.clone(),
257            params,
258            return_type,
259            is_async: hf.is_async,
260            async_return_fields,
261        });
262    }
263
264    // Resolve additional JS file paths (multi-root mode)
265    let additional_js_paths: Vec<std::path::PathBuf> = input
266        .additional_js_files
267        .iter()
268        .map(|f| std::path::Path::new(&manifest_dir).join(f))
269        .collect();
270
271    // Build ProjectConfig
272    let config = js2zig_core::ProjectConfig {
273        name: input.group.clone(),
274        js_file: js_file_path.clone(),
275        additional_js_files: additional_js_paths,
276        out_dir: cache_dir.clone(),
277        host_config: if host_functions.is_empty() {
278            None
279        } else {
280            Some(js2zig_core::HostConfig {
281                functions: host_functions,
282            })
283        },
284        force_rebuild: false,
285        run_zig_build: false,
286    };
287
288    // Transpile!
289    let project_result = match js2zig_core::transpile_project(&config) {
290        Ok(result) => result,
291        Err(e) => {
292            return syn::Error::new(
293                proc_macro2::Span::call_site(),
294                format!(
295                    "js2rust_bridge: transpilation failed for '{}': {}",
296                    js_file_path.display(),
297                    e
298                ),
299            )
300            .to_compile_error()
301            .into();
302        }
303    };
304
305    // Find the group result (there is exactly one group from analyze_single_group)
306    let group_result = project_result.groups.first();
307
308    let group_result = match group_result {
309        Some(g) => g,
310        None => {
311            let mut msg = format!(
312                "js2rust_bridge: no groups found in transpilation result for '{}'.",
313                js_file_path.display()
314            );
315            if !project_result.diagnostics.is_empty() {
316                msg.push_str("\n\nTranspilation diagnostics:");
317                for diag in &project_result.diagnostics {
318                    msg.push_str(&format!("\n  - {}", diag));
319                }
320            }
321            return syn::Error::new(proc_macro2::Span::call_site(), msg)
322                .to_compile_error()
323                .into();
324        }
325    };
326
327    // Parse cabi_exports_json
328    let exports: Vec<CabiExport> = match serde_json::from_str(&group_result.cabi_exports_json) {
329        Ok(v) => v,
330        Err(e) => {
331            return syn::Error::new(
332                proc_macro2::Span::call_site(),
333                format!(
334                    "js2rust_bridge: failed to parse cabi_exports for group '{}': {}",
335                    group_result.name, e
336                ),
337            )
338            .to_compile_error()
339            .into();
340        }
341    };
342
343    // Optionally run zig build (side effect — generates static library for linking).
344    // Only run if the .lib doesn't already exist (build.rs may have built it first).
345    let zig_project_dir = cache_dir.join(&input.group);
346    let lib_path = zig_project_dir
347        .join("zig-out")
348        .join("lib")
349        .join(format!(
350            "{}.lib",
351            if cfg!(target_os = "windows") {
352                &input.group
353            } else {
354                "lib"
355            }
356        ));
357    let lib_exists = lib_path.exists()
358        || zig_project_dir
359            .join("zig-out")
360            .join("lib")
361            .join(format!("lib{}.a", &input.group))
362            .exists();
363    if zig_project_dir.join("build.zig").exists() && !lib_exists {
364        let _ = std::process::Command::new("zig")
365            .arg("build")
366            .current_dir(&zig_project_dir)
367            .status();
368    }
369
370    // Generate Rust FFI bindings from cabi exports
371    let mut generated = generate_bindings(&exports, &input.group);
372
373    // Generate host function stub documentation (zero-copy C ABI signatures)
374    if !input.host_fns.is_empty() {
375        if let Some(host_stubs) = generate_host_stubs(&input.host_fns, &input.group) {
376            generated.push('\n');
377            generated.push_str(&host_stubs);
378        }
379    }
380
381    match generated.parse::<TokenStream>() {
382        Ok(ts) => ts,
383        Err(e) => syn::Error::new(
384            proc_macro2::Span::call_site(),
385            format!(
386                "js2rust_bridge: internal error generating bindings for '{}': {}",
387                js_file_path.display(),
388                e
389            ),
390        )
391        .to_compile_error()
392        .into(),
393    }
394}
395
396// ── FFI bindings generation ───────────────────────────────────────
397
398fn generate_bindings(exports: &[CabiExport], group_suffix: &str) -> String {
399    let mut extern_fns = Vec::new();
400    let mut safe_wrappers = Vec::new();
401    let mut needs_jsstr = false;
402
403    let raw_mod = format_ident!("__js2rust_ffi_raw_{group_suffix}");
404    let safe_mod = format_ident!("__js2rust_ffi_safe_{group_suffix}");
405
406    for exp in exports {
407        let fn_name = format_ident!("{}", exp.name);
408        let free_fn_name = format_ident!("free_{}", exp.name);
409
410        let mut extern_params = Vec::new();
411        for param in &exp.params {
412            let param_ident = format_ident!("{}", param.name);
413            let param_ty = zig_type_to_rust_ffi_type(&param.zig_type);
414            extern_params.push(quote! { #param_ident: #param_ty });
415        }
416
417        // For non-StrRet can_throw functions: add err_out parameter
418        let has_err_out = exp.can_throw && exp.ret_type != "StrRet";
419        if has_err_out {
420            extern_params.push(quote! { err_out: *mut *const std::ffi::c_char });
421        }
422
423        let ret_ty = zig_ret_type_to_rust_ffi(&exp.ret_type);
424
425        extern_fns.push(quote! {
426            pub fn #fn_name( #(#extern_params),* ) -> #ret_ty;
427        });
428
429        if exp.ret_type == "StrRet" {
430            needs_jsstr = true;
431        }
432
433        let safe_wrapper =
434            generate_safe_wrapper(exp, &fn_name, &free_fn_name, &raw_mod, group_suffix, has_err_out);
435        safe_wrappers.push(safe_wrapper);
436    }
437
438    // Always provide js2rust_init/deinit safe wrappers (C ABI exports from lib.zig)
439    // Use Once to ensure js2rust_init() is called exactly once before any FFI call.
440    let runtime_init = quote! {
441        use std::sync::Once;
442
443        static INIT: Once = Once::new();
444
445        /// Initialize the Zig runtime (allocator + Io for async functions).
446        /// Call this before any async export function.
447        /// Safe to call multiple times (uses Once internally).
448        pub fn js2rust_init() {
449            extern "C" {
450                #[link_name = "js2rust_init"]
451                fn _js2rust_init();
452            }
453            INIT.call_once(|| {
454                unsafe { _js2rust_init() };
455            });
456        }
457
458        /// Ensure the Zig runtime is initialized (calls js2rust_init() exactly once).
459        /// Called automatically by all generated wrapper functions.
460        fn ensure_initialized() {
461            js2rust_init();
462        }
463
464        /// Release Zig runtime resources.
465        pub fn js2rust_deinit() {
466            extern "C" {
467                #[link_name = "js2rust_deinit"]
468                fn _js2rust_deinit();
469            }
470            unsafe { _js2rust_deinit() };
471        }
472
473        /// Reset the Zig arena allocator (free all allocated memory, keep allocator active).
474        /// Call this periodically to prevent excessive memory usage.
475        /// Thread-safe: uses atomic spinlock internally (in Zig code).
476        /// After reset, all previously returned pointers from Zig functions become invalid.
477        /// Make sure no Zig function is running when calling this.
478        pub fn js2rust_reset() {
479            extern "C" {
480                #[link_name = "js2rust_reset"]
481                fn _js2rust_reset();
482            }
483            unsafe { _js2rust_reset() };
484        }
485    };
486    safe_wrappers.push(runtime_init);
487
488    // Conditionally define __JsStr in raw_mod for StrRet-returning functions.
489    let jsstr_def = if needs_jsstr {
490        quote! {
491            #[repr(C)]
492            pub struct __JsStr { pub ptr: *const u8, pub len: isize }
493        }
494    } else {
495        quote! {}
496    };
497
498    let output = quote! {
499        #[allow(non_snake_case)]
500        #[allow(dead_code)]
501        #[allow(clippy::not_unsafe_ptr_arg_deref)]
502        mod #raw_mod {
503            #jsstr_def
504            unsafe extern "C" {
505                #(#extern_fns)*
506            }
507        }
508
509        #[allow(non_snake_case)]
510        #[allow(dead_code)]
511        #[allow(clippy::not_unsafe_ptr_arg_deref)]
512        mod #safe_mod {
513            use super::#raw_mod;
514
515            #(#safe_wrappers)*
516        }
517
518        pub use #safe_mod::*;
519    };
520
521    output.to_string()
522}
523
524/// Generate host function stub documentation for the Rust side.
525///
526/// For each host function declared in the macro, this generates:
527/// 1. `__JsStr` struct definition (if any str-returning host fn)
528/// 2. `js_allocator_alloc` extern declaration (for zero-copy string returns)
529/// 3. Doc comments showing the exact zero-copy C ABI signature
530///
531/// Users should copy these signatures into their `host.rs` and replace
532/// `unimplemented!()` with actual logic.
533fn generate_host_stubs(host_fns: &[HostFnDecl], group_suffix: &str) -> Option<String> {
534    if host_fns.is_empty() {
535        return None;
536    }
537
538    let stub_mod = format_ident!("__js2rust_host_stubs_{group_suffix}");
539
540    let mut has_str_ret = false;
541
542    // Build the extern function declarations
543    let mut extern_fns = Vec::new();
544
545    for hf in host_fns {
546        let fn_sym = format_ident!("{}", hf.name);
547
548        // Build C ABI param types: string → ptr+len pair
549        let mut cabi_params = Vec::new();
550        for (i, param_ty) in hf.params.iter().enumerate() {
551            if param_ty == "str" {
552                let ptr_name = format_ident!("arg{}_ptr", i);
553                let len_name = format_ident!("arg{}_len", i);
554                cabi_params.push(quote! { #ptr_name: *const u8, #len_name: usize });
555            } else {
556                let name = format_ident!("arg{}", i);
557                let rust_ty = host_type_to_rust_cabi_ffi(param_ty);
558                cabi_params.push(quote! { #name: #rust_ty });
559            }
560        }
561
562        // Return type
563        let ret_ty = if !hf.async_return_fields.is_empty() {
564            // Async struct return — user defines struct in host.rs, stub uses () 
565            quote! { () }
566        } else if hf.return_type == "str" {
567            has_str_ret = true;
568            quote! { __JsStr }
569        } else if hf.return_type == "void" {
570            quote! { () }
571        } else {
572            host_type_to_rust_cabi_ffi(&hf.return_type)
573        };
574
575        // Doc comment with JS-level signature and C ABI signature
576        let js_params = hf.params.join(", ");
577        let js_ret = if hf.return_type == "void" {
578            "void".to_string()
579        } else {
580            hf.return_type.clone()
581        };
582        let doc = format!(
583            "Host fn: {name}({js_params}) -> {js_ret}\
584             \nZero-copy C ABI: fn({cabi_sig}) -> {ret_sig}\
585             \nString params: pass .ptr and .len (in Zig Arena, no copy)\
586             \nString returns: allocate via js_allocator_alloc(), return __JsStr",
587            name = hf.name,
588            js_params = js_params,
589            js_ret = js_ret,
590            cabi_sig = hf.params.iter().enumerate().map(|(i, t)| {
591                if t == "str" { format!("arg{}_ptr: *const u8, arg{}_len: usize", i, i) }
592                else { format!("arg{}: {}", i, t) }
593            }).collect::<Vec<_>>().join(", "),
594            ret_sig = if hf.return_type == "str" { "__JsStr" }
595                else if hf.return_type == "void" { "void" }
596                else { &hf.return_type },
597        );
598
599        extern_fns.push(quote! {
600            #[doc = #doc]
601            #[allow(dead_code)]
602            pub unsafe extern "C" fn #fn_sym( #(#cabi_params),* ) -> #ret_ty {
603                unimplemented!("TODO: implement {}", stringify!(#fn_sym))
604            }
605        });
606    }
607
608    // __JsStr definition (only if needed by host fns or exports)
609    let jsstr_def = if has_str_ret {
610        quote! {
611            /// C ABI return type for zero-copy strings (memory in Zig Arena).
612            /// ptr+len pair with sign-bit convention:
613            ///   len >= 0 → normal string of that length
614            ///   len < 0  → panic/error, |len| bytes contain error name
615            #[repr(C)]
616            pub struct __JsStr {
617                pub ptr: *const u8,
618                pub len: isize,
619            }
620        }
621    } else {
622        quote! {}
623    };
624
625    // js_allocator_alloc declaration (only if any host fn returns string)
626    let alloc_decl = if has_str_ret {
627        quote! {
628            extern "C" {
629                /// Allocate memory in Zig's Arena for zero-copy string returns.
630                /// Memory is managed by Zig's dual-arena allocator — no free needed.
631                pub fn js_allocator_alloc(size: usize) -> *mut u8;
632            }
633        }
634    } else {
635        quote! {}
636    };
637
638    let output = quote! {
639        /// Host function stubs generated by js2rust_bridge.
640        /// Copy the signatures below into your `host.rs` with `#[unsafe(no_mangle)]`
641        /// and replace the `unimplemented!()` bodies with your actual logic.
642        #[allow(dead_code, non_snake_case, clippy::not_unsafe_ptr_arg_deref)]
643        mod #stub_mod {
644            #jsstr_def
645
646            #alloc_decl
647
648            #(#extern_fns)*
649        }
650    };
651
652    Some(output.to_string())
653}
654
655/// Convert macro-level host type name to Rust C ABI FFI type.
656fn host_type_to_rust_cabi_ffi(type_name: &str) -> proc_macro2::TokenStream {
657    match type_name {
658        "i64" => quote! { i64 },
659        "i32" => quote! { i32 },
660        "f64" => quote! { f64 },
661        "bool" => quote! { bool },
662        "void" => quote! { () },
663        _ => quote! { *mut std::ffi::c_void },
664    }
665}
666
667fn generate_safe_wrapper(
668    exp: &CabiExport,
669    fn_name: &syn::Ident,
670    free_fn_name: &syn::Ident,
671    raw_mod: &syn::Ident,
672    group_suffix: &str,
673    has_err_out: bool,
674) -> proc_macro2::TokenStream {
675    let wrapper_name = format_ident!("{}_{}", exp.name, group_suffix);
676    let mut safe_params = Vec::new();
677    let mut ffi_args = Vec::new();
678    // For functions that return StrRet: need JsStr struct
679    let needs_jsstr = exp.ret_type == "StrRet";
680
681    for param in &exp.params {
682        let param_ident = format_ident!("{}", param.name);
683        let safe_ty = zig_type_to_rust_safe_type(&param.zig_type);
684        safe_params.push(quote! { #param_ident: #safe_ty });
685        ffi_args.push(convert_safe_to_ffi(&param.zig_type, &param_ident));
686    }
687
688    let (ret_ty, call_expr) = if needs_jsstr {
689        // Returns StrRet (extern struct { ptr: *const u8, len: isize }).
690        // Sign-bit convention: len >= 0 → normal string; len < 0 → async panic.
691        // Rust safe wrapper converts to Result<String, String>.
692        (
693            quote! { Result<String, String> },
694            quote! {
695                {
696                    let ret: #raw_mod::__JsStr = unsafe { super::#raw_mod::#fn_name(#(#ffi_args),*) };
697                    if ret.len < 0 {
698                        let err_len = (-ret.len) as usize;
699                        let err_msg = if err_len > 0 && !ret.ptr.is_null() {
700                            let slice = unsafe { std::slice::from_raw_parts(ret.ptr, err_len) };
701                            String::from_utf8_lossy(slice).into_owned()
702                        } else {
703                            "unknown async error".to_string()
704                        };
705                        return Err(err_msg);
706                    }
707                    if ret.ptr.is_null() {
708                        Ok(String::new())
709                    } else {
710                        let len = ret.len as usize;
711                        let slice = unsafe { std::slice::from_raw_parts(ret.ptr, len) };
712                        Ok(String::from_utf8_lossy(slice).into_owned())
713                    }
714                }
715            },
716        )
717    } else if exp.ret_type == "[]const u8" {
718        if has_err_out {
719            // Non-StrRet string return with throw: Result<String, String> via err_out
720            let mut all_ffi_args: Vec<proc_macro2::TokenStream> = ffi_args.clone();
721            all_ffi_args.push(quote! { &mut err_ptr });
722            (
723                quote! { Result<String, String> },
724                quote! {
725                    {
726                        let mut err_ptr: *const std::ffi::c_char = std::ptr::null();
727                        let ptr = unsafe { super::#raw_mod::#fn_name(#(#all_ffi_args),*) };
728                        if !err_ptr.is_null() {
729                            let err_msg = unsafe { std::ffi::CStr::from_ptr(err_ptr).to_string_lossy().into_owned() };
730                            return Err(err_msg);
731                        }
732                        if ptr.is_null() {
733                            Ok(String::new())
734                        } else {
735                            let s = unsafe {
736                                std::ffi::CStr::from_ptr(ptr)
737                                    .to_string_lossy()
738                                    .into_owned()
739                            };
740                            unsafe { super::#raw_mod::#free_fn_name(ptr as *mut std::ffi::c_void) };
741                            Ok(s)
742                        }
743                    }
744                },
745            )
746        } else {
747            (
748                quote! { String },
749                quote! {
750                    {
751                        let ptr = unsafe { super::#raw_mod::#fn_name(#(#ffi_args),*) };
752                        if ptr.is_null() {
753                            String::new()
754                        } else {
755                            let s = unsafe {
756                                std::ffi::CStr::from_ptr(ptr)
757                                    .to_string_lossy()
758                                    .into_owned()
759                            };
760                            unsafe { super::#raw_mod::#free_fn_name(ptr as *mut std::ffi::c_void) };
761                            s
762                        }
763                    }
764                },
765            )
766        }
767    } else if has_err_out {
768        // Non-StrRet can_throw: Result<T, String> via err_out
769        let rust_ret = zig_ret_type_to_rust_safe(&exp.ret_type);
770        let rust_ret_wrapped = match exp.ret_type.as_str() {
771            "void" => quote! { Result<(), String> },
772            _ => quote! { Result<#rust_ret, String> },
773        };
774        let extract_result = match exp.ret_type.as_str() {
775            "void" => quote! { Ok(()) },
776            _ => quote! { Ok(result) },
777        };
778        // Build all ffi args including err_out
779        let mut all_ffi_args: Vec<proc_macro2::TokenStream> = ffi_args.clone();
780        all_ffi_args.push(quote! { &mut err_ptr });
781        (
782            rust_ret_wrapped,
783            quote! {
784                {
785                    let mut err_ptr: *const std::ffi::c_char = std::ptr::null();
786                    let result = unsafe { super::#raw_mod::#fn_name(#(#all_ffi_args),*) };
787                    if !err_ptr.is_null() {
788                        let err_msg = unsafe { std::ffi::CStr::from_ptr(err_ptr).to_string_lossy().into_owned() };
789                        return Err(err_msg);
790                    }
791                    #extract_result
792                }
793            },
794        )
795    } else {
796        let rust_ret = zig_ret_type_to_rust_safe(&exp.ret_type);
797        (
798            rust_ret.clone(),
799            quote! {
800                unsafe { super::#raw_mod::#fn_name(#(#ffi_args),*) }
801            },
802        )
803    };
804
805    quote! {
806        #[allow(non_snake_case)]
807        pub fn #wrapper_name( #(#safe_params),* ) -> #ret_ty {
808            // Ensure Zig runtime (allocator) is initialized before calling FFI
809            ensure_initialized();
810            #call_expr
811        }
812    }
813}
814
815// ── Type conversion helpers ───────────────────────────────────────
816
817fn zig_type_to_rust_ffi_type(zig_type: &str) -> proc_macro2::TokenStream {
818    match zig_type {
819        "[]const u8" => quote! { *const std::ffi::c_char },
820        "i32" => quote! { i32 },
821        "i64" => quote! { i64 },
822        "f64" => quote! { f64 },
823        "bool" => quote! { bool },
824        "void" => quote! { () },
825        "*usize" => quote! { *mut usize }, // result_len parameter
826        _ => quote! { *mut std::ffi::c_void },
827    }
828}
829
830fn zig_ret_type_to_rust_ffi(ret_type: &str) -> proc_macro2::TokenStream {
831    match ret_type {
832        "[]const u8" => quote! { *const std::ffi::c_char },
833        "StrRet" => quote! { __JsStr },
834        "i32" => quote! { i32 },
835        "i64" => quote! { i64 },
836        "f64" => quote! { f64 },
837        "bool" => quote! { bool },
838        "void" => quote! { () },
839        _ => quote! { *mut std::ffi::c_void },
840    }
841}
842
843fn zig_type_to_rust_safe_type(zig_type: &str) -> proc_macro2::TokenStream {
844    match zig_type {
845        "[]const u8" => quote! { &str },
846        "i32" => quote! { i32 },
847        "i64" => quote! { i64 },
848        "f64" => quote! { f64 },
849        "bool" => quote! { bool },
850        _ => quote! { *mut std::ffi::c_void },
851    }
852}
853
854fn convert_safe_to_ffi(zig_type: &str, ident: &syn::Ident) -> proc_macro2::TokenStream {
855    match zig_type {
856        "[]const u8" => quote! { std::ffi::CString::new(#ident).unwrap().into_raw() },
857        _ => quote! { #ident },
858    }
859}
860
861fn zig_ret_type_to_rust_safe(ret_type: &str) -> proc_macro2::TokenStream {
862    match ret_type {
863        "[]const u8" => quote! { String },
864        "i32" => quote! { i32 },
865        "i64" => quote! { i64 },
866        "f64" => quote! { f64 },
867        "bool" => quote! { bool },
868        "void" => quote! { () },
869        _ => quote! { *mut std::ffi::c_void },
870    }
871}