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