1use crate::infer::ZigType;
13use std::path::Path;
14
15#[derive(Debug, Clone)]
19pub struct HostStructField {
20 pub name: String,
21 pub zig_type: String,
23 pub c_type: String,
25}
26
27#[derive(Debug, Clone)]
29pub struct HostStructDef {
30 pub zig_name: String,
32 pub c_name: String,
34 pub fields: Vec<HostStructField>,
36}
37
38#[derive(Debug, Clone)]
42pub struct HostFnDef {
43 pub name: String,
45 pub c_name: String,
47 pub params: Vec<(String, ZigType)>,
49 pub ret_type: ZigType,
51 pub is_async: bool,
53}
54
55pub 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 pub fn is_empty(&self) -> bool {
71 self.fns.is_empty()
72 }
73
74 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 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 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 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 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 pub fn lookup(&self, name: &str) -> Option<&HostFnDef> {
151 self.fns.iter().find(|f| f.name == name)
152 }
153
154 pub fn iter(&self) -> impl Iterator<Item = &HostFnDef> {
156 self.fns.iter()
157 }
158
159 pub fn sync_fns(&self) -> impl Iterator<Item = &HostFnDef> {
161 self.fns.iter().filter(|f| !f.is_async)
162 }
163
164 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 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 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 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 for def in &self.fns {
218 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 pub fn generate_async_wrappers(&self) -> String {
481 String::new()
482 }
483
484 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 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 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 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 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}