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