Skip to main content

js2zig_core/
host.rs

1//! Host function registry — allows JS code to call custom Rust functions.
2//!
3//! This module provides a registry where developers can register Rust functions
4//! (marked `#[no_mangle] pub extern "C"`) that should be callable from
5//! translated JS/Zig code via the C ABI.
6//!
7//! # Usage
8//!
9//! In `main.rs`, create a `HostFnRegistry`, register Rust functions, and pass it
10//! to `project.rs` for metadata generation and to the transpiler pipeline for translation.
11
12use crate::types::ZigType;
13use std::path::Path;
14
15// ── Struct definitions ──
16
17/// A field in a host struct (for C ABI ↔ Zig conversion).
18#[derive(Debug, Clone)]
19pub struct HostStructField {
20    pub name: String,
21    /// Zig type for the clean struct (e.g. "i64", "[]const u8")
22    pub zig_type: String,
23    /// C ABI type for the extern struct (e.g. "i64", "\[128\]u8")
24    pub c_type: String,
25}
26
27/// Definition of a struct used by host functions.
28#[derive(Debug, Clone)]
29pub struct HostStructDef {
30    /// Clean Zig struct name (e.g. "UserInfo")
31    pub zig_name: String,
32    /// C ABI extern struct name (e.g. "HostUserInfo")
33    pub c_name: String,
34    /// Fields
35    pub fields: Vec<HostStructField>,
36}
37
38// ── Function definitions ──
39
40/// Definition of a single host function that JS can call.
41#[derive(Debug, Clone)]
42pub struct HostFnDef {
43    /// JS-side function name (e.g. "hostAdd" for sync, "fetchUser" for async)
44    pub name: String,
45    /// C ABI symbol name (e.g. "hostFetchUser"). Same as `name` for sync fns.
46    pub c_name: String,
47    /// Parameter names and Zig types (wrapper-level types)
48    pub params: Vec<(String, ZigType)>,
49    /// Return type (wrapper-level)
50    pub ret_type: ZigType,
51    /// Whether this is an async function (needs io.async wrapper)
52    pub is_async: bool,
53}
54
55/// Registry of Rust host functions exposed to JS via C ABI.
56pub struct HostFnRegistry {
57    pub fns: Vec<HostFnDef>,
58    pub structs: Vec<HostStructDef>,
59}
60
61impl HostFnRegistry {
62    pub fn new() -> Self {
63        Self {
64            fns: Vec::new(),
65            structs: Vec::new(),
66        }
67    }
68
69    /// Check if the registry is empty (no host functions registered).
70    pub fn is_empty(&self) -> bool {
71        self.fns.is_empty()
72    }
73
74    /// Register a sync host function that JS code can call directly.
75    pub fn register(&mut self, name: &str, params: Vec<(String, ZigType)>, ret_type: ZigType) {
76        self.fns.push(HostFnDef {
77            name: name.to_string(),
78            c_name: name.to_string(),
79            params,
80            ret_type,
81            is_async: false,
82        });
83    }
84
85    /// Register an async host function that JS code calls with `await`.
86    ///
87    /// The async wrapper `fn {name}(io: Io, ...) !{ret_type}` is generated
88    /// automatically and calls the C ABI function `{c_name}`.
89    pub fn register_async(
90        &mut self,
91        name: &str,
92        c_name: &str,
93        params: Vec<(String, ZigType)>,
94        ret_struct: HostStructDef,
95    ) {
96        let struct_zig_name = ret_struct.zig_name.clone();
97        self.structs.push(ret_struct);
98        self.fns.push(HostFnDef {
99            name: name.to_string(),
100            c_name: c_name.to_string(),
101            params,
102            ret_type: ZigType::NamedStruct(struct_zig_name),
103            is_async: true,
104        });
105    }
106
107    /// Register an async host function with a simple (non-struct) return type.
108    pub fn register_async_simple(
109        &mut self,
110        name: &str,
111        c_name: &str,
112        params: Vec<(String, ZigType)>,
113        ret_type: ZigType,
114    ) {
115        self.fns.push(HostFnDef {
116            name: name.to_string(),
117            c_name: c_name.to_string(),
118            params,
119            ret_type,
120            is_async: true,
121        });
122    }
123
124    /// Return the JS-side names of all registered async functions.
125    pub fn async_fn_names(&self) -> Vec<String> {
126        self.fns
127            .iter()
128            .filter(|f| f.is_async)
129            .map(|f| f.name.clone())
130            .collect()
131    }
132
133    /// Return struct field types for all registered host structs.
134    /// Key: Zig struct name, Value: Vec<(field_name, field_zig_type)>
135    pub fn struct_fields_map(&self) -> std::collections::HashMap<String, Vec<(String, ZigType)>> {
136        let mut map = std::collections::HashMap::new();
137        for s in &self.structs {
138            let fields: Vec<(String, ZigType)> = s
139                .fields
140                .iter()
141                .map(|f| (f.name.clone(), ZigType::from_zig_str(&f.zig_type)))
142                .collect();
143            map.insert(s.zig_name.clone(), fields);
144        }
145        map
146    }
147
148    /// Look up a host function by JS name.
149    pub fn lookup(&self, name: &str) -> Option<&HostFnDef> {
150        self.fns.iter().find(|f| f.name == name)
151    }
152
153    /// Iterate over all registered host functions.
154    pub fn iter(&self) -> impl Iterator<Item = &HostFnDef> {
155        self.fns.iter()
156    }
157
158    /// Generate the Zig `host.zig` file content.
159    ///
160    /// Emits:
161    /// - `extern struct` definitions for C ABI types
162    /// - `extern "c" fn` declarations for C ABI host functions defined in Rust
163    /// - Wrapper functions for string params/returns (converts `[]const u8` ↔ `[*:0]const u8`)
164    ///
165    /// For functions with string parameters or string return types, a `_cabi` extern
166    /// declaration is emitted alongside a wrapper function with the original name.
167    /// The wrapper converts Zig-level `[]const u8` to null-terminated `[*:0]const u8`
168    /// via `dupeZ`, and converts the return value back via `std.mem.span`.
169    ///
170    /// Note: `zig build test` (standalone Zig tests) may fail to link if test code
171    /// calls host functions. Host-dependent functions are tested via Rust FFI instead.
172    pub fn generate_zig_header(&self) -> String {
173        if self.fns.is_empty() {
174            return String::new();
175        }
176        let mut out = String::new();
177        out.push_str("// Auto-generated host function declarations (Rust via C ABI)\n");
178        out.push_str("// These symbols are defined in Rust with #[no_mangle] pub extern \"C\".\n");
179        out.push_str("// Allocator: uses the global allocator from the runtime.\n");
180        out.push_str("const std = @import(\"std\");\n");
181        out.push_str("pub const Io = std.Io;\n");
182        out.push_str("const js_allocator = @import(\"js_runtime/js_allocator.zig\");\n");
183        out.push_str("const StrRet = @import(\"js_runtime/string.zig\").StrRet;\n\n");
184
185        // Emit C ABI struct definitions (extern structs).
186        // String fields are represented as ptr+len in C ABI (matches JsStrField layout).
187        // Field order and types must exactly match Rust #[repr(C)] layout.
188        // Rust JsStrField = { ptr: *const u8, len: usize } (16 bytes, two fields).
189        for s in &self.structs {
190            out.push_str(&format!("pub const {} = extern struct {{\n", s.c_name));
191            for f in &s.fields {
192                if f.zig_type == "[]const u8" {
193                    // Emit ptr+len pair matching JsStrField memory layout.
194                    // Field names: {name}_ptr, {name}_len (so async wrapper can access them).
195                    out.push_str(&format!(
196                        "    {}_ptr: [*]const u8,\n    {}_len: usize,\n",
197                        f.name, f.name
198                    ));
199                } else {
200                    out.push_str(&format!("    {}: {},\n", f.name, f.c_type));
201                }
202            }
203            out.push_str("};\n\n");
204        }
205
206        // Emit clean Zig struct definitions (for async wrapper return types)
207        for s in &self.structs {
208            out.push_str(&format!("pub const {} = struct {{\n", s.zig_name));
209            for f in &s.fields {
210                out.push_str(&format!("    {}: {},\n", f.name, f.zig_type));
211            }
212            out.push_str("};\n\n");
213        }
214
215        // Emit extern "c" function declarations and wrappers
216        for def in &self.fns {
217            // ── Async functions: emit extern + async wrapper, skip _wrap ──
218            if def.is_async {
219                let params_cabi = Self::build_cabi_params(&def.params);
220                let ret_cabi = self.resolve_cabi_ret_type(&def.ret_type);
221
222                // Extern declaration (C ABI symbol defined in Rust)
223                out.push_str(&format!(
224                    "extern \"c\" fn {}({}) callconv(.c) {};\n",
225                    def.c_name, params_cabi, ret_cabi
226                ));
227
228                // Async wrapper function (callable from Zig via host.{name}_async)
229                let ret_type_str = def.ret_type.to_zig_type();
230                let params_zig: Vec<String> = def
231                    .params
232                    .iter()
233                    .map(|(n, t)| format!("{}: {}", n, t.to_zig_type()))
234                    .collect();
235
236                out.push_str(&format!(
237                    "pub fn {}_async(io: Io, {}) !{} {{\n",
238                    def.name,
239                    params_zig.join(", "),
240                    ret_type_str
241                ));
242                out.push_str("    _ = io;\n");
243
244                // Build call args: string params pass .ptr and .len (zero-copy)
245                let call_args = Self::build_call_args(&def.params);
246
247                // Call extern and convert return
248                if let ZigType::NamedStruct(ref zig_name) = def.ret_type {
249                    if let Some(s) = self.structs.iter().find(|s| &s.zig_name == zig_name) {
250                        out.push_str(&format!(
251                            "    const raw = {}({});\n",
252                            def.c_name,
253                            call_args.join(", ")
254                        ));
255                        // Convert string fields: zero-copy ptr+len from Zig Arena
256                        let field_inits: Vec<String> = s
257                            .fields
258                            .iter()
259                            .map(|f| {
260                                if f.zig_type == "[]const u8" {
261                                    format!(
262                                        "    .{} = raw.{}_ptr[0..raw.{}_len]",
263                                        f.name, f.name, f.name
264                                    )
265                                } else {
266                                    format!("    .{} = raw.{}", f.name, f.name)
267                                }
268                            })
269                            .collect();
270                        out.push_str(&format!(
271                            "    return .{{\n{}\n    }};\n",
272                            field_inits.join(",\n")
273                        ));
274                    }
275                } else if def.ret_type == ZigType::Str {
276                    // Zero-copy string return: result is in Zig Arena
277                    out.push_str(&format!(
278                        "    const result = {}({});\n",
279                        def.c_name,
280                        call_args.join(", ")
281                    ));
282                    out.push_str("    return result.toSlice();\n");
283                } else {
284                    out.push_str(&format!(
285                        "    return {}({});\n",
286                        def.c_name,
287                        call_args.join(", ")
288                    ));
289                }
290
291                out.push_str("}\n\n");
292                continue;
293            }
294
295            // ── Sync functions ──
296            let params_cabi = Self::build_cabi_params(&def.params);
297            let ret_cabi = self.resolve_cabi_ret_type(&def.ret_type);
298
299            // Check if this function needs string conversion wrappers
300            let has_string_params = def.params.iter().any(|(_, t)| *t == ZigType::Str);
301            let has_string_return = def.ret_type == ZigType::Str;
302            let is_void = def.ret_type == ZigType::Void;
303
304            let call_args = Self::build_call_args(&def.params);
305
306            // ── String params or return: generate wrapper ──
307            if has_string_params || has_string_return {
308                // Extern declaration with original name (matches Rust symbol)
309                out.push_str(&format!(
310                    "extern \"c\" fn {}({}) callconv(.c) {};\n",
311                    def.c_name, params_cabi, ret_cabi
312                ));
313
314                // Wrapper function with _wrap suffix (Zig-level types)
315                let wrap_name = format!("{}_wrap", def.c_name);
316                let params_zig: Vec<String> = def
317                    .params
318                    .iter()
319                    .map(|(n, t)| format!("{}: {}", n, t.to_zig_type()))
320                    .collect();
321                let ret_zig = def.ret_type.to_zig_type();
322
323                out.push_str(&format!(
324                    "pub fn {}({}) {} {{\n",
325                    wrap_name,
326                    params_zig.join(", "),
327                    ret_zig
328                ));
329
330                // Call extern (zero-copy: pass .ptr/.len, receive StrRet)
331                if has_string_return {
332                    out.push_str(&format!(
333                        "    const result = {}({});\n",
334                        def.c_name,
335                        call_args.join(", ")
336                    ));
337                    out.push_str("    return result.toSlice();\n");
338                } else if is_void {
339                    out.push_str(&format!("    {}({});\n", def.c_name, call_args.join(", ")));
340                } else {
341                    out.push_str(&format!(
342                        "    return {}({});\n",
343                        def.c_name,
344                        call_args.join(", ")
345                    ));
346                }
347
348                out.push_str("}\n\n");
349            } else {
350                // No string conversion needed: direct extern with original name
351                out.push_str(&format!(
352                    "pub extern \"c\" fn {}({}) callconv(.c) {};\n",
353                    def.c_name, params_cabi, ret_cabi
354                ));
355            }
356        }
357
358        // ── Aliases for native_proto emission ──
359        // The Emitter strips the `host_` prefix from host function
360        // calls (e.g. host_add → host.add). Add short-name aliases so that
361        // `host.add(...)` resolves to the correct extern/wrapper function.
362        let has_aliases = self
363            .fns
364            .iter()
365            .any(|f| !f.is_async && f.name.starts_with("host_"));
366        if has_aliases {
367            out.push_str("\n// Aliases for native_proto emission (strips host_ prefix)\n");
368            for def in &self.fns {
369                if def.is_async {
370                    continue; // async aliases are generated in lib.zig
371                }
372                let Some(short) = def.name.strip_prefix("host_") else {
373                    continue;
374                };
375                let has_string = def.params.iter().any(|(_, t)| *t == ZigType::Str)
376                    || def.ret_type == ZigType::Str;
377                if has_string {
378                    out.push_str(&format!("pub const {} = {}_wrap;\n", short, def.name));
379                } else {
380                    out.push_str(&format!("pub const {} = {};\n", short, def.name));
381                }
382            }
383            out.push('\n');
384        }
385
386        out
387    }
388
389    /// Build C ABI parameter list string (expands string params to ptr+len).
390    fn build_cabi_params(params: &[(String, ZigType)]) -> String {
391        let mut parts = Vec::new();
392        for (n, t) in params {
393            for (cabi_name, cabi_type) in Self::get_c_abi_param_types(n, t) {
394                parts.push(format!("{}: {}", cabi_name, cabi_type));
395            }
396        }
397        parts.join(", ")
398    }
399
400    /// Resolve C ABI return type (NamedStruct → C ABI struct name, Str → StrRet).
401    fn resolve_cabi_ret_type(&self, ret_type: &ZigType) -> String {
402        match ret_type {
403            ZigType::NamedStruct(name) => self
404                .structs
405                .iter()
406                .find(|s| &s.zig_name == name)
407                .map(|s| s.c_name.clone())
408                .unwrap_or_else(|| name.clone()),
409            other => Self::get_c_abi_ret_type(other),
410        }
411    }
412
413    /// Build call arguments (string params expand to .ptr/.len for zero-copy).
414    fn build_call_args(params: &[(String, ZigType)]) -> Vec<String> {
415        let mut args = Vec::new();
416        for (n, t) in params {
417            if *t == ZigType::Str {
418                args.push(format!("{}.ptr", n));
419                args.push(format!("{}.len", n));
420            } else {
421                args.push(n.clone());
422            }
423        }
424        args
425    }
426
427    /// Convert a ZigType to the corresponding C ABI type string (for return types).
428    /// String returns use StrRet (zero-copy: memory is in Zig Arena).
429    fn get_c_abi_ret_type(ty: &ZigType) -> String {
430        match ty {
431            ZigType::Str => "StrRet".to_string(),
432            other => other.to_zig_type().into_owned(),
433        }
434    }
435
436    /// Expand a single Zig-level param into one or more C ABI params.
437    /// String params expand to `ptr: [*]const u8, len_name: usize` (zero-copy).
438    /// Other types pass through as-is.
439    fn get_c_abi_param_types(param_name: &str, ty: &ZigType) -> Vec<(String, String)> {
440        match ty {
441            ZigType::Str => vec![
442                (format!("{}_ptr", param_name), "[*]const u8".to_string()),
443                (format!("{}_len", param_name), "usize".to_string()),
444            ],
445            other => vec![(param_name.to_string(), other.to_zig_type().into_owned())],
446        }
447    }
448
449    /// Generate async wrapper functions for all registered async host functions.
450    ///
451    /// **Deprecated**: Async wrappers are now generated in `generate_zig_header()`
452    /// as part of host.zig. This method returns an empty string.
453    pub fn generate_async_wrappers(&self) -> String {
454        String::new()
455    }
456
457    /// Load host function definitions from a JSON config file.
458    ///
459    /// Format:
460    /// ```json
461    /// {
462    ///   "host_functions": [
463    ///     { "name": "hostAdd", "params": [{"name":"a","type":"i64"}], "ret_type": "i64" },
464    ///     { "name": "fetchUser", "c_name": "hostFetchUser",
465    ///       "params": [{"name":"name","type":"string"}],
466    ///       "ret_type": "struct", "ret_struct": "UserInfo", "async": true }
467    ///   ],
468    ///   "host_structs": [
469    ///     { "zig_name": "UserInfo", "c_name": "HostUserInfo",
470    ///       "fields": [{"name":"id","zig_type":"i64","c_type":"i64"}] }
471    ///   ]
472    /// }
473    /// ```
474    pub fn load_from_file(path: &Path) -> Result<Self, String> {
475        let content = std::fs::read_to_string(path)
476            .map_err(|e| format!("cannot read '{}': {}", path.display(), e))?;
477        let json: serde_json::Value = serde_json::from_str(&content)
478            .map_err(|e| format!("invalid JSON in '{}': {}", path.display(), e))?;
479
480        let mut registry = Self::new();
481        let mut struct_map: std::collections::HashMap<String, HostStructDef> =
482            std::collections::HashMap::new();
483
484        // Parse struct definitions first (needed by async functions).
485        // Store in a temporary map; register_async will add them to registry.
486        if let Some(structs) = json["host_structs"].as_array() {
487            for s in structs {
488                let zig_name = s["zig_name"].as_str().ok_or("missing zig_name in struct")?;
489                let c_name = s["c_name"].as_str().ok_or("missing c_name in struct")?;
490                let fields: Vec<HostStructField> = s["fields"]
491                    .as_array()
492                    .ok_or("missing fields array in struct")?
493                    .iter()
494                    .map(|f| {
495                        Ok(HostStructField {
496                            name: f["name"].as_str().ok_or("missing field name")?.into(),
497                            zig_type: f["zig_type"].as_str().ok_or("missing zig_type")?.into(),
498                            c_type: f["c_type"].as_str().ok_or("missing c_type")?.into(),
499                        })
500                    })
501                    .collect::<Result<Vec<_>, &str>>()?;
502                struct_map.insert(
503                    zig_name.to_string(),
504                    HostStructDef {
505                        zig_name: zig_name.into(),
506                        c_name: c_name.into(),
507                        fields,
508                    },
509                );
510            }
511        }
512
513        // Parse function definitions
514        if let Some(fns) = json["host_functions"].as_array() {
515            for f in fns {
516                let name = f["name"].as_str().ok_or("missing name in host function")?;
517                let params: Vec<(String, ZigType)> = f["params"]
518                    .as_array()
519                    .ok_or("missing params array")?
520                    .iter()
521                    .map(|p| {
522                        let n = p["name"].as_str().ok_or("missing param name")?;
523                        let t =
524                            Self::parse_type_str(p["type"].as_str().ok_or("missing param type")?);
525                        Ok((n.into(), t))
526                    })
527                    .collect::<Result<Vec<_>, &str>>()?;
528                let is_async = f["async"].as_bool().unwrap_or(false);
529
530                if is_async {
531                    let c_name = f["c_name"].as_str().ok_or("async fn missing c_name")?;
532                    let ret_struct_name = f["ret_struct"]
533                        .as_str()
534                        .ok_or("async fn missing ret_struct")?;
535                    let ret_struct = struct_map
536                        .get(ret_struct_name)
537                        .cloned()
538                        .ok_or_else(|| format!("undefined struct: {}", ret_struct_name))?;
539                    registry.register_async(name, c_name, params, ret_struct);
540                } else {
541                    let ret_type =
542                        Self::parse_type_str(f["ret_type"].as_str().ok_or("missing ret_type")?);
543                    registry.register(name, params, ret_type);
544                }
545            }
546        }
547
548        Ok(registry)
549    }
550
551    /// Parse a type string from JSON config into ZigType.
552    fn parse_type_str(s: &str) -> ZigType {
553        ZigType::from_zig_str(s)
554    }
555
556    /// Generate JSON metadata for cabi_imports.json (consumed by sys/build.rs).
557    pub fn to_json_value(&self) -> Vec<serde_json::Value> {
558        let mut imports = Vec::new();
559        for def in &self.fns {
560            let params: Vec<serde_json::Value> = def
561                .params
562                .iter()
563                .map(|(n, t)| {
564                    serde_json::json!({
565                        "name": n,
566                        "zig_type": t.to_zig_type() // JSON metadata is consumed by pipeline.rs (lib.zig)
567                    })
568                })
569                .collect();
570            imports.push(serde_json::json!({
571                "name": def.c_name,
572                "params": params,
573                "ret_type": def.ret_type.to_zig_type(), // JSON metadata is consumed by pipeline.rs (lib.zig)
574            }));
575        }
576        imports
577    }
578}
579
580impl Default for HostFnRegistry {
581    fn default() -> Self {
582        Self::new()
583    }
584}