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