Skip to main content

js2zig_core/
cabi.rs

1//! C ABI wrapper generation and metadata serialization.
2//!
3//! This module contains all logic for generating `pub export fn` C ABI wrapper
4//! code (consumed by `project::generate` as part of `lib.zig`) and for writing
5//! C ABI export/import JSON metadata files (consumed by `js2rust-bridge-macro`).
6
7use std::collections::{HashMap, HashSet};
8use std::fs;
9use std::path::Path;
10
11use crate::host::HostFnRegistry;
12use crate::types::{NativeCabiExport, ZigType};
13
14// ── Helpers ─────────────────────────────────────────────
15
16/// Format conversion statements: empty → empty string, otherwise joined with newlines.
17fn format_conversions(convs: &[String]) -> String {
18    if convs.is_empty() {
19        String::new()
20    } else {
21        format!("{}\n", convs.join("\n"))
22    }
23}
24
25/// Emit `comptime { @export(...) }` line for a CABI wrapper.
26fn emit_comptime_export(out: &mut String, name: &str) {
27    out.push_str(&format!(
28        "comptime {{ @export(&{name}_cabi, .{{ .name = \"{name}\", .linkage = .strong }}); }}\n",
29        name = name,
30    ));
31}
32
33/// Emit a `pub const` alias for exports that bypass C ABI wrapping (JsAny,
34/// ArrayList, or functions with unsupported parameter types).
35fn emit_const_alias(out: &mut String, name: &str, bare_name: &str, module: &str) {
36    out.push_str(&format!(
37        "pub const {name} = {mod}.{bare};\n\n",
38        name = name,
39        bare = bare_name,
40        mod = module,
41    ));
42}
43
44/// Disambiguate a name by appending the module name if it collides.
45pub(super) fn disambiguate_name(
46    name: &str,
47    module: &str,
48    is_colliding: impl Fn(&str) -> bool,
49) -> String {
50    if is_colliding(name) {
51        format!("{}_{}", name, module)
52    } else {
53        name.to_string()
54    }
55}
56
57/// Emit an async Zig-friendly adapter function.
58fn emit_async_adapter(
59    out: &mut String,
60    name: &str,
61    bare: &str,
62    params: &str,
63    ret_type: &str,
64    module: &str,
65    args: &str,
66) {
67    out.push_str(&format!(
68        "pub fn {name}({params}) {ret_type} {{\n    return {module}.{bare}({args}) catch @panic(\"async error in {name}\");\n}}\n",
69        name = name,
70        bare = bare,
71        params = params,
72        ret_type = ret_type,
73        module = module,
74        args = args,
75    ));
76}
77
78// ── Public API ──────────────────────────────────────────
79
80/// Generate `pub export fn` wrapper code for lib.zig.
81/// Each wrapper calls the per-file module function and lives in the root lib.zig,
82/// so Zig correctly propagates the symbols into the final .lib.
83///
84/// For string-returning functions, ALSO generate a Zig-friendly adapter
85/// (`pub fn greet(s: []const u8) []const u8`) so test code can call
86/// the function with idiomatic Zig string types.
87///
88/// `cabi_rename` maps disambiguated CABI names → bare function names.
89/// When an export name collides across modules, the CABI wrapper gets the
90/// disambiguated name (`{fn}_{module}`) as its public symbol, but calls the
91/// original bare-named function inside the per-file module.
92pub fn gen_cabi_wrappers(
93    name_to_module: &HashMap<String, String>,
94    name_to_cabi: &HashMap<String, &NativeCabiExport>,
95    cabi_rename: &HashMap<String, String>,
96) -> String {
97    let mut out = String::new();
98    let mut emitted: HashSet<&str> = HashSet::new();
99
100    for (cabi_name, exp) in name_to_cabi {
101        if !emitted.insert(cabi_name.as_str()) {
102            continue;
103        }
104        let Some(module) = name_to_module.get(cabi_name) else {
105            continue;
106        };
107        // Prefix module name with _ to match orchestrator import (const _mod = @import(...))
108        let module = format!("_{}", module);
109        // Bare function name inside the per-file module (may differ from cabi_name when collision)
110        let bare_name = cabi_rename
111            .get(cabi_name)
112            .map(|s| s.as_str())
113            .unwrap_or(cabi_name.as_str());
114        // `name` = public/disambiguated name (used for wrapper declarations, @export, etc.)
115        let name = cabi_name.as_str();
116
117        let returns_string = exp.ret_type == ZigType::Str;
118        let ret_is_non_cabi = matches!(
119            exp.ret_type,
120            ZigType::Anytype | ZigType::JsAny | ZigType::JsSymbol
121        );
122        let ret_is_arraylist = matches!(exp.ret_type, ZigType::ArrayList(_));
123
124        // Non-C-ABI-safe returns (Anytype/JsAny/JsSymbol/ArrayList): re-export as const alias.
125        // These types cannot cross the C ABI boundary, so no pub export fn is emitted.
126        // Async functions with NamedStruct returns are excluded — they use out-pointer C ABI wrappers.
127        let skip_for_ret = ret_is_non_cabi || ret_is_arraylist;
128        let skip_for_async_struct = exp.is_async && matches!(exp.ret_type, ZigType::NamedStruct(_));
129        if skip_for_ret && !skip_for_async_struct {
130            emit_const_alias(&mut out, name, bare_name, &module);
131            continue;
132        }
133
134        // Skip functions with non-C-ABI-safe parameters (Anytype/JsAny/JsSymbol/Void).
135        // AsyncIo params are handled separately — they're filtered from C ABI param lists
136        // and obtained via js_runtime.getIo() internally.
137        let has_js_obj_param = exp.params.iter().any(|(_, ty)| {
138            matches!(
139                ty,
140                ZigType::Void | ZigType::Anytype | ZigType::JsAny | ZigType::JsSymbol
141            )
142        });
143        if has_js_obj_param {
144            emit_const_alias(&mut out, name, bare_name, &module);
145            continue;
146        }
147
148        // Build parameter lists for all function types
149        let mut cabi_params: Vec<String> = Vec::new();
150        let mut zig_params: Vec<String> = Vec::new();
151        let mut arg_names: Vec<String> = Vec::new();
152        let mut cabi_to_zig_conversions: Vec<String> = Vec::new();
153
154        for (pname, ptype) in &exp.params {
155            // Skip the injected 'io: AsyncIo' parameter —
156            // C ABI wrappers obtain it via js_runtime.getIo() internally.
157            if matches!(ptype, ZigType::AsyncIo) {
158                continue;
159            }
160            arg_names.push(pname.clone());
161            if *ptype == ZigType::Str {
162                cabi_params.push(format!("{}: [*:0]const u8", pname));
163                zig_params.push(format!("{}: []const u8", pname));
164                cabi_to_zig_conversions.push(format!(
165                    "    const {p}_slice: []const u8 = std.mem.span({p});",
166                    p = pname
167                ));
168            } else {
169                let zig_ty = ptype.to_zig_type();
170                cabi_params.push(format!("{}: {}", pname, zig_ty));
171                zig_params.push(format!("{}: {}", pname, zig_ty));
172            }
173        }
174
175        // Build call args: for CABI wrapper, string params use _slice version
176        let zig_call_args: String = arg_names.join(", ");
177        let cabi_call_args: String = exp
178            .params
179            .iter()
180            .filter(|(_, ptype)| !matches!(ptype, ZigType::AsyncIo))
181            .map(|(pname, ptype)| {
182                if *ptype == ZigType::Str {
183                    format!("{}_slice", pname)
184                } else {
185                    pname.clone()
186                }
187            })
188            .collect::<Vec<_>>()
189            .join(", ");
190
191        // ── Async exports: call _impl with js_runtime.getIo(), catch errors ──
192        if exp.is_async {
193            let async_zig_args = if zig_call_args.is_empty() {
194                "js_runtime.getIo()".to_string()
195            } else {
196                format!("js_runtime.getIo(), {}", zig_call_args)
197            };
198            let async_cabi_args = if cabi_call_args.is_empty() {
199                "js_runtime.getIo()".to_string()
200            } else {
201                format!("js_runtime.getIo(), {}", cabi_call_args)
202            };
203
204            if returns_string {
205                // Zig-friendly adapter (for tests) — calls _impl directly
206                emit_async_adapter(
207                    &mut out,
208                    name,
209                    bare_name,
210                    &zig_params.join(", "),
211                    "[]const u8",
212                    &module,
213                    &async_zig_args,
214                );
215                // C ABI wrapper (StrRet — zero-copy, panic via negative len)
216                let conversions = format_conversions(&cabi_to_zig_conversions);
217                out.push_str(&format!(
218                    "pub export fn {name}_cabi({cabi_params}) StrRet {{\n{conv}    return StrRet.from({mod}.{bare}({args}) catch |err| return StrRet.from_panic(err));\n}}\n",
219                    name = name,
220                    bare = bare_name,
221                    cabi_params = cabi_params.join(", "),
222                    conv = conversions,
223                    mod = module,
224                    args = async_cabi_args,
225                ));
226                emit_comptime_export(&mut out, name);
227            } else if let ZigType::NamedStruct(ref sn) = exp.ret_type {
228                // Async struct return: use out-pointer C ABI wrapper
229                let struct_name = format!("host.{}", sn);
230                let conversions = format_conversions(&cabi_to_zig_conversions);
231
232                // Zig-friendly adapter (for tests)
233                emit_async_adapter(
234                    &mut out,
235                    name,
236                    bare_name,
237                    &zig_params.join(", "),
238                    &struct_name,
239                    &module,
240                    &async_zig_args,
241                );
242
243                // C ABI wrapper: add *<struct_name> out-pointer parameter
244                let mut cabi_params_with_out = cabi_params.clone();
245                cabi_params_with_out.push(format!("result: *{}", struct_name));
246                let cabi_params_str = cabi_params_with_out.join(", ");
247
248                let cabi_call = format!(
249                    "{mod}.{bare}({args})",
250                    mod = module,
251                    bare = bare_name,
252                    args = async_cabi_args,
253                );
254                out.push_str(&format!(
255                    "pub export fn {name}_cabi({params}) void {{\n{conv}    const _result = {cabi_call} catch @panic(\"async error in {name}\");\n    result.* = _result;\n}}\n",
256                    name = name,
257                    params = cabi_params_str,
258                    conv = conversions,
259                    cabi_call = cabi_call,
260                ));
261                emit_comptime_export(&mut out, name);
262            } else {
263                // Async non-string, non-struct return (e.g., i64, bool)
264                let ret_zig = exp.ret_type.to_zig_type();
265                let conversions = format_conversions(&cabi_to_zig_conversions);
266
267                // Zig-friendly adapter (for tests)
268                emit_async_adapter(
269                    &mut out,
270                    name,
271                    bare_name,
272                    &zig_params.join(", "),
273                    &ret_zig,
274                    &module,
275                    &async_zig_args,
276                );
277
278                // C ABI wrapper
279                let cabi_params_str = cabi_params.join(", ");
280
281                let cabi_call = format!(
282                    "{mod}.{bare}({args})",
283                    mod = module,
284                    bare = bare_name,
285                    args = async_cabi_args,
286                );
287                out.push_str(&format!(
288                    "pub export fn {name}_cabi({params}) {ret} {{\n{conv}    return {cabi_call} catch @panic(\"async error in {name}\");\n}}\n",
289                    name = name,
290                    params = cabi_params_str,
291                    ret = ret_zig,
292                    conv = conversions,
293                    cabi_call = cabi_call,
294                ));
295                emit_comptime_export(&mut out, name);
296            }
297
298            out.push('\n');
299            continue;
300        }
301
302        if returns_string {
303            // ── Zig-friendly adapter (for tests) — calls _impl directly, no conversion ──
304            let test_call = if exp.can_throw {
305                format!(
306                    "{mod}.{bare}({args}) catch @panic(\"error in {name}\")",
307                    mod = module,
308                    bare = bare_name,
309                    name = name,
310                    args = zig_call_args,
311                )
312            } else {
313                format!(
314                    "{mod}.{bare}({args})",
315                    mod = module,
316                    bare = bare_name,
317                    args = zig_call_args
318                )
319            };
320            out.push_str(&format!(
321                "pub fn {name}({params}) []const u8 {{\n    return {test_call};\n}}\n",
322                name = name,
323                params = zig_params.join(", "),
324                test_call = test_call,
325            ));
326
327            // ── C ABI wrapper (StrRet — zero-copy, error via sign-bit) ──
328            let conversions = format_conversions(&cabi_to_zig_conversions);
329            let cabi_call = if exp.can_throw {
330                format!(
331                    "{mod}.{bare}({args}) catch |err| return StrRet.from_panic(err)",
332                    mod = module,
333                    bare = bare_name,
334                    args = cabi_call_args,
335                )
336            } else {
337                format!(
338                    "{mod}.{bare}({args})",
339                    mod = module,
340                    bare = bare_name,
341                    args = cabi_call_args,
342                )
343            };
344            out.push_str(&format!(
345                "pub export fn {name}_cabi({cabi_params}) StrRet {{\n{conv}    return StrRet.from({cabi_call});\n}}\n",
346                name = name,
347                cabi_params = cabi_params.join(", "),
348                conv = conversions,
349                cabi_call = cabi_call,
350            ));
351            emit_comptime_export(&mut out, name);
352        } else {
353            let ret_zig = exp.ret_type.to_cabi_str();
354
355            // Build C ABI param list: add _err out-param for can_throw non-string exports
356            let mut cabi_params_with_err = cabi_params.clone();
357            if exp.can_throw {
358                cabi_params_with_err.push("err_out: *?[*:0]const u8".to_string());
359            }
360            let cabi_params_str = cabi_params_with_err.join(", ");
361
362            // Build the call expression with error handling for can_throw
363            let (call_expr, err_setup) = if exp.can_throw {
364                let err_handle = if ret_zig == "void" {
365                    // Void: call without assignment
366                    format!(
367                        "    {mod}.{bare}({args}) catch |err| {{\n        err_out.* = @errorName(err);\n        return;\n    }};",
368                        mod = module,
369                        bare = bare_name,
370                        args = cabi_call_args,
371                    )
372                } else {
373                    // Use type-appropriate zero value for the catch fallback
374                    let ret_zero = if ret_zig == "bool" { "false" } else { "0" };
375                    format!(
376                        "    const _result = {mod}.{bare}({args}) catch |err| {{\n        err_out.* = @errorName(err);\n        return {ret_zero};\n    }};",
377                        mod = module,
378                        bare = bare_name,
379                        args = cabi_call_args,
380                        ret_zero = ret_zero,
381                    )
382                };
383                let setup = if ret_zig == "void" {
384                    "    err_out.* = null;\n".to_string()
385                } else {
386                    String::new()
387                };
388                (err_handle, setup)
389            } else {
390                (
391                    format!(
392                        "{mod}.{bare}({args})",
393                        mod = module,
394                        bare = bare_name,
395                        args = cabi_call_args,
396                    ),
397                    String::new(),
398                )
399            };
400
401            let conversions = format_conversions(&cabi_to_zig_conversions);
402
403            if ret_zig == "void" {
404                if exp.can_throw {
405                    out.push_str(&format!(
406                        "pub export fn {name}({params}) void {{\n{conv}{err_setup}{call_expr}\n}}\n",
407                        name = name,
408                        params = cabi_params_str,
409                        conv = conversions,
410                        err_setup = err_setup,
411                        call_expr = call_expr,
412                    ));
413                } else {
414                    out.push_str(&format!(
415                        "pub export fn {name}({params}) void {{\n{conv}    {mod}.{bare}({args});\n}}\n",
416                        name = name,
417                        bare = bare_name,
418                        params = cabi_params_str,
419                        conv = conversions,
420                        mod = module,
421                        args = cabi_call_args,
422                    ));
423                }
424            } else {
425                // Use type-appropriate zero value for void fallback
426                let rz = if ret_zig == "bool" { "false" } else { "0" };
427                if exp.can_throw {
428                    out.push_str(&format!(
429                        "pub export fn {name}({params}) {ret} {{\n{conv}{call_expr}\n    if (@TypeOf(_result) == void) {{\n        return {rz};\n    }} else {{\n        return _result;\n    }}\n}}\n",
430                        name = name,
431                        params = cabi_params_str,
432                        conv = conversions,
433                        ret = ret_zig,
434                        call_expr = call_expr,
435                        rz = rz,
436                    ));
437                } else {
438                    out.push_str(&format!(
439                        "pub export fn {name}({params}) {ret} {{\n{conv}    const _result = {mod}.{bare}({args});\n    if (@TypeOf(_result) == void) {{\n        return {rz};\n    }} else {{\n        return _result;\n    }}\n}}\n",
440                        name = name,
441                        bare = bare_name,
442                        params = cabi_params_str,
443                        ret = ret_zig,
444                        conv = conversions,
445                        mod = module,
446                        args = cabi_call_args,
447                        rz = rz,
448                    ));
449                }
450            }
451        }
452
453        out.push('\n');
454    }
455
456    out
457}
458
459/// Write C ABI exports/imports JSON metadata.
460///
461/// `cabi_exports` is a list of (module_name, export) pairs.
462/// `cabi_rename` maps disambiguated CABI names → bare function names.
463/// When a name collides across modules, the JSON "name" field uses the
464/// disambiguated form (`{fn}_{module}`) so that the bridge macro generates
465/// unique Rust function definitions.
466pub fn write_cabi_metadata(
467    out_dir: &Path,
468    project_name: &str,
469    cabi_exports: &[(String, NativeCabiExport)],
470    host_fns: &HostFnRegistry,
471    include_init: bool,
472    cabi_rename: &HashMap<String, String>,
473) {
474    let project_dir = out_dir.join(project_name);
475
476    // cabi_exports.json — filter out exports with Anytype returns or params (no C ABI export generated)
477    let exports_path = project_dir.join("cabi_exports.json");
478    let mut exports_value: Vec<serde_json::Value> = cabi_exports
479        .iter()
480        .filter(|(_, exp)| {
481            // Only include exports with C-ABI-safe return types and parameter types.
482            // Anytype/JsAny/JsSymbol are Zig-only types that cannot cross the C ABI boundary.
483            // AsyncIo params are filtered from exports (obtained via js_runtime.getIo()).
484            // NamedStruct returns for async functions use out-pointer C ABI wrappers.
485            let ret_ok = !matches!(
486                exp.ret_type,
487                ZigType::Anytype | ZigType::JsAny | ZigType::JsSymbol
488            ) || (exp.is_async && matches!(exp.ret_type, ZigType::NamedStruct(_)));
489            let param_ok = !exp
490                .params
491                .iter()
492                .filter(|(_, ty)| !matches!(ty, ZigType::AsyncIo))
493                .any(|(_, ty)| matches!(ty, ZigType::Anytype | ZigType::JsAny | ZigType::JsSymbol));
494            ret_ok && param_ok
495        })
496        .map(|(mod_name, exp)| {
497            // Build params list — exclude injected 'io: AsyncIo' (handled internally)
498            let params: Vec<serde_json::Value> = exp
499                .params
500                .iter()
501                .filter(|(_, ty)| !matches!(ty, ZigType::AsyncIo))
502                .map(|(name, ty)| {
503                    serde_json::json!({
504                        "name": name,
505                        "zig_type": ty.to_zig_type() // JSON metadata is consumed by macro (lib.zig)
506                    })
507                })
508                .collect();
509
510            // Determine ret_type string for C ABI
511            let ret_type_str = exp.ret_type.to_cabi_str();
512
513            // For NamedStruct returns, look up struct fields from host_fns
514            let (ret_struct_name, ret_struct_fields) =
515                if let ZigType::NamedStruct(ref struct_name) = exp.ret_type {
516                    // Look up the struct definition from host_fns
517                    let struct_fields: Option<Vec<serde_json::Value>> = host_fns
518                        .structs
519                        .iter()
520                        .find(|s| &s.zig_name == struct_name)
521                        .map(|s| {
522                            s.fields
523                                .iter()
524                                .map(|f| {
525                                    serde_json::json!({
526                                        "name": f.name,
527                                        "zig_type": f.zig_type,
528                                        "cabi_type": f.c_type,
529                                    })
530                                })
531                                .collect()
532                        });
533                    (Some(struct_name.clone()), struct_fields)
534                } else {
535                    (None, None)
536                };
537
538            // Use disambiguated name if this export collides across modules
539            let export_name = disambiguate_name(&exp.name, mod_name, |n| {
540                cabi_rename.contains_key(&format!("{}_{}", n, mod_name))
541            });
542
543            let mut json_obj = serde_json::json!({
544                "name": export_name,
545                "params": params,
546                "ret_type": ret_type_str,
547                "can_throw": exp.can_throw,
548            });
549
550            // Add struct info if returning a NamedStruct
551            if let Some(sn) = ret_struct_name {
552                json_obj["ret_struct_name"] = serde_json::json!(sn);
553            }
554            if let Some(sf) = ret_struct_fields {
555                json_obj["ret_struct_fields"] = serde_json::json!(sf);
556            }
557
558            json_obj
559        })
560        .collect();
561
562    // Deduplicate exports by name — when multiple JS files produce identically-named
563    // C ABI exports, the bridge macro would generate duplicate Rust function definitions,
564    // causing E0428 compilation errors. With collision disambiguation, duplicates are
565    // resolved by the {fn}_{module} naming, but we still deduplicate as a safety net.
566    {
567        let mut seen = HashSet::new();
568        exports_value.retain(|exp| {
569            let name = exp["name"].as_str().unwrap_or("");
570            seen.insert(name.to_string())
571        });
572    }
573
574    // Only include js2rust_init and js2rust_deinit for non-test projects
575    if include_init {
576        exports_value.push(serde_json::json!({
577            "name": "js2rust_init",
578            "params": [],
579            "ret_type": "void",
580        }));
581        exports_value.push(serde_json::json!({
582            "name": "js2rust_deinit",
583            "params": [],
584            "ret_type": "void",
585        }));
586    }
587
588    if let Ok(json_str) = serde_json::to_string_pretty(&exports_value) {
589        let _ = fs::write(&exports_path, &json_str);
590    }
591
592    // cabi_imports.json
593    let imports_path = project_dir.join("cabi_imports.json");
594    let imports_value = host_fns.to_json_value();
595    if let Ok(json_str) = serde_json::to_string_pretty(&imports_value) {
596        let _ = fs::write(&imports_path, &json_str);
597    }
598}