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    /// 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::Struct(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.iter().filter(|f| f.is_async).map(|f| f.name.clone()).collect()
127    }
128
129    /// Return struct field types for all registered host structs.
130    /// Key: Zig struct name, Value: Vec<(field_name, field_zig_type)>
131    pub fn struct_fields_map(&self) -> std::collections::HashMap<String, Vec<(String, ZigType)>> {
132        let mut map = std::collections::HashMap::new();
133        for s in &self.structs {
134            let fields: Vec<(String, ZigType)> = s.fields.iter().map(|f| {
135                let zig_type = match f.zig_type.as_str() {
136                    "i64" | "i32" => ZigType::I64,
137                    "f64" => ZigType::F64,
138                    "bool" => ZigType::Bool,
139                    "[]const u8" => ZigType::String,
140                    _ => ZigType::JsValue,
141                };
142                (f.name.clone(), zig_type)
143            }).collect();
144            map.insert(s.zig_name.clone(), fields);
145        }
146        map
147    }
148
149    /// Look up a host function by JS name.
150    pub fn lookup(&self, name: &str) -> Option<&HostFnDef> {
151        self.fns.iter().find(|f| f.name == name)
152    }
153
154    /// Iterate over all registered host functions.
155    pub fn iter(&self) -> impl Iterator<Item = &HostFnDef> {
156        self.fns.iter()
157    }
158
159    /// Iterate over only sync host functions (for builtins registration).
160    pub fn sync_fns(&self) -> impl Iterator<Item = &HostFnDef> {
161        self.fns.iter().filter(|f| !f.is_async)
162    }
163
164    /// Generate the Zig `host.zig` file content.
165    ///
166    /// Emits:
167    /// - `extern struct` definitions for C ABI types
168    /// - `extern "c" fn` declarations for C ABI host functions defined in Rust
169    /// - Wrapper functions for string params/returns (converts `[]const u8` ↔ `[*:0]const u8`)
170    ///
171    /// For functions with string parameters or string return types, a `_cabi` extern
172    /// declaration is emitted alongside a wrapper function with the original name.
173    /// The wrapper converts Zig-level `[]const u8` to null-terminated `[*:0]const u8`
174    /// via `dupeZ`, and converts the return value back via `std.mem.span`.
175    ///
176    /// Note: `zig build test` (standalone Zig tests) may fail to link if test code
177    /// calls host functions. Host-dependent functions are tested via Rust FFI instead.
178    pub fn generate_zig_header(&self) -> String {
179        if self.fns.is_empty() {
180            return String::new();
181        }
182        let mut out = String::new();
183        out.push_str("// Auto-generated host function declarations (Rust via C ABI)\n");
184        out.push_str("// These symbols are defined in Rust with #[no_mangle] pub extern \"C\".\n");
185        out.push_str("// Allocator: uses the global allocator from the runtime.\n");
186        out.push_str("const std = @import(\"std\");\n");
187        out.push_str("const Io = std.Io;\n");
188        out.push_str("const js_allocator = @import(\"js_runtime/js_allocator.zig\");\n\n");
189
190        // Emit C ABI struct definitions (extern structs)
191        for s in &self.structs {
192            out.push_str(&format!("pub const {} = extern struct {{\n", s.c_name));
193            for f in &s.fields {
194                out.push_str(&format!("    {}: {},\n", f.name, f.c_type));
195            }
196            out.push_str("};\n\n");
197        }
198
199        // Emit clean Zig struct definitions (for async wrapper return types)
200        for s in &self.structs {
201            out.push_str(&format!("pub const {} = struct {{\n", s.zig_name));
202            for f in &s.fields {
203                out.push_str(&format!("    {}: {},\n", f.name, f.zig_type));
204            }
205            out.push_str("};\n\n");
206        }
207
208        // Emit host_free declaration if any function returns a string
209        // (needed to free Rust-allocated string memory after copying to Zig allocator)
210        let has_string_return_fn = self.fns.iter().any(|f| f.ret_type == ZigType::String);
211        if has_string_return_fn {
212            out.push_str("// Free string memory allocated by Rust (CString::into_raw)\n");
213            out.push_str("extern \"c\" fn host_free(ptr: ?*anyopaque) callconv(.c) void;\n\n");
214        }
215
216        // Emit extern "c" function declarations and wrappers
217        for def in &self.fns {
218            // ── Async functions: emit extern + async wrapper, skip _wrap ──
219            if def.is_async {
220                let params_cabi: Vec<String> = def
221                    .params
222                    .iter()
223                    .map(|(n, t)| format!("{}: {}", n, Self::to_c_abi_type(t)))
224                    .collect();
225
226                let ret_cabi = match &def.ret_type {
227                    ZigType::Struct(name) => {
228                        self.structs
229                            .iter()
230                            .find(|s| &s.zig_name == name)
231                            .map(|s| s.c_name.clone())
232                            .unwrap_or_else(|| name.clone())
233                    }
234                    other => Self::to_c_abi_type(other),
235                };
236
237                // Extern declaration (C ABI symbol defined in Rust)
238                out.push_str(&format!(
239                    "extern \"c\" fn {}({}) callconv(.c) {};\n",
240                    def.c_name,
241                    params_cabi.join(", "),
242                    ret_cabi
243                ));
244
245                // Async wrapper function (callable from Zig via host.{name}_async)
246                let ret_type_str = def.ret_type.to_zig_str();
247                let params_zig: Vec<String> = def
248                    .params
249                    .iter()
250                    .map(|(n, t)| format!("{}: {}", n, t.to_zig_str()))
251                    .collect();
252
253                out.push_str(&format!(
254                    "pub fn {}_async(io: Io, {}) !{} {{\n",
255                    def.name,
256                    params_zig.join(", "),
257                    ret_type_str
258                ));
259                out.push_str("    _ = io;\n");
260
261                // Convert string params to null-terminated C strings
262                for (pname, ptype) in &def.params {
263                    if *ptype == ZigType::String {
264                        out.push_str(&format!(
265                            "    const c_{} = js_allocator.g_alloc().dupeZ(u8, {}) catch return error.OutOfMemory;\n",
266                            pname, pname
267                        ));
268                    }
269                }
270                for (pname, ptype) in &def.params {
271                    if *ptype == ZigType::String {
272                        out.push_str(&format!("    defer js_allocator.g_alloc().free(c_{});\n", pname));
273                    }
274                }
275                if def.params.iter().any(|(_, t)| *t == ZigType::String) {
276                    out.push('\n');
277                }
278
279                // Build call args (string params use c_ prefix)
280                let call_args: Vec<String> = def
281                    .params
282                    .iter()
283                    .map(|(n, t)| {
284                        if *t == ZigType::String {
285                            format!("c_{}", n)
286                        } else {
287                            n.clone()
288                        }
289                    })
290                    .collect();
291
292                // Call extern and convert return
293                if let ZigType::Struct(ref zig_name) = def.ret_type {
294                    if let Some(s) = self.structs.iter().find(|s| &s.zig_name == zig_name) {
295                        out.push_str(&format!(
296                            "    const raw = {}({});\n",
297                            def.c_name,
298                            call_args.join(", ")
299                        ));
300                        // Convert string fields from fixed buffer to []const u8
301                        for f in &s.fields {
302                            if f.zig_type == "[]const u8" {
303                                out.push_str(&format!(
304                                    "    const {}_len = std.mem.indexOfScalar(u8, &raw.{}, 0) orelse raw.{}.len;\n",
305                                    f.name, f.name, f.name
306                                ));
307                            }
308                        }
309                        let field_inits: Vec<String> = s.fields.iter().map(|f| {
310                            if f.zig_type == "[]const u8" {
311                                format!("    .{} = js_allocator.g_alloc().dupe(u8, raw.{}[0..{}_len]) catch return error.OutOfMemory", f.name, f.name, f.name)
312                            } else {
313                                format!("    .{} = raw.{}", f.name, f.name)
314                            }
315                        }).collect();
316                        out.push_str(&format!(
317                            "    return .{{\n{}\n    }};\n",
318                            field_inits.join(",\n")
319                        ));
320                    }
321                } else {
322                    out.push_str(&format!(
323                        "    return {}({});\n",
324                        def.c_name,
325                        call_args.join(", ")
326                    ));
327                }
328
329                out.push_str("}\n\n");
330                continue;
331            }
332
333            // ── Sync functions: existing logic ──
334            let params_cabi: Vec<String> = def
335                .params
336                .iter()
337                .map(|(n, t)| format!("{}: {}", n, Self::to_c_abi_type(t)))
338                .collect();
339
340            // Return type in C ABI representation
341            let ret_cabi = match &def.ret_type {
342                ZigType::Struct(name) => {
343                    self.structs
344                        .iter()
345                        .find(|s| &s.zig_name == name)
346                        .map(|s| s.c_name.clone())
347                        .unwrap_or_else(|| name.clone())
348                }
349                other => Self::to_c_abi_type(other),
350            };
351
352            // Check if this function needs string conversion wrappers
353            let has_string_params = def.params.iter().any(|(_, t)| *t == ZigType::String);
354            let has_string_return = def.ret_type == ZigType::String;
355
356            if has_string_params || has_string_return {
357                // Extern declaration with original name (matches Rust symbol)
358                out.push_str(&format!(
359                    "extern \"c\" fn {}({}) callconv(.c) {};\n",
360                    def.c_name,
361                    params_cabi.join(", "),
362                    ret_cabi
363                ));
364
365                // Wrapper function with _wrap suffix (Zig-level types)
366                let wrap_name = format!("{}_wrap", def.c_name);
367                let params_zig: Vec<String> = def
368                    .params
369                    .iter()
370                    .map(|(n, t)| format!("{}: {}", n, t.to_zig_str()))
371                    .collect();
372                let ret_zig = def.ret_type.to_zig_str();
373                let catch_default = Self::default_return_value(&def.ret_type);
374
375                out.push_str(&format!(
376                    "pub fn {}({}) {} {{\n",
377                    wrap_name,
378                    params_zig.join(", "),
379                    ret_zig
380                ));
381
382                // Convert string params to null-terminated C strings
383                let is_void = def.ret_type == ZigType::Void;
384                for (pname, ptype) in &def.params {
385                    if *ptype == ZigType::String {
386                        if is_void {
387                            out.push_str(&format!(
388                                "    const c_{} = js_allocator.g_alloc().dupeZ(u8, {}) catch return;\n",
389                                pname, pname
390                            ));
391                        } else {
392                            out.push_str(&format!(
393                                "    const c_{} = js_allocator.g_alloc().dupeZ(u8, {}) catch return {};\n",
394                                pname, pname, catch_default
395                            ));
396                        }
397                        out.push_str(&format!(
398                            "    defer js_allocator.g_alloc().free(c_{});\n",
399                            pname
400                        ));
401                    }
402                }
403
404                // Build call args (string params use c_ prefix)
405                let call_args: Vec<String> = def
406                    .params
407                    .iter()
408                    .map(|(n, t)| {
409                        if *t == ZigType::String {
410                            format!("c_{}", n)
411                        } else {
412                            n.clone()
413                        }
414                    })
415                    .collect();
416
417                // Call extern and convert return if needed
418                if has_string_return {
419                    out.push_str(&format!(
420                        "    const raw = {}({});\n",
421                        def.c_name,
422                        call_args.join(", ")
423                    ));
424                    out.push_str("    const span = std.mem.span(raw);\n");
425                    out.push_str("    const owned = js_allocator.g_alloc().dupe(u8, span) catch return \"\";\n");
426                    out.push_str("    host_free(@ptrCast(@constCast(raw)));\n");
427                    out.push_str("    return owned;\n");
428                } else if is_void {
429                    out.push_str(&format!(
430                        "    {}({});\n",
431                        def.c_name,
432                        call_args.join(", ")
433                    ));
434                } else {
435                    out.push_str(&format!(
436                        "    return {}({});\n",
437                        def.c_name,
438                        call_args.join(", ")
439                    ));
440                }
441
442                out.push_str("}\n\n");
443            } else {
444                // No string conversion needed: direct extern with original name
445                out.push_str(&format!(
446                    "pub extern \"c\" fn {}({}) callconv(.c) {};\n",
447                    def.c_name,
448                    params_cabi.join(", "),
449                    ret_cabi
450                ));
451            }
452        }
453        out
454    }
455
456    /// Return the default value literal for a ZigType (used in `catch return <default>`).
457    fn default_return_value(ret_type: &ZigType) -> &'static str {
458        match ret_type {
459            ZigType::String => "\"\"",
460            ZigType::I64 | ZigType::I32 | ZigType::Usize => "0",
461            ZigType::F64 => "0.0",
462            ZigType::Bool => "false",
463            ZigType::Void => "",
464            _ => "null",
465        }
466    }
467
468    /// Convert a ZigType to the corresponding C ABI type string.
469    fn to_c_abi_type(ty: &ZigType) -> String {
470        match ty {
471            ZigType::String => "[*:0]const u8".to_string(),
472            other => other.to_zig_str(),
473        }
474    }
475
476    /// Generate async wrapper functions for all registered async host functions.
477    ///
478    /// **Deprecated**: Async wrappers are now generated in `generate_zig_header()`
479    /// as part of host.zig. This method returns an empty string.
480    pub fn generate_async_wrappers(&self) -> String {
481        String::new()
482    }
483
484    /// Load host function definitions from a JSON config file.
485    ///
486    /// Format:
487    /// ```json
488    /// {
489    ///   "host_functions": [
490    ///     { "name": "hostAdd", "params": [{"name":"a","type":"i64"}], "ret_type": "i64" },
491    ///     { "name": "fetchUser", "c_name": "hostFetchUser",
492    ///       "params": [{"name":"name","type":"string"}],
493    ///       "ret_type": "struct", "ret_struct": "UserInfo", "async": true }
494    ///   ],
495    ///   "host_structs": [
496    ///     { "zig_name": "UserInfo", "c_name": "HostUserInfo",
497    ///       "fields": [{"name":"id","zig_type":"i64","c_type":"i64"}] }
498    ///   ]
499    /// }
500    /// ```
501    pub fn load_from_file(path: &Path) -> Result<Self, String> {
502        let content = std::fs::read_to_string(path)
503            .map_err(|e| format!("cannot read '{}': {}", path.display(), e))?;
504        let json: serde_json::Value = serde_json::from_str(&content)
505            .map_err(|e| format!("invalid JSON in '{}': {}", path.display(), e))?;
506
507        let mut registry = Self::new();
508        let mut struct_map: std::collections::HashMap<String, HostStructDef> =
509            std::collections::HashMap::new();
510
511        // Parse struct definitions first (needed by async functions).
512        // Store in a temporary map; register_async will add them to registry.
513        if let Some(structs) = json["host_structs"].as_array() {
514            for s in structs {
515                let zig_name = s["zig_name"].as_str().ok_or("missing zig_name in struct")?;
516                let c_name = s["c_name"].as_str().ok_or("missing c_name in struct")?;
517                let fields: Vec<HostStructField> = s["fields"]
518                    .as_array()
519                    .ok_or("missing fields array in struct")?
520                    .iter()
521                    .map(|f| {
522                        Ok(HostStructField {
523                            name: f["name"].as_str().ok_or("missing field name")?.into(),
524                            zig_type: f["zig_type"].as_str().ok_or("missing zig_type")?.into(),
525                            c_type: f["c_type"].as_str().ok_or("missing c_type")?.into(),
526                        })
527                    })
528                    .collect::<Result<Vec<_>, &str>>()?;
529                struct_map.insert(
530                    zig_name.to_string(),
531                    HostStructDef {
532                        zig_name: zig_name.into(),
533                        c_name: c_name.into(),
534                        fields,
535                    },
536                );
537            }
538        }
539
540        // Parse function definitions
541        if let Some(fns) = json["host_functions"].as_array() {
542            for f in fns {
543                let name = f["name"].as_str().ok_or("missing name in host function")?;
544                let params: Vec<(String, ZigType)> = f["params"]
545                    .as_array()
546                    .ok_or("missing params array")?
547                    .iter()
548                    .map(|p| {
549                        let n = p["name"].as_str().ok_or("missing param name")?;
550                        let t = Self::parse_type_str(p["type"].as_str().ok_or("missing param type")?);
551                        Ok((n.into(), t))
552                    })
553                    .collect::<Result<Vec<_>, &str>>()?;
554                let is_async = f["async"].as_bool().unwrap_or(false);
555
556                if is_async {
557                    let c_name = f["c_name"].as_str().ok_or("async fn missing c_name")?;
558                    let ret_struct_name = f["ret_struct"].as_str().ok_or("async fn missing ret_struct")?;
559                    let ret_struct = struct_map
560                        .get(ret_struct_name)
561                        .cloned()
562                        .ok_or_else(|| format!("undefined struct: {}", ret_struct_name))?;
563                    registry.register_async(name, c_name, params, ret_struct);
564                } else {
565                    let ret_type = Self::parse_type_str(f["ret_type"].as_str().ok_or("missing ret_type")?);
566                    registry.register(name, params, ret_type);
567                }
568            }
569        }
570
571        Ok(registry)
572    }
573
574    /// Parse a type string from JSON config into ZigType.
575    fn parse_type_str(s: &str) -> ZigType {
576        match s {
577            "i64" => ZigType::I64,
578            "f64" => ZigType::F64,
579            "bool" => ZigType::Bool,
580            "string" => ZigType::String,
581            "any" => ZigType::JsValue,
582            "jsvalue" => ZigType::JsValue,
583            "jsany" => ZigType::JsAny,
584            "void" => ZigType::Void,
585            other if other.starts_with("struct:") => ZigType::Struct(other[7..].into()),
586            _ => ZigType::JsValue,
587        }
588    }
589
590    /// Generate JSON metadata for cabi_imports.json (consumed by sys/build.rs).
591    pub fn to_json_value(&self) -> Vec<serde_json::Value> {
592        let mut imports = Vec::new();
593        for def in &self.fns {
594            let params: Vec<serde_json::Value> = def
595                .params
596                .iter()
597                .map(|(n, t)| {
598                    serde_json::json!({
599                        "name": n,
600                        "zig_type": t.to_zig_str()
601                    })
602                })
603                .collect();
604            imports.push(serde_json::json!({
605                "name": def.c_name,
606                "params": params,
607                "ret_type": def.ret_type.to_zig_str(),
608            }));
609        }
610        imports
611    }
612}
613
614impl Default for HostFnRegistry {
615    fn default() -> Self {
616        Self::new()
617    }
618}