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