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// Re-export types from the dedicated types module.
7pub use crate::types::{
8    ClosureManager, Diagnostic, DiagnosticKind, ExportedFunction, JSDocData, NameGen,
9    NativeCabiExport, TranspileResult, ZigType,
10};
11
12use oxc_ast::ast::Program;
13
14use crate::zigir::types::IrDecl;
15
16pub use crate::infer::TypeCheckResult;
17
18/// Transpile JS source text to Zig (native type system).
19///
20/// **New API** — accepts a pre-parsed `&Program` plus the original source text
21/// (needed for JSDoc extraction).  The caller should obtain the `Program` from
22/// `analyze_single_group` so that the AST is only built once.
23///
24/// Returns full `TranspileResult` with generated code AND metadata
25/// (exported functions, diagnostics, etc.).
26///
27/// `exported_functions`: Optional set of exported function names.
28/// If provided, only functions in this set generate `pub fn` (export semantics).
29/// If None, treat all toplevel functions as exports (backward compatibility).
30pub fn transpile_js(
31    program: &Program<'_>,
32    js_source: &str,
33    exported_functions: Option<std::collections::HashSet<String>>,
34    host_fns: Option<&crate::host::HostFnRegistry>,
35) -> Result<TranspileResult, String> {
36    transpile_js_inner(program, js_source, exported_functions, host_fns)
37}
38
39/// Internal helper: transpile JS AST to Zig, returning TranspileResult.
40///
41/// Production pipeline (ZigIR):
42///   1. TypeInferrer::infer_all() — walk AST, collect type info
43///   2. Lowerer::lower() — convert AST to ZigIR (IrModule)
44///   3. PassPipeline — optimize IrModule (dead code, constant fold, validate)
45///   4. Emitter::emit_module() — emit Zig source from IrModule
46fn transpile_js_inner(
47    program: &Program<'_>,
48    js_source: &str,
49    exported_functions: Option<std::collections::HashSet<String>>,
50    host_fns: Option<&crate::host::HostFnRegistry>,
51) -> Result<TranspileResult, String> {
52    // JSDoc extraction (still needs raw source text)
53    let (typedefs, type_annotations, return_types, param_types) =
54        crate::jsdoc::extract_all_jsdoc(js_source);
55    let jsdoc_data = JSDocData {
56        typedefs,
57        type_annotations,
58        return_types,
59        param_types,
60    };
61
62    // ── Step 1: Type inference ──
63    let mut inferrer = crate::infer::TypeInferrer::new();
64    inferrer.set_jsdoc_data(jsdoc_data.clone());
65    if let Some(hf) = host_fns {
66        inferrer.set_host_fn_types(hf);
67    }
68    let type_info = inferrer.infer_all(program, exported_functions.clone());
69
70    let infer_errors = type_info.errors.clone();
71    let var_types = type_info.var_types.clone();
72
73    // Extract async host function names for io.async() emission.
74    let async_host_fns: std::collections::HashSet<String> = if let Some(hf) = host_fns {
75        hf.async_fn_names().into_iter().collect()
76    } else {
77        std::collections::HashSet::new()
78    };
79
80    // ── Step 2: Lower AST → ZigIR ──
81    use crate::zigir::lower::Lowerer;
82    let mut lowerer = Lowerer::new(
83        type_info,
84        jsdoc_data,
85        exported_functions.clone(),
86        async_host_fns.clone(),
87        js_source.to_string(),
88    );
89    let mut ir_module = lowerer.lower(program);
90
91    // ── Step 3: Optimization passes ──
92    let mut pipeline = crate::zigir::passes::PassPipeline::default_pipeline();
93    let _pipeline_result = pipeline.run(&mut ir_module);
94
95    // ── Step 4: Emit Zig source ──
96    use crate::zigir::emit::Emitter;
97    let zig_code = Emitter::emit_module(&ir_module);
98
99    // ── Extract TranspileResult fields from IrModule ──
100
101    // Errors / warnings from Lowerer diagnostics
102    let mut errors: Vec<String> = infer_errors;
103    let mut warnings: Vec<String> = Vec::new();
104    for diag in &ir_module.diagnostics {
105        match diag.level {
106            crate::zigir::source_span::DiagnosticLevel::Error => {
107                errors.push(diag.message.clone());
108            }
109            crate::zigir::source_span::DiagnosticLevel::Warning => {
110                warnings.push(diag.message.clone());
111            }
112        }
113    }
114
115    // Exported functions from IrDecl::Fn where is_export
116    let exports: Vec<ExportedFunction> = ir_module
117        .declarations
118        .iter()
119        .filter_map(|decl| {
120            if let IrDecl::Fn(f) = decl
121                && f.is_export
122            {
123                Some(ExportedFunction {
124                    name: f.name.zig_name.clone(),
125                    params: f.params.iter().map(|p| p.zig_type.clone()).collect(),
126                    return_type: f.return_type.clone(),
127                    can_throw: f.can_throw,
128                })
129            } else {
130                None
131            }
132        })
133        .collect();
134
135    // C ABI exports from IrModule
136    let cabi_exports: Vec<NativeCabiExport> = ir_module
137        .cabi_exports
138        .iter()
139        .map(|ce| NativeCabiExport {
140            name: ce.name.clone(),
141            params: ce
142                .params
143                .iter()
144                .enumerate()
145                .map(|(i, p)| (format!("arg{}", i), p.zig_type.clone()))
146                .collect(),
147            ret_type: ce.return_type.clone(),
148            is_async: ce.is_async,
149            can_throw: ce.can_throw,
150            ret_struct_name: ce.ret_struct_name.clone(),
151            ret_struct_fields: None, // populated from host_fns in pipeline.rs
152        })
153        .collect();
154
155    Ok(TranspileResult {
156        zig_code,
157        errors,
158        warnings,
159        exports,
160        var_types,
161        cabi_exports,
162    })
163}