1use crate::native_proto::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::NamedStruct(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
127 .iter()
128 .filter(|f| f.is_async)
129 .map(|f| f.name.clone())
130 .collect()
131 }
132
133 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 pub fn lookup(&self, name: &str) -> Option<&HostFnDef> {
159 self.fns.iter().find(|f| f.name == name)
160 }
161
162 pub fn iter(&self) -> impl Iterator<Item = &HostFnDef> {
164 self.fns.iter()
165 }
166
167 pub fn sync_fns(&self) -> impl Iterator<Item = &HostFnDef> {
169 self.fns.iter().filter(|f| !f.is_async)
170 }
171
172 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 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 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 for def in &self.fns {
219 if def.is_async {
221 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 out.push_str(&format!(
242 "extern \"c\" fn {}({}) callconv(.c) {};\n",
243 def.c_name,
244 params_cabi,
245 ret_cabi
246 ));
247
248 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 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 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 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 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 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 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 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 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 if has_string_params || has_string_return {
363 out.push_str(&format!(
365 "extern \"c\" fn {}({}) callconv(.c) {};\n",
366 def.c_name,
367 params_cabi,
368 ret_cabi
369 ));
370
371 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 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 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 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; }
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 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 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 pub fn generate_async_wrappers(&self) -> String {
479 String::new()
480 }
481
482 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 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 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 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 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}