Skip to main content

js2zig_core/
native_proto.rs

1// js2zig-core/src/native_proto.rs
2//
3// Native-type system transpilation module.
4// Pipeline: AST → Lowerer → ZigIR → PassPipeline → Emitter → Zig source.
5
6// Transpile function lives here; type definitions are in crate::types.
7use crate::types::{JSDocData, NativeCabiExport, TranspileResult};
8
9use oxc_ast::ast::Program;
10
11use crate::zigir::types::{IrDecl, IrExpr, IrStmt};
12
13/// Transpile JS source text to Zig (native type system).
14///
15/// Accepts a pre-parsed `&Program` plus the original source text
16/// (needed for JSDoc extraction).  The caller should obtain the `Program` from
17/// `analyze_project` so that the AST is only built once.
18///
19/// Returns full `TranspileResult` with generated code AND metadata
20/// (diagnostics, cabi_exports, etc.).
21///
22/// `exported_functions`: Optional set of exported function names.
23/// If provided, only functions in this set generate `pub fn` (export semantics).
24/// If None, treat all toplevel functions as exports (backward compatibility).
25///
26/// Production pipeline (ZigIR):
27///   1. TypeInferrer::infer_all() — walk AST, collect type info
28///   2. Lowerer::lower() — convert AST to ZigIR (IrModule)
29///   3. PassPipeline — optimize IrModule (dead code, constant fold, validate)
30///   4. Emitter::emit_module() — emit Zig source from IrModule
31pub fn transpile_js(
32    program: &Program<'_>,
33    js_source: &str,
34    exported_functions: Option<std::collections::HashSet<String>>,
35    host_fns: Option<&crate::host::HostFnRegistry>,
36    module_name: &str,
37) -> Result<TranspileResult, String> {
38    // JSDoc extraction (still needs raw source text)
39    let (typedefs, type_annotations, return_types, param_types) =
40        crate::jsdoc::extract_all_jsdoc(js_source);
41    let jsdoc_data = JSDocData {
42        typedefs,
43        type_annotations,
44        return_types,
45        param_types,
46    };
47
48    // ── Step 1: Type inference ──
49    let mut inferrer = crate::infer::TypeInferrer::new();
50    inferrer.set_jsdoc_data(jsdoc_data.clone());
51    if let Some(hf) = host_fns {
52        inferrer.set_host_fn_types(hf);
53    }
54    let type_info = inferrer.infer_all(program, exported_functions.clone());
55
56    let infer_errors = type_info.errors.clone();
57    let var_types = type_info.var_types.clone();
58
59    // Extract async host function names for io.async() emission.
60    let async_host_fns: std::collections::HashSet<String> = if let Some(hf) = host_fns {
61        hf.async_fn_names().into_iter().collect()
62    } else {
63        std::collections::HashSet::new()
64    };
65
66    // ── Step 2: Lower AST → ZigIR ──
67    use crate::zigir::lower::Lowerer;
68    let mut lowerer = Lowerer::new(
69        type_info,
70        jsdoc_data,
71        exported_functions,
72        async_host_fns,
73        js_source.to_string(),
74        module_name.to_string(),
75    );
76    let mut ir_module = lowerer.lower(program);
77
78    // ── Step 3: Optimization passes ──
79    let mut pipeline = crate::zigir::passes::PassPipeline::default_pipeline();
80    let pass_result = pipeline.run(&mut ir_module);
81    // Merge validation diagnostics from passes into the module
82    if !pass_result.diagnostics.is_empty() {
83        ir_module.diagnostics.extend(pass_result.diagnostics);
84    }
85
86    // ── Step 3.5: Collect @compileError messages from IR ──
87    let compile_errors = collect_compile_errors(&ir_module);
88
89    // ── Step 4: Emit Zig source ──
90    use crate::zigir::emit::Emitter;
91    let zig_code = Emitter::emit_module(&ir_module);
92
93    // ── Extract TranspileResult fields from IrModule ──
94
95    // Errors / warnings from Lowerer diagnostics
96    let mut errors: Vec<String> = infer_errors;
97    let mut warnings: Vec<String> = Vec::new();
98    for diag in &ir_module.diagnostics {
99        match diag.level {
100            crate::zigir::source_span::DiagnosticLevel::Error => {
101                errors.push(diag.message.clone());
102            }
103            crate::zigir::source_span::DiagnosticLevel::Warning => {
104                warnings.push(diag.message.clone());
105            }
106        }
107    }
108
109    // C ABI exports from IrModule
110    let cabi_exports: Vec<NativeCabiExport> = ir_module
111        .cabi_exports
112        .iter()
113        .map(|ce| NativeCabiExport {
114            name: ce.name.clone(),
115            params: ce
116                .params
117                .iter()
118                .enumerate()
119                .map(|(i, p)| (format!("arg{}", i), p.zig_type.clone()))
120                .collect(),
121            ret_type: ce.return_type.clone(),
122            is_async: ce.is_async,
123            can_throw: ce.can_throw,
124            ret_struct_name: ce.ret_struct_name.clone(),
125        })
126        .collect();
127
128    Ok(TranspileResult {
129        zig_code,
130        errors,
131        warnings,
132        compile_errors,
133        var_types,
134        cabi_exports,
135    })
136}
137
138/// Collect all `@compileError` messages from the IR tree.
139///
140/// Walks the entire `IrModule` — declarations, closure structs, typedefs —
141/// and extracts messages from `IrDecl::CompileError`, `IrStmt::CompileError`,
142/// and `IrExpr::CompileError` nodes.
143///
144/// These correspond to JS features that the transpiler does not support.
145/// Zig's lazy analysis may never trigger the generated `@compileError`,
146/// so we surface them at transpile time as non-blocking warnings.
147fn collect_compile_errors(module: &crate::zigir::types::IrModule) -> Vec<String> {
148    use crate::zigir::passes::walk;
149    use std::cell::RefCell;
150
151    let results = RefCell::new(Vec::new());
152
153    fn push_msg(msg: &str, results: &RefCell<Vec<String>>) {
154        // Split merged messages (joined with "\n\nAlso: ") into individual entries
155        for part in msg.split("\n\nAlso: ") {
156            results.borrow_mut().push(part.to_string());
157        }
158    }
159
160    fn collect_from_block(block: &crate::zigir::types::IrBlock, results: &RefCell<Vec<String>>) {
161        for stmt in &block.stmts {
162            collect_from_stmt(stmt, results);
163        }
164    }
165
166    fn collect_from_stmt(stmt: &IrStmt, results: &RefCell<Vec<String>>) {
167        match stmt {
168            IrStmt::CompileError { msg, .. } => push_msg(msg, results),
169            _ => walk::for_each_stmt_child(
170                stmt,
171                &mut |block| collect_from_block(block, results),
172                &mut |s| collect_from_stmt(s, results),
173                &mut |expr| collect_from_expr(expr, results),
174                &mut |_| {},
175            ),
176        }
177    }
178
179    fn collect_from_expr(expr: &IrExpr, results: &RefCell<Vec<String>>) {
180        match expr {
181            IrExpr::CompileError { msg, .. } => push_msg(msg, results),
182            _ => walk::for_each_expr_child(
183                expr,
184                &mut |block| collect_from_block(block, results),
185                &mut |s| collect_from_stmt(s, results),
186                &mut |expr| collect_from_expr(expr, results),
187                &mut |_| {},
188            ),
189        }
190    }
191
192    // Top-level declarations
193    for decl in &module.declarations {
194        match decl {
195            IrDecl::CompileError { msg, .. } => push_msg(msg, &results),
196            _ => walk::for_each_decl_child(
197                decl,
198                &mut |block| collect_from_block(block, &results),
199                &mut |expr| collect_from_expr(expr, &results),
200            ),
201        }
202    }
203
204    // Closure structs (their body may contain CompileError)
205    for cs in &module.closure_structs {
206        collect_from_block(&cs.body, &results);
207    }
208
209    results.into_inner()
210}
211
212#[cfg(test)]
213mod tests {
214    use super::*;
215
216    #[test]
217    fn test_collect_compile_errors_from_ir() {
218        use crate::types::ZigType;
219        use crate::zigir::ident::IrIdent;
220        use crate::zigir::source_span::SourceSpan;
221        use crate::zigir::types::{IrBlock, IrDecl, IrFnDecl, IrModule, IrStmt};
222
223        let mut module = IrModule::new("test".to_string());
224
225        // Add a CompileError declaration
226        module.declarations.push(IrDecl::CompileError {
227            span: SourceSpan::new(1, 1),
228            msg: "unsupported import".to_string(),
229        });
230
231        // Add a function with a CompileError statement
232        module.declarations.push(IrDecl::Fn(IrFnDecl {
233            name: IrIdent::new("testFn"),
234            params: vec![],
235            return_type: ZigType::Void,
236            body: IrBlock::new(vec![IrStmt::CompileError {
237                span: SourceSpan::new(5, 10),
238                msg: "nested class not supported".to_string(),
239            }]),
240            is_export: false,
241            is_async: false,
242            can_throw: false,
243            is_cabi: false,
244            typeof_return_body: None,
245        }));
246
247        let results = collect_compile_errors(&module);
248        assert_eq!(results.len(), 2);
249        assert!(results.iter().any(|m| m.contains("unsupported import")));
250        assert!(
251            results
252                .iter()
253                .any(|m| m.contains("nested class not supported"))
254        );
255    }
256
257    #[test]
258    fn test_collect_compile_errors_splits_merged() {
259        use crate::types::ZigType;
260        use crate::zigir::ident::IrIdent;
261        use crate::zigir::source_span::SourceSpan;
262        use crate::zigir::types::{IrBlock, IrDecl, IrFnDecl, IrModule, IrStmt};
263
264        let mut module = IrModule::new("test".to_string());
265
266        // Simulate a merged CompileError (from Scheme B)
267        module.declarations.push(IrDecl::Fn(IrFnDecl {
268            name: IrIdent::new("testFn"),
269            params: vec![],
270            return_type: ZigType::Void,
271            body: IrBlock::new(vec![IrStmt::CompileError {
272                span: SourceSpan::new(1, 1),
273                msg: "error 1\n\nAlso: error 2\n\nAlso: error 3".to_string(),
274            }]),
275            is_export: false,
276            is_async: false,
277            can_throw: false,
278            is_cabi: false,
279            typeof_return_body: None,
280        }));
281
282        let results = collect_compile_errors(&module);
283        assert_eq!(results.len(), 3);
284        assert_eq!(results[0], "error 1");
285        assert_eq!(results[1], "error 2");
286        assert_eq!(results[2], "error 3");
287    }
288}