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    /// R8-C7: When set (during a constructor body), `this.field = value`
103    /// statements are rewritten to `const field = value` so the Emitter can
104    /// build the struct return. Propagates automatically into nested
105    /// if/loop/switch/try bodies (they lower via `lower_stmt`).
106    /// Reset to `None` inside nested function contexts (via `enter_fn`)
107    /// because their `this` differs from the constructor's.
108    pub(super) this_rewrite_fields: Option<Vec<String>>,
109
110    /// C5: When true, `this` inside a closure/arrow function body should be
111    /// lowered as `IrExpr::Ident("__self")` instead of `IrExpr::This`.
112    /// Set during lowering of arrow functions / function expressions that
113    /// capture `this` from their enclosing class method.
114    pub(super) in_closure_with_this: bool,
115
116    /// Whether we're lowering inside an ExpressionStatement.
117    /// Affects UpdateExpression lowering (e.g., `i++` → `i += 1` vs block expr).
118    pub(super) in_expr_stmt: bool,
119
120    /// Counter for anonymous class expressions (to generate unique names).
121    pub(super) anon_class_counter: u32,
122
123    /// When lowering a class expression assigned to a variable (e.g. `const X = class { ... }`),
124    /// this holds the variable name. The type inferrer stores field types under the variable
125    /// name, but `lower_class_decl` generates `_AnonClass_N` for anonymous classes. This field
126    /// allows field type lookups to fall back to the variable name.
127    pub(super) class_expr_var_name: Option<String>,
128
129    // ── Diagnostics ───────────────────────────────────
130    pub(super) diagnostics: Vec<IrDiagnostic>,
131}
132
133// ═══════════════════════════════════════════════════════
134//  Constructor
135// ═══════════════════════════════════════════════════════
136
137impl Lowerer {
138    /// Create a new Lowerer.
139    pub fn new(
140        type_info: TypeCheckResult,
141        jsdoc_data: JSDocData,
142        exported_functions: Option<HashSet<String>>,
143        async_host_fns: HashSet<String>,
144        source: String,
145        module_name: String,
146    ) -> Self {
147        Self {
148            type_info,
149            jsdoc_data,
150            async_host_fns,
151            exported_functions,
152            source,
153            module_name,
154            name_mangler: NameMangler::new(),
155            fn_ctx: None,
156            closure_mgr: ClosureManager::new(),
157            class_names: HashSet::new(),
158            class_static_fields: HashMap::new(),
159            class_extends_map: HashMap::new(),
160            pending_expr_fns: Vec::new(),
161            pending_arrow_structs: Vec::new(),
162            pending_label: None,
163            current_class: None,
164            in_static_block: false,
165            this_rewrite_fields: None,
166            in_closure_with_this: false,
167            in_expr_stmt: false,
168            anon_class_counter: 0,
169            class_expr_var_name: None,
170            diagnostics: Vec::new(),
171        }
172    }
173}
174
175// ═══════════════════════════════════════════════════════
176//  Main entry point
177// ═══════════════════════════════════════════════════════
178
179impl Lowerer {
180    /// Lower a complete JS `Program` into an `IrModule`.
181    pub fn lower(&mut self, program: &Program) -> IrModule {
182        let module_name = self.module_name.clone();
183
184        // 1. Lower JSDoc @typedef definitions
185        let typedefs = self.lower_typedefs();
186
187        // 2. Lower top-level declarations
188        //    (Also collects class names, closure structs, etc.)
189        let mut declarations = Vec::new();
190        for stmt in &program.body {
191            let mut stmt_decls = self.lower_toplevel(stmt);
192            declarations.append(&mut stmt_decls);
193        }
194
195        // 3. Collect deferred closure structs
196        let mut closure_structs = self.lower_closure_structs();
197        // Also add arrow function struct definitions from var decl lowering
198        closure_structs.append(&mut self.pending_arrow_structs);
199
200        // 4. Build CABI exports metadata
201        let cabi_exports = self.build_cabi_exports(&declarations);
202
203        IrModule {
204            name: module_name,
205            typedefs,
206            closure_structs,
207            declarations,
208            diagnostics: std::mem::take(&mut self.diagnostics),
209            cabi_exports,
210        }
211    }
212}
213
214// ═══════════════════════════════════════════════════════
215//  Typedef lowering
216// ═══════════════════════════════════════════════════════
217
218impl Lowerer {
219    /// Lower JSDoc @typedef definitions into IrTypedef nodes.
220    fn lower_typedefs(&self) -> Vec<IrTypedef> {
221        let mut typedefs = Vec::new();
222        for (name, td) in &self.jsdoc_data.typedefs {
223            let fields: Vec<IrTypedefField> = td
224                .fields
225                .iter()
226                .map(|f| {
227                    let zig_type_str =
228                        crate::jsdoc::jsdoc_type_to_zig(&f.ty, &self.jsdoc_data.typedefs);
229                    IrTypedefField {
230                        name: f.name.clone(),
231                        zig_type: if f.optional {
232                            format!("?{}", zig_type_str)
233                        } else {
234                            zig_type_str
235                        },
236                        optional: f.optional,
237                    }
238                })
239                .collect();
240
241            let is_opaque = fields.is_empty();
242            typedefs.push(IrTypedef {
243                name: name.clone(),
244                fields,
245                is_opaque,
246                has_to_json: !is_opaque,
247            });
248        }
249        typedefs
250    }
251}
252
253// ═══════════════════════════════════════════════════════
254//  Top-level dispatch
255// ═══════════════════════════════════════════════════════
256
257impl Lowerer {
258    /// Lower a top-level statement into zero or more IrDecl nodes.
259    fn lower_toplevel(&mut self, stmt: &Statement) -> Vec<IrDecl> {
260        // Flush pending expression functions (def-before-use ordering)
261        let mut decls = std::mem::take(&mut self.pending_expr_fns);
262
263        match stmt {
264            Statement::VariableDeclaration(vd) => {
265                for decl in &vd.declarations {
266                    decls.push(self.lower_var_decl(decl, vd.kind.is_const()));
267                }
268            }
269            Statement::ClassDeclaration(cd) => {
270                if cd.super_class.is_some() {
271                    let span = self.span_to_source_span(cd.span);
272                    self.add_error(
273                        span.clone(),
274                        "class extends is not supported: use composition instead",
275                    );
276                    decls.push(IrDecl::CompileError {
277                        span,
278                        msg: "class extends is not supported: use composition instead".to_string(),
279                    });
280                } else if let Some(ir_class) = self.lower_class_decl(cd) {
281                    self.class_names.insert(ir_class.name.js_name.clone());
282                    // Register extends relationship for instanceof chain traversal
283                    if let Some(ref parent) = ir_class.extends {
284                        self.class_extends_map
285                            .insert(ir_class.name.js_name.clone(), parent.clone());
286                    }
287                    decls.push(IrDecl::Class(ir_class));
288                }
289            }
290            Statement::FunctionDeclaration(fd) => {
291                let is_export = self.is_export_fn(fd.id.as_ref().map(|id| id.name.as_str()));
292                if let Some(ir_fn) = self.lower_fn_decl(fd, is_export) {
293                    decls.push(IrDecl::Fn(ir_fn));
294                }
295            }
296            Statement::ExportNamedDeclaration(export_decl) => {
297                if let Some(decl) = &export_decl.declaration {
298                    match decl {
299                        Declaration::FunctionDeclaration(fd) => {
300                            let is_export =
301                                self.is_export_fn(fd.id.as_ref().map(|id| id.name.as_str()));
302                            if let Some(ir_fn) = self.lower_fn_decl(fd, is_export) {
303                                decls.push(IrDecl::Fn(ir_fn));
304                            }
305                        }
306                        Declaration::VariableDeclaration(vd) => {
307                            for decl in &vd.declarations {
308                                decls.push(self.lower_var_decl(decl, vd.kind.is_const()));
309                            }
310                        }
311                        _ => { /* skip unsupported */ }
312                    }
313                }
314            }
315            Statement::WithStatement(ws) => {
316                let span = self.span_to_source_span(ws.span);
317                self.diagnostics.push(IrDiagnostic {
318                    level: DiagnosticLevel::Error,
319                    span: Some(span),
320                    message: "with statement is not supported and deprecated in strict mode. Use explicit property access instead.".to_string(),
321                });
322            }
323            _ => { /* skip */ }
324        }
325
326        // Any new pending_expr_fns generated during this statement
327        // should be inserted before the NEXT statement's output.
328        let pending = std::mem::take(&mut self.pending_expr_fns);
329        decls.extend(pending);
330
331        decls
332    }
333}
334
335// ═══════════════════════════════════════════════════════
336//  Tests
337// ═══════════════════════════════════════════════════════
338
339#[cfg(test)]
340mod tests {
341    use super::*;
342    use crate::types::{JSDocData, ZigType};
343    use std::collections::{HashMap, HashSet};
344
345    fn empty_type_info() -> TypeCheckResult {
346        empty_type_info_base()
347    }
348
349    fn make_jsdoc_data() -> JSDocData {
350        JSDocData {
351            typedefs: HashMap::new(),
352            type_annotations: HashMap::new(),
353            return_types: HashMap::new(),
354            param_types: HashMap::new(),
355        }
356    }
357
358    fn empty_type_info_base() -> TypeCheckResult {
359        TypeCheckResult {
360            var_types: HashMap::new(),
361            array_element_types: HashMap::new(),
362            fn_return_types: HashMap::new(),
363            fn_param_types: HashMap::new(),
364            mutated_vars: HashSet::new(),
365            reassigned_vars: HashSet::new(),
366            used_names: HashSet::new(),
367            has_json_parse_types: HashSet::new(),
368            errors: Vec::new(),
369            is_async: HashMap::new(),
370            class_field_types: HashMap::new(),
371            host_return_types: HashMap::new(),
372            functions_needing_synthetic_rest: HashSet::new(),
373        }
374    }
375
376    #[test]
377    fn test_lowerer_new() {
378        let type_info = empty_type_info();
379        let lowerer = Lowerer::new(
380            type_info,
381            make_jsdoc_data(),
382            None,
383            HashSet::new(),
384            "let x = 1;".to_string(),
385            String::from("test"),
386        );
387        assert!(lowerer.fn_ctx.is_none());
388        assert!(lowerer.class_names.is_empty());
389        assert!(lowerer.diagnostics.is_empty());
390    }
391
392    #[test]
393    fn test_lowerer_empty_program() {
394        let type_info = empty_type_info();
395        let mut lowerer = Lowerer::new(
396            type_info,
397            make_jsdoc_data(),
398            None,
399            HashSet::new(),
400            String::new(),
401            String::from("test"),
402        );
403
404        // Parse an empty program
405        let js = "";
406        let allocator = oxc_allocator::Allocator::default();
407        let source_type = SourceType::default();
408        let parser = oxc_parser::Parser::new(&allocator, js, source_type);
409        let result = parser.parse();
410        let module = lowerer.lower(&result.program);
411
412        assert_eq!(module.name, "test");
413        assert!(module.declarations.is_empty());
414        assert!(module.closure_structs.is_empty());
415        assert!(module.diagnostics.is_empty());
416    }
417
418    #[test]
419    fn test_fn_context_enter_exit() {
420        let type_info = empty_type_info();
421        let mut lowerer = Lowerer::new(
422            type_info,
423            make_jsdoc_data(),
424            None,
425            HashSet::new(),
426            String::new(),
427            String::from("test"),
428        );
429
430        // Enter a function
431        let saved = lowerer.enter_fn("foo", true, Some(ZigType::I64));
432        assert!(saved.is_none()); // No previous context
433        assert!(lowerer.fn_ctx.is_some());
434
435        let ctx = lowerer.fn_ctx.as_ref().unwrap();
436        assert_eq!(ctx.name, "foo");
437        assert!(ctx.is_export);
438
439        // Exit and check returned context
440        let returned = lowerer.exit_fn(None);
441        assert_eq!(returned.name, "foo");
442        assert!(lowerer.fn_ctx.is_none());
443    }
444
445    #[test]
446    fn test_fn_context_nesting() {
447        let type_info = empty_type_info();
448        let mut lowerer = Lowerer::new(
449            type_info,
450            make_jsdoc_data(),
451            None,
452            HashSet::new(),
453            String::new(),
454            String::from("test"),
455        );
456
457        // Enter outer function
458        let saved_outer = lowerer.enter_fn("outer", true, Some(ZigType::Void));
459        assert!(saved_outer.is_none());
460
461        // Enter inner function (nested)
462        let saved_inner = lowerer.enter_fn("inner", false, Some(ZigType::I64));
463        assert!(saved_inner.is_some()); // Previous context saved
464        assert_eq!(saved_inner.as_ref().unwrap().name, "outer");
465
466        // Exit inner
467        let inner_ctx = lowerer.exit_fn(saved_inner);
468        assert_eq!(inner_ctx.name, "inner");
469
470        // Outer context restored
471        assert!(lowerer.fn_ctx.is_some());
472        assert_eq!(lowerer.fn_ctx.as_ref().unwrap().name, "outer");
473
474        // Exit outer
475        let outer_ctx = lowerer.exit_fn(saved_outer);
476        assert_eq!(outer_ctx.name, "outer");
477        assert!(lowerer.fn_ctx.is_none());
478    }
479
480    #[test]
481    fn test_is_export_fn() {
482        let type_info = empty_type_info();
483        let mut exported = HashSet::new();
484        exported.insert("greet".to_string());
485
486        let lowerer = Lowerer::new(
487            type_info,
488            make_jsdoc_data(),
489            Some(exported),
490            HashSet::new(),
491            String::new(),
492            String::from("test"),
493        );
494
495        assert!(lowerer.is_export_fn(Some("greet")));
496        assert!(!lowerer.is_export_fn(Some("helper")));
497        assert!(!lowerer.is_export_fn(None));
498    }
499}