Skip to main content

js2zig_core/
infer.rs

1use oxc_ast::ast::*;
2use std::collections::{HashMap, HashSet};
3
4use crate::codegen::collect_binding_names;
5
6// ============================================================
7// Diagnostic types
8// ============================================================
9
10#[derive(Debug, Clone, PartialEq)]
11pub enum DiagnosticKind {
12    Error,
13    Warning,
14}
15
16/// A diagnostic message with optional source location.
17#[derive(Debug, Clone)]
18pub struct Diagnostic {
19    pub kind: DiagnosticKind,
20    pub message: String,
21    /// Byte offset range in the merged source text, if available.
22    pub span: Option<(usize, usize)>,
23}
24
25impl Diagnostic {
26    /// Create a new diagnostic without source location.
27    pub fn new(kind: DiagnosticKind, message: String) -> Self {
28        Self { kind, message, span: None }
29    }
30
31    /// Attach a source span to this diagnostic.
32    pub fn with_span(mut self, start: usize, end: usize) -> Self {
33        self.span = Some((start, end));
34        self
35    }
36
37    /// Format the diagnostic with line:column info from source text.
38    pub fn format_with_source(&self, source: &str) -> String {
39        let prefix = match self.kind {
40            DiagnosticKind::Error => "error",
41            DiagnosticKind::Warning => "warning",
42        };
43        match self.span {
44            Some((start, _end)) => {
45                let (line, col) = byte_offset_to_line_col(source, start);
46                format!("{}: [{}:{}] {}", prefix, line, col, self.message)
47            }
48            None => format!("{}: {}", prefix, self.message),
49        }
50    }
51}
52
53/// Convert a byte offset in source text to 1-based line:column.
54fn byte_offset_to_line_col(source: &str, offset: usize) -> (usize, usize) {
55    let offset = offset.min(source.len());
56    let prefix = &source[..offset];
57    let line = prefix.bytes().filter(|&b| b == b'\n').count() + 1;
58    let last_newline = prefix.rfind('\n').map(|i| i + 1).unwrap_or(0);
59    let col = offset - last_newline + 1;
60    (line, col)
61}
62
63// ============================================================
64// ZigType
65// ============================================================
66
67#[derive(Debug, Clone, PartialEq)]
68pub enum ZigType {
69    I64,
70    I32,
71    Usize,
72    F64,
73    F32,
74    Bool,
75    String,
76    Null,
77    Void,
78    Array(Box<ZigType>),
79    /// Slice type for function parameters ([]const T).
80    /// Unlike Array (\[_\]T), Slice does not require a compile-time size.
81    Slice(Box<ZigType>),
82    Optional(Box<ZigType>),
83    FunctionPtr(Box<ZigFuncSig>),
84    /// Named struct type (e.g., class-based: "Rectangle")
85    Struct(String),
86    /// Anonymous object struct with known field types (e.g., `{ name: "Alice", age: 30 }`)
87    Object {
88        fields: Vec<(String, ZigType)>,
89    },
90    /// Union type (e.g., `number | string` from heterogeneous returns)
91    /// Generated as a tagged union in Zig.
92    Union(Vec<ZigType>),
93    /// Dynamic JS value type — maps to Zig `JsValue` union enum.
94    /// Used for `var` declarations with value-type expressions (string/number/bool).
95    JsValue,
96    /// General-purpose container type — maps to Zig `JsAny`.
97    /// Used for dynamic arrays (ArrayList), dynamic objects (HashMap), and nested structures.
98    JsAny,
99}
100
101#[derive(Debug, Clone, PartialEq)]
102pub struct ZigFuncSig {
103    pub params: Vec<ZigType>,
104    pub return_type: Box<ZigType>,
105}
106
107impl ZigType {
108    pub fn to_zig_str(&self) -> String {
109        match self {
110            ZigType::I64 => "i64".to_string(),
111            ZigType::I32 => "i32".to_string(),
112            ZigType::Usize => "usize".to_string(),
113            ZigType::F64 => "f64".to_string(),
114            ZigType::F32 => "f32".to_string(),
115            ZigType::Bool => "bool".to_string(),
116            ZigType::String => "[]const u8".to_string(),
117            ZigType::Null => "null".to_string(),
118            ZigType::Void => "void".to_string(),
119            ZigType::JsValue => "JsValue".to_string(),
120            ZigType::JsAny => "JsAny".to_string(),
121            ZigType::Array(elem) => format!("[_]{}", elem.to_zig_str()),
122            ZigType::Slice(elem) => format!("[]const {}", elem.to_zig_str()),
123            ZigType::Optional(inner) => format!("?{}", inner.to_zig_str()),
124            ZigType::FunctionPtr(sig) => {
125                let params: Vec<String> = sig.params.iter().map(|p| p.to_zig_str()).collect();
126                format!("fn ({}) {}", params.join(", "), sig.return_type.to_zig_str())
127            }
128            ZigType::Struct(name) => name.clone(),
129            ZigType::Object { .. } => "JsAny".to_string(),
130            ZigType::Union(_) => "JsValue".to_string(),
131        }
132    }
133
134    /// Return the C ABI compatible type string.
135    /// JsValue/JsAny are represented as i64 over C ABI (extracting .int field).
136    pub fn to_cabi_str(&self) -> String {
137        match self {
138            ZigType::JsValue | ZigType::JsAny => "i64".to_string(),
139            _ => self.to_zig_str(),
140        }
141    }
142
143    pub fn is_numeric(&self) -> bool {
144        matches!(self, ZigType::I64 | ZigType::I32 | ZigType::F64 | ZigType::F32 | ZigType::Usize)
145    }
146
147    /// Widen: if both numeric, pick wider; if JsAny involved → JsAny; otherwise JsValue
148    pub fn widen(left: &ZigType, right: &ZigType) -> ZigType {
149        // JsAny absorbs everything (most general container)
150        if matches!(left, ZigType::JsAny) || matches!(right, ZigType::JsAny) {
151            return ZigType::JsAny;
152        }
153        // JsValue absorbs non-JsAny types
154        if matches!(left, ZigType::JsValue) || matches!(right, ZigType::JsValue) {
155            return ZigType::JsValue;
156        }
157        match (left, right) {
158            (ZigType::F64, _) | (_, ZigType::F64) => ZigType::F64,
159            (ZigType::F32, _) | (_, ZigType::F32) => ZigType::F64,
160            (ZigType::I64, _) | (_, ZigType::I64) => ZigType::I64,
161            (ZigType::I32, ZigType::I32) => ZigType::I32,
162            (ZigType::Usize, ZigType::Usize) => ZigType::Usize,
163            // Union types: merge and simplify
164            (ZigType::Union(l), ZigType::Union(r)) => {
165                let mut merged = l.clone();
166                merged.extend(r.clone());
167                ZigType::simplify_union(merged)
168            }
169            (ZigType::Union(u), other) | (other, ZigType::Union(u)) => {
170                let mut merged = u.clone();
171                merged.push(other.clone());
172                ZigType::simplify_union(merged)
173            }
174            _ => ZigType::JsValue,
175        }
176    }
177
178    /// Create a union type, simplifying if possible
179    pub fn make_union(types: Vec<ZigType>) -> ZigType {
180        if types.is_empty() {
181            return ZigType::Void;
182        }
183        if types.len() == 1 {
184            return types[0].clone();
185        }
186        // Deduplicate
187        let mut dedup = Vec::new();
188        for t in types {
189            if !dedup.iter().any(|d| d == &t) {
190                dedup.push(t);
191            }
192        }
193        if dedup.len() == 1 {
194            return dedup[0].clone();
195        }
196        ZigType::simplify_union(dedup)
197    }
198
199    /// Simplify a union type: flatten Optionals, widen numerics, etc.
200    fn simplify_union(types: Vec<ZigType>) -> ZigType {
201        // Defensive: empty union → JsValue
202        if types.is_empty() {
203            return ZigType::JsValue;
204        }
205        // Defensive: single-element union → flatten
206        if types.len() == 1 {
207            return types[0].clone();
208        }
209
210        // Optional flattening: JS `T | null` → Zig `?T`
211        let has_null = types.iter().any(|t| matches!(t, ZigType::Null));
212        if has_null {
213            let non_null: Vec<ZigType> = types
214                .into_iter()
215                .filter(|t| !matches!(t, ZigType::Null))
216                .collect();
217            let simplified = ZigType::simplify_union(non_null);
218            return ZigType::Optional(Box::new(simplified));
219        }
220
221        // JsAny absorbs everything (most general container type)
222        if types.iter().any(|t| matches!(t, ZigType::JsAny)) {
223            return ZigType::JsAny;
224        }
225
226        // JsValue absorbs non-JsAny types
227        if types.iter().any(|t| matches!(t, ZigType::JsValue)) {
228            return ZigType::JsValue;
229        }
230
231        // If all numeric, widen to the widest type
232        if types.iter().all(|t| t.is_numeric()) {
233            let mut result = types[0].clone();
234            for t in &types[1..] {
235                result = ZigType::widen(&result, t);
236            }
237            return result;
238        }
239
240        ZigType::Union(types)
241    }
242
243    /// Check if this type is a primitive value type (int, float, bool, string, null).
244    pub fn is_value_type(&self) -> bool {
245        matches!(self, ZigType::I64 | ZigType::I32 | ZigType::F64 | ZigType::F32
246            | ZigType::Bool | ZigType::String | ZigType::Null | ZigType::Usize)
247    }
248
249    /// Check if this type is a static array or object (Layer 1).
250    pub fn is_static_aggregate(&self) -> bool {
251        matches!(self, ZigType::Array(_) | ZigType::Object { .. } | ZigType::Slice(_))
252    }
253}
254
255// ============================================================
256// Constant expression detection
257// ============================================================
258
259/// Determine if an expression is a compile-time constant.
260/// Used to decide whether a `const` variable gets a precise Zig type (Layer 1)
261/// or falls back to JsAny (Layer 3).
262///
263/// A constant expression is:
264/// - A literal (number, string, boolean, null, bigint)
265/// - A binary expression where both operands are constant
266/// - A unary expression where the argument is constant
267/// - A template literal with no interpolated expressions
268/// - An array where all elements are constant
269/// - An object where all property values are constant
270/// - A parenthesized expression wrapping a constant
271pub fn is_constant_expr(expr: &Expression) -> bool {
272    match expr {
273        // Literals — always constant
274        Expression::NumericLiteral(_)
275        | Expression::StringLiteral(_)
276        | Expression::BooleanLiteral(_)
277        | Expression::NullLiteral(_)
278        | Expression::BigIntLiteral(_) => true,
279
280        // Binary expression — constant if both operands are constant
281        Expression::BinaryExpression(bin) => {
282            is_constant_expr(&bin.left) && is_constant_expr(&bin.right)
283        }
284
285        // Unary expression — constant if argument is constant
286        Expression::UnaryExpression(un) => is_constant_expr(&un.argument),
287
288        // Template literal — constant only if no interpolated expressions
289        Expression::TemplateLiteral(tl) => tl.expressions.is_empty(),
290
291        // Array — constant if all elements are constant
292        Expression::ArrayExpression(arr) => {
293            arr.elements.iter().all(|elem| {
294                elem.as_expression().is_some_and(is_constant_expr)
295            })
296        }
297
298        // Object — constant if all property values are constant (no spread)
299        Expression::ObjectExpression(obj) => {
300            obj.properties.iter().all(|prop| match prop {
301                ObjectPropertyKind::ObjectProperty(p) => is_constant_expr(&p.value),
302                ObjectPropertyKind::SpreadProperty(_) => false,
303            })
304        }
305
306        // Parenthesized — constant if inner is constant
307        Expression::ParenthesizedExpression(p) => is_constant_expr(&p.expression),
308
309        // Everything else is not constant
310        _ => false,
311    }
312}
313
314// ============================================================
315// BindingInfo
316// ============================================================
317
318#[derive(Debug, Clone)]
319pub struct BindingInfo {
320    pub zig_type: ZigType,
321    pub is_const: bool,
322}
323
324// ============================================================
325// ParamConstraint — how a parameter is used, constraining its type
326// ============================================================
327
328#[derive(Debug, Clone)]
329enum ParamConstraint {
330    /// Used in binary expression: (other_operand_type, operator, is_left_operand)
331    BinaryWith(ZigType, BinaryOperator, bool),
332    /// Passed as argument to a function: (callee_name, arg_index)
333    CallArg(String, usize),
334    /// Used with a unary operator
335    UnaryOp(UnaryOperator),
336    /// Used as update target (++/--)
337    Update,
338    /// Used as if/while test condition
339    Condition,
340    /// Used in return position only (no type constraint from this alone)
341    ReturnPos,
342    /// Parameter was referenced but the usage doesn't constrain its type
343    /// (e.g., member access obj.prop, array index arr[0])
344    Referenced,
345    /// Parameter is the iterable target of a for-of loop (e.g., `for (const x of arr)`)
346    IteratedInto,
347}
348
349// ============================================================
350// TypeInferrer
351// ============================================================
352
353pub struct TypeInferrer {
354    env: HashMap<String, BindingInfo>,
355    fn_return_types: HashMap<String, ZigType>,
356    fn_param_types: HashMap<String, Vec<ZigType>>,
357    fn_param_names: HashMap<String, Vec<String>>,
358    diagnostics: Vec<Diagnostic>,
359    /// Variables whose objects need HashMap-based dynamic property access
360    /// (detected when computed member expr uses a variable key, e.g., obj[key])
361    dynamic_access_vars: HashSet<String>,
362    /// Variables whose arrays need ArrayList-based dynamic storage
363    /// (detected when push/pop/shift/unshift/splice/sort/reverse is called on them)
364    dynamic_arrays: HashSet<String>,
365    /// Persistent storage for local variable types per function.
366    /// Key: function name, Value: map from local variable name to its type.
367    /// Populated during inference, used by codegen via get_var_type.
368    fn_local_types: HashMap<String, HashMap<String, ZigType>>,
369    /// Current function being analyzed (set by register_fn_env, cleared by unregister).
370    /// Used to populate fn_local_types correctly.
371    /// Also set by codegen before generating each function body,
372    /// so that get_var_type() can look up fn_local_types.
373    pub(crate) current_fn: Option<String>,
374}
375
376/// Pre-indexed function data for O(1) lookup.
377/// Built once at the start of inference, eliminating repeated linear scans
378/// of `program.body` (previously ~7Nx for N functions).
379struct FnIndex<'a> {
380    /// All top-level statements (for initialization scans)
381    top_level: &'a [Statement<'a>],
382    /// fn_name → body statements
383    fn_bodies: HashMap<String, &'a [Statement<'a>]>,
384    /// fn_name → formal parameters (with defaults)
385    fn_params: HashMap<String, &'a FormalParameters<'a>>,
386}
387
388impl<'a> FnIndex<'a> {
389    fn build(program: &'a Program<'a>) -> Self {
390        let mut fn_bodies: HashMap<String, &'a [Statement<'a>]> = HashMap::new();
391        let mut fn_params: HashMap<String, &'a FormalParameters<'a>> = HashMap::new();
392
393        for stmt in &program.body {
394            match stmt {
395                Statement::FunctionDeclaration(fd) => {
396                    if let Some(id) = &fd.id {
397                        let name = id.name.to_string();
398                        fn_params.insert(name.clone(), &fd.params);
399                        if let Some(body) = &fd.body {
400                            fn_bodies.insert(name, body.statements.as_slice());
401                        }
402                    }
403                }
404                Statement::VariableDeclaration(vd) => {
405                    for decl in &vd.declarations {
406                        let mut names = Vec::new();
407                        collect_binding_names(&decl.id, &mut names);
408                        if names.len() == 1
409                            && !names[0].starts_with("test_")
410                            && let Some(init) = &decl.init
411                        {
412                            match init {
413                                Expression::ArrowFunctionExpression(a) => {
414                                    fn_params.insert(names[0].clone(), &a.params);
415                                    fn_bodies.insert(names[0].clone(), a.body.statements.as_slice());
416                                }
417                                Expression::FunctionExpression(fe) => {
418                                    fn_params.insert(names[0].clone(), &fe.params);
419                                    if let Some(body) = &fe.body {
420                                        fn_bodies.insert(names[0].clone(), body.statements.as_slice());
421                                    }
422                                }
423                                _ => {}
424                            }
425                        }
426                    }
427                }
428                _ => {}
429            }
430        }
431
432        FnIndex { top_level: &program.body, fn_bodies, fn_params }
433    }
434
435    fn has_body(&self, fn_name: &str) -> bool {
436        self.fn_bodies.contains_key(fn_name)
437    }
438
439    fn params(&self, fn_name: &str) -> Option<&&'a FormalParameters<'a>> {
440        self.fn_params.get(fn_name)
441    }
442
443    fn body_stmts(&self, fn_name: &str) -> Option<&&'a [Statement<'a>]> {
444        self.fn_bodies.get(fn_name)
445    }
446}
447
448// ============================================================
449// Generic AST walkers — shared structural traversal for
450// detect_dynamic_access and collect_constraints passes.
451// ============================================================
452
453/// Event dispatched by walk_stmt for each expression or sub-statement encountered.
454enum WalkEvent<'a> {
455    Expr(&'a Expression<'a>),
456    Stmt(&'a Statement<'a>),
457}
458
459/// Walk all sub-statements and sub-expressions within a statement.
460/// Dispatches `WalkEvent::Expr` for every expression and `WalkEvent::Stmt`
461/// for every nested statement. This is pure structural traversal — no business logic.
462fn walk_stmt<'a, F>(stmt: &'a Statement<'a>, on_event: &mut F)
463where
464    F: FnMut(WalkEvent<'a>),
465{
466    match stmt {
467        Statement::VariableDeclaration(v) => {
468            for decl in &v.declarations {
469                if let Some(init) = &decl.init {
470                    on_event(WalkEvent::Expr(init));
471                }
472            }
473        }
474        Statement::ExpressionStatement(e) => on_event(WalkEvent::Expr(&e.expression)),
475        Statement::ReturnStatement(r) => {
476            if let Some(arg) = &r.argument {
477                on_event(WalkEvent::Expr(arg));
478            }
479        }
480        Statement::IfStatement(i) => {
481            on_event(WalkEvent::Expr(&i.test));
482            on_event(WalkEvent::Stmt(&i.consequent));
483            if let Some(alt) = &i.alternate {
484                on_event(WalkEvent::Stmt(alt));
485            }
486        }
487        Statement::ForStatement(f) => {
488            if let Some(init) = &f.init
489                && let Some(e) = init.as_expression()
490            {
491                on_event(WalkEvent::Expr(e));
492            }
493            if let Some(test) = &f.test {
494                on_event(WalkEvent::Expr(test));
495            }
496            if let Some(update) = &f.update {
497                on_event(WalkEvent::Expr(update));
498            }
499            on_event(WalkEvent::Stmt(&f.body));
500        }
501        Statement::WhileStatement(w) => {
502            on_event(WalkEvent::Expr(&w.test));
503            on_event(WalkEvent::Stmt(&w.body));
504        }
505        Statement::DoWhileStatement(d) => {
506            on_event(WalkEvent::Stmt(&d.body));
507            on_event(WalkEvent::Expr(&d.test));
508        }
509        Statement::BlockStatement(b) => {
510            for s in &b.body {
511                on_event(WalkEvent::Stmt(s));
512            }
513        }
514        Statement::SwitchStatement(s) => {
515            on_event(WalkEvent::Expr(&s.discriminant));
516            for case in &s.cases {
517                if let Some(test) = &case.test {
518                    on_event(WalkEvent::Expr(test));
519                }
520                for st in &case.consequent {
521                    on_event(WalkEvent::Stmt(st));
522                }
523            }
524        }
525        Statement::FunctionDeclaration(f) => {
526            if let Some(body) = &f.body {
527                for s in &body.statements {
528                    on_event(WalkEvent::Stmt(s));
529                }
530            }
531        }
532        Statement::ThrowStatement(t) => on_event(WalkEvent::Expr(&t.argument)),
533        Statement::TryStatement(t) => {
534            for s in &t.block.body {
535                on_event(WalkEvent::Stmt(s));
536            }
537            if let Some(h) = &t.handler {
538                for s in &h.body.body {
539                    on_event(WalkEvent::Stmt(s));
540                }
541            }
542            if let Some(f) = &t.finalizer {
543                for s in &f.body {
544                    on_event(WalkEvent::Stmt(s));
545                }
546            }
547        }
548        Statement::LabeledStatement(l) => on_event(WalkEvent::Stmt(&l.body)),
549        Statement::ForOfStatement(f) => {
550            on_event(WalkEvent::Expr(&f.right));
551            on_event(WalkEvent::Stmt(&f.body));
552        }
553        Statement::ForInStatement(f) => {
554            on_event(WalkEvent::Expr(&f.right));
555            on_event(WalkEvent::Stmt(&f.body));
556        }
557        _ => {}
558    }
559}
560
561/// Walk all immediate child expressions of an expression node.
562/// Pure structural recursion — callers add their own specialized logic
563/// before or after calling this.
564fn walk_expr_children<'a>(
565    expr: &'a Expression<'a>,
566    on_expr: &mut dyn FnMut(&'a Expression<'a>),
567) {
568    match expr {
569        Expression::BinaryExpression(b) => {
570            on_expr(&b.left);
571            on_expr(&b.right);
572        }
573        Expression::LogicalExpression(l) => {
574            on_expr(&l.left);
575            on_expr(&l.right);
576        }
577        Expression::UnaryExpression(u) => on_expr(&u.argument),
578        Expression::CallExpression(c) => {
579            on_expr(&c.callee);
580            for arg in &c.arguments {
581                if let Some(e) = arg.as_expression() {
582                    on_expr(e);
583                }
584            }
585        }
586        Expression::AssignmentExpression(a) => on_expr(&a.right),
587        Expression::ConditionalExpression(c) => {
588            on_expr(&c.test);
589            on_expr(&c.consequent);
590            on_expr(&c.alternate);
591        }
592        Expression::ArrayExpression(a) => {
593            for elem in &a.elements {
594                if let Some(e) = elem.as_expression() {
595                    on_expr(e);
596                }
597            }
598        }
599        Expression::ObjectExpression(o) => {
600            for prop in &o.properties {
601                match prop {
602                    ObjectPropertyKind::ObjectProperty(p) => on_expr(&p.value),
603                    ObjectPropertyKind::SpreadProperty(s) => on_expr(&s.argument),
604                }
605            }
606        }
607        Expression::ParenthesizedExpression(p) => on_expr(&p.expression),
608        Expression::SequenceExpression(s) => {
609            for e in &s.expressions {
610                on_expr(e);
611            }
612        }
613        Expression::ComputedMemberExpression(m) => {
614            on_expr(&m.object);
615            on_expr(&m.expression);
616        }
617        Expression::StaticMemberExpression(m) => on_expr(&m.object),
618        Expression::AwaitExpression(a) => on_expr(&a.argument),
619        Expression::YieldExpression(y) => {
620            if let Some(arg) = &y.argument {
621                on_expr(arg);
622            }
623        }
624        Expression::NewExpression(n) => {
625            for arg in &n.arguments {
626                if let Some(e) = arg.as_expression() {
627                    on_expr(e);
628                }
629            }
630        }
631        // Bodies of function/arrow expressions are handled by walk_stmt,
632        // not by this expr-level walker.
633        Expression::ArrowFunctionExpression(_) | Expression::FunctionExpression(_) => {}
634        _ => {}
635    }
636}
637
638impl Default for TypeInferrer {
639    fn default() -> Self {
640        Self::new()
641    }
642}
643
644impl TypeInferrer {
645    pub fn new() -> Self {
646        Self {
647            env: HashMap::new(),
648            fn_return_types: HashMap::new(),
649            fn_param_types: HashMap::new(),
650            fn_param_names: HashMap::new(),
651            diagnostics: Vec::new(),
652            dynamic_access_vars: HashSet::new(),
653            dynamic_arrays: HashSet::new(),
654            fn_local_types: HashMap::new(),
655            current_fn: None,
656        }
657    }
658
659    // ============================================================
660    // Main entry point
661    // ============================================================
662
663    pub fn infer_program(&mut self, program: &Program) {
664        // Pre-pass: detect variables accessed with dynamic (non-literal) keys.
665        // These variables must use HashMap instead of struct.
666        self.detect_dynamic_access(program);
667
668        // Pre-pass: detect arrays that have mutation methods called on them
669        // (push/pop/shift/unshift/splice/sort/reverse).
670        // These arrays must use ArrayList instead of fixed-size [_]T.
671        self.detect_dynamic_arrays(program);
672
673        // Build O(1) function index to eliminate repeated program.body scans
674        let index = FnIndex::build(program);
675
676        // Pass 1: collect assignments, register function signatures
677        self.collect_top_level(&index);
678        // Pass 2: infer function params from body usages
679        self.infer_all_fn_params(&index);
680        // Pass 3: infer return types with known param types
681        self.infer_all_return_types(&index);
682        // Pass 4: cross-function propagation + call-site propagation
683        self.propagate_cross_fn(&index);
684        // Pass 5: validate and report
685        self.validate_types();
686        // Pass 6: register all function params permanently for codegen queries
687        self.install_all_fn_params();
688    }
689
690    // ============================================================
691    // Public query methods
692    // ============================================================
693
694    pub fn diagnostics(&self) -> &[Diagnostic] { &self.diagnostics }
695    pub fn has_errors(&self) -> bool {
696        self.diagnostics.iter().any(|d| d.kind == DiagnosticKind::Error)
697    }
698
699    pub fn get_var_type(&self, name: &str) -> ZigType {
700        // Check temporary env first (populated during inference)
701        if let Some(ty) = self.env.get(name).map(|bi| bi.zig_type.clone()) {
702            return ty;
703        }
704        // Fall back to persistent fn_local_types (populated during inference,
705        // used during codegen when env is not populated).
706        if let Some(ref fn_name) = self.current_fn
707            && let Some(local_map) = self.fn_local_types.get(fn_name)
708            && let Some(ty) = local_map.get(name)
709        {
710            return ty.clone();
711        }
712        // If current_fn is set but var not found, try all functions (edge case)
713        for local_map in self.fn_local_types.values() {
714            if let Some(ty) = local_map.get(name) {
715                return ty.clone();
716            }
717        }
718        ZigType::JsValue
719    }
720
721    /// Check if a variable name is in the dynamic_arrays set
722    /// (i.e., push/pop/shift/unshift/splice/sort/reverse was called on it)
723    pub fn is_dynamic_array(&self, name: &str) -> bool {
724        self.dynamic_arrays.contains(name)
725    }
726
727    /// Check if a name is a parameter of a specific function.
728    pub fn is_fn_param_of(&self, fn_name: &str, param_name: &str) -> bool {
729        self.fn_param_names.get(fn_name)
730            .map(|params| params.iter().any(|p| p == param_name))
731            .unwrap_or(false)
732    }
733
734    /// Check if a name is a parameter of any known function.
735    pub fn is_fn_param(&self, name: &str) -> bool {
736        self.fn_param_names.values().any(|params| params.iter().any(|p| p == name))
737    }
738
739    pub fn get_fn_return_type(&self, name: &str) -> ZigType {
740        self.fn_return_types.get(name).cloned().unwrap_or(ZigType::JsValue)
741    }
742
743    pub fn all_fn_return_types(&self) -> HashMap<String, ZigType> {
744        self.fn_return_types.clone()
745    }
746
747    /// Determine the Zig type for a variable based on the three-layer type system.
748    ///
749    /// Layer 1 (ZigType): `const` + constant expression → precise Zig type
750    /// Layer 2 (JsValue): `var` + value type (no dynamic usage) → JsValue
751    /// Layer 3 (JsAny): dynamic arrays/objects, or `const` with non-constant init
752    pub fn infer_var_type(&self, name: &str, init: &Expression, is_const: bool) -> ZigType {
753        let is_constant = is_constant_expr(init);
754
755        // Rule 1: const + constant expression → precise Zig type (Layer 1)
756        if is_const && is_constant {
757            return self.infer_expr(init);
758        }
759
760        // Rule 2.3: const + new ClassName() → Struct (preserve class type)
761        if is_const
762            && let Expression::NewExpression(_) = init {
763                return self.infer_expr(init);
764            }
765
766        // Rule 2.3b: const + arrow/function expression → FunctionPtr (preserve callable type)
767        if is_const && matches!(init,
768            Expression::ArrowFunctionExpression(_) | Expression::FunctionExpression(_)
769        ) {
770            return self.infer_expr(init);
771        }
772
773        // Rule 2.4: const but not constant → JsAny (Layer 3)
774        if is_const {
775            return ZigType::JsAny;
776        }
777
778        // var declaration — check usage context for dynamic arrays/objects
779        let is_dyn_array = self.dynamic_arrays.contains(name);
780        let is_dyn_obj = self.dynamic_access_vars.contains(name);
781
782        // Dynamic usage → JsAny (Layer 3)
783        if is_dyn_array || is_dyn_obj {
784            return ZigType::JsAny;
785        }
786
787        let init_type = self.infer_expr(init);
788
789        // Rule 2.2/2.3: var + static array/object (no dynamic usage) → keep type
790        if init_type.is_static_aggregate() {
791            return init_type;
792        }
793
794        // Rule 2.1: var + value type → JsValue (Layer 2)
795        if init_type.is_value_type() {
796            return ZigType::JsValue;
797        }
798
799        // Function expressions keep their type
800        if matches!(init_type, ZigType::FunctionPtr(_)) {
801            return init_type;
802        }
803
804        // Default → JsValue
805        ZigType::JsValue
806    }
807
808    pub fn get_fn_param_types(&self, name: &str) -> Vec<ZigType> {
809        self.fn_param_types.get(name).cloned().unwrap_or_default()
810    }
811
812    /// Infer the type of an arrow function parameter from how it's used in the body.
813    /// Uses the same body-driven constraint approach as regular function params.
814    /// `arrow_body` is the body of the ArrowFunctionExpression.
815    pub fn infer_arrow_param_type(
816        &self,
817        param_name: &str,
818        arrow_body: &oxc_ast::ast::FunctionBody,
819    ) -> ZigType {
820        let mut constraints = Vec::new();
821        for s in &arrow_body.statements {
822            self.collect_constraints_in_stmt(param_name, s, &mut constraints);
823        }
824        if constraints.is_empty() {
825            return ZigType::I64; // aggressive default for arrow params
826        }
827        self.resolve_param_type(&constraints)
828    }
829
830    /// After all inference passes, register all function params in the env
831    /// so that codegen's closure pre-scan can look up captured variable types.
832    /// NOTE: This is a temporary workaround. Proper scoping should be implemented
833    /// to avoid cross-scope variable name conflicts.
834    fn install_all_fn_params(&mut self) {
835        for (fn_name, param_types) in &self.fn_param_types {
836            if let Some(param_names) = self.fn_param_names.get(fn_name) {
837                for (i, pn) in param_names.iter().enumerate() {
838                    let ty = if i < param_types.len() {
839                        param_types[i].clone()
840                    } else {
841                        ZigType::I64
842                    };
843                    // Do NOT overwrite an existing variable with a more accurate type.
844                    // This avoids cross-scope conflicts (e.g., a param named "base"
845                    // overwriting a top-level object variable also named "base").
846                    if let Some(existing) = self.env.get_mut(pn) {
847                        // Only upgrade from Any to a concrete type; never downgrade.
848                        if existing.zig_type == ZigType::JsValue {
849                            existing.zig_type = ty;
850                        }
851                    } else {
852                        self.env.insert(pn.clone(), BindingInfo { zig_type: ty, is_const: true });
853                    }
854                }
855            }
856        }
857    }
858
859    // ============================================================
860    // PASS 1: collect top-level declarations
861    // ============================================================
862
863    fn collect_top_level(&mut self, index: &FnIndex) {
864        // First: register all function names for cross-reference
865        for name in index.fn_bodies.keys() {
866            self.fn_param_types.entry(name.clone()).or_default();
867            self.fn_return_types.entry(name.clone()).or_insert(ZigType::Void);
868        }
869        // Also register bodyless functions (host functions with params only)
870        for (name, params) in &index.fn_params {
871            if !self.fn_param_types.contains_key(name) {
872                self.fn_param_types.entry(name.clone()).or_default();
873                self.fn_return_types.entry(name.clone()).or_insert(ZigType::Void);
874            }
875            let pnames: Vec<String> = params.items.iter()
876                .map(|p| {
877                    let mut n = Vec::new();
878                    collect_binding_names(&p.pattern, &mut n);
879                    // Use "_" as placeholder for destructured/anonymous params
880                    // to avoid generating empty parameter names in Zig output
881                    let name = n.into_iter().next().unwrap_or_default();
882                    if name.is_empty() { "_".to_string() } else { name }
883                })
884                .collect();
885            if !pnames.is_empty() {
886                self.fn_param_names.insert(name.clone(), pnames);
887            }
888        }
889
890        // Second: infer assignment types and register function sigs
891        for stmt in index.top_level {
892            match stmt {
893                Statement::VariableDeclaration(vd) => {
894                    let is_const = matches!(vd.kind, VariableDeclarationKind::Const);
895                    for decl in &vd.declarations {
896                        let mut names = Vec::new();
897                        collect_binding_names(&decl.id, &mut names);
898                        let ty = decl.init.as_ref()
899                            .map(|init| {
900                                if names.len() == 1 {
901                                    // Single binding — apply three-layer type inference
902                                    self.infer_var_type(&names[0], init, is_const)
903                                } else {
904                                    // Destructured — infer from expression
905                                    self.infer_expr(init)
906                                }
907                            })
908                            .unwrap_or(ZigType::JsValue);
909
910                        for name in &names {
911                            self.env.insert(name.clone(), BindingInfo { zig_type: ty.clone(), is_const });
912                        }
913
914                        if names.len() == 1
915                            && !names[0].starts_with("test_")
916                            && let Some(init) = &decl.init
917                                && let Some(sig) = self.extract_fn_sig(init) {
918                                    let fn_name = &names[0];
919                                    self.fn_return_types.insert(fn_name.clone(), (*sig.return_type).clone());
920                                    self.fn_param_types.insert(fn_name.clone(), sig.params);
921                                    if !self.fn_param_names.contains_key(fn_name) {
922                                        self.fn_param_names.insert(fn_name.clone(), Vec::new());
923                                    }
924                                }
925                    }
926                }
927                Statement::FunctionDeclaration(fd) => {
928                    if let Some(id) = &fd.id {
929                        let name = id.name.to_string();
930                        let sig = ZigFuncSig {
931                            params: self.fn_param_types.get(&name).cloned().unwrap_or_default(),
932                            return_type: Box::new(
933                                self.fn_return_types.get(&name).cloned().unwrap_or(ZigType::Void),
934                            ),
935                        };
936                        self.env.insert(name, BindingInfo {
937                            zig_type: ZigType::FunctionPtr(Box::new(sig)),
938                            is_const: true,
939                        });
940                    }
941                }
942                _ => {}
943            }
944        }
945    }
946
947    // ============================================================
948    // PASS 2: infer function params from body usages
949    // ============================================================
950
951    fn infer_all_fn_params(&mut self, index: &FnIndex) {
952        // Collect fn names first to avoid borrow issues
953        let fn_names: Vec<String> = self.fn_param_types.keys().cloned().collect();
954
955        for fn_name in &fn_names {
956            // Check if this function has a body; if not, only validate defaults
957            if !index.has_body(fn_name) {
958                if let Some(pnames) = self.fn_param_names.get(fn_name) {
959                    let params = self.fn_param_types.get(fn_name).cloned().unwrap_or_default();
960                    for (i, pname) in pnames.iter().enumerate() {
961                        if i < params.len() && params[i] == ZigType::JsValue {
962                            self.diagnostics.push(Diagnostic::new(
963                                DiagnosticKind::Error,
964                                format!(
965                                    "function '{}' parameter '{}' has no body to infer from",
966                                    fn_name, pname
967                                ),
968                            ));
969                        }
970                    }
971                }
972                continue;
973            }
974
975            let param_names: Vec<String> = self.fn_param_names
976                .get(fn_name)
977                .cloned()
978                .unwrap_or_default();
979
980            let mut inferred: Vec<ZigType> = Vec::new();
981
982            for (i, pname) in param_names.iter().enumerate() {
983                // Check default value first
984                let default_ty = self.get_param_default_type(fn_name, i, index);
985
986                if default_ty != ZigType::JsValue {
987                    inferred.push(default_ty);
988                    continue;
989                }
990
991                // Analyze body usages — O(1) body lookup via FnIndex
992                let body_stmts = index.body_stmts(fn_name)
993                    .copied()
994                    .unwrap_or(&[]);
995                let mut constraints = Vec::new();
996                for s in body_stmts {
997                    self.collect_constraints_in_stmt(pname, s, &mut constraints);
998                }
999                if constraints.is_empty() {
1000                    self.diagnostics.push(Diagnostic::new(
1001                        DiagnosticKind::Error,
1002                        format!(
1003                            "function '{}' parameter '{}' is never referenced in the function body",
1004                            fn_name, pname
1005                        ),
1006                    ));
1007                    inferred.push(ZigType::JsValue);
1008                } else {
1009                    inferred.push(self.resolve_param_type(&constraints));
1010                }
1011            }
1012
1013            self.fn_param_types.insert(fn_name.clone(), inferred);
1014        }
1015    }
1016
1017    /// Get the default value type for parameter index i of function fn_name
1018    fn get_param_default_type(&self, fn_name: &str, param_idx: usize, index: &FnIndex) -> ZigType {
1019        if let Some(params) = index.params(fn_name)
1020            && param_idx < params.items.len()
1021        {
1022            return params.items[param_idx].initializer.as_ref()
1023                .map(|d| self.infer_expr(d))
1024                .unwrap_or(ZigType::JsValue);
1025        }
1026        ZigType::JsValue
1027    }
1028
1029    // ============================================================
1030    // Parameter constraint collection (walking AST)
1031    // ============================================================
1032
1033    fn collect_constraints_in_stmt(
1034        &self,
1035        param_name: &str,
1036        stmt: &Statement,
1037        constraints: &mut Vec<ParamConstraint>,
1038    ) {
1039        // Specialized constraint checks for specific statement types.
1040        // These happen before structural traversal so the constraints are
1041        // recorded even if walk_stmt would also trigger them via expr walk.
1042        match stmt {
1043            Statement::ReturnStatement(rs) => {
1044                if let Some(arg) = &rs.argument
1045                    && self.is_name_ref_expr(arg, param_name)
1046                {
1047                    constraints.push(ParamConstraint::ReturnPos);
1048                }
1049            }
1050            Statement::IfStatement(ifs)
1051                if self.is_name_ref_expr(&ifs.test, param_name) =>
1052            {
1053                constraints.push(ParamConstraint::Condition);
1054            }
1055            Statement::WhileStatement(ws)
1056                if self.is_name_ref_expr(&ws.test, param_name) =>
1057            {
1058                constraints.push(ParamConstraint::Condition);
1059            }
1060            Statement::ForOfStatement(fos)
1061                if self.is_name_ref_expr(&fos.right, param_name) =>
1062            {
1063                constraints.push(ParamConstraint::IteratedInto);
1064            }
1065            _ => {}
1066        }
1067
1068        // Structural traversal via shared walker
1069        walk_stmt(stmt, &mut |event| match event {
1070            WalkEvent::Expr(e) => self.collect_constraints_in_expr(param_name, e, constraints),
1071            WalkEvent::Stmt(s) => self.collect_constraints_in_stmt(param_name, s, constraints),
1072        });
1073    }
1074
1075    fn collect_constraints_in_expr(
1076        &self,
1077        param_name: &str,
1078        expr: &Expression,
1079        constraints: &mut Vec<ParamConstraint>,
1080    ) {
1081        match expr {
1082            Expression::BinaryExpression(bin) => {
1083                let left_is = self.is_name_ref_expr(&bin.left, param_name);
1084                let right_is = self.is_name_ref_expr(&bin.right, param_name);
1085                if left_is || right_is {
1086                    let other_ty = if left_is {
1087                        self.infer_expr(&bin.right)
1088                    } else {
1089                        self.infer_expr(&bin.left)
1090                    };
1091                    constraints.push(ParamConstraint::BinaryWith(
1092                        other_ty, bin.operator, left_is,
1093                    ));
1094                } else {
1095                    self.collect_constraints_in_expr(param_name, &bin.left, constraints);
1096                    self.collect_constraints_in_expr(param_name, &bin.right, constraints);
1097                }
1098            }
1099            Expression::LogicalExpression(logic) => {
1100                self.collect_constraints_in_expr(param_name, &logic.left, constraints);
1101                self.collect_constraints_in_expr(param_name, &logic.right, constraints);
1102            }
1103            Expression::UnaryExpression(unary) => {
1104                if self.is_name_ref_expr(&unary.argument, param_name) {
1105                    constraints.push(ParamConstraint::UnaryOp(unary.operator));
1106                } else {
1107                    self.collect_constraints_in_expr(param_name, &unary.argument, constraints);
1108                }
1109            }
1110            Expression::CallExpression(call) => {
1111                for (i, arg) in call.arguments.iter().enumerate() {
1112                    if let Some(e) = arg.as_expression() {
1113                        if self.is_name_ref_expr(e, param_name) {
1114                            if let Some(callee_name) = self.get_callee_name(&call.callee) {
1115                                constraints.push(ParamConstraint::CallArg(callee_name, i));
1116                            }
1117                        } else {
1118                            self.collect_constraints_in_expr(param_name, e, constraints);
1119                        }
1120                    }
1121                }
1122                self.collect_constraints_in_expr(param_name, &call.callee, constraints);
1123            }
1124            Expression::AssignmentExpression(assign) => {
1125                self.collect_constraints_in_expr(param_name, &assign.right, constraints);
1126            }
1127            Expression::ConditionalExpression(cond) => {
1128                self.collect_constraints_in_expr(param_name, &cond.test, constraints);
1129                self.collect_constraints_in_expr(param_name, &cond.consequent, constraints);
1130                self.collect_constraints_in_expr(param_name, &cond.alternate, constraints);
1131            }
1132            Expression::ArrayExpression(arr) => {
1133                for elem in &arr.elements {
1134                    if let Some(e) = elem.as_expression() {
1135                        self.collect_constraints_in_expr(param_name, e, constraints);
1136                    }
1137                }
1138            }
1139            Expression::ParenthesizedExpression(p) => {
1140                self.collect_constraints_in_expr(param_name, &p.expression, constraints);
1141            }
1142            Expression::SequenceExpression(seq) => {
1143                for e in &seq.expressions {
1144                    self.collect_constraints_in_expr(param_name, e, constraints);
1145                }
1146            }
1147            Expression::TemplateLiteral(tl) => {
1148                for e in &tl.expressions {
1149                    self.collect_constraints_in_expr(param_name, e, constraints);
1150                }
1151            }
1152            Expression::UpdateExpression(up)
1153                if self.is_name_ref_simple_target(&up.argument, param_name) => {
1154                    constraints.push(ParamConstraint::Update);
1155                }
1156            Expression::StaticMemberExpression(mem) => {
1157                if self.is_name_ref_expr(&mem.object, param_name) {
1158                    constraints.push(ParamConstraint::Referenced);
1159                }
1160                self.collect_constraints_in_expr(param_name, &mem.object, constraints);
1161            }
1162            Expression::ComputedMemberExpression(mem) => {
1163                if self.is_name_ref_expr(&mem.object, param_name) {
1164                    constraints.push(ParamConstraint::Referenced);
1165                }
1166                self.collect_constraints_in_expr(param_name, &mem.object, constraints);
1167                self.collect_constraints_in_expr(param_name, &mem.expression, constraints);
1168            }
1169            Expression::AwaitExpression(await_expr) => {
1170                self.collect_constraints_in_expr(param_name, &await_expr.argument, constraints);
1171            }
1172            Expression::YieldExpression(yield_expr) => {
1173                if let Some(arg) = &yield_expr.argument {
1174                    self.collect_constraints_in_expr(param_name, arg, constraints);
1175                }
1176            }
1177            // Descend into nested function/arrow bodies (closures capturing outer params)
1178            Expression::ArrowFunctionExpression(arrow) => {
1179                for s in &arrow.body.statements {
1180                    self.collect_constraints_in_stmt(param_name, s, constraints);
1181                }
1182            }
1183            Expression::FunctionExpression(fe) => {
1184                if let Some(body) = &fe.body {
1185                    for s in &body.statements {
1186                        self.collect_constraints_in_stmt(param_name, s, constraints);
1187                    }
1188                }
1189            }
1190            // Descend into object expressions (e.g., { x: param })
1191            Expression::ObjectExpression(obj) => {
1192                for prop in &obj.properties {
1193                    match prop {
1194                        oxc_ast::ast::ObjectPropertyKind::ObjectProperty(p) => {
1195                            self.collect_constraints_in_expr(param_name, &p.value, constraints);
1196                        }
1197                        oxc_ast::ast::ObjectPropertyKind::SpreadProperty(s) => {
1198                            self.collect_constraints_in_expr(param_name, &s.argument, constraints);
1199                        }
1200                    }
1201                }
1202            }
1203            // Descend into new expressions (e.g., new Foo(param))
1204            Expression::NewExpression(new_expr) => {
1205                for arg in &new_expr.arguments {
1206                    if let Some(e) = arg.as_expression() {
1207                        self.collect_constraints_in_expr(param_name, e, constraints);
1208                    }
1209                }
1210            }
1211            // Catch-all: if the expression IS the parameter identifier,
1212            // mark it as referenced (handles const x = param, someVar = param, etc.)
1213            e if self.is_name_ref_expr(e, param_name) => {
1214                constraints.push(ParamConstraint::Referenced);
1215            }
1216            _ => {}
1217        }
1218    }
1219
1220    fn is_name_ref_expr(&self, expr: &Expression, name: &str) -> bool {
1221        matches!(expr, Expression::Identifier(id) if id.name.as_str() == name)
1222    }
1223
1224    fn is_name_ref_simple_target(&self, target: &SimpleAssignmentTarget, name: &str) -> bool {
1225        matches!(target,
1226            SimpleAssignmentTarget::AssignmentTargetIdentifier(id)
1227            if id.name.as_str() == name
1228        )
1229    }
1230
1231    fn get_callee_name(&self, callee: &Expression) -> Option<String> {
1232        match callee {
1233            Expression::Identifier(id) => Some(id.name.to_string()),
1234            Expression::StaticMemberExpression(mem) => {
1235                if let Expression::Identifier(obj) = &mem.object {
1236                    Some(format!("{}.{}", obj.name, mem.property.name))
1237                } else {
1238                    None
1239                }
1240            }
1241            _ => None,
1242        }
1243    }
1244
1245    // ============================================================
1246    // Constraint resolution
1247    // ============================================================
1248
1249    fn resolve_param_type(&self, constraints: &[ParamConstraint]) -> ZigType {
1250        let types: Vec<ZigType> = constraints.iter()
1251            .map(|c| self.constraint_to_type(c))
1252            .filter(|t| *t != ZigType::JsValue) // skip non-constraining
1253            .collect();
1254
1255        if types.is_empty() {
1256            return ZigType::I64; // aggressive default: numeric
1257        }
1258
1259        if types.iter().all(|t| *t == types[0]) {
1260            return types[0].clone();
1261        }
1262
1263        if types.iter().all(|t| t.is_numeric()) {
1264            let mut result = types[0].clone();
1265            for t in &types[1..] {
1266                result = ZigType::widen(&result, t);
1267                if result == ZigType::JsValue {
1268                    return ZigType::I64;
1269                }
1270            }
1271            return result;
1272        }
1273
1274        // Heterogeneous types: create Union instead of falling back to Any
1275        ZigType::make_union(types)
1276    }
1277
1278    fn constraint_to_type(&self, c: &ParamConstraint) -> ZigType {
1279        match c {
1280            ParamConstraint::BinaryWith(other, op, _is_left) => match op {
1281                BinaryOperator::Addition => {
1282                    if *other == ZigType::String { ZigType::String }
1283                    else if other.is_numeric() { other.clone() }
1284                    else { ZigType::I64 }
1285                }
1286                BinaryOperator::Subtraction
1287                | BinaryOperator::Multiplication
1288                | BinaryOperator::Remainder
1289                | BinaryOperator::Exponential => {
1290                    if other.is_numeric() { other.clone() } else { ZigType::I64 }
1291                }
1292                BinaryOperator::Division => ZigType::F64,
1293                BinaryOperator::ShiftLeft
1294                | BinaryOperator::ShiftRight
1295                | BinaryOperator::ShiftRightZeroFill => ZigType::I64,
1296                BinaryOperator::BitwiseOR
1297                | BinaryOperator::BitwiseXOR
1298                | BinaryOperator::BitwiseAnd => ZigType::I64,
1299                // Comparison ops don't constrain:
1300                BinaryOperator::StrictEquality
1301                | BinaryOperator::StrictInequality
1302                | BinaryOperator::Equality
1303                | BinaryOperator::Inequality
1304                | BinaryOperator::LessThan
1305                | BinaryOperator::LessEqualThan
1306                | BinaryOperator::GreaterThan
1307                | BinaryOperator::GreaterEqualThan
1308                | BinaryOperator::In
1309                | BinaryOperator::Instanceof => ZigType::JsValue,
1310            },
1311            ParamConstraint::CallArg(callee, arg_idx) => {
1312                self.builtin_param_type(callee, *arg_idx)
1313                    .or_else(|| {
1314                        self.fn_param_types.get(callee)
1315                            .and_then(|params| params.get(*arg_idx))
1316                            .cloned()
1317                    })
1318                    .unwrap_or(ZigType::JsValue)
1319            }
1320            ParamConstraint::UnaryOp(op) => match op {
1321                UnaryOperator::LogicalNot => ZigType::Bool,
1322                UnaryOperator::BitwiseNot => ZigType::I64,
1323                UnaryOperator::UnaryNegation | UnaryOperator::UnaryPlus => ZigType::I64,
1324                UnaryOperator::Typeof => ZigType::JsValue,
1325                UnaryOperator::Void => ZigType::JsValue,
1326                UnaryOperator::Delete => ZigType::JsValue,
1327            },
1328            ParamConstraint::Update => ZigType::I64,
1329            ParamConstraint::Condition => ZigType::JsValue,
1330            ParamConstraint::ReturnPos => ZigType::JsValue,
1331            ParamConstraint::Referenced => ZigType::JsValue,
1332            ParamConstraint::IteratedInto => ZigType::Slice(Box::new(ZigType::I64)),
1333        }
1334    }
1335
1336    fn builtin_param_type(&self, callee: &str, arg_idx: usize) -> Option<ZigType> {
1337        match (callee, arg_idx) {
1338            ("Math.abs" | "Math.sqrt" | "Math.sin" | "Math.cos" | "Math.tan"
1339                | "Math.log" | "Math.floor" | "Math.ceil" | "Math.round"
1340                | "Math.trunc" | "Math.sign" | "Math.cbrt" | "Math.exp", 0) => Some(ZigType::I64),
1341            ("Math.pow" | "Math.min" | "Math.max", _) => Some(ZigType::I64),
1342            ("parseInt" | "parseFloat" | "Number" | "String" | "Boolean", 0) => Some(ZigType::JsValue),
1343            ("JSON.stringify", 0) => Some(ZigType::JsValue),
1344            ("JSON.parse", 0) => Some(ZigType::String),
1345            ("console.log" | "console.warn" | "console.error"
1346                | "console.info" | "console.debug", _) => Some(ZigType::JsValue),
1347            ("Array.isArray" | "isNaN", 0) => Some(ZigType::JsValue),
1348            ("encodeURIComponent" | "decodeURIComponent", 0) => Some(ZigType::String),
1349            _ => None,
1350        }
1351    }
1352
1353    // ============================================================
1354    // PASS 3: infer return types
1355    // ============================================================
1356
1357    fn infer_all_return_types(&mut self, index: &FnIndex) {
1358        let fn_names: Vec<String> = self.fn_return_types.keys().cloned().collect();
1359
1360        for fn_name in &fn_names {
1361            // Register params and local vars in env for this function's body analysis
1362            let saved = self.register_fn_env(fn_name, index);
1363
1364            // Walk body to collect return types — O(1) via FnIndex
1365            let body_stmts = index.body_stmts(fn_name)
1366                .copied()
1367                .unwrap_or(&[]);
1368            let ret = self.infer_return_type_from_stmts(body_stmts);
1369
1370            self.fn_return_types.insert(fn_name.clone(), ret);
1371
1372            // Restore env
1373            self.unregister_params_for_fn(saved);
1374        }
1375
1376        // Fixup pass: re-compute return types now that callee return types are known.
1377        // This fixes functions like `useSafeDivide` whose return type depends on
1378        // the return type of `safeDivide` (processed in an arbitrary order above).
1379        for _ in 0..2 {
1380            let mut any_changed = false;
1381            for fn_name in &fn_names {
1382                let saved = self.register_fn_env(fn_name, index);
1383                let body_stmts = index.body_stmts(fn_name).copied().unwrap_or(&[]);
1384                let ret = self.infer_return_type_from_stmts(body_stmts);
1385                let old = self.fn_return_types.get(fn_name).cloned();
1386                if old.as_ref() != Some(&ret) {
1387                    self.fn_return_types.insert(fn_name.clone(), ret);
1388                    any_changed = true;
1389                }
1390                self.unregister_params_for_fn(saved);
1391            }
1392            if !any_changed { break; }
1393        }
1394    }
1395
1396    /// Register both parameter bindings and local variable declarations
1397    /// for a function, returning saved env entries for later restoration.
1398    fn register_fn_env(
1399        &mut self,
1400        fn_name: &str,
1401        index: &FnIndex,
1402    ) -> Vec<(String, Option<BindingInfo>)> {
1403        let mut saved = Vec::new();
1404
1405        // 0. Set current function for fn_local_types tracking
1406        self.current_fn = Some(fn_name.to_string());
1407
1408        // 1. Register parameters
1409        let param_types = self.fn_param_types.get(fn_name).cloned().unwrap_or_default();
1410        if let Some(params) = index.params(fn_name) {
1411            for (i, param) in params.items.iter().enumerate() {
1412                let mut names = Vec::new();
1413                collect_binding_names(&param.pattern, &mut names);
1414                let ty = if i < param_types.len() {
1415                    param_types[i].clone()
1416                } else if let Some(d) = &param.initializer {
1417                    self.infer_expr(d)
1418                } else {
1419                    ZigType::JsValue
1420                };
1421                for pn in &names {
1422                    let old = self.env.remove(pn);
1423                    saved.push((pn.clone(), old));
1424                    self.env.insert(pn.clone(), BindingInfo { zig_type: ty.clone(), is_const: true });
1425                }
1426            }
1427        }
1428
1429        // 2. Register local variables from function body
1430        let body_stmts = index.body_stmts(fn_name).copied().unwrap_or(&[]);
1431        self.register_local_decls(body_stmts, &mut saved);
1432
1433        saved
1434    }
1435
1436    fn unregister_params_for_fn(&mut self, saved: Vec<(String, Option<BindingInfo>)>) {
1437        // Clear current function tracking
1438        self.current_fn = None;
1439        for (name, old) in saved {
1440            self.env.remove(&name);
1441            if let Some(bi) = old {
1442                self.env.insert(name, bi);
1443            }
1444        }
1445    }
1446
1447    /// Walk statements and register local variable declarations in env.
1448    fn register_local_decls(
1449        &mut self,
1450        stmts: &[Statement],
1451        saved: &mut Vec<(String, Option<BindingInfo>)>,
1452    ) {
1453        for stmt in stmts {
1454            // Handle top-level VariableDeclaration directly.
1455            // walk_stmt only emits Expr(init) for VariableDeclarations, never
1456            // Stmt(VariableDeclaration), so we must handle them here at the top level.
1457            if let Statement::VariableDeclaration(vd) = stmt {
1458                let is_const = matches!(vd.kind, VariableDeclarationKind::Const);
1459                for decl in &vd.declarations {
1460                    if let Some(init) = &decl.init {
1461                        self.register_binding_with_expr(&decl.id, init, is_const, saved);
1462                    }
1463                }
1464            }
1465
1466            // ForStatement VariableDeclaration init — not reached by walk_stmt
1467            if let Statement::ForStatement(f) = stmt
1468                && let Some(init_box) = &f.init
1469            {
1470                let fi_ref: &ForStatementInit = init_box;
1471                if let ForStatementInit::VariableDeclaration(v) = fi_ref {
1472                    let is_const = matches!(v.kind, VariableDeclarationKind::Const);
1473                    for decl in &v.declarations {
1474                        if let Some(init_expr) = &decl.init {
1475                            self.register_binding_with_expr(&decl.id, init_expr, is_const, saved);
1476                        }
1477                    }
1478                }
1479            }
1480
1481            // Walk for nested VariableDeclarations (inside if/while/for/etc. bodies).
1482            walk_stmt(stmt, &mut |event| {
1483                if let WalkEvent::Stmt(Statement::VariableDeclaration(vd)) = event {
1484                    let is_const = matches!(vd.kind, VariableDeclarationKind::Const);
1485                    for decl in &vd.declarations {
1486                        if let Some(init) = &decl.init {
1487                            self.register_binding_with_expr(&decl.id, init, is_const, saved);
1488                        }
1489                    }
1490                }
1491            });
1492        }
1493    }
1494
1495    /// Register a binding pattern with its initializer expression.
1496    fn register_binding_with_expr(
1497        &mut self,
1498        pattern: &BindingPattern,
1499        init: &Expression,
1500        is_const: bool,
1501        saved: &mut Vec<(String, Option<BindingInfo>)>,
1502    ) {
1503        let mut names = Vec::new();
1504        collect_binding_names(pattern, &mut names);
1505
1506        // For destructured patterns, try to infer individual binding types
1507        let types: Vec<ZigType> = match pattern {
1508            BindingPattern::ObjectPattern(obj_pat) => {
1509                if let Expression::ObjectExpression(obj_expr) = init {
1510                    self.infer_destructured_obj_types(obj_pat, obj_expr)
1511                } else if let Expression::Identifier(id) = init {
1512                    // If init is an identifier with Object type, extract field types
1513                    let obj_type = self.get_var_type(id.name.as_str());
1514                    if let ZigType::Object { fields } = &obj_type {
1515                        let mut types = Vec::new();
1516                        for prop in &obj_pat.properties {
1517                            let name = match &prop.key {
1518                                oxc_ast::ast::PropertyKey::StaticIdentifier(id) => id.name.as_str(),
1519                                _ => {
1520                                    types.push(ZigType::JsValue);
1521                                    continue;
1522                                }
1523                            };
1524                            let ty = fields.iter()
1525                                .find(|(n, _)| n == name)
1526                                .map(|(_, ty)| ty.clone())
1527                                .unwrap_or(ZigType::JsValue);
1528                            types.push(ty);
1529                        }
1530                        types
1531                    } else {
1532                        let overall = self.infer_expr(init);
1533                        std::iter::repeat_n(overall, names.len()).collect()
1534                    }
1535                } else {
1536                    let overall = self.infer_expr(init);
1537                    std::iter::repeat_n(overall, names.len()).collect()
1538                }
1539            }
1540            BindingPattern::ArrayPattern(arr_pat) => {
1541                if let Expression::ArrayExpression(arr_expr) = init {
1542                    self.infer_destructured_array_types(arr_pat, arr_expr)
1543                } else {
1544                    let overall = self.infer_expr(init);
1545                    // If init is an array/slice type, unwrap element type for each binding
1546                    let elem_ty = match &overall {
1547                        ZigType::Array(elem) | ZigType::Slice(elem) => Some(elem.as_ref().clone()),
1548                        _ => None,
1549                    };
1550                    if let Some(elem) = elem_ty {
1551                        std::iter::repeat_n(elem, names.len()).collect()
1552                    } else {
1553                        std::iter::repeat_n(overall, names.len()).collect()
1554                    }
1555                }
1556            }
1557            _ => {
1558                // Special case: const + arrow function → infer return type with
1559                // arrow params properly registered in env (fixes closure return type).
1560                if is_const && names.len() == 1 {
1561                    if let Expression::ArrowFunctionExpression(arrow) = init {
1562                        let arrow_params: Vec<(String, ZigType)> = arrow.params.items.iter()
1563                            .map(|p| {
1564                                let mut pnames = Vec::new();
1565                                collect_binding_names(&p.pattern, &mut pnames);
1566                                let pname = pnames.into_iter().next().unwrap_or_default();
1567                                let pname = if pname.is_empty() { "_".to_string() } else { pname };
1568                                let ptype = self.infer_arrow_param_type(&pname, &arrow.body);
1569                                (pname, ptype)
1570                            })
1571                            .collect();
1572
1573                        let ret = self.infer_return_type_from_arrow_with_params(arrow, &arrow_params);
1574                        let sig = ZigFuncSig {
1575                            params: arrow_params.iter().map(|(_, t)| t.clone()).collect(),
1576                            return_type: Box::new(ret),
1577                        };
1578                        vec![ZigType::FunctionPtr(Box::new(sig))]
1579                    } else {
1580                        vec![self.infer_var_type(&names[0], init, is_const)]
1581                    }
1582                } else if names.len() == 1 {
1583                    // Single binding — apply three-layer type inference
1584                    vec![self.infer_var_type(&names[0], init, is_const)]
1585                } else {
1586                    vec![self.infer_expr(init)]
1587                }
1588            }
1589        };
1590
1591        for (i, pn) in names.iter().enumerate() {
1592            let ty = types.get(i).cloned().unwrap_or_else(|| self.infer_expr(init));
1593            let old = self.env.remove(pn);
1594            saved.push((pn.clone(), old));
1595            self.env.insert(pn.clone(), BindingInfo { zig_type: ty.clone(), is_const });
1596            // Also persist the type in fn_local_types for codegen use
1597            if let Some(ref fn_name) = self.current_fn {
1598                self.fn_local_types
1599                    .entry(fn_name.clone())
1600                    .or_default()
1601                    .insert(pn.clone(), ty);
1602            }
1603        }
1604    }
1605
1606    /// For destructured object bindings, infer each field's type from the object literal.
1607    fn infer_destructured_obj_types(
1608        &self,
1609        obj_pat: &oxc_ast::ast::ObjectPattern,
1610        obj_expr: &oxc_ast::ast::ObjectExpression,
1611    ) -> Vec<ZigType> {
1612        let mut types = Vec::new();
1613        for prop in &obj_pat.properties {
1614            let name = match &prop.key {
1615                oxc_ast::ast::PropertyKey::StaticIdentifier(id) => id.name.as_str(),
1616                _ => {
1617                    types.push(ZigType::JsValue);
1618                    continue;
1619                }
1620            };
1621            let found_type = obj_expr.properties.iter().find_map(|p| {
1622                if let oxc_ast::ast::ObjectPropertyKind::ObjectProperty(op) = p {
1623                    let prop_name = match &op.key {
1624                        oxc_ast::ast::PropertyKey::StaticIdentifier(id) => id.name.as_str(),
1625                        _ => return None,
1626                    };
1627                    if prop_name == name {
1628                        return Some(self.infer_expr(&op.value));
1629                    }
1630                }
1631                None
1632            }).unwrap_or(ZigType::JsValue);
1633            types.push(found_type);
1634        }
1635        types
1636    }
1637
1638    /// For destructured array bindings, infer each element's type from the array literal.
1639    fn infer_destructured_array_types(
1640        &self,
1641        _arr_pat: &oxc_ast::ast::ArrayPattern,
1642        arr_expr: &oxc_ast::ast::ArrayExpression,
1643    ) -> Vec<ZigType> {
1644        arr_expr.elements.iter().map(|elem| {
1645            elem.as_expression().map(|e| self.infer_expr(e)).unwrap_or(ZigType::JsValue)
1646        }).collect()
1647    }
1648
1649    // ============================================================
1650    // PASS 4: cross-function propagation
1651    // ============================================================
1652
1653    fn propagate_cross_fn(&mut self, index: &FnIndex) {
1654        let mut changed = true;
1655        for _ in 0..5 {
1656            if !changed { break; }
1657            changed = false;
1658
1659            // Forward propagation: param passed to another function
1660            let fn_names: Vec<String> = self.fn_param_types.keys().cloned().collect();
1661            for fn_name in &fn_names {
1662                if !index.has_body(fn_name) { continue; }
1663
1664                if let Some(param_names) = self.fn_param_names.get(fn_name) {
1665                    let mut updates: Vec<(usize, ZigType)> = Vec::new();
1666
1667                    // First pass: collect propagations (immutable borrows)
1668                    for i in 0..param_names.len() {
1669                        let types = self.fn_param_types.get(fn_name);
1670                        // Allow re-consideration of I64 (default) params too, so that
1671                        // callee's concrete types (e.g. f64) can propagate back to caller.
1672                        if types.is_some_and(|t| i < t.len() && t[i] != ZigType::JsValue && t[i] != ZigType::I64) {
1673                            continue;
1674                        }
1675                        if let Some(propagated) = self.find_direct_forward(
1676                            &param_names[i], fn_name, index,
1677                        ) {
1678                            updates.push((i, propagated));
1679                        }
1680                    }
1681
1682                    // Second pass: apply updates (mutable borrow)
1683                    if !updates.is_empty() {
1684                        if let Some(current) = self.fn_param_types.get_mut(fn_name) {
1685                            for (i, ty) in updates {
1686                                if i < current.len() {
1687                                    current[i] = ty;
1688                                }
1689                            }
1690                        }
1691                        changed = true;
1692                    }
1693                }
1694            }
1695
1696            // Call-site propagation: argument type → parameter type
1697            let site_changed = self.propagate_from_call_sites(index);
1698            if site_changed {
1699                changed = true;
1700            }
1701
1702            // Phase 3: Widen local variables based on function return type.
1703            // If a function returns f64 and a returned local variable is i64,
1704            // widen the variable to f64 so that `return cleaned;` compiles.
1705            for fn_name in &fn_names {
1706                let ret = self.fn_return_types.get(fn_name).cloned();
1707                if ret != Some(ZigType::F64) { continue; }
1708                if let Some(local_map) = self.fn_local_types.get_mut(fn_name) {
1709                    let mut widened: Vec<String> = Vec::new();
1710                    for (var_name, var_type) in local_map.iter_mut() {
1711                        if *var_type == ZigType::I64 {
1712                            *var_type = ZigType::F64;
1713                            widened.push(var_name.clone());
1714                        }
1715                    }
1716                    // Also update env if this function is currently registered
1717                    if self.current_fn.as_deref() == Some(fn_name) {
1718                        for var_name in &widened {
1719                            if let Some(bi) = self.env.get_mut(var_name) {
1720                                bi.zig_type = ZigType::F64;
1721                            }
1722                        }
1723                    }
1724                }
1725            }
1726        }
1727    }
1728
1729    /// Walk every call expression in `program`.  For each argument
1730    /// whose type is concrete (not Any), propagate it to the
1731    /// corresponding parameter of the callee.
1732    /// Returns `true` if any parameter type was updated.
1733    fn propagate_from_call_sites(&mut self, index: &FnIndex) -> bool {
1734        let mut changed = false;
1735        let mut propagations: Vec<(String, usize, ZigType)> = Vec::new();
1736
1737        // Scan top-level statements
1738        for stmt in index.top_level {
1739            self.collect_call_site_propagations(stmt, &mut propagations);
1740        }
1741
1742        // P1: Scan inside function bodies for nested call sites.
1743        // (e.g., function main() { helper(42); } → propagate i64 to helper's param)
1744        for body_stmts in index.fn_bodies.values() {
1745            for stmt in *body_stmts {
1746                self.collect_call_site_propagations(stmt, &mut propagations);
1747            }
1748        }
1749
1750        for (fn_name, param_idx, ty) in propagations {
1751            if let Some(params) = self.fn_param_types.get_mut(&fn_name)
1752                && param_idx < params.len()
1753            {
1754                let current = &params[param_idx];
1755                // Propagate if current is Any, or is the default I64 with no real constraint
1756                if *current == ZigType::JsValue || *current == ZigType::I64 {
1757                    params[param_idx] = ty;
1758                    changed = true;
1759                }
1760            }
1761        }
1762
1763        changed
1764    }
1765
1766    /// Recursively walk a statement, collecting (callee, param_idx, arg_type)
1767    /// triples from every CallExpression found.
1768    fn collect_call_site_propagations(
1769        &self,
1770        stmt: &Statement,
1771        propagations: &mut Vec<(String, usize, ZigType)>,
1772    ) {
1773        // walk_stmt doesn't handle ForStatement VariableDeclaration init
1774        if let Statement::ForStatement(f) = stmt
1775            && let Some(init_box) = &f.init
1776        {
1777            let fi_ref: &ForStatementInit = init_box;
1778            if let ForStatementInit::VariableDeclaration(v) = fi_ref {
1779                for decl in &v.declarations {
1780                    if let Some(init) = &decl.init {
1781                        self.collect_from_expr(init, propagations);
1782                    }
1783                }
1784            }
1785        }
1786
1787        walk_stmt(stmt, &mut |event| match event {
1788            WalkEvent::Expr(e) => self.collect_from_expr(e, propagations),
1789            WalkEvent::Stmt(s) => self.collect_call_site_propagations(s, propagations),
1790        });
1791    }
1792
1793    /// Walk an expression; if it is a CallExpression, propagate arg types.
1794    fn collect_from_expr(
1795        &self,
1796        expr: &Expression,
1797        propagations: &mut Vec<(String, usize, ZigType)>,
1798    ) {
1799        if let Expression::CallExpression(call) = expr {
1800            self.collect_from_call(call, propagations);
1801        }
1802        walk_expr_children(expr, &mut |e| self.collect_from_expr(e, propagations));
1803    }
1804
1805    /// For a single CallExpression, infer each argument's type and
1806    /// record a propagation (callee, arg_idx, arg_type) if the
1807    /// argument's type is concrete.
1808    fn collect_from_call(
1809        &self,
1810        call: &CallExpression,
1811        propagations: &mut Vec<(String, usize, ZigType)>,
1812    ) {
1813        let callee_name = match self.get_callee_name(&call.callee) {
1814            Some(name) => name,
1815            None => return,
1816        };
1817
1818        if self.is_builtin_name(&callee_name) {
1819            return;
1820        }
1821
1822        for (i, arg) in call.arguments.iter().enumerate() {
1823            if let Some(expr) = arg.as_expression() {
1824                let arg_type = self.infer_expr(expr);
1825                if arg_type != ZigType::JsValue {
1826                    propagations.push((callee_name.clone(), i, arg_type));
1827                }
1828            }
1829        }
1830    }
1831
1832    fn is_builtin_name(&self, name: &str) -> bool {
1833        matches!(name,
1834            "console.log" | "console.error" | "console.warn"
1835            | "console.info" | "console.debug"
1836            | "Math.abs" | "Math.sqrt" | "Math.sin" | "Math.cos"
1837            | "Math.tan" | "Math.log" | "Math.floor" | "Math.ceil"
1838            | "Math.round" | "Math.trunc" | "Math.sign" | "Math.cbrt"
1839            | "Math.exp" | "Math.pow" | "Math.min" | "Math.max"
1840            | "parseInt" | "parseFloat" | "Number" | "String"
1841            | "Boolean" | "JSON.stringify" | "JSON.parse"
1842            | "Array.isArray" | "isNaN"
1843            | "encodeURIComponent" | "decodeURIComponent"
1844        )
1845    }
1846
1847    fn find_direct_forward(
1848        &self, param_name: &str, fn_name: &str, index: &FnIndex,
1849    ) -> Option<ZigType> {
1850        let body_stmts = index.body_stmts(fn_name).copied()?;
1851        self.forward_in_stmts(param_name, body_stmts)
1852    }
1853
1854    fn forward_in_stmts(&self, param_name: &str, stmts: &[Statement]) -> Option<ZigType> {
1855        let mut result: Option<ZigType> = None;
1856        for stmt in stmts {
1857            walk_stmt(stmt, &mut |event| {
1858                if result.is_some() { return; }
1859                if let WalkEvent::Expr(e) = event
1860                    && let Some(ty) = self.check_forward_call(param_name, e) {
1861                        result = Some(ty);
1862                }
1863            });
1864            if result.is_some() { break; }
1865        }
1866        result
1867    }
1868
1869    fn check_forward_call(&self, param_name: &str, expr: &Expression) -> Option<ZigType> {
1870        if let Expression::CallExpression(call) = expr {
1871            let callee_name = self.get_callee_name(&call.callee)?;
1872            for (i, arg) in call.arguments.iter().enumerate() {
1873                if let Some(e) = arg.as_expression()
1874                    && self.is_name_ref_expr(e, param_name) {
1875                        if let Some(params) = self.fn_param_types.get(&callee_name) {
1876                            return params.get(i).cloned();
1877                        }
1878                        return self.builtin_param_type(&callee_name, i);
1879                    }
1880            }
1881        }
1882        None
1883    }
1884
1885    // ============================================================
1886    // PASS 5: validation
1887    // ============================================================
1888
1889    fn validate_types(&mut self) {
1890        for (name, ret) in &self.fn_return_types {
1891            if *ret == ZigType::JsValue {
1892                self.diagnostics.push(Diagnostic::new(
1893                    DiagnosticKind::Warning,
1894                    format!("cannot infer return type of '{}', using JsValue", name),
1895                ));
1896            }
1897        }
1898
1899        for (name, params) in &self.fn_param_types {
1900            for (i, ty) in params.iter().enumerate() {
1901                if *ty == ZigType::JsValue {
1902                    let pname = self.fn_param_names.get(name)
1903                        .and_then(|ns| ns.get(i))
1904                        .map(|s| s.as_str())
1905                        .unwrap_or("?");
1906                    self.diagnostics.push(Diagnostic::new(
1907                        DiagnosticKind::Warning,
1908                        format!(
1909                            "cannot infer type of parameter '{}' (#{}) in '{}', using JsValue",
1910                            pname, i, name
1911                        ),
1912                    ));
1913                }
1914            }
1915        }
1916
1917        for (name, info) in &self.env {
1918            if info.zig_type == ZigType::JsValue {
1919                let name_str = name.as_str();
1920                match name_str {
1921                    "undefined" | "NaN" | "Infinity" => continue,
1922                    _ => {
1923                        self.diagnostics.push(Diagnostic::new(
1924                            DiagnosticKind::Warning,
1925                            format!("cannot infer type of variable '{}', using JsValue", name),
1926                        ));
1927                    }
1928                }
1929            }
1930        }
1931    }
1932
1933    // ============================================================
1934    // Expression type inference
1935    // ============================================================
1936
1937    pub fn infer_expr(&self, expr: &Expression) -> ZigType {
1938        match expr {
1939            Expression::NumericLiteral(lit) => {
1940                // Use parsed value: fractional part → F64, else I64
1941                if lit.value.fract() != 0.0 || lit.value.is_infinite() || lit.value.is_nan() {
1942                    ZigType::F64
1943                } else {
1944                    ZigType::I64
1945                }
1946            }
1947            Expression::StringLiteral(_) => ZigType::String,
1948            Expression::TemplateLiteral(_) => ZigType::String,
1949            Expression::BooleanLiteral(_) => ZigType::Bool,
1950            Expression::NullLiteral(_) => ZigType::Optional(Box::new(ZigType::Void)),
1951            Expression::RegExpLiteral(_) => ZigType::String, // regex patterns are strings
1952            Expression::BigIntLiteral(_) => ZigType::I64,
1953            Expression::Identifier(id) => match id.name.as_str() {
1954                "undefined" => ZigType::Optional(Box::new(ZigType::Void)),
1955                "NaN" | "Infinity" => ZigType::F64,
1956                _ => self.get_var_type(&id.name),
1957            },
1958            Expression::BinaryExpression(bin) => {
1959                let left_ty = self.infer_expr(&bin.left);
1960                let right_ty = self.infer_expr(&bin.right);
1961                match &bin.operator {
1962                    BinaryOperator::StrictEquality
1963                    | BinaryOperator::StrictInequality
1964                    | BinaryOperator::Equality
1965                    | BinaryOperator::Inequality
1966                    | BinaryOperator::LessThan
1967                    | BinaryOperator::LessEqualThan
1968                    | BinaryOperator::GreaterThan
1969                    | BinaryOperator::GreaterEqualThan
1970                    | BinaryOperator::In
1971                    | BinaryOperator::Instanceof => ZigType::Bool,
1972                    BinaryOperator::Addition => {
1973                        if left_ty == ZigType::String || right_ty == ZigType::String {
1974                            ZigType::String
1975                        } else {
1976                            ZigType::widen(&left_ty, &right_ty)
1977                        }
1978                    }
1979                    BinaryOperator::Subtraction
1980                    | BinaryOperator::Multiplication
1981                    | BinaryOperator::Remainder
1982                    | BinaryOperator::Exponential => ZigType::widen(&left_ty, &right_ty),
1983                    BinaryOperator::Division => ZigType::F64,
1984                    BinaryOperator::ShiftLeft
1985                    | BinaryOperator::ShiftRight
1986                    | BinaryOperator::ShiftRightZeroFill
1987                    | BinaryOperator::BitwiseOR
1988                    | BinaryOperator::BitwiseXOR
1989                    | BinaryOperator::BitwiseAnd => ZigType::I64,
1990                }
1991            }
1992            Expression::LogicalExpression(logic) => {
1993                let left_ty = self.infer_expr(&logic.left);
1994                let right_ty = self.infer_expr(&logic.right);
1995                match logic.operator {
1996                    LogicalOperator::And | LogicalOperator::Or => {
1997                        if left_ty == right_ty { left_ty } else { ZigType::make_union(vec![left_ty, right_ty]) }
1998                    }
1999                    LogicalOperator::Coalesce => ZigType::Optional(Box::new(left_ty)),
2000                }
2001            }
2002            Expression::UnaryExpression(unary) => match unary.operator {
2003                UnaryOperator::LogicalNot => ZigType::Bool,
2004                UnaryOperator::BitwiseNot => ZigType::I64,
2005                UnaryOperator::UnaryPlus => self.infer_expr(&unary.argument),
2006                UnaryOperator::UnaryNegation => self.infer_expr(&unary.argument),
2007                UnaryOperator::Typeof => ZigType::String,
2008                UnaryOperator::Void => ZigType::Void,
2009                UnaryOperator::Delete => ZigType::Bool,
2010            },
2011            Expression::UpdateExpression(_) => ZigType::I64,
2012            Expression::CallExpression(call) => self.infer_call_return(&call.callee),
2013            Expression::AssignmentExpression(assign) => self.infer_expr(&assign.right),
2014            Expression::ConditionalExpression(cond) => {
2015                let cons = self.infer_expr(&cond.consequent);
2016                let alt = self.infer_expr(&cond.alternate);
2017                if cons == alt { cons } else { ZigType::make_union(vec![cons, alt]) }
2018            }
2019            Expression::ArrayExpression(arr) => {
2020                if arr.elements.is_empty() { return ZigType::JsValue; }
2021                let first_ty = arr.elements.iter().find_map(|elem| match elem {
2022                    ArrayExpressionElement::SpreadElement(_) | ArrayExpressionElement::Elision(_) => None,
2023                    _ => elem.as_expression().map(|e| self.infer_expr(e)),
2024                });
2025                if let Some(ref ty) = first_ty {
2026                    let all_same = arr.elements.iter().all(|elem| match elem {
2027                        ArrayExpressionElement::SpreadElement(_) | ArrayExpressionElement::Elision(_) => true,
2028                        _ => elem.as_expression().map(|e| self.infer_expr(e) == *ty).unwrap_or(true),
2029                    });
2030                    if all_same && *ty != ZigType::JsValue {
2031                        return ZigType::Array(Box::new(ty.clone()));
2032                    }
2033                }
2034                ZigType::Array(Box::new(first_ty.unwrap_or(ZigType::JsValue)))
2035            }
2036            Expression::ParenthesizedExpression(p) => self.infer_expr(&p.expression),
2037            Expression::SequenceExpression(seq) => {
2038                seq.expressions.last().map(|e| self.infer_expr(e)).unwrap_or(ZigType::Void)
2039            }
2040            Expression::ArrowFunctionExpression(arrow) => {
2041                let ret = self.infer_return_type_from_arrow(arrow);
2042                ZigType::FunctionPtr(Box::new(ZigFuncSig {
2043                    params: vec![ZigType::JsValue; arrow.params.items.len()],
2044                    return_type: Box::new(ret),
2045                }))
2046            }
2047            Expression::TSAsExpression(ts) => self.infer_expr(&ts.expression),
2048            Expression::TSTypeAssertion(ts) => self.infer_expr(&ts.expression),
2049            Expression::TSNonNullExpression(ts) => self.infer_expr(&ts.expression),
2050            Expression::TSSatisfiesExpression(ts) => self.infer_expr(&ts.expression),
2051            Expression::TSInstantiationExpression(ts) => self.infer_expr(&ts.expression),
2052            Expression::StaticMemberExpression(mem) => self.infer_member_expr(mem),
2053            Expression::ComputedMemberExpression(mem) => self.infer_computed_member_expr(mem),
2054            Expression::ObjectExpression(obj) => self.infer_object_expr(obj),
2055            Expression::NewExpression(ne) => {
2056                // Check for built-in constructors
2057                if let Expression::Identifier(id) = &ne.callee {
2058                    match id.name.as_str() {
2059                        "Map" => return ZigType::Struct("Map".to_string()),
2060                        "Set" => return ZigType::Struct("Set".to_string()),
2061                        // For class constructors, return Struct with class name
2062                        _ => return ZigType::Struct(id.name.to_string()),
2063                    }
2064                }
2065                ZigType::JsValue
2066            }
2067            Expression::FunctionExpression(_) => ZigType::JsValue,
2068            Expression::AwaitExpression(await_expr) => self.infer_expr(&await_expr.argument),
2069            _ => ZigType::JsValue,
2070        }
2071    }
2072
2073    fn infer_object_expr(&self, obj: &ObjectExpression) -> ZigType {
2074        let mut fields: Vec<(String, ZigType)> = Vec::new();
2075        for prop in &obj.properties {
2076            match prop {
2077                oxc_ast::ast::ObjectPropertyKind::ObjectProperty(p) => {
2078                    let field_name = match &p.key {
2079                        oxc_ast::ast::PropertyKey::StaticIdentifier(id) => id.name.to_string(),
2080                        oxc_ast::ast::PropertyKey::StringLiteral(s) => s.value.to_string(),
2081                        _ => continue, // skip computed keys
2082                    };
2083                    let field_type = self.infer_expr(&p.value);
2084                    // Merge: if field already exists (from spread), override it
2085                    if let Some(pos) = fields.iter().position(|(n, _)| n == &field_name) {
2086                        fields[pos] = (field_name, field_type);
2087                    } else {
2088                        fields.push((field_name, field_type));
2089                    }
2090                }
2091                oxc_ast::ast::ObjectPropertyKind::SpreadProperty(spread) => {
2092                    let base_type = self.infer_expr(&spread.argument);
2093                    match base_type {
2094                        ZigType::Object { fields: base_fields } => {
2095                            for (name, ty) in &base_fields {
2096                                if !fields.iter().any(|(n, _)| n == name) {
2097                                    fields.push((name.clone(), ty.clone()));
2098                                }
2099                            }
2100                        }
2101                        _ => {
2102                            // Spread of non-Object type: can't merge fields
2103                            return ZigType::JsValue;
2104                        }
2105                    }
2106                }
2107            }
2108        }
2109        ZigType::Object { fields }
2110    }
2111
2112    fn infer_member_expr(&self, mem: &StaticMemberExpression) -> ZigType {
2113        // this.field → all class fields are i64
2114        if matches!(&mem.object, Expression::ThisExpression(_)) {
2115            return ZigType::I64;
2116        }
2117        if let Expression::Identifier(id) = &mem.object {
2118            let obj_name = id.name.as_str();
2119            let prop = mem.property.name.as_str();
2120            let obj_type = self.get_var_type(obj_name);
2121            match &obj_type {
2122                ZigType::String => match prop {
2123                    "length" => ZigType::I64,
2124                    "charAt" | "slice" | "substring" | "toLowerCase" | "toUpperCase"
2125                        | "trim" | "padStart" | "padEnd" | "repeat" | "concat"
2126                        | "replace" | "replaceAll" | "split" | "toString" => ZigType::String,
2127                    "indexOf" | "lastIndexOf" | "search" | "charCodeAt" | "codePointAt" => ZigType::I64,
2128                    "includes" | "startsWith" | "endsWith" => ZigType::Bool,
2129                    _ => ZigType::JsValue,
2130                },
2131                ZigType::Array(elem) => match prop {
2132                    "length" => ZigType::I64,
2133                    "push" | "unshift" => ZigType::Usize,
2134                    "pop" | "shift" => ZigType::Optional(elem.clone()),
2135                    "splice" => ZigType::Array(elem.clone()),
2136                    "indexOf" | "lastIndexOf" => ZigType::I64,
2137                    "includes" => ZigType::Bool,
2138                    "join" | "reverse" | "sort" | "flat" | "flatMap" => ZigType::Array(elem.clone()),
2139                    "slice" | "concat" => ZigType::Array(elem.clone()),
2140                    _ => ZigType::JsValue,
2141                },
2142                ZigType::Object { fields } => {
2143                    // Look up the property in the object's field list
2144                    fields.iter()
2145                        .find(|(n, _)| n == prop)
2146                        .map(|(_, ty)| ty.clone())
2147                        .unwrap_or(ZigType::JsValue)
2148                }
2149                ZigType::Struct(_struct_name) => {
2150                    // Named struct from class: can't enumerate fields at infer time
2151                    // Fall through to Any — class fields are all i64 anyway
2152                    ZigType::JsValue
2153                }
2154                _ => match (obj_name, prop) {
2155                    ("Math", "PI" | "E" | "LN2" | "LN10" | "LOG2E" | "LOG10E"
2156                        | "SQRT2" | "SQRT1_2") => ZigType::F64,
2157                    ("Number", "MAX_SAFE_INTEGER" | "MIN_SAFE_INTEGER" | "MAX_VALUE"
2158                        | "MIN_VALUE" | "POSITIVE_INFINITY" | "NEGATIVE_INFINITY"
2159                        | "EPSILON") => ZigType::F64,
2160                    _ => ZigType::JsValue,
2161                },
2162            }
2163        } else {
2164            ZigType::JsValue
2165        }
2166    }
2167
2168    fn infer_computed_member_expr(&self, mem: &ComputedMemberExpression) -> ZigType {
2169        // Check if object is a dynamic access variable (uses HashMap)
2170        // If so, person[key] returns JsValue (?Any type)
2171        if let Expression::Identifier(id) = &mem.object
2172            && self.dynamic_access_vars.contains(id.name.as_str()) {
2173                return ZigType::JsValue;  // JsValue
2174            }
2175
2176        let obj_type = self.infer_expr(&mem.object);
2177        match &obj_type {
2178            ZigType::Array(elem) | ZigType::Slice(elem) => elem.as_ref().clone(),
2179            ZigType::String => ZigType::I32,
2180            ZigType::Object { fields } => {
2181                // If the computed key is a string literal, we can resolve it
2182                if let Expression::StringLiteral(s) = &mem.expression {
2183                    let key = s.value.as_str();
2184                    fields.iter()
2185                        .find(|(n, _)| n == key)
2186                        .map(|(_, ty)| ty.clone())
2187                        .unwrap_or(ZigType::JsValue)
2188                } else {
2189                    // For non-literal keys, return Any (JsValue)
2190                    ZigType::JsValue
2191                }
2192            }
2193            _ => ZigType::JsValue,
2194        }
2195    }
2196
2197    // ============================================================
2198    // Return type inference
2199    // ============================================================
2200
2201    /// Infer arrow return type with arrow params temporarily registered.
2202    /// This fixes the case where `x` in `(x) => x + base` is unknown (Any)
2203    /// because arrow params aren't in the TypeInferrer's env by default.
2204    pub fn infer_return_type_from_arrow_with_params(
2205        &mut self,
2206        arrow: &ArrowFunctionExpression,
2207        arrow_params: &[(String, ZigType)],
2208    ) -> ZigType {
2209        // Temporarily register arrow params so infer_expr can find their types
2210        let mut saved: Vec<(String, Option<BindingInfo>)> = Vec::new();
2211        for (pname, ptype) in arrow_params {
2212            let old = self.env.remove(pname.as_str());
2213            saved.push((pname.clone(), old));
2214            self.env.insert(
2215                pname.clone(),
2216                BindingInfo {
2217                    zig_type: ptype.clone(),
2218                    is_const: true,
2219                },
2220            );
2221        }
2222
2223        let result = self.infer_return_type_from_arrow(arrow);
2224
2225        // Restore original env state
2226        for (pname, old) in saved {
2227            if let Some(bi) = old {
2228                self.env.insert(pname, bi);
2229            } else {
2230                self.env.remove(&pname);
2231            }
2232        }
2233
2234        result
2235    }
2236
2237    pub fn infer_return_type_from_arrow(&self, arrow: &ArrowFunctionExpression) -> ZigType {
2238        if arrow.expression {
2239            if let Some(first) = arrow.body.statements.first() {
2240                match first {
2241                    Statement::ExpressionStatement(es) => return self.infer_expr(&es.expression),
2242                    Statement::ReturnStatement(rs) => {
2243                        return rs.argument.as_ref().map(|a| self.infer_expr(a)).unwrap_or(ZigType::Void);
2244                    }
2245                    _ => {}
2246                }
2247            }
2248            ZigType::Void
2249        } else {
2250            self.infer_return_type_from_stmts(&arrow.body.statements)
2251        }
2252    }
2253
2254    pub fn infer_return_type_from_function_body(
2255        &self,
2256        body: &Option<oxc_allocator::Box<'_, FunctionBody<'_>>>,
2257    ) -> ZigType {
2258        match body {
2259            Some(b) => self.infer_return_type_from_stmts(&b.statements),
2260            None => ZigType::Void,
2261        }
2262    }
2263
2264    fn infer_return_type_from_stmts(&self, stmts: &[Statement]) -> ZigType {
2265        let mut ret_types: Vec<ZigType> = Vec::new();
2266        self.collect_return_types(stmts, &mut ret_types);
2267
2268        if ret_types.is_empty() {
2269            return ZigType::Void;
2270        }
2271        if ret_types.iter().all(|t| t == &ret_types[0]) {
2272            return ret_types[0].clone();
2273        }
2274
2275        let first_non_void = ret_types.iter().find(|t| **t != ZigType::Void);
2276        if let Some(ty) = first_non_void {
2277            if ret_types.iter().filter(|t| **t != ZigType::Void).all(|t| *t == *ty) {
2278                return ty.clone();
2279            }
2280            let non_void: Vec<&ZigType> = ret_types.iter().filter(|t| **t != ZigType::Void).collect();
2281            if non_void.iter().all(|t| t.is_numeric()) {
2282                let mut result = first_non_void.unwrap().clone();
2283                for ty in &non_void[1..] {
2284                    result = ZigType::widen(&result, ty);
2285                    if matches!(result, ZigType::JsValue | ZigType::JsAny) { break; }
2286                }
2287                if !matches!(result, ZigType::JsValue | ZigType::JsAny) { return result; }
2288            }
2289        }
2290
2291        // Heterogeneous return types: create Union instead of falling back to Any
2292        let non_void_types: Vec<ZigType> = ret_types.into_iter()
2293            .filter(|t| *t != ZigType::Void)
2294            .collect();
2295        ZigType::make_union(non_void_types)
2296    }
2297
2298    fn collect_return_types(&self, stmts: &[Statement], out: &mut Vec<ZigType>) {
2299        for stmt in stmts {
2300            self.collect_return_types_rec(stmt, out);
2301        }
2302    }
2303
2304    /// Recurse into a statement to find return statements.
2305    /// Handles ReturnStatement directly; uses walk_stmt for structural traversal
2306    /// of all other statement types.
2307    fn collect_return_types_rec(&self, stmt: &Statement, out: &mut Vec<ZigType>) {
2308        if let Statement::ReturnStatement(rs) = stmt {
2309            out.push(rs.argument.as_ref()
2310                .map(|a| self.infer_expr(a))
2311                .unwrap_or(ZigType::Void));
2312            return;
2313        }
2314        // Don't descend into inner function declarations
2315        if matches!(stmt, Statement::FunctionDeclaration(_)) {
2316            return;
2317        }
2318        walk_stmt(stmt, &mut |event| {
2319            if let WalkEvent::Stmt(s) = event {
2320                self.collect_return_types_rec(s, out);
2321            }
2322        });
2323    }
2324
2325    // ============================================================
2326    // Call return type inference
2327    // ============================================================
2328
2329    fn infer_call_return(&self, callee: &Expression) -> ZigType {
2330        match callee {
2331            Expression::Identifier(id) => {
2332                let name = id.name.as_str();
2333                if let Some(ret) = self.fn_return_types.get(name) {
2334                    return ret.clone();
2335                }
2336                // Look up local variable in env (e.g., arrow function assigned to const)
2337                if let Some(bi) = self.env.get(name)
2338                    && let ZigType::FunctionPtr(sig) = &bi.zig_type {
2339                        return (*sig.return_type).clone();
2340                    }
2341                self.builtin_return_type(name)
2342            }
2343            Expression::StaticMemberExpression(mem) => {
2344                if let Expression::Identifier(id) = &mem.object {
2345                    let obj_name = id.name.as_str();
2346                    let method_key = format!("{}.{}", obj_name, mem.property.name);
2347                    // Check builtins first (console.log, Math.abs, etc.)
2348                    let builtin = self.builtin_return_type(&method_key);
2349                    if builtin != ZigType::JsValue {
2350                        return builtin;
2351                    }
2352                    // Check for regexp methods (re.test(str), re.exec(str))
2353                    // Regexp literals are emitted as strings, so String-typed vars
2354                    // with .test()/.exec() methods are regexp dispatch.
2355                    let prop_name = mem.property.name.as_str();
2356                    if let Some(var_info) = self.env.get(obj_name)
2357                        && var_info.zig_type == ZigType::String {
2358                            return match prop_name {
2359                                // String search methods
2360                                "includes" | "startsWith" | "endsWith" => ZigType::Bool,
2361                                "indexOf" | "lastIndexOf" | "search" | "charCodeAt" | "codePointAt" => ZigType::I64,
2362                                // String transform methods
2363                                "charAt" | "slice" | "substring" | "toLowerCase" | "toUpperCase"
2364                                    | "trim" | "trimStart" | "trimEnd" | "padStart" | "padEnd"
2365                                    | "repeat" | "concat" | "replace" | "replaceAll" | "toString" => ZigType::String,
2366                                "split" => ZigType::Array(Box::new(ZigType::String)),
2367                                // Regexp methods (re.test/exec on string-typed vars used as patterns)
2368                                "test" => ZigType::Bool,
2369                                "exec" => ZigType::Optional(Box::new(ZigType::String)),
2370                                _ => ZigType::JsValue,
2371                            };
2372                        }
2373                    // Check if obj_name is a local variable (e.g., rect.area())
2374                    // Class structs: fields and method returns are all i64.
2375                    if let Some(var_info) = self.env.get(obj_name)
2376                        && matches!(&var_info.zig_type, ZigType::Struct(_)) {
2377                            return ZigType::I64;
2378                        }
2379                    // Check array methods (arr.pop(), arr.push(), etc.)
2380                    if let Some(var_info) = self.env.get(obj_name)
2381                        && let ZigType::Array(elem) = &var_info.zig_type {
2382                            return match prop_name {
2383                                "length" => ZigType::I64,
2384                                "push" | "unshift" => ZigType::I64,
2385                                "pop" | "shift" => ZigType::Optional(elem.clone()),
2386                                "indexOf" | "lastIndexOf" => ZigType::I64,
2387                                "includes" => ZigType::Bool,
2388                                "join" | "reverse" | "sort" | "slice" | "concat" => ZigType::Array(elem.clone()),
2389                                "forEach" | "map" | "filter" | "reduce" | "some" | "every" | "find" | "findIndex"
2390                                    | "flatMap" | "flat" => ZigType::Array(elem.clone()),
2391                                _ => ZigType::JsValue,
2392                            };
2393                        }
2394                }
2395                ZigType::JsValue
2396            }
2397            _ => ZigType::JsValue,
2398        }
2399    }
2400
2401    fn builtin_return_type(&self, name: &str) -> ZigType {
2402        match name {
2403            "parseInt" => ZigType::I64,
2404            "parseFloat" | "Number" | "Math.random" | "Math.floor" | "Math.ceil"
2405                | "Math.round" | "Math.abs" | "Math.sqrt" | "Math.sin" | "Math.cos"
2406                | "Math.tan" | "Math.log" | "Math.pow" | "Math.min" | "Math.max"
2407                | "Math.trunc" | "Math.sign" | "Math.cbrt" | "Math.exp" => ZigType::F64,
2408            "String" | "JSON.parse" => ZigType::String,
2409            "Boolean" | "Array.isArray" | "isNaN" | "Number.isInteger"
2410                | "Number.isNaN" | "Number.isFinite" => ZigType::Bool,
2411            "encodeURIComponent" | "decodeURIComponent" => ZigType::String,
2412            "console.log" | "console.warn" | "console.error" | "console.info"
2413                | "console.debug" | "console.assert" | "console.table" | "console.dir"
2414                | "console.time" | "console.timeEnd" | "console.group" | "console.groupEnd"
2415                | "console.clear" | "console.count" | "console.trace" => ZigType::Void,
2416            _ => ZigType::JsValue,
2417        }
2418    }
2419
2420    // ============================================================
2421    // Helpers
2422    // ============================================================
2423
2424    fn extract_fn_sig(&self, expr: &Expression) -> Option<ZigFuncSig> {
2425        match expr {
2426            Expression::ArrowFunctionExpression(arrow) => {
2427                let ret = self.infer_return_type_from_arrow(arrow);
2428                Some(ZigFuncSig {
2429                    params: vec![ZigType::JsValue; arrow.params.items.len()],
2430                    return_type: Box::new(ret),
2431                })
2432            }
2433            Expression::FunctionExpression(fe) => {
2434                let ret = self.infer_return_type_from_function_body(&fe.body);
2435                Some(ZigFuncSig {
2436                    params: vec![ZigType::JsValue; fe.params.items.len()],
2437                    return_type: Box::new(ret),
2438                })
2439            }
2440            _ => None,
2441        }
2442    }
2443
2444    /// Returns the set of variable names accessed with a dynamic (non-literal) key.
2445    pub fn get_dynamic_access_vars(&self) -> &HashSet<String> {
2446        &self.dynamic_access_vars
2447    }
2448
2449    /// Pre-pass: detect variables that are accessed with a dynamic (non-literal) key.
2450    /// These variables must use HashMap instead of struct.
2451    fn detect_dynamic_access(&mut self, program: &Program) {
2452        for stmt in &program.body {
2453            self.detect_dynamic_access_stmt(stmt);
2454        }
2455    }
2456
2457    fn detect_dynamic_access_stmt(&mut self, stmt: &Statement) {
2458        // Special case: ForStatement with VariableDeclaration init.
2459        // walk_stmt only handles expression inits via as_expression();
2460        // VariableDeclaration inits (e.g., for (var i = ...)) need explicit handling.
2461        if let Statement::ForStatement(f) = stmt
2462            && let Some(init_box) = &f.init
2463        {
2464            // Deref coercion: &Box<FI> → &FI
2465            let fi_ref: &ForStatementInit = init_box;
2466            if let ForStatementInit::VariableDeclaration(v) = fi_ref {
2467                for decl in &v.declarations {
2468                    if let Some(init) = &decl.init {
2469                        self.detect_dynamic_access_expr(init);
2470                    }
2471                }
2472            }
2473        }
2474
2475        walk_stmt(stmt, &mut |event| match event {
2476            WalkEvent::Expr(e) => self.detect_dynamic_access_expr(e),
2477            WalkEvent::Stmt(s) => self.detect_dynamic_access_stmt(s),
2478        });
2479    }
2480
2481    fn detect_dynamic_access_assign_target(&mut self, target: &AssignmentTarget) {
2482        // Use as_member_expression() to check if target is a MemberExpression
2483        if let Some(mem) = target.as_member_expression()
2484            && let MemberExpression::ComputedMemberExpression(cm) = mem
2485                && !matches!(&cm.expression, Expression::StringLiteral(_) | Expression::NumericLiteral(_))
2486                    && let Expression::Identifier(id) = &cm.object {
2487                        self.dynamic_access_vars.insert(id.name.to_string());
2488                    }
2489    }
2490
2491    fn detect_dynamic_access_expr(&mut self, expr: &Expression) {
2492        // Specialized detection: ComputedMemberExpression with non-literal key
2493        // Exclude string and numeric literals — they are static indexing, not dynamic access.
2494        if let Expression::ComputedMemberExpression(mem) = expr
2495            && !matches!(&mem.expression, Expression::StringLiteral(_) | Expression::NumericLiteral(_))
2496                && let Expression::Identifier(id) = &mem.object {
2497                    self.dynamic_access_vars.insert(id.name.to_string());
2498                }
2499
2500        // AssignmentExpression also needs to check the left side (AssignmentTarget)
2501        if let Expression::AssignmentExpression(a) = expr {
2502            self.detect_dynamic_access_assign_target(&a.left);
2503        }
2504
2505        // Structural recursion via shared walker
2506        walk_expr_children(expr, &mut |e| self.detect_dynamic_access_expr(e));
2507
2508        // walk_expr_children skips function bodies; recurse manually
2509        if let Expression::FunctionExpression(fe) = expr
2510            && let Some(body) = &fe.body
2511        {
2512            for s in &body.statements {
2513                self.detect_dynamic_access_stmt(s);
2514            }
2515        }
2516    }
2517
2518    /// Pre-pass: detect arrays that have mutation methods called on them
2519    /// (push/pop/shift/unshift/splice/sort/reverse).
2520    /// These arrays must use ArrayList instead of fixed-size [_]T.
2521    fn detect_dynamic_arrays(&mut self, program: &Program) {
2522        for stmt in &program.body {
2523            self.detect_dynamic_arrays_stmt(stmt);
2524        }
2525    }
2526
2527    fn detect_dynamic_arrays_stmt(&mut self, stmt: &Statement) {
2528        // Check for variable declarations that assign from a dynamic array
2529        if let Statement::VariableDeclaration(vd) = stmt {
2530            for decl in &vd.declarations {
2531                if let Some(init) = &decl.init
2532                    && let Expression::Identifier(id) = init
2533                    && self.dynamic_arrays.contains(id.name.as_str())
2534                {
2535                    // If assigning from a dynamic array, mark the new variable as dynamic
2536                    if let oxc_ast::ast::BindingPattern::BindingIdentifier(bi) = &decl.id {
2537                        self.dynamic_arrays.insert(bi.name.to_string());
2538                    }
2539                }
2540            }
2541        }
2542
2543        walk_stmt(stmt, &mut |event| match event {
2544            WalkEvent::Expr(e) => self.detect_dynamic_arrays_expr(e),
2545            WalkEvent::Stmt(s) => self.detect_dynamic_arrays_stmt(s),
2546        });
2547    }
2548
2549    fn detect_dynamic_arrays_expr(&mut self, expr: &Expression) {
2550        // Detect arr.push(), arr.pop(), arr.shift(), arr.unshift(),
2551        // arr.splice(), arr.sort(), arr.reverse()
2552        if let Expression::CallExpression(call) = expr
2553            && let Expression::StaticMemberExpression(mem) = &call.callee
2554            && let Expression::Identifier(id) = &mem.object
2555        {
2556            let method = mem.property.name.as_str();
2557            if matches!(method, "push" | "pop" | "shift" | "unshift" | "splice" | "sort" | "reverse") {
2558                self.dynamic_arrays.insert(id.name.to_string());
2559            }
2560        }
2561
2562        // Check for assignment expressions: x = arr (where arr is dynamic)
2563        if let Expression::AssignmentExpression(assign) = expr
2564            && let Some(target_id) = Self::get_assignment_target_id(&assign.left)
2565            && let Expression::Identifier(src_id) = &assign.right
2566            && self.dynamic_arrays.contains(src_id.name.as_str())
2567        {
2568            self.dynamic_arrays.insert(target_id);
2569        }
2570
2571        // Structural recursion via shared walker
2572        walk_expr_children(expr, &mut |e| self.detect_dynamic_arrays_expr(e));
2573
2574        // walk_expr_children skips function bodies; recurse manually
2575        if let Expression::FunctionExpression(fe) = expr
2576            && let Some(body) = &fe.body
2577        {
2578            for s in &body.statements {
2579                self.detect_dynamic_arrays_stmt(s);
2580            }
2581        }
2582    }
2583
2584    /// Helper: get the variable name from an assignment target
2585    fn get_assignment_target_id(target: &AssignmentTarget) -> Option<String> {
2586        match target {
2587            AssignmentTarget::AssignmentTargetIdentifier(id) => Some(id.name.to_string()),
2588            _ => None,
2589        }
2590    }
2591
2592}