js2zig_core/native_proto.rs
1// js2zig-core/src/native_proto.rs
2//
3// Native-type system codegen module.
4// Codegen impl methods are in codegen/; type inference in infer/.
5use std::collections::{HashMap, HashSet};
6
7// Strict static type system:
8// - All types must be known at compile time.
9// - No dynamic types (JsAny, Map, etc.).
10// - ComputedMemberExpression (obj[key]) is a compile error.
11// - Array elements must all have the same type.
12// - push() must push the same type as the array element type.
13
14/// C ABI export metadata for a single function.
15/// Used by pipeline.rs to generate C ABI wrappers.
16#[derive(Debug, Clone)]
17pub struct NativeCabiExport {
18 pub name: String,
19 /// (param_name, param_type)
20 pub params: Vec<(String, ZigType)>,
21 pub ret_type: ZigType,
22 /// Whether this is an async export (impl takes io: Io as first param).
23 pub is_async: bool,
24 /// Whether this function can throw (contains throw/try-catch).
25 /// When true, C ABI wrappers generate error propagation (StrRet sign-bit or _err out-param).
26 pub can_throw: bool,
27 /// For async functions returning a struct: the struct name (e.g., "FetchUserResult").
28 /// Set when `ret_type` is `ZigType::NamedStruct(name)`.
29 pub ret_struct_name: Option<String>,
30 /// For async functions returning a struct: the struct fields as (name, zig_type) pairs.
31 /// Used by js2rust-bridge-macro to generate the #[repr(C)] struct.
32 pub ret_struct_fields: Option<Vec<(String, String)>>,
33}
34
35/// Diagnostic severity level.
36#[derive(Debug, Clone, Copy, PartialEq, Eq)]
37pub enum DiagnosticKind {
38 Error,
39 Warning,
40}
41
42/// A single diagnostic message (compile error/warning).
43#[derive(Debug, Clone)]
44pub struct Diagnostic {
45 pub kind: DiagnosticKind,
46 /// (line, col) in JS source — None for non-location errors.
47 pub span: Option<(usize, usize)>,
48 pub message: String,
49}
50
51/// Result of transpiling a JS file to Zig.
52/// Contains the generated Zig source AND metadata needed by the pipeline
53/// (exported functions, diagnostics, etc.).
54#[derive(Debug)]
55pub struct TranspileResult {
56 /// Generated Zig source code.
57 pub zig_code: String,
58 /// Compile errors (type inference failures, etc.).
59 pub errors: Vec<String>,
60 /// Non-fatal warnings (try-catch limitations, etc.) — do NOT block file generation.
61 pub warnings: Vec<String>,
62 /// Exported functions: (name, param_types, return_type).
63 pub exports: Vec<ExportedFunction>,
64 /// Inferred variable types (for cross-file type propagation, future use).
65 pub var_types: std::collections::HashMap<String, ZigType>,
66 /// C ABI exports metadata (for bridge macro to generate Rust FFI bindings).
67 /// Uses `codegen::CabiExport` for compatibility with the pipeline.
68 pub cabi_exports: Vec<NativeCabiExport>,
69}
70
71/// An exported function from a JS file.
72#[derive(Debug, Clone)]
73pub struct ExportedFunction {
74 pub name: String,
75 pub params: Vec<ZigType>,
76 pub return_type: ZigType,
77 /// Whether this function contains throw/try-catch statements.
78 pub can_throw: bool,
79}
80
81/// Zig type representation for type inference.
82/// Only static types are supported; unknown types are compile errors.
83#[derive(Debug, Clone, PartialEq, Eq, Hash)]
84pub enum ZigType {
85 /// No return value
86 Void,
87 /// i64
88 I64,
89 /// f64
90 F64,
91 /// bool
92 Bool,
93 /// []const u8
94 Str,
95 /// std.ArrayList(T) — T must be a static type
96 ArrayList(Box<ZigType>),
97 /// Anonymous struct: .{ .field1 = T1, .field2 = T2 }
98 Struct(Vec<(String, ZigType)>),
99 /// Named struct referenced by name. Covers four sources:
100 /// - Host-defined structs (via `HostStructDef`, e.g. `"UserInfo"`)
101 /// - Built-in runtime types (`"Map"`, `"Set"`, `"Date"`)
102 /// - User-defined JS classes (e.g. `"MyClass"`)
103 /// - JSDoc `@typedef` types (e.g. `"User"`, `"Point"`)
104 NamedStruct(String),
105 /// anytype (for non-export function parameters)
106 Anytype,
107 /// Dynamic JSON value (JsAny in generated code).
108 /// Used for JSON.parse() return type and dynamic property access.
109 /// Allows runtime type coercion via asI64(), asF64(), asBool(), asString().
110 JsAny,
111 /// Symbol value (JsSymbol in generated code).
112 /// Represents a unique identifier with optional description.
113 JsSymbol,
114 /// Arbitrary-precision integer (JsBigInt in generated code).
115 /// Wraps `std.math.big.int.Managed`.
116 BigInt,
117 /// Return type depends on anytype parameters (non-export functions only).
118 /// Codegen emits `@TypeOf(return_expr)` instead of a concrete Zig type.
119 /// This allows Zig to infer the return type at compile time from the
120 /// actual concrete types of anytype parameters.
121 AnytypeReturn,
122}
123
124impl ZigType {
125 /// Get the Zig type string for code generation.
126 /// NOTE: This method does NOT add "host." prefix for NamedStruct.
127 /// If the type refers to a host-defined struct, the caller must add "host."
128 /// prefix manually (e.g., in codegen when generating non-host module code).
129 pub fn to_zig_type(&self) -> String {
130 match self {
131 ZigType::Void => "void".to_string(),
132 ZigType::I64 => "i64".to_string(),
133 ZigType::F64 => "f64".to_string(),
134 ZigType::Bool => "bool".to_string(),
135 ZigType::Str => "[]const u8".to_string(),
136 ZigType::ArrayList(inner) => {
137 format!("std.ArrayList({})", inner.to_zig_type())
138 }
139 ZigType::Struct(fields) => {
140 // Generate anonymous struct type.
141 let mut s = ".{ ".to_string();
142 for (i, (name, ty)) in fields.iter().enumerate() {
143 if i > 0 {
144 s.push_str(", ");
145 }
146 s.push_str(&format!(".{} = {}", name, ty.to_zig_type()));
147 }
148 s.push_str(" }");
149 s
150 }
151 ZigType::NamedStruct(name) => {
152 // Do NOT add "host." prefix here.
153 // The caller is responsible for adding it if needed.
154 name.clone()
155 }
156 ZigType::Anytype => "anytype".to_string(),
157 ZigType::JsAny => "JsAny".to_string(),
158 ZigType::JsSymbol => "JsSymbol".to_string(),
159 ZigType::BigInt => "js_bigint.JsBigInt".to_string(),
160 ZigType::AnytypeReturn => "anytype".to_string(), // placeholder — Codegen replaces with @TypeOf
161 }
162 }
163 /// Get the Zig type string for C ABI wrapper generation.
164 pub fn to_cabi_str(&self) -> String {
165 match self {
166 ZigType::Void => "void".to_string(),
167 ZigType::I64 => "i64".to_string(),
168 ZigType::F64 => "f64".to_string(),
169 ZigType::Bool => "bool".to_string(),
170 ZigType::Str => "StrRet".to_string(), // C ABI: extern struct { ptr, len }
171 ZigType::ArrayList(_) => "void".to_string(), // ArrayLists cannot be directly exported via C ABI
172 ZigType::Struct(_) => "struct".to_string(), // Anonymous struct - not directly supported in C ABI
173 ZigType::NamedStruct(_) => "struct".to_string(), // Named struct - C ABI name depends on HostStructDef
174 ZigType::Anytype => "i64".to_string(), // Default for anytype (not used in C ABI)
175 ZigType::JsAny => "JsAny".to_string(), // JsAny is not directly supported in C ABI
176 ZigType::JsSymbol => "JsSymbol".to_string(), // JsSymbol is not directly supported in C ABI
177 ZigType::BigInt => "i64".to_string(), // C ABI: degrade to i64
178 ZigType::AnytypeReturn => "i64".to_string(), // C ABI: shouldn't be used (exports can't be AnytypeReturn)
179 }
180 }
181
182 /// Map ZigType to JS typeof string.
183 /// Returns None for dynamic types (JsAny, Anytype) that need runtime dispatch.
184 pub fn to_js_typeof(&self) -> Option<&'static str> {
185 match self {
186 ZigType::I64 | ZigType::F64 => Some("\"number\""),
187 ZigType::Bool => Some("\"boolean\""),
188 ZigType::Str => Some("\"string\""),
189 ZigType::JsSymbol => Some("\"symbol\""),
190 ZigType::Void => Some("\"undefined\""),
191 ZigType::Struct(_) | ZigType::NamedStruct(_) | ZigType::ArrayList(_) => {
192 Some("\"object\"")
193 }
194 ZigType::BigInt => Some("\"bigint\""),
195 // Dynamic types — need runtime typeof helper
196 ZigType::JsAny | ZigType::Anytype | ZigType::AnytypeReturn => None,
197 }
198 }
199}
200
201/// Convert HostType to ZigType.
202impl From<crate::HostType> for ZigType {
203 fn from(t: crate::HostType) -> Self {
204 match t {
205 crate::HostType::Void => ZigType::Void,
206 crate::HostType::Bool => ZigType::Bool,
207 crate::HostType::I32 => ZigType::I64, // i32 widens to i64
208 crate::HostType::I64 => ZigType::I64,
209 crate::HostType::F64 => ZigType::F64,
210 crate::HostType::Str => ZigType::Str,
211 }
212 }
213}
214
215/// JSDoc 解析结果,传递给 Codegen
216#[derive(Debug, Clone)]
217pub struct JSDocData {
218 /// @typedef 定义:类型名 → TypedefDef
219 pub typedefs: std::collections::HashMap<String, jsdoc::TypedefDef>,
220 /// @type 注解:变量名 → 类型名
221 pub type_annotations: std::collections::HashMap<String, String>,
222 /// @returns 注解:函数名 → 类型名
223 pub return_types: std::collections::HashMap<String, String>,
224 /// @param 注解:函数名 → [(参数名, 类型名)]
225 pub param_types: std::collections::HashMap<String, Vec<(String, String)>>,
226}
227
228use oxc_ast::ast::Program;
229
230// Submodules declared in lib.rs (flattened from native_proto/ directory).
231// Re-exported here to preserve `crate::native_proto::<module>::*` paths.
232pub(crate) use crate::codegen;
233pub(crate) use crate::infer;
234pub(crate) use crate::jsdoc;
235pub(crate) use crate::native_builtins as builtins;
236
237pub use infer::TypeCheckResult;
238
239/// Transpile JS source text to Zig (native type system).
240///
241/// **New API** — accepts a pre-parsed `&Program` plus the original source text
242/// (needed for JSDoc extraction). The caller should obtain the `Program` from
243/// `analyze_single_group` so that the AST is only built once.
244///
245/// Returns full `TranspileResult` with generated code AND metadata
246/// (exported functions, diagnostics, etc.).
247///
248/// `exported_functions`: Optional set of exported function names.
249/// If provided, only functions in this set generate `pub fn` (export semantics).
250/// If None, treat all toplevel functions as exports (backward compatibility).
251pub fn transpile_js(
252 program: &Program<'_>,
253 js_source: &str,
254 exported_functions: Option<std::collections::HashSet<String>>,
255 host_fns: Option<&crate::host::HostFnRegistry>,
256) -> Result<TranspileResult, String> {
257 transpile_js_inner(program, js_source, exported_functions, host_fns)
258}
259
260/// Internal helper: transpile JS AST to Zig, returning TranspileResult.
261///
262/// Two-pass flow (Phase A):
263/// 1. TypeInferrer::infer_all() — walk AST once, collect all type info
264/// 2. Codegen::generate() — read pre-computed type info, emit Zig code
265fn transpile_js_inner(
266 program: &Program<'_>,
267 js_source: &str,
268 exported_functions: Option<std::collections::HashSet<String>>,
269 host_fns: Option<&crate::host::HostFnRegistry>,
270) -> Result<TranspileResult, String> {
271 // JSDoc extraction (still needs raw source text)
272 let (typedefs, type_annotations, return_types, param_types) =
273 jsdoc::extract_all_jsdoc(js_source);
274 let jsdoc_data = JSDocData {
275 typedefs,
276 type_annotations,
277 return_types,
278 param_types,
279 };
280
281 // ── Pass 1: Type inference ──
282 let mut inferrer = infer::TypeInferrer::new();
283 inferrer.set_jsdoc_data(jsdoc_data.clone());
284 if let Some(hf) = host_fns {
285 inferrer.set_host_fn_types(hf);
286 }
287 let type_info = inferrer.infer_all(program, exported_functions.clone());
288
289 // Extract TypeInferrer errors before type_info is moved to Codegen.
290 let infer_errors = type_info.errors.clone();
291
292 // ── Pass 2: Code generation ──
293 // Extract async host function names for io.async() codegen.
294 let async_host_fns: std::collections::HashSet<String> = if let Some(hf) = host_fns {
295 hf.async_fn_names().into_iter().collect()
296 } else {
297 std::collections::HashSet::new()
298 };
299 let mut cg = Codegen::new(
300 type_info,
301 jsdoc_data,
302 exported_functions,
303 async_host_fns,
304 js_source.to_string(),
305 );
306 cg.generate(program);
307
308 // Merge TypeInferrer errors with Codegen errors.
309 let mut combined_errors = infer_errors;
310 combined_errors.append(&mut cg.errors.clone());
311 let warnings = cg.warnings.clone();
312
313 Ok(TranspileResult {
314 zig_code: cg.output,
315 errors: combined_errors,
316 warnings,
317 exports: cg.exported_fns.clone(),
318 var_types: cg.type_info.var_types.clone(),
319 cabi_exports: cg
320 .exported_fns
321 .into_iter()
322 .map(|ef| {
323 let params: Vec<(String, ZigType)> = ef
324 .params
325 .iter()
326 .enumerate()
327 .map(|(i, p)| (format!("arg{}", i), p.clone()))
328 .collect();
329 let is_async = cg
330 .type_info
331 .is_async
332 .get(&ef.name)
333 .copied()
334 .unwrap_or(false);
335 // Extract struct name if return type is NamedStruct
336 let ret_struct_name =
337 if let crate::native_proto::ZigType::NamedStruct(ref s) = ef.return_type {
338 Some(s.clone())
339 } else {
340 None
341 };
342 NativeCabiExport {
343 name: ef.name,
344 params,
345 ret_type: ef.return_type,
346 is_async,
347 can_throw: ef.can_throw,
348 ret_struct_name,
349 ret_struct_fields: None, // populated from host_fns in pipeline.rs
350 }
351 })
352 .collect(),
353 })
354}
355
356/// Shared state for native-type codegen.
357///
358/// Phase A: Codegen is now purely generative — all type inference runs in
359/// `TypeInferrer::infer_all()` before codegen. `type_info` holds the
360/// pre-computed type snapshot.
361pub struct Codegen {
362 pub output: String,
363 pub indent: usize,
364 /// Compile errors collected during codegen.
365 pub errors: Vec<String>,
366 /// Non-fatal warnings (try-catch limitations, etc.) — do NOT block file generation.
367 pub warnings: Vec<String>,
368 /// Pre-computed type information (read-only during codegen).
369 pub type_info: TypeCheckResult,
370 /// JSDoc data for typedef generation.
371 pub jsdoc_data: Option<JSDocData>,
372 /// Whether the current function being emitted is an export function.
373 pub current_fn_is_export: bool,
374 /// The return type of the current function (derived from type_info).
375 pub current_fn_return_type: Option<ZigType>,
376 /// Exported functions metadata (for pipeline C ABI wrapper generation).
377 pub exported_fns: Vec<ExportedFunction>,
378 /// Task counter for generating unique task variable names in async/await code.
379 pub task_counter: u32,
380 /// Exported function names (from pipeline).
381 pub exported_functions: Option<std::collections::HashSet<String>>,
382 /// Whether a return/throw statement was seen in the current function body.
383 pub seen_return: bool,
384 /// Whether the current function contains `throw` or `try-catch` statements.
385 /// Determined by pre-scan before signature generation. When true, the function
386 /// return type is `!T` (error union) instead of plain `T`.
387 pub fn_has_throw: bool,
388 /// Whether we are currently emitting the return value expression.
389 /// When true, array methods that normally discard with `_ = ` should skip the prefix.
390 pub in_return_expr: bool,
391 /// Whether we are currently emitting the top-level expression of an ExpressionStatement.
392 /// When true, builtins that return non-void values should discard with `_ = `.
393 pub in_expr_stmt: bool,
394 /// Whether the current call expression generated a `catch |_| { ... }` block.
395 /// Used to suppress the `_ = ` discard prefix in emit_fn_stmt when a catch
396 /// block is already present (Zig 0.16 rejects `_ = <err union> catch |_| { }`).
397 pub call_generated_catch: bool,
398 /// Counter for generating unique try-block labels (for nested try-catch).
399 pub try_label_counter: u32,
400 /// Counter for generating unique arrow function names.
401 pub arrow_counter: u32,
402 /// When inside a try block, the label name for `break :label`.
403 /// throw statements inside the try block emit `break :label error.JsThrow`
404 /// instead of `return error.JsThrow`.
405 pub inside_try_block: Option<String>,
406 /// Current function name being generated (for function-scoped mutated_vars).
407 pub current_fn: Option<String>,
408 /// Captured variables for the current arrow function: (name, type, is_mutable)
409 pub current_captured: Vec<(String, ZigType, bool)>,
410 /// Map: closure variable name → list of (captured_name, type, is_mutable)
411 /// Used to generate struct instance at assignment and .call() at call site.
412 pub closure_vars: HashMap<String, Vec<(String, ZigType, bool)>>,
413 /// Set of variable names that are closure instances (assigned from arrow functions with captures).
414 /// Used to rewrite `fn(args)` to `fn.call(args)` in emit_call.
415 pub closure_instances: HashSet<String>,
416 /// Closure struct definitions to be prepended to output (module-level).
417 pub closure_defs: Vec<String>,
418 /// Counter for generating unique temp variable names in optional chaining (?.)
419 pub oc_counter: u32,
420 /// Counter for generating unique temp variable names in destructuring patterns.
421 pub destructure_counter: u32,
422 /// Counter for generating unique iterator variable names in for-of (Map/Set) loops.
423 pub for_of_counter: u32,
424 /// Counter for generating unique function expression names.
425 pub fn_expr_counter: u32,
426 /// Function definitions deferred from expression context (Arrow/FunctionExpression in emit_expr).
427 /// These need to be emitted before the current statement at the current indent level.
428 pub pending_expr_fns: Vec<String>,
429 /// Variables initialized with TypedArray constructors (Int32Array, Uint8Array, Float64Array).
430 /// Maps variable name → element Zig type suffix (e.g. "I32", "U8", "F64").
431 /// Used to route method calls and property accesses correctly.
432 pub typedarray_vars: std::collections::HashMap<String, String>,
433 /// Variables initialized with `new RegExp(expr)` — dynamic RegExp objects.
434 /// Used to route .test()/.exec() calls on RegExp variables, and
435 /// str.match(regexpVar) / str.search(regexpVar) calls.
436 pub regexp_vars: std::collections::HashSet<String>,
437 /// Async host function names (for io.async() codegen).
438 /// When await calls an async host function, use `{name}_async` wrapper.
439 pub async_host_fns: std::collections::HashSet<String>,
440 /// Names of nested function declarations (inside another function body).
441 /// Used to rewrite `nestedFn(args)` to `nestedFn.call(args)` in emit_call.
442 pub nested_fn_names: std::collections::HashSet<String>,
443 /// When generating a nested function declaration's body via emit_fn(),
444 /// this holds the outer JS function name so emit_fn can override the
445 /// generated function signature to use `pub fn call(...)` instead of
446 /// `pub fn <js_name>(...)`.
447 pub current_nested_fn_name: Option<String>,
448 /// When inside a class method body, this holds the class name.
449 /// Used to rewrite `this.x` → `self.x`.
450 pub current_class: Option<String>,
451 /// Set of class names known at the module level.
452 /// Used to route `new ClassName()` → `ClassName.init()` in emit_expr.
453 pub class_names: std::collections::HashSet<String>,
454 /// Original JS source text, used to convert byte offsets → line:col for diagnostics.
455 pub source: String,
456 /// Counter for generating unique block labels (blk_0, blk_1, ...).
457 /// Prevents "redefinition of label" errors when multiple block expressions
458 /// appear in the same scope.
459 pub label_counter: u32,
460 /// Set of variable names declared in the current function scope.
461 /// Used to detect shadowing in nested blocks (Zig 0.16.0 forbids it).
462 pub fn_scope_vars: std::collections::HashSet<String>,
463 /// Stack of shadowing rename maps: one HashMap per block scope depth.
464 /// When a shadowed variable is declared, its original name → renamed name
465 /// mapping is stored in the topmost HashMap. `zig_safe_name()` checks this
466 /// stack to rewrite references to the renamed variable.
467 pub shadow_renames: Vec<std::collections::HashMap<String, String>>,
468 /// Counter for generating unique renamed variable names when shadowing occurs.
469 pub shadow_counter: u32,
470}