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_with_runtime = {
280                    let mut p = cabi_params.clone();
281                    p.push("js_runtime: *JSRuntime".to_string());
282                    p
283                };
284                let cabi_params_str = cabi_params_with_runtime.join(", ");
285
286                let cabi_call = format!(
287                    "{mod}.{bare}({args})",
288                    mod = module,
289                    bare = bare_name,
290                    args = async_cabi_args,
291                );
292                out.push_str(&format!(
293                    "pub export fn {name}_cabi({params}) {ret} {{\n{conv}    return {cabi_call} catch @panic(\"async error in {name}\");\n}}\n",
294                    name = name,
295                    params = cabi_params_str,
296                    ret = ret_zig,
297                    conv = conversions,
298                    cabi_call = cabi_call,
299                ));
300                emit_comptime_export(&mut out, name);
301            }
302
303            out.push('\n');
304            continue;
305        }
306
307        if returns_string {
308            // ── Zig-friendly adapter (for tests) — calls _impl directly, no conversion ──
309            let test_call = if exp.can_throw {
310                format!(
311                    "{mod}.{bare}({args}) catch @panic(\"error in {name}\")",
312                    mod = module,
313                    bare = bare_name,
314                    name = name,
315                    args = zig_call_args,
316                )
317            } else {
318                format!(
319                    "{mod}.{bare}({args})",
320                    mod = module,
321                    bare = bare_name,
322                    args = zig_call_args
323                )
324            };
325            out.push_str(&format!(
326                "pub fn {name}({params}) []const u8 {{\n    return {test_call};\n}}\n",
327                name = name,
328                params = zig_params.join(", "),
329                test_call = test_call,
330            ));
331
332            // ── C ABI wrapper (StrRet — zero-copy, error via sign-bit) ──
333            let conversions = format_conversions(&cabi_to_zig_conversions);
334            let cabi_call = if exp.can_throw {
335                format!(
336                    "{mod}.{bare}({args}) catch |err| return StrRet.from_panic(err)",
337                    mod = module,
338                    bare = bare_name,
339                    args = cabi_call_args,
340                )
341            } else {
342                format!(
343                    "{mod}.{bare}({args})",
344                    mod = module,
345                    bare = bare_name,
346                    args = cabi_call_args,
347                )
348            };
349            out.push_str(&format!(
350                "pub export fn {name}_cabi({cabi_params}) StrRet {{\n{conv}    return StrRet.from({cabi_call});\n}}\n",
351                name = name,
352                cabi_params = cabi_params.join(", "),
353                conv = conversions,
354                cabi_call = cabi_call,
355            ));
356            emit_comptime_export(&mut out, name);
357        } else {
358            let ret_zig = exp.ret_type.to_cabi_str();
359
360            // Build C ABI param list: add _err out-param for can_throw non-string exports
361            let mut cabi_params_with_err = cabi_params.clone();
362            if exp.can_throw {
363                cabi_params_with_err.push("err_out: *?[*:0]const u8".to_string());
364            }
365            let cabi_params_str = cabi_params_with_err.join(", ");
366
367            // Build the call expression with error handling for can_throw
368            let (call_expr, err_setup) = if exp.can_throw {
369                let err_handle = if ret_zig == "void" {
370                    // Void: call without assignment
371                    format!(
372                        "    {mod}.{bare}({args}) catch |err| {{\n        err_out.* = @errorName(err);\n        return;\n    }};",
373                        mod = module,
374                        bare = bare_name,
375                        args = cabi_call_args,
376                    )
377                } else {
378                    // Use type-appropriate zero value for the catch fallback
379                    let ret_zero = if ret_zig == "bool" { "false" } else { "0" };
380                    format!(
381                        "    const _result = {mod}.{bare}({args}) catch |err| {{\n        err_out.* = @errorName(err);\n        return {ret_zero};\n    }};",
382                        mod = module,
383                        bare = bare_name,
384                        args = cabi_call_args,
385                        ret_zero = ret_zero,
386                    )
387                };
388                let setup = if ret_zig == "void" {
389                    "    err_out.* = null;\n".to_string()
390                } else {
391                    String::new()
392                };
393                (err_handle, setup)
394            } else {
395                (
396                    format!(
397                        "{mod}.{bare}({args})",
398                        mod = module,
399                        bare = bare_name,
400                        args = cabi_call_args,
401                    ),
402                    String::new(),
403                )
404            };
405
406            let conversions = format_conversions(&cabi_to_zig_conversions);
407
408            if ret_zig == "void" {
409                if exp.can_throw {
410                    out.push_str(&format!(
411                        "pub export fn {name}({params}) void {{\n{conv}{err_setup}{call_expr}\n}}\n",
412                        name = name,
413                        params = cabi_params_str,
414                        conv = conversions,
415                        err_setup = err_setup,
416                        call_expr = call_expr,
417                    ));
418                } else {
419                    out.push_str(&format!(
420                        "pub export fn {name}({params}) void {{\n{conv}    {mod}.{bare}({args});\n}}\n",
421                        name = name,
422                        bare = bare_name,
423                        params = cabi_params_str,
424                        conv = conversions,
425                        mod = module,
426                        args = cabi_call_args,
427                    ));
428                }
429            } else {
430                // Use type-appropriate zero value for void fallback
431                let rz = if ret_zig == "bool" { "false" } else { "0" };
432                if exp.can_throw {
433                    out.push_str(&format!(
434                        "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",
435                        name = name,
436                        params = cabi_params_str,
437                        conv = conversions,
438                        ret = ret_zig,
439                        call_expr = call_expr,
440                        rz = rz,
441                    ));
442                } else {
443                    out.push_str(&format!(
444                        "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",
445                        name = name,
446                        bare = bare_name,
447                        params = cabi_params_str,
448                        ret = ret_zig,
449                        conv = conversions,
450                        mod = module,
451                        args = cabi_call_args,
452                        rz = rz,
453                    ));
454                }
455            }
456        }
457
458        out.push('\n');
459    }
460
461    out
462}
463
464/// Write C ABI exports/imports JSON metadata.
465///
466/// `cabi_exports` is a list of (module_name, export) pairs.
467/// `cabi_rename` maps disambiguated CABI names → bare function names.
468/// When a name collides across modules, the JSON "name" field uses the
469/// disambiguated form (`{fn}_{module}`) so that the bridge macro generates
470/// unique Rust function definitions.
471pub fn write_cabi_metadata(
472    out_dir: &Path,
473    project_name: &str,
474    cabi_exports: &[(String, NativeCabiExport)],
475    host_fns: &HostFnRegistry,
476    include_init: bool,
477    cabi_rename: &HashMap<String, String>,
478) {
479    let project_dir = out_dir.join(project_name);
480
481    // cabi_exports.json — filter out exports with Anytype returns or params (no C ABI export generated)
482    let exports_path = project_dir.join("cabi_exports.json");
483    let mut exports_value: Vec<serde_json::Value> = cabi_exports
484        .iter()
485        .filter(|(_, exp)| {
486            // Only include exports with C-ABI-safe return types and parameter types.
487            // Anytype/JsAny/JsSymbol are Zig-only types that cannot cross the C ABI boundary.
488            // AsyncIo params are filtered from exports (obtained via js_runtime.getIo()).
489            // NamedStruct returns for async functions use out-pointer C ABI wrappers.
490            let ret_ok = !matches!(
491                exp.ret_type,
492                ZigType::Anytype | ZigType::JsAny | ZigType::JsSymbol
493            ) || (exp.is_async && matches!(exp.ret_type, ZigType::NamedStruct(_)));
494            let param_ok = !exp
495                .params
496                .iter()
497                .filter(|(_, ty)| !matches!(ty, ZigType::AsyncIo))
498                .any(|(_, ty)| matches!(ty, ZigType::Anytype | ZigType::JsAny | ZigType::JsSymbol));
499            ret_ok && param_ok
500        })
501        .map(|(mod_name, exp)| {
502            // Build params list — exclude injected 'io: AsyncIo' (handled internally)
503            let params: Vec<serde_json::Value> = exp
504                .params
505                .iter()
506                .filter(|(_, ty)| !matches!(ty, ZigType::AsyncIo))
507                .map(|(name, ty)| {
508                    serde_json::json!({
509                        "name": name,
510                        "zig_type": ty.to_zig_type() // JSON metadata is consumed by macro (lib.zig)
511                    })
512                })
513                .collect();
514
515            // Determine ret_type string for C ABI
516            let ret_type_str = exp.ret_type.to_cabi_str();
517
518            // For NamedStruct returns, look up struct fields from host_fns
519            let (ret_struct_name, ret_struct_fields) =
520                if let ZigType::NamedStruct(ref struct_name) = exp.ret_type {
521                    // Look up the struct definition from host_fns
522                    let struct_fields: Option<Vec<serde_json::Value>> = host_fns
523                        .structs
524                        .iter()
525                        .find(|s| &s.zig_name == struct_name)
526                        .map(|s| {
527                            s.fields
528                                .iter()
529                                .map(|f| {
530                                    serde_json::json!({
531                                        "name": f.name,
532                                        "zig_type": f.zig_type,
533                                        "cabi_type": f.c_type,
534                                    })
535                                })
536                                .collect()
537                        });
538                    (Some(struct_name.clone()), struct_fields)
539                } else {
540                    (None, None)
541                };
542
543            // Use disambiguated name if this export collides across modules
544            let export_name = disambiguate_name(&exp.name, mod_name, |n| {
545                cabi_rename.contains_key(&format!("{}_{}", n, mod_name))
546            });
547
548            let mut json_obj = serde_json::json!({
549                "name": export_name,
550                "params": params,
551                "ret_type": ret_type_str,
552                "can_throw": exp.can_throw,
553            });
554
555            // Add struct info if returning a NamedStruct
556            if let Some(sn) = ret_struct_name {
557                json_obj["ret_struct_name"] = serde_json::json!(sn);
558            }
559            if let Some(sf) = ret_struct_fields {
560                json_obj["ret_struct_fields"] = serde_json::json!(sf);
561            }
562
563            json_obj
564        })
565        .collect();
566
567    // Deduplicate exports by name — when multiple JS files produce identically-named
568    // C ABI exports, the bridge macro would generate duplicate Rust function definitions,
569    // causing E0428 compilation errors. With collision disambiguation, duplicates are
570    // resolved by the {fn}_{module} naming, but we still deduplicate as a safety net.
571    {
572        let mut seen = HashSet::new();
573        exports_value.retain(|exp| {
574            let name = exp["name"].as_str().unwrap_or("");
575            seen.insert(name.to_string())
576        });
577    }
578
579    // Only include js2rust_init and js2rust_deinit for non-test projects
580    if include_init {
581        exports_value.push(serde_json::json!({
582            "name": "js2rust_init",
583            "params": [],
584            "ret_type": "void",
585        }));
586        exports_value.push(serde_json::json!({
587            "name": "js2rust_deinit",
588            "params": [],
589            "ret_type": "void",
590        }));
591    }
592
593    if let Ok(json_str) = serde_json::to_string_pretty(&exports_value) {
594        let _ = fs::write(&exports_path, &json_str);
595    }
596
597    // cabi_imports.json
598    let imports_path = project_dir.join("cabi_imports.json");
599    let imports_value = host_fns.to_json_value();
600    if let Ok(json_str) = serde_json::to_string_pretty(&imports_value) {
601        let _ = fs::write(&imports_path, &json_str);
602    }
603}