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 `builtins`/`codegen` for translation.
11
12use crate::infer::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    fns: Vec<HostFnDef>,
58    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    /// Register a sync host function that JS code can call directly.
70    pub fn register(&mut self, name: &str, params: Vec<(String, ZigType)>, ret_type: ZigType) {
71        self.fns.push(HostFnDef {
72            name: name.to_string(),
73            c_name: name.to_string(),
74            params,
75            ret_type,
76            is_async: false,
77        });
78    }
79
80    /// Register an async host function that JS code calls with `await`.
81    ///
82    /// The async wrapper `fn {name}(io: Io, ...) !{ret_type}` is generated
83    /// automatically and calls the C ABI function `{c_name}`.
84    pub fn register_async(
85        &mut self,
86        name: &str,
87        c_name: &str,
88        params: Vec<(String, ZigType)>,
89        ret_struct: HostStructDef,
90    ) {
91        let struct_zig_name = ret_struct.zig_name.clone();
92        self.structs.push(ret_struct);
93        self.fns.push(HostFnDef {
94            name: name.to_string(),
95            c_name: c_name.to_string(),
96            params,
97            ret_type: ZigType::Struct(struct_zig_name),
98            is_async: true,
99        });
100    }
101
102    /// Look up a host function by JS name.
103    pub fn lookup(&self, name: &str) -> Option<&HostFnDef> {
104        self.fns.iter().find(|f| f.name == name)
105    }
106
107    /// Iterate over all registered host functions.
108    pub fn iter(&self) -> impl Iterator<Item = &HostFnDef> {
109        self.fns.iter()
110    }
111
112    /// Iterate over only sync host functions (for builtins registration).
113    pub fn sync_fns(&self) -> impl Iterator<Item = &HostFnDef> {
114        self.fns.iter().filter(|f| !f.is_async)
115    }
116
117    /// Generate the Zig `host.zig` file content.
118    ///
119    /// Emits:
120    /// - `extern struct` definitions for C ABI types
121    /// - `extern "c" fn` declarations for C ABI host functions defined in Rust
122    ///
123    /// Note: `zig build test` (standalone Zig tests) may fail to link if test code
124    /// calls host functions. Host-dependent functions are tested via Rust FFI instead.
125    pub fn generate_zig_header(&self) -> String {
126        if self.fns.is_empty() {
127            return String::new();
128        }
129        let mut out = String::new();
130        out.push_str("// Auto-generated host function declarations (Rust via C ABI)\n");
131        out.push_str("// These symbols are defined in Rust with #[no_mangle] pub extern \"C\".\n");
132        out.push_str("// Allocator: uses the global allocator from the runtime.\n");
133        out.push_str("const js_allocator = @import(\"js_runtime/js_allocator.zig\");\n\n");
134
135        // Emit C ABI struct definitions
136        for s in &self.structs {
137            out.push_str(&format!("pub const {} = extern struct {{\n", s.c_name));
138            for f in &s.fields {
139                out.push_str(&format!("    {}: {},\n", f.name, f.c_type));
140            }
141            out.push_str("};\n\n");
142        }
143
144        // Emit extern "c" function declarations
145        for def in &self.fns {
146            let params_zig: Vec<String> = def
147                .params
148                .iter()
149                .map(|(n, t)| format!("{}: {}", n, Self::to_c_abi_type(t)))
150                .collect();
151            let ret_name = match &def.ret_type {
152                ZigType::Struct(name) => {
153                    // Find the matching struct's C name
154                    self.structs
155                        .iter()
156                        .find(|s| &s.zig_name == name)
157                        .map(|s| s.c_name.clone())
158                        .unwrap_or_else(|| name.clone())
159                }
160                other => other.to_zig_str(),
161            };
162
163            out.push_str(&format!(
164                "pub extern \"c\" fn {}({}) callconv(.c) {};\n",
165                def.c_name,
166                params_zig.join(", "),
167                ret_name
168            ));
169        }
170        out
171    }
172
173    /// Convert a ZigType to the corresponding C ABI type string.
174    fn to_c_abi_type(ty: &ZigType) -> String {
175        match ty {
176            ZigType::String => "[*:0]const u8".to_string(),
177            other => other.to_zig_str(),
178        }
179    }
180
181    /// Generate async wrapper functions for all registered async host functions.
182    ///
183    /// These wrappers are emitted into lib.zig alongside the translated JS code.
184    /// Each wrapper:
185    /// 1. Converts JS-level params to C ABI params (null-terminated strings)
186    /// 2. Calls the C ABI function
187    /// 3. Converts the C ABI return struct to a clean Zig struct
188    pub fn generate_async_wrappers(&self) -> String {
189        if !self.fns.iter().any(|f| f.is_async) {
190            return String::new();
191        }
192        let mut out = String::new();
193        out.push_str("// ── Async host function wrappers ──\n\n");
194
195        // Collect unique struct defs used by async wrappers
196        let mut emitted_structs: std::collections::HashSet<String> = std::collections::HashSet::new();
197
198        for def in &self.fns {
199            if !def.is_async {
200                continue;
201            }
202
203            // Emit clean Zig struct definition
204            if let ZigType::Struct(ref zig_name) = def.ret_type
205                && !emitted_structs.contains(zig_name)
206            {
207                emitted_structs.insert(zig_name.clone());
208                if let Some(s) = self.structs.iter().find(|s| &s.zig_name == zig_name) {
209                    out.push_str(&format!("pub const {} = struct {{\n", s.zig_name));
210                    for f in &s.fields {
211                        out.push_str(&format!("    {}: {},\n", f.name, f.zig_type));
212                    }
213                    out.push_str("};\n\n");
214                }
215            }
216
217            // Generate async wrapper function
218            let ret_type_str = def.ret_type.to_zig_str();
219            let params_str: Vec<String> = def
220                .params
221                .iter()
222                .map(|(n, t)| format!("{}: {}", n, t.to_zig_str()))
223                .collect();
224
225            out.push_str(&format!(
226                "fn {}(io: Io, {}) !{} {{\n",
227                def.name,
228                params_str.join(", "),
229                ret_type_str
230            ));
231
232            // Emit body
233            out.push_str("    _ = io;\n");
234
235            // Convert string params to null-terminated C strings
236            for (pname, ptype) in &def.params {
237                if *ptype == ZigType::String {
238                    out.push_str(&format!(
239                        "    const c_{} = js_allocator.g_alloc().dupeZ(u8, {}) catch return error.OutOfMemory;\n",
240                        pname, pname
241                    ));
242                }
243            }
244
245            // Defer-free string params
246            for (pname, ptype) in &def.params {
247                if *ptype == ZigType::String {
248                    out.push_str(&format!("    defer js_allocator.g_alloc().free(c_{});\n", pname));
249                }
250            }
251            out.push('\n');
252
253            // Call C ABI function
254            let call_args: Vec<String> = def
255                .params
256                .iter()
257                .map(|(n, t)| {
258                    if *t == ZigType::String {
259                        format!("c_{}", n)
260                    } else {
261                        n.clone()
262                    }
263                })
264                .collect();
265
266            // Build the call and conversion
267            if matches!(&def.ret_type, ZigType::Struct(_)) {
268                // Return struct: call C function, convert to clean struct
269                if let Some(s) = self.structs.iter().find(|s| s.zig_name == ret_type_str) {
270                    out.push_str(&format!(
271                        "    const raw = host.{}({});\n",
272                        def.c_name,
273                        call_args.join(", ")
274                    ));
275
276                    // Convert each string field from C buffer to []const u8
277                    for f in &s.fields {
278                        if f.zig_type == "[]const u8" {
279                            // Need to find null terminator in fixed buffer
280                            out.push_str(&format!(
281                                "    const {}_len = std.mem.indexOfScalar(u8, &raw.{}, 0) orelse raw.{}.len;\n",
282                                f.name, f.name, f.name
283                            ));
284                        }
285                    }
286
287                    // Build return struct
288                    let field_inits: Vec<String> = s.fields.iter().map(|f| {
289                        if f.zig_type == "[]const u8" {
290                            format!("    .{} = raw.{}[0..{}_len]", f.name, f.name, f.name)
291                        } else {
292                            format!("    .{} = raw.{}", f.name, f.name)
293                        }
294                    }).collect();
295
296                    out.push_str(&format!(
297                        "    return .{{\n{}\n    }};\n",
298                        field_inits.join(",\n")
299                    ));
300                }
301            } else {
302                // Simple return type
303                out.push_str(&format!(
304                    "    return host.{}({});\n",
305                    def.c_name,
306                    call_args.join(", ")
307                ));
308            }
309
310            out.push_str("}\n\n");
311        }
312        out
313    }
314
315    /// Load host function definitions from a JSON config file.
316    ///
317    /// Format:
318    /// ```json
319    /// {
320    ///   "host_functions": [
321    ///     { "name": "hostAdd", "params": [{"name":"a","type":"i64"}], "ret_type": "i64" },
322    ///     { "name": "fetchUser", "c_name": "hostFetchUser",
323    ///       "params": [{"name":"name","type":"string"}],
324    ///       "ret_type": "struct", "ret_struct": "UserInfo", "async": true }
325    ///   ],
326    ///   "host_structs": [
327    ///     { "zig_name": "UserInfo", "c_name": "HostUserInfo",
328    ///       "fields": [{"name":"id","zig_type":"i64","c_type":"i64"}] }
329    ///   ]
330    /// }
331    /// ```
332    pub fn load_from_file(path: &Path) -> Result<Self, String> {
333        let content = std::fs::read_to_string(path)
334            .map_err(|e| format!("cannot read '{}': {}", path.display(), e))?;
335        let json: serde_json::Value = serde_json::from_str(&content)
336            .map_err(|e| format!("invalid JSON in '{}': {}", path.display(), e))?;
337
338        let mut registry = Self::new();
339        let mut struct_map: std::collections::HashMap<String, HostStructDef> =
340            std::collections::HashMap::new();
341
342        // Parse struct definitions first (needed by async functions).
343        // Store in a temporary map; register_async will add them to registry.
344        if let Some(structs) = json["host_structs"].as_array() {
345            for s in structs {
346                let zig_name = s["zig_name"].as_str().ok_or("missing zig_name in struct")?;
347                let c_name = s["c_name"].as_str().ok_or("missing c_name in struct")?;
348                let fields: Vec<HostStructField> = s["fields"]
349                    .as_array()
350                    .ok_or("missing fields array in struct")?
351                    .iter()
352                    .map(|f| {
353                        Ok(HostStructField {
354                            name: f["name"].as_str().ok_or("missing field name")?.into(),
355                            zig_type: f["zig_type"].as_str().ok_or("missing zig_type")?.into(),
356                            c_type: f["c_type"].as_str().ok_or("missing c_type")?.into(),
357                        })
358                    })
359                    .collect::<Result<Vec<_>, &str>>()?;
360                struct_map.insert(
361                    zig_name.to_string(),
362                    HostStructDef {
363                        zig_name: zig_name.into(),
364                        c_name: c_name.into(),
365                        fields,
366                    },
367                );
368            }
369        }
370
371        // Parse function definitions
372        if let Some(fns) = json["host_functions"].as_array() {
373            for f in fns {
374                let name = f["name"].as_str().ok_or("missing name in host function")?;
375                let params: Vec<(String, ZigType)> = f["params"]
376                    .as_array()
377                    .ok_or("missing params array")?
378                    .iter()
379                    .map(|p| {
380                        let n = p["name"].as_str().ok_or("missing param name")?;
381                        let t = Self::parse_type_str(p["type"].as_str().ok_or("missing param type")?);
382                        Ok((n.into(), t))
383                    })
384                    .collect::<Result<Vec<_>, &str>>()?;
385                let is_async = f["async"].as_bool().unwrap_or(false);
386
387                if is_async {
388                    let c_name = f["c_name"].as_str().ok_or("async fn missing c_name")?;
389                    let ret_struct_name = f["ret_struct"].as_str().ok_or("async fn missing ret_struct")?;
390                    let ret_struct = struct_map
391                        .get(ret_struct_name)
392                        .cloned()
393                        .ok_or_else(|| format!("undefined struct: {}", ret_struct_name))?;
394                    registry.register_async(name, c_name, params, ret_struct);
395                } else {
396                    let ret_type = Self::parse_type_str(f["ret_type"].as_str().ok_or("missing ret_type")?);
397                    registry.register(name, params, ret_type);
398                }
399            }
400        }
401
402        Ok(registry)
403    }
404
405    /// Parse a type string from JSON config into ZigType.
406    fn parse_type_str(s: &str) -> ZigType {
407        match s {
408            "i64" => ZigType::I64,
409            "f64" => ZigType::F64,
410            "bool" => ZigType::Bool,
411            "string" => ZigType::String,
412            "any" => ZigType::JsValue,
413            "jsvalue" => ZigType::JsValue,
414            "jsany" => ZigType::JsAny,
415            "void" => ZigType::Void,
416            other if other.starts_with("struct:") => ZigType::Struct(other[7..].into()),
417            _ => ZigType::JsValue,
418        }
419    }
420
421    /// Generate JSON metadata for cabi_imports.json (consumed by sys/build.rs).
422    pub fn to_json_value(&self) -> Vec<serde_json::Value> {
423        let mut imports = Vec::new();
424        for def in &self.fns {
425            let params: Vec<serde_json::Value> = def
426                .params
427                .iter()
428                .map(|(n, t)| {
429                    serde_json::json!({
430                        "name": n,
431                        "zig_type": t.to_zig_str()
432                    })
433                })
434                .collect();
435            imports.push(serde_json::json!({
436                "name": def.c_name,
437                "params": params,
438                "ret_type": def.ret_type.to_zig_str(),
439            }));
440        }
441        imports
442    }
443}
444
445impl Default for HostFnRegistry {
446    fn default() -> Self {
447        Self::new()
448    }
449}