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 register(&mut self, name: &str, params: Vec<(String, ZigType)>, ret_type: ZigType) {
71 self.fns.push(HostFnDef {
72 name: name.to_string(),
73 c_name: name.to_string(),
74 params,
75 ret_type,
76 is_async: false,
77 });
78 }
79
80 pub fn register_async(
85 &mut self,
86 name: &str,
87 c_name: &str,
88 params: Vec<(String, ZigType)>,
89 ret_struct: HostStructDef,
90 ) {
91 let struct_zig_name = ret_struct.zig_name.clone();
92 self.structs.push(ret_struct);
93 self.fns.push(HostFnDef {
94 name: name.to_string(),
95 c_name: c_name.to_string(),
96 params,
97 ret_type: ZigType::Struct(struct_zig_name),
98 is_async: true,
99 });
100 }
101
102 pub fn lookup(&self, name: &str) -> Option<&HostFnDef> {
104 self.fns.iter().find(|f| f.name == name)
105 }
106
107 pub fn iter(&self) -> impl Iterator<Item = &HostFnDef> {
109 self.fns.iter()
110 }
111
112 pub fn sync_fns(&self) -> impl Iterator<Item = &HostFnDef> {
114 self.fns.iter().filter(|f| !f.is_async)
115 }
116
117 pub fn generate_zig_header(&self) -> String {
126 if self.fns.is_empty() {
127 return String::new();
128 }
129 let mut out = String::new();
130 out.push_str("// Auto-generated host function declarations (Rust via C ABI)\n");
131 out.push_str("// These symbols are defined in Rust with #[no_mangle] pub extern \"C\".\n");
132 out.push_str("// Allocator: uses the global allocator from the runtime.\n");
133 out.push_str("const js_allocator = @import(\"js_runtime/js_allocator.zig\");\n\n");
134
135 for s in &self.structs {
137 out.push_str(&format!("pub const {} = extern struct {{\n", s.c_name));
138 for f in &s.fields {
139 out.push_str(&format!(" {}: {},\n", f.name, f.c_type));
140 }
141 out.push_str("};\n\n");
142 }
143
144 for def in &self.fns {
146 let params_zig: Vec<String> = def
147 .params
148 .iter()
149 .map(|(n, t)| format!("{}: {}", n, Self::to_c_abi_type(t)))
150 .collect();
151 let ret_name = match &def.ret_type {
152 ZigType::Struct(name) => {
153 self.structs
155 .iter()
156 .find(|s| &s.zig_name == name)
157 .map(|s| s.c_name.clone())
158 .unwrap_or_else(|| name.clone())
159 }
160 other => other.to_zig_str(),
161 };
162
163 out.push_str(&format!(
164 "pub extern \"c\" fn {}({}) callconv(.c) {};\n",
165 def.c_name,
166 params_zig.join(", "),
167 ret_name
168 ));
169 }
170 out
171 }
172
173 fn to_c_abi_type(ty: &ZigType) -> String {
175 match ty {
176 ZigType::String => "[*:0]const u8".to_string(),
177 other => other.to_zig_str(),
178 }
179 }
180
181 pub fn generate_async_wrappers(&self) -> String {
189 if !self.fns.iter().any(|f| f.is_async) {
190 return String::new();
191 }
192 let mut out = String::new();
193 out.push_str("// ── Async host function wrappers ──\n\n");
194
195 let mut emitted_structs: std::collections::HashSet<String> = std::collections::HashSet::new();
197
198 for def in &self.fns {
199 if !def.is_async {
200 continue;
201 }
202
203 if let ZigType::Struct(ref zig_name) = def.ret_type
205 && !emitted_structs.contains(zig_name)
206 {
207 emitted_structs.insert(zig_name.clone());
208 if let Some(s) = self.structs.iter().find(|s| &s.zig_name == zig_name) {
209 out.push_str(&format!("pub const {} = struct {{\n", s.zig_name));
210 for f in &s.fields {
211 out.push_str(&format!(" {}: {},\n", f.name, f.zig_type));
212 }
213 out.push_str("};\n\n");
214 }
215 }
216
217 let ret_type_str = def.ret_type.to_zig_str();
219 let params_str: Vec<String> = def
220 .params
221 .iter()
222 .map(|(n, t)| format!("{}: {}", n, t.to_zig_str()))
223 .collect();
224
225 out.push_str(&format!(
226 "fn {}(io: Io, {}) !{} {{\n",
227 def.name,
228 params_str.join(", "),
229 ret_type_str
230 ));
231
232 out.push_str(" _ = io;\n");
234
235 for (pname, ptype) in &def.params {
237 if *ptype == ZigType::String {
238 out.push_str(&format!(
239 " const c_{} = js_allocator.g_alloc().dupeZ(u8, {}) catch return error.OutOfMemory;\n",
240 pname, pname
241 ));
242 }
243 }
244
245 for (pname, ptype) in &def.params {
247 if *ptype == ZigType::String {
248 out.push_str(&format!(" defer js_allocator.g_alloc().free(c_{});\n", pname));
249 }
250 }
251 out.push('\n');
252
253 let call_args: Vec<String> = def
255 .params
256 .iter()
257 .map(|(n, t)| {
258 if *t == ZigType::String {
259 format!("c_{}", n)
260 } else {
261 n.clone()
262 }
263 })
264 .collect();
265
266 if matches!(&def.ret_type, ZigType::Struct(_)) {
268 if let Some(s) = self.structs.iter().find(|s| s.zig_name == ret_type_str) {
270 out.push_str(&format!(
271 " const raw = host.{}({});\n",
272 def.c_name,
273 call_args.join(", ")
274 ));
275
276 for f in &s.fields {
278 if f.zig_type == "[]const u8" {
279 out.push_str(&format!(
281 " const {}_len = std.mem.indexOfScalar(u8, &raw.{}, 0) orelse raw.{}.len;\n",
282 f.name, f.name, f.name
283 ));
284 }
285 }
286
287 let field_inits: Vec<String> = s.fields.iter().map(|f| {
289 if f.zig_type == "[]const u8" {
290 format!(" .{} = raw.{}[0..{}_len]", f.name, f.name, f.name)
291 } else {
292 format!(" .{} = raw.{}", f.name, f.name)
293 }
294 }).collect();
295
296 out.push_str(&format!(
297 " return .{{\n{}\n }};\n",
298 field_inits.join(",\n")
299 ));
300 }
301 } else {
302 out.push_str(&format!(
304 " return host.{}({});\n",
305 def.c_name,
306 call_args.join(", ")
307 ));
308 }
309
310 out.push_str("}\n\n");
311 }
312 out
313 }
314
315 pub fn load_from_file(path: &Path) -> Result<Self, String> {
333 let content = std::fs::read_to_string(path)
334 .map_err(|e| format!("cannot read '{}': {}", path.display(), e))?;
335 let json: serde_json::Value = serde_json::from_str(&content)
336 .map_err(|e| format!("invalid JSON in '{}': {}", path.display(), e))?;
337
338 let mut registry = Self::new();
339 let mut struct_map: std::collections::HashMap<String, HostStructDef> =
340 std::collections::HashMap::new();
341
342 if let Some(structs) = json["host_structs"].as_array() {
345 for s in structs {
346 let zig_name = s["zig_name"].as_str().ok_or("missing zig_name in struct")?;
347 let c_name = s["c_name"].as_str().ok_or("missing c_name in struct")?;
348 let fields: Vec<HostStructField> = s["fields"]
349 .as_array()
350 .ok_or("missing fields array in struct")?
351 .iter()
352 .map(|f| {
353 Ok(HostStructField {
354 name: f["name"].as_str().ok_or("missing field name")?.into(),
355 zig_type: f["zig_type"].as_str().ok_or("missing zig_type")?.into(),
356 c_type: f["c_type"].as_str().ok_or("missing c_type")?.into(),
357 })
358 })
359 .collect::<Result<Vec<_>, &str>>()?;
360 struct_map.insert(
361 zig_name.to_string(),
362 HostStructDef {
363 zig_name: zig_name.into(),
364 c_name: c_name.into(),
365 fields,
366 },
367 );
368 }
369 }
370
371 if let Some(fns) = json["host_functions"].as_array() {
373 for f in fns {
374 let name = f["name"].as_str().ok_or("missing name in host function")?;
375 let params: Vec<(String, ZigType)> = f["params"]
376 .as_array()
377 .ok_or("missing params array")?
378 .iter()
379 .map(|p| {
380 let n = p["name"].as_str().ok_or("missing param name")?;
381 let t = Self::parse_type_str(p["type"].as_str().ok_or("missing param type")?);
382 Ok((n.into(), t))
383 })
384 .collect::<Result<Vec<_>, &str>>()?;
385 let is_async = f["async"].as_bool().unwrap_or(false);
386
387 if is_async {
388 let c_name = f["c_name"].as_str().ok_or("async fn missing c_name")?;
389 let ret_struct_name = f["ret_struct"].as_str().ok_or("async fn missing ret_struct")?;
390 let ret_struct = struct_map
391 .get(ret_struct_name)
392 .cloned()
393 .ok_or_else(|| format!("undefined struct: {}", ret_struct_name))?;
394 registry.register_async(name, c_name, params, ret_struct);
395 } else {
396 let ret_type = Self::parse_type_str(f["ret_type"].as_str().ok_or("missing ret_type")?);
397 registry.register(name, params, ret_type);
398 }
399 }
400 }
401
402 Ok(registry)
403 }
404
405 fn parse_type_str(s: &str) -> ZigType {
407 match s {
408 "i64" => ZigType::I64,
409 "f64" => ZigType::F64,
410 "bool" => ZigType::Bool,
411 "string" => ZigType::String,
412 "any" => ZigType::JsValue,
413 "jsvalue" => ZigType::JsValue,
414 "jsany" => ZigType::JsAny,
415 "void" => ZigType::Void,
416 other if other.starts_with("struct:") => ZigType::Struct(other[7..].into()),
417 _ => ZigType::JsValue,
418 }
419 }
420
421 pub fn to_json_value(&self) -> Vec<serde_json::Value> {
423 let mut imports = Vec::new();
424 for def in &self.fns {
425 let params: Vec<serde_json::Value> = def
426 .params
427 .iter()
428 .map(|(n, t)| {
429 serde_json::json!({
430 "name": n,
431 "zig_type": t.to_zig_str()
432 })
433 })
434 .collect();
435 imports.push(serde_json::json!({
436 "name": def.c_name,
437 "params": params,
438 "ret_type": def.ret_type.to_zig_str(),
439 }));
440 }
441 imports
442 }
443}
444
445impl Default for HostFnRegistry {
446 fn default() -> Self {
447 Self::new()
448 }
449}