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