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