Skip to main content

js2zig_core/zigir/lower/
mod.rs

1// zigir/lower/mod.rs
2// AST → ZigIR lowering: transforms JS AST + type info into structured IR.
3//
4// The Lowerer transforms JS AST + type-inference results into structured
5// ZigIR. All semantic decisions (type resolution, name mangling, closure
6// lowering) happen in sub-modules; the Emitter phase is pure formatting.
7//
8// Sub-module layout:
9//   decl.rs    — variable / function / destructure declaration lowering
10//   stmt.rs    — statement lowering (if/for/switch/try/loop/etc.)
11//   class.rs   — class declaration + method lowering
12//   expr.rs    — expression lowering (literals, operators, calls, etc.)
13//   closure.rs — closure struct generation + capture analysis
14//   cabi.rs    — C ABI export metadata + utility/query methods + free helpers
15//   helpers.rs — FnContext struct + SetFlagGuard
16
17pub mod cabi;
18pub mod class;
19pub mod closure;
20pub mod decl;
21pub mod expr;
22pub mod helpers;
23pub mod stmt;
24
25use std::collections::{HashMap, HashSet};
26
27use oxc_ast::ast::*;
28
29use crate::infer::TypeCheckResult;
30use crate::types::{ClosureManager, JSDocData};
31use crate::zigir::ident::NameMangler;
32use crate::zigir::source_span::{DiagnosticLevel, IrDiagnostic};
33use crate::zigir::types::{IrDecl, IrModule, IrTypedef, IrTypedefField};
34
35use helpers::FnContext;
36
37// ═══════════════════════════════════════════════════════
38//  Lowerer struct
39// ═══════════════════════════════════════════════════════
40
41/// AST → ZigIR lowering engine.
42///
43/// Composes 3 sub-structures:
44/// - `name_mangler`: counter-per-prefix + shadow-scope stack
45/// - `fn_ctx`:       per-function context
46/// - `closure_mgr`:  closure struct collection
47pub struct Lowerer {
48    // ── Read-only inputs ──────────────────────────────
49    /// Pre-computed type-inference results (read-only during lowering).
50    pub(super) type_info: TypeCheckResult,
51    /// JSDoc annotations (typedefs, type/return/param annotations).
52    pub(super) jsdoc_data: JSDocData,
53    /// Async host function names (for await lowering).
54    pub(super) async_host_fns: HashSet<String>,
55    /// Exported function names from pipeline.
56    pub(super) exported_functions: Option<HashSet<String>>,
57    /// Original JS source text (for diagnostics line:col).
58    pub(super) source: String,
59    /// Module name (derived from JS filename, e.g. "main" or "array_methods").
60    pub(super) module_name: String,
61
62    // ── Name management ───────────────────────────────
63    pub(super) name_mangler: NameMangler,
64
65    // ── Function context stack ────────────────────────
66    pub(super) fn_ctx: Option<FnContext>,
67
68    // ── Closure management ────────────────────────────
69    pub(super) closure_mgr: ClosureManager,
70
71    // ── Module-level tracking ─────────────────────────
72    /// Known class names (used to route `new ClassName()` correctly).
73    pub(super) class_names: HashSet<String>,
74
75    /// Static field names per class: class_name → {field_name, ...}.
76    /// Used to route `ClassName.field` access to `__ClassName_field` module-scope var.
77    pub(super) class_static_fields: HashMap<String, HashSet<String>>,
78
79    /// Class inheritance map: class_name → parent_class_name.
80    /// Used for `instanceof` prototype chain traversal.
81    pub(super) class_extends_map: HashMap<String, String>,
82
83    // ── Deferred declarations ─────────────────────────
84    /// Function definitions deferred from expression context (def-before-use).
85    /// These are inserted before the statement that triggered them.
86    pub(super) pending_expr_fns: Vec<IrDecl>,
87
88    /// Arrow function / closure struct definitions collected during var decl lowering.
89    /// These are moved to IrModule.closure_structs at the end of lowering.
90    pub(super) pending_arrow_structs: Vec<crate::zigir::types::IrClosureStruct>,
91
92    /// Pending loop label from a LabeledStatement parent.
93    /// Consumed by the next loop statement (while/for/do-while/for-of/for-in).
94    pub(super) pending_label: Option<String>,
95
96    /// Currently inside a class (affects `this` lowering).
97    pub(super) current_class: Option<String>,
98
99    /// Currently inside a static block (affects `this` → ClassName rewriting).
100    pub(super) in_static_block: bool,
101
102    /// Whether we're lowering inside an ExpressionStatement.
103    /// Affects UpdateExpression lowering (e.g., `i++` → `i += 1` vs block expr).
104    pub(super) in_expr_stmt: bool,
105
106    /// Counter for anonymous class expressions (to generate unique names).
107    pub(super) anon_class_counter: u32,
108
109    /// When lowering a class expression assigned to a variable (e.g. `const X = class { ... }`),
110    /// this holds the variable name. The type inferrer stores field types under the variable
111    /// name, but `lower_class_decl` generates `_AnonClass_N` for anonymous classes. This field
112    /// allows field type lookups to fall back to the variable name.
113    pub(super) class_expr_var_name: Option<String>,
114
115    /// Source file name (for `import.meta.url`). Empty string if unavailable.
116    #[allow(dead_code)]
117    pub(super) source_name: String,
118
119    // ── Diagnostics ───────────────────────────────────
120    pub(super) diagnostics: Vec<IrDiagnostic>,
121}
122
123// ═══════════════════════════════════════════════════════
124//  Constructor
125// ═══════════════════════════════════════════════════════
126
127impl Lowerer {
128    /// Create a new Lowerer.
129    pub fn new(
130        type_info: TypeCheckResult,
131        jsdoc_data: JSDocData,
132        exported_functions: Option<HashSet<String>>,
133        async_host_fns: HashSet<String>,
134        source: String,
135        module_name: String,
136    ) -> Self {
137        Self {
138            type_info,
139            jsdoc_data,
140            async_host_fns,
141            exported_functions,
142            source,
143            module_name,
144            name_mangler: NameMangler::new(),
145            fn_ctx: None,
146            closure_mgr: ClosureManager::new(),
147            class_names: HashSet::new(),
148            class_static_fields: HashMap::new(),
149            class_extends_map: HashMap::new(),
150            pending_expr_fns: Vec::new(),
151            pending_arrow_structs: Vec::new(),
152            pending_label: None,
153            current_class: None,
154            in_static_block: false,
155            in_expr_stmt: false,
156            anon_class_counter: 0,
157            class_expr_var_name: None,
158            source_name: String::new(),
159            diagnostics: Vec::new(),
160        }
161    }
162}
163
164// ═══════════════════════════════════════════════════════
165//  Main entry point
166// ═══════════════════════════════════════════════════════
167
168impl Lowerer {
169    /// Lower a complete JS `Program` into an `IrModule`.
170    pub fn lower(&mut self, program: &Program) -> IrModule {
171        let module_name = self.module_name.clone();
172
173        // 1. Lower JSDoc @typedef definitions
174        let typedefs = self.lower_typedefs();
175
176        // 2. Lower top-level declarations
177        //    (Also collects class names, closure structs, etc.)
178        let mut declarations = Vec::new();
179        for stmt in &program.body {
180            let mut stmt_decls = self.lower_toplevel(stmt);
181            declarations.append(&mut stmt_decls);
182        }
183
184        // 3. Collect deferred closure structs
185        let mut closure_structs = self.lower_closure_structs();
186        // Also add arrow function struct definitions from var decl lowering
187        closure_structs.append(&mut self.pending_arrow_structs);
188
189        // 4. Build CABI exports metadata
190        let cabi_exports = self.build_cabi_exports(&declarations);
191
192        IrModule {
193            name: module_name,
194            typedefs,
195            closure_structs,
196            declarations,
197            diagnostics: std::mem::take(&mut self.diagnostics),
198            cabi_exports,
199        }
200    }
201}
202
203// ═══════════════════════════════════════════════════════
204//  Typedef lowering
205// ═══════════════════════════════════════════════════════
206
207impl Lowerer {
208    /// Lower JSDoc @typedef definitions into IrTypedef nodes.
209    fn lower_typedefs(&self) -> Vec<IrTypedef> {
210        let mut typedefs = Vec::new();
211        for (name, td) in &self.jsdoc_data.typedefs {
212            let fields: Vec<IrTypedefField> = td
213                .fields
214                .iter()
215                .map(|f| {
216                    let zig_type_str =
217                        crate::jsdoc::jsdoc_type_to_zig(&f.ty, &self.jsdoc_data.typedefs);
218                    IrTypedefField {
219                        name: f.name.clone(),
220                        zig_type: if f.optional {
221                            format!("?{}", zig_type_str)
222                        } else {
223                            zig_type_str
224                        },
225                        optional: f.optional,
226                    }
227                })
228                .collect();
229
230            let is_opaque = fields.is_empty();
231            typedefs.push(IrTypedef {
232                name: name.clone(),
233                fields,
234                is_opaque,
235                has_to_json: !is_opaque,
236            });
237        }
238        typedefs
239    }
240}
241
242// ═══════════════════════════════════════════════════════
243//  Top-level dispatch
244// ═══════════════════════════════════════════════════════
245
246impl Lowerer {
247    /// Lower a top-level statement into zero or more IrDecl nodes.
248    fn lower_toplevel(&mut self, stmt: &Statement) -> Vec<IrDecl> {
249        // Flush pending expression functions (def-before-use ordering)
250        let mut decls = std::mem::take(&mut self.pending_expr_fns);
251
252        match stmt {
253            Statement::VariableDeclaration(vd) => {
254                for decl in &vd.declarations {
255                    decls.push(self.lower_var_decl(decl, vd.kind.is_const()));
256                }
257            }
258            Statement::ClassDeclaration(cd) => {
259                if cd.super_class.is_some() {
260                    let span = self.span_to_source_span(cd.span);
261                    self.add_error(
262                        span.clone(),
263                        "class extends is not supported: use composition instead",
264                    );
265                    decls.push(IrDecl::CompileError {
266                        span,
267                        msg: "class extends is not supported: use composition instead".to_string(),
268                    });
269                } else if let Some(ir_class) = self.lower_class_decl(cd) {
270                    self.class_names.insert(ir_class.name.js_name.clone());
271                    // Register extends relationship for instanceof chain traversal
272                    if let Some(ref parent) = ir_class.extends {
273                        self.class_extends_map
274                            .insert(ir_class.name.js_name.clone(), parent.clone());
275                    }
276                    decls.push(IrDecl::Class(ir_class));
277                }
278            }
279            Statement::FunctionDeclaration(fd) => {
280                let is_export = self.is_export_fn(fd.id.as_ref().map(|id| id.name.as_str()));
281                if let Some(ir_fn) = self.lower_fn_decl(fd, is_export) {
282                    decls.push(IrDecl::Fn(ir_fn));
283                }
284            }
285            Statement::ExportNamedDeclaration(export_decl) => {
286                if let Some(decl) = &export_decl.declaration {
287                    match decl {
288                        Declaration::FunctionDeclaration(fd) => {
289                            let is_export =
290                                self.is_export_fn(fd.id.as_ref().map(|id| id.name.as_str()));
291                            if let Some(ir_fn) = self.lower_fn_decl(fd, is_export) {
292                                decls.push(IrDecl::Fn(ir_fn));
293                            }
294                        }
295                        Declaration::VariableDeclaration(vd) => {
296                            for decl in &vd.declarations {
297                                decls.push(self.lower_var_decl(decl, vd.kind.is_const()));
298                            }
299                        }
300                        _ => { /* skip unsupported */ }
301                    }
302                }
303            }
304            Statement::WithStatement(ws) => {
305                let span = self.span_to_source_span(ws.span);
306                self.diagnostics.push(IrDiagnostic {
307                    level: DiagnosticLevel::Error,
308                    span: Some(span),
309                    message: "with statement is not supported and deprecated in strict mode. Use explicit property access instead.".to_string(),
310                });
311            }
312            _ => { /* skip */ }
313        }
314
315        // Any new pending_expr_fns generated during this statement
316        // should be inserted before the NEXT statement's output.
317        let pending = std::mem::take(&mut self.pending_expr_fns);
318        decls.extend(pending);
319
320        decls
321    }
322}
323
324// ═══════════════════════════════════════════════════════
325//  Tests
326// ═══════════════════════════════════════════════════════
327
328#[cfg(test)]
329mod tests {
330    use super::*;
331    use crate::types::{JSDocData, ZigType};
332    use std::collections::{HashMap, HashSet};
333
334    fn empty_type_info() -> TypeCheckResult {
335        empty_type_info_base()
336    }
337
338    fn make_jsdoc_data() -> JSDocData {
339        JSDocData {
340            typedefs: HashMap::new(),
341            type_annotations: HashMap::new(),
342            return_types: HashMap::new(),
343            param_types: HashMap::new(),
344        }
345    }
346
347    fn empty_type_info_base() -> TypeCheckResult {
348        TypeCheckResult {
349            var_types: HashMap::new(),
350            array_element_types: HashMap::new(),
351            fn_return_types: HashMap::new(),
352            fn_param_types: HashMap::new(),
353            mutated_vars: HashSet::new(),
354            reassigned_vars: HashSet::new(),
355            used_names: HashSet::new(),
356            has_json_parse_types: HashSet::new(),
357            errors: Vec::new(),
358            is_async: HashMap::new(),
359            class_field_types: HashMap::new(),
360            host_return_types: HashMap::new(),
361            functions_needing_synthetic_rest: HashSet::new(),
362        }
363    }
364
365    #[test]
366    fn test_lowerer_new() {
367        let type_info = empty_type_info();
368        let lowerer = Lowerer::new(
369            type_info,
370            make_jsdoc_data(),
371            None,
372            HashSet::new(),
373            "let x = 1;".to_string(),
374            String::from("test"),
375        );
376        assert!(lowerer.fn_ctx.is_none());
377        assert!(lowerer.class_names.is_empty());
378        assert!(lowerer.diagnostics.is_empty());
379    }
380
381    #[test]
382    fn test_lowerer_empty_program() {
383        let type_info = empty_type_info();
384        let mut lowerer = Lowerer::new(
385            type_info,
386            make_jsdoc_data(),
387            None,
388            HashSet::new(),
389            String::new(),
390            String::from("test"),
391        );
392
393        // Parse an empty program
394        let js = "";
395        let allocator = oxc_allocator::Allocator::default();
396        let source_type = SourceType::default();
397        let parser = oxc_parser::Parser::new(&allocator, js, source_type);
398        let result = parser.parse();
399        let module = lowerer.lower(&result.program);
400
401        assert_eq!(module.name, "test");
402        assert!(module.declarations.is_empty());
403        assert!(module.closure_structs.is_empty());
404        assert!(module.diagnostics.is_empty());
405    }
406
407    #[test]
408    fn test_fn_context_enter_exit() {
409        let type_info = empty_type_info();
410        let mut lowerer = Lowerer::new(
411            type_info,
412            make_jsdoc_data(),
413            None,
414            HashSet::new(),
415            String::new(),
416            String::from("test"),
417        );
418
419        // Enter a function
420        let saved = lowerer.enter_fn("foo", true, Some(ZigType::I64));
421        assert!(saved.is_none()); // No previous context
422        assert!(lowerer.fn_ctx.is_some());
423
424        let ctx = lowerer.fn_ctx.as_ref().unwrap();
425        assert_eq!(ctx.name, "foo");
426        assert!(ctx.is_export);
427
428        // Exit and check returned context
429        let returned = lowerer.exit_fn(None);
430        assert_eq!(returned.name, "foo");
431        assert!(lowerer.fn_ctx.is_none());
432    }
433
434    #[test]
435    fn test_fn_context_nesting() {
436        let type_info = empty_type_info();
437        let mut lowerer = Lowerer::new(
438            type_info,
439            make_jsdoc_data(),
440            None,
441            HashSet::new(),
442            String::new(),
443            String::from("test"),
444        );
445
446        // Enter outer function
447        let saved_outer = lowerer.enter_fn("outer", true, Some(ZigType::Void));
448        assert!(saved_outer.is_none());
449
450        // Enter inner function (nested)
451        let saved_inner = lowerer.enter_fn("inner", false, Some(ZigType::I64));
452        assert!(saved_inner.is_some()); // Previous context saved
453        assert_eq!(saved_inner.as_ref().unwrap().name, "outer");
454
455        // Exit inner
456        let inner_ctx = lowerer.exit_fn(saved_inner);
457        assert_eq!(inner_ctx.name, "inner");
458
459        // Outer context restored
460        assert!(lowerer.fn_ctx.is_some());
461        assert_eq!(lowerer.fn_ctx.as_ref().unwrap().name, "outer");
462
463        // Exit outer
464        let outer_ctx = lowerer.exit_fn(saved_outer);
465        assert_eq!(outer_ctx.name, "outer");
466        assert!(lowerer.fn_ctx.is_none());
467    }
468
469    #[test]
470    fn test_is_export_fn() {
471        let type_info = empty_type_info();
472        let mut exported = HashSet::new();
473        exported.insert("greet".to_string());
474
475        let lowerer = Lowerer::new(
476            type_info,
477            make_jsdoc_data(),
478            Some(exported),
479            HashSet::new(),
480            String::new(),
481            String::from("test"),
482        );
483
484        assert!(lowerer.is_export_fn(Some("greet")));
485        assert!(!lowerer.is_export_fn(Some("helper")));
486        assert!(!lowerer.is_export_fn(None));
487    }
488}