js2zig_core/native_proto/mod.rs
1// js2zig-core/src/native_proto/mod.rs
2//
3// Native-type system codegen module.
4// All Codegen impl methods are in codegen.rs.
5//
6use std::collections::{HashMap, HashSet};
7
8// Strict static type system:
9// - All types must be known at compile time.
10// - No dynamic types (JsAny, Map, etc.).
11// - ComputedMemberExpression (obj[key]) is a compile error.
12// - Array elements must all have the same type.
13// - push() must push the same type as the array element type.
14
15/// C ABI export metadata for a single function.
16/// Used by pipeline.rs to generate C ABI wrappers.
17#[derive(Debug, Clone)]
18pub struct NativeCabiExport {
19 pub name: String,
20 /// (param_name, param_type)
21 pub params: Vec<(String, ZigType)>,
22 pub ret_type: ZigType,
23 /// Whether this is an async export (impl takes io: Io as first param).
24 pub is_async: bool,
25 /// Whether this function can throw (contains throw/try-catch).
26 /// When true, C ABI wrappers generate error propagation (StrRet sign-bit or _err out-param).
27 pub can_throw: bool,
28}
29
30/// Diagnostic severity level.
31#[derive(Debug, Clone, Copy, PartialEq, Eq)]
32pub enum DiagnosticKind {
33 Error,
34 Warning,
35}
36
37/// A single diagnostic message (compile error/warning).
38#[derive(Debug, Clone)]
39pub struct Diagnostic {
40 pub kind: DiagnosticKind,
41 /// (line, col) in JS source — None for non-location errors.
42 pub span: Option<(usize, usize)>,
43 pub message: String,
44}
45
46/// Result of transpiling a JS file to Zig.
47/// Contains the generated Zig source AND metadata needed by the pipeline
48/// (exported functions, diagnostics, etc.).
49#[derive(Debug)]
50pub struct TranspileResult {
51 /// Generated Zig source code.
52 pub zig_code: String,
53 /// Compile errors (type inference failures, etc.).
54 pub errors: Vec<String>,
55 /// Non-fatal warnings (try-catch limitations, etc.) — do NOT block file generation.
56 pub warnings: Vec<String>,
57 /// Exported functions: (name, param_types, return_type).
58 pub exports: Vec<ExportedFunction>,
59 /// Inferred variable types (for cross-file type propagation, future use).
60 pub var_types: std::collections::HashMap<String, ZigType>,
61 /// C ABI exports metadata (for bridge macro to generate Rust FFI bindings).
62 /// Uses `codegen::CabiExport` for compatibility with the pipeline.
63 pub cabi_exports: Vec<NativeCabiExport>,
64}
65
66/// An exported function from a JS file.
67#[derive(Debug, Clone)]
68pub struct ExportedFunction {
69 pub name: String,
70 pub params: Vec<ZigType>,
71 pub return_type: ZigType,
72 /// Whether this function contains throw/try-catch statements.
73 pub can_throw: bool,
74}
75
76/// Zig type representation for type inference.
77/// Only static types are supported; unknown types are compile errors.
78#[derive(Debug, Clone, PartialEq, Eq, Hash)]
79pub enum ZigType {
80 /// No return value
81 Void,
82 /// i64
83 I64,
84 /// f64
85 F64,
86 /// bool
87 Bool,
88 /// []const u8
89 Str,
90 /// std.ArrayList(T) — T must be a static type
91 ArrayList(Box<ZigType>),
92 /// Anonymous struct: .{ .field1 = T1, .field2 = T2 }
93 Struct(Vec<(String, ZigType)>),
94 /// Named struct (defined in HostStructDef, e.g. "UserInfo")
95 NamedStruct(String),
96 /// anytype (for non-export function parameters)
97 Anytype,
98}
99
100impl ZigType {
101 /// Check if this type is compatible with another type for assignment.
102 /// Returns true if assignment is allowed.
103 pub fn is_compatible_with(&self, other: &ZigType) -> bool {
104 match (self, other) {
105 // Same type is always compatible.
106 (a, b) if a == b => true,
107 // I64 can be widened to F64.
108 (ZigType::I64, ZigType::F64) => true,
109 // F64 cannot be narrowed to I64 (would lose precision).
110 (ZigType::F64, ZigType::I64) => false,
111 // Void is only compatible with Void.
112 (ZigType::Void, ZigType::Void) => true,
113 // Otherwise, not compatible.
114 _ => false,
115 }
116 }
117
118 /// Get the Zig type string for code generation.
119 pub fn to_zig_type(&self) -> String {
120 match self {
121 ZigType::Void => "void".to_string(),
122 ZigType::I64 => "i64".to_string(),
123 ZigType::F64 => "f64".to_string(),
124 ZigType::Bool => "bool".to_string(),
125 ZigType::Str => "[]const u8".to_string(),
126 ZigType::ArrayList(inner) => format!("std.ArrayList({})", inner.to_zig_type()),
127 ZigType::Struct(fields) => {
128 // Generate anonymous struct type.
129 let mut s = ".{ ".to_string();
130 for (i, (name, ty)) in fields.iter().enumerate() {
131 if i > 0 {
132 s.push_str(", ");
133 }
134 s.push_str(&format!(".{} = {}", name, ty.to_zig_type()));
135 }
136 s.push_str(" }");
137 s
138 }
139 ZigType::NamedStruct(name) => name.clone(),
140 ZigType::Anytype => "anytype".to_string(),
141 }
142 }
143 /// Get the Zig type string for C ABI wrapper generation.
144 pub fn to_cabi_str(&self) -> String {
145 match self {
146 ZigType::Void => "void".to_string(),
147 ZigType::I64 => "i64".to_string(),
148 ZigType::F64 => "f64".to_string(),
149 ZigType::Bool => "bool".to_string(),
150 ZigType::Str => "StrRet".to_string(), // C ABI: extern struct { ptr, len }
151 ZigType::ArrayList(_) => "std.ArrayList".to_string(), // Not directly supported in C ABI
152 ZigType::Struct(_) => "struct".to_string(), // Anonymous struct - not directly supported in C ABI
153 ZigType::NamedStruct(_) => "struct".to_string(), // Named struct - C ABI name depends on HostStructDef
154 ZigType::Anytype => "i64".to_string(), // Default for anytype (not used in C ABI)
155 }
156 }
157
158 /// Check if this type is a string type (returns StrRet in C ABI).
159 pub fn is_string(&self) -> bool {
160 matches!(self, ZigType::Str)
161 }
162 /// Check if this type is void (no return value).
163 pub fn is_void(&self) -> bool {
164 matches!(self, ZigType::Void)
165 }
166}
167
168/// Convert HostType to ZigType.
169impl From<crate::HostType> for ZigType {
170 fn from(t: crate::HostType) -> Self {
171 match t {
172 crate::HostType::Void => ZigType::Void,
173 crate::HostType::Bool => ZigType::Bool,
174 crate::HostType::I32 => ZigType::I64, // i32 widens to i64
175 crate::HostType::I64 => ZigType::I64,
176 crate::HostType::F64 => ZigType::F64,
177 crate::HostType::Str => ZigType::Str,
178 }
179 }
180}
181
182/// JSDoc 解析结果,传递给 Codegen
183#[derive(Debug, Clone)]
184pub struct JSDocData {
185 /// @typedef 定义:类型名 → TypedefDef
186 pub typedefs: std::collections::HashMap<String, jsdoc::TypedefDef>,
187 /// @type 注解:变量名 → 类型名
188 pub type_annotations: std::collections::HashMap<String, String>,
189 /// @returns 注解:函数名 → 类型名
190 pub return_types: std::collections::HashMap<String, String>,
191 /// @param 注解:函数名 → [(参数名, 类型名)]
192 pub param_types: std::collections::HashMap<String, Vec<(String, String)>>,
193}
194
195use oxc_ast::ast::Program;
196
197mod builtins;
198mod codegen;
199mod infer;
200mod jsdoc;
201#[cfg(test)]
202mod tests;
203
204pub use infer::TypeCheckResult;
205
206/// Transpile JS source text to Zig (native type system).
207///
208/// **New API** — accepts a pre-parsed `&Program` plus the original source text
209/// (needed for JSDoc extraction). The caller should obtain the `Program` from
210/// `analyze_single_group` so that the AST is only built once.
211///
212/// Returns full `TranspileResult` with generated code AND metadata
213/// (exported functions, diagnostics, etc.).
214///
215/// `exported_functions`: Optional set of exported function names.
216/// If provided, only functions in this set generate `pub fn` (export semantics).
217/// If None, treat all toplevel functions as exports (backward compatibility).
218pub fn transpile_js(
219 program: &Program<'_>,
220 js_source: &str,
221 exported_functions: Option<std::collections::HashSet<String>>,
222 host_fns: Option<&crate::host::HostFnRegistry>,
223) -> Result<TranspileResult, String> {
224 transpile_js_inner(program, js_source, exported_functions, host_fns)
225}
226
227/// Internal helper: transpile JS AST to Zig, returning TranspileResult.
228///
229/// Two-pass flow (Phase A):
230/// 1. TypeInferrer::infer_all() — walk AST once, collect all type info
231/// 2. Codegen::generate() — read pre-computed type info, emit Zig code
232fn transpile_js_inner(
233 program: &Program<'_>,
234 js_source: &str,
235 exported_functions: Option<std::collections::HashSet<String>>,
236 host_fns: Option<&crate::host::HostFnRegistry>,
237) -> Result<TranspileResult, String> {
238 // JSDoc extraction (still needs raw source text)
239 let (typedefs, type_annotations, return_types, param_types) =
240 jsdoc::extract_all_jsdoc(js_source);
241 let jsdoc_data = JSDocData {
242 typedefs,
243 type_annotations,
244 return_types,
245 param_types,
246 };
247
248 // ── Pass 1: Type inference ──
249 let mut inferrer = infer::TypeInferrer::new();
250 inferrer.set_jsdoc_data(jsdoc_data.clone());
251 if let Some(hf) = host_fns {
252 inferrer.set_host_fn_types(hf);
253 }
254 let type_info = inferrer.infer_all(program, exported_functions.clone());
255
256 // Extract TypeInferrer errors before type_info is moved to Codegen.
257 let infer_errors = type_info.errors.clone();
258
259 // ── Pass 2: Code generation ──
260 let mut cg = Codegen::new(type_info, jsdoc_data, exported_functions);
261 cg.generate(program);
262
263 // Merge TypeInferrer errors with Codegen errors.
264 let mut combined_errors = infer_errors;
265 combined_errors.append(&mut cg.errors.clone());
266 let warnings = cg.warnings.clone();
267
268 Ok(TranspileResult {
269 zig_code: cg.output,
270 errors: combined_errors,
271 warnings,
272 exports: cg.exported_fns.clone(),
273 var_types: cg.type_info.var_types.clone(),
274 cabi_exports: cg
275 .exported_fns
276 .into_iter()
277 .map(|ef| {
278 let params: Vec<(String, ZigType)> = ef
279 .params
280 .iter()
281 .enumerate()
282 .map(|(i, p)| (format!("arg{}", i), p.clone()))
283 .collect();
284 let is_async = cg.type_info.is_async.get(&ef.name).copied().unwrap_or(false);
285 NativeCabiExport {
286 name: ef.name,
287 params,
288 ret_type: ef.return_type,
289 is_async,
290 can_throw: ef.can_throw,
291 }
292 })
293 .collect(),
294 })
295}
296
297/// Shared state for native-type codegen.
298///
299/// Phase A: Codegen is now purely generative — all type inference runs in
300/// `TypeInferrer::infer_all()` before codegen. `type_info` holds the
301/// pre-computed type snapshot.
302pub struct Codegen {
303 pub output: String,
304 pub indent: usize,
305 /// Compile errors collected during codegen.
306 pub errors: Vec<String>,
307 /// Non-fatal warnings (try-catch limitations, etc.) — do NOT block file generation.
308 pub warnings: Vec<String>,
309 /// Pre-computed type information (read-only during codegen).
310 pub type_info: TypeCheckResult,
311 /// JSDoc data for typedef generation.
312 pub jsdoc_data: Option<JSDocData>,
313 /// Whether the current function being emitted is an export function.
314 pub current_fn_is_export: bool,
315 /// The return type of the current function (derived from type_info).
316 pub current_fn_return_type: Option<ZigType>,
317 /// Exported functions metadata (for pipeline C ABI wrapper generation).
318 pub exported_fns: Vec<ExportedFunction>,
319 /// C ABI exports metadata (for pipeline C ABI wrapper generation).
320 pub cabi_exports: Vec<NativeCabiExport>,
321 /// Task counter for generating unique task variable names in async/await code.
322 pub task_counter: u32,
323 /// Exported function names (from pipeline).
324 pub exported_functions: Option<std::collections::HashSet<String>>,
325 /// Whether a return/throw statement was seen in the current function body.
326 pub seen_return: bool,
327 /// Whether the current function contains `throw` or `try-catch` statements.
328 /// Determined by pre-scan before signature generation. When true, the function
329 /// return type is `!T` (error union) instead of plain `T`.
330 pub fn_has_throw: bool,
331 /// Whether we are currently emitting the return value expression.
332 /// When true, array methods that normally discard with `_ = ` should skip the prefix.
333 pub in_return_expr: bool,
334 /// Whether we are currently emitting the top-level expression of an ExpressionStatement.
335 /// When true, builtins that return non-void values should discard with `_ = `.
336 pub in_expr_stmt: bool,
337 /// Counter for generating unique try-block labels (for nested try-catch).
338 pub try_label_counter: u32,
339 /// Counter for generating unique arrow function names.
340 pub arrow_counter: u32,
341 /// Pending arrow function declarations to be emitted at the top level.
342 pub pending_arrow_fns: Vec<String>,
343 /// When inside a try block, the label name for `break :label`.
344 /// throw statements inside the try block emit `break :label error.JsThrow`
345 /// instead of `return error.JsThrow`.
346 pub inside_try_block: Option<String>,
347 /// Current function name being generated (for function-scoped mutated_vars).
348 pub current_fn: Option<String>,
349 /// Captured variables for the current arrow function: (name, type, is_mutable)
350 pub current_captured: Vec<(String, ZigType, bool)>,
351 /// Map: closure variable name → list of (captured_name, type, is_mutable)
352 /// Used to generate struct instance at assignment and .call() at call site.
353 pub closure_vars: HashMap<String, Vec<(String, ZigType, bool)>>,
354 /// Set of variable names that are closure instances (assigned from arrow functions with captures).
355 /// Used to rewrite `fn(args)` to `fn.call(args)` in emit_call.
356 pub closure_instances: HashSet<String>,
357 /// Closure struct definitions to be prepended to output (module-level).
358 pub closure_defs: Vec<String>,
359 /// Counter for generating unique temp variable names in optional chaining (?.)
360 pub oc_counter: u32,
361 /// Variables initialized with TypedArray constructors (Int32Array, Uint8Array, Float64Array).
362 /// Maps variable name → element Zig type suffix (e.g. "I32", "U8", "F64").
363 /// Used to route method calls and property accesses correctly.
364 pub typedarray_vars: std::collections::HashMap<String, String>,
365}