Skip to main content

js2zig_core/zigir/lower/
stmt.rs

1// zigir/lower/stmt.rs
2// Statement lowering: control flow (if/for/while/switch/try/labeled), blocks.
3
4use std::collections::HashSet;
5
6use oxc_ast::ast::*;
7
8use crate::types::ZigType;
9use crate::zigir::ident::IrIdent;
10use crate::zigir::source_span::SourceSpan;
11use crate::zigir::types::{IrBlock, IrDecl, IrForInKind, IrForOfKind};
12
13use super::Lowerer;
14
15// ¨T¨T¨T¨T¨T¨T¨T¨T¨T¨T¨T¨T¨T¨T¨T¨T¨T¨T¨T¨T¨T¨T¨T¨T¨T¨T¨T¨T¨T¨T¨T¨T¨T¨T¨T¨T¨T¨T¨T¨T¨T¨T¨T¨T¨T¨T¨T¨T¨T¨T¨T¨T¨T¨T¨T
16//  Declaration lowering (remaining stubs)
17// ¨T¨T¨T¨T¨T¨T¨T¨T¨T¨T¨T¨T¨T¨T¨T¨T¨T¨T¨T¨T¨T¨T¨T¨T¨T¨T¨T¨T¨T¨T¨T¨T¨T¨T¨T¨T¨T¨T¨T¨T¨T¨T¨T¨T¨T¨T¨T¨T¨T¨T¨T¨T¨T¨T¨T
18
19impl Lowerer {
20    /// Lower a statement into an IrStmt.
21    ///
22    /// This is the main dispatch method for statement-level AST ¡ú IR
23    /// transformation. Each branch extracts semantic information and
24    /// defers formatting (indentation, `_ = ` discard prefixes, etc.)
25    /// to the Emitter phase.
26    pub(super) fn lower_stmt(&mut self, stmt: &Statement) -> crate::zigir::types::IrStmt {
27        match stmt {
28            // ©¤©¤ Variable declarations ©¤©¤©¤©¤©¤©¤©¤©¤©¤©¤©¤©¤©¤©¤©¤©¤©¤©¤©¤©¤©¤©¤
29            Statement::VariableDeclaration(vd) => {
30                // Multi-declarator: emit as a block of statements
31                if vd.declarations.len() == 1 {
32                    let decl = &vd.declarations[0];
33                    match &decl.id {
34                        BindingPattern::ObjectPattern(_) | BindingPattern::ArrayPattern(_) => {
35                            self.lower_destructure_decl(decl)
36                        }
37                        _ => {
38                            let ir_decl = self.lower_var_decl(decl, vd.kind.is_const());
39                            match ir_decl {
40                                IrDecl::Var(v) => crate::zigir::types::IrStmt::VarDecl(v),
41                                IrDecl::CompileError { span, msg } => {
42                                    crate::zigir::types::IrStmt::CompileError { span, msg }
43                                }
44                                _ => crate::zigir::types::IrStmt::Comment(
45                                    "// unexpected decl type in statement context".to_string(),
46                                ),
47                            }
48                        }
49                    }
50                } else {
51                    let stmts: Vec<crate::zigir::types::IrStmt> = vd
52                        .declarations
53                        .iter()
54                        .flat_map(|decl| match &decl.id {
55                            BindingPattern::ObjectPattern(_) | BindingPattern::ArrayPattern(_) => {
56                                vec![self.lower_destructure_decl(decl)]
57                            }
58                            _ => {
59                                let ir_decl = self.lower_var_decl(decl, vd.kind.is_const());
60                                match ir_decl {
61                                    IrDecl::Var(v) => vec![crate::zigir::types::IrStmt::VarDecl(v)],
62                                    IrDecl::CompileError { span, msg } => {
63                                        vec![crate::zigir::types::IrStmt::CompileError {
64                                            span,
65                                            msg,
66                                        }]
67                                    }
68                                    _ => vec![],
69                                }
70                            }
71                        })
72                        .collect();
73                    if stmts.len() == 1 {
74                        stmts.into_iter().next().expect("stmts.len()==1 guarantees one element")
75                    } else {
76                        // Transparent block: emits flat without {} braces so that
77                        // `const a = 1, b = 2;` doesn't create a new Zig scope.
78                        crate::zigir::types::IrStmt::Block(IrBlock::new_transparent(stmts))
79                    }
80                }
81            }
82
83            // ©¤©¤ Control flow ©¤©¤©¤©¤©¤©¤©¤©¤©¤©¤©¤©¤©¤©¤©¤©¤©¤©¤©¤©¤©¤©¤©¤©¤©¤©¤©¤©¤©¤©¤©¤
84            Statement::IfStatement(is) => self.lower_if(is),
85
86            Statement::WhileStatement(ws) => {
87                let label = self.current_loop_label();
88                crate::zigir::types::IrStmt::While {
89                    cond: self.lower_expr(&ws.test),
90                    body: self.lower_stmt_as_block(&ws.body, None),
91                    label,
92                }
93            }
94
95            Statement::DoWhileStatement(dws) => {
96                let label = self.current_loop_label();
97                crate::zigir::types::IrStmt::DoWhile {
98                    body: self.lower_stmt_as_block(&dws.body, None),
99                    cond: self.lower_expr(&dws.test),
100                    label,
101                }
102            }
103
104            Statement::ForStatement(fs) => self.lower_for(fs),
105            Statement::ForOfStatement(fos) => self.lower_for_of(fos),
106            Statement::ForInStatement(fis) => self.lower_for_in(fis),
107
108            Statement::SwitchStatement(ss) => self.lower_switch(ss),
109
110            // ©¤©¤ Exception handling ©¤©¤©¤©¤©¤©¤©¤©¤©¤©¤©¤©¤©¤©¤©¤©¤©¤©¤©¤©¤©¤©¤©¤©¤©¤
111            Statement::TryStatement(ts) => self.lower_try(ts),
112            Statement::ThrowStatement(ts) => crate::zigir::types::IrStmt::Throw {
113                value: self.lower_expr(&ts.argument),
114                error_name: None,
115            },
116
117            // ©¤©¤ Function control ©¤©¤©¤©¤©¤©¤©¤©¤©¤©¤©¤©¤©¤©¤©¤©¤©¤©¤©¤©¤©¤©¤©¤©¤©¤©¤©¤©¤
118            Statement::ReturnStatement(rs) => {
119                if let Some(fn_ctx) = self.fn_ctx.as_mut() {
120                    fn_ctx.seen_return = true;
121                }
122                let value = rs.argument.as_ref().map(|expr| {
123                    let mut val = self.lower_expr(expr);
124                    // When the function return type is i64, RemExpr, DivExpr, and PowExpr need
125                    // result_type = Some(I64) so the emitter wraps in @intFromFloat.
126                    // Also, calls to JsAny-returning functions need .asI64() wrapping.
127                    if let Some(ref fn_ctx) = self.fn_ctx
128                        && fn_ctx.return_type == Some(ZigType::I64)
129                    {
130                        val = self.coerce_i64_result_type(val);
131                    }
132                    // When the function return type is f64, I64 expressions
133                    // (IntLiteral, Ident, BuiltinCall, HostCall, Date methods)
134                    // need wrapping in @floatFromInt so the return type matches.
135                    if let Some(ref fn_ctx) = self.fn_ctx
136                        && fn_ctx.return_type == Some(ZigType::F64)
137                    {
138                        val = self.coerce_f64_result_type(val);
139                    }
140                    // When the function return type is JsAny (e.g., P1-B7 default
141                    // for non-export functions without JSDoc), wrap non-JsAny
142                    // expressions in JsAny.from() so the types match.
143                    if let Some(ref fn_ctx) = self.fn_ctx
144                        && fn_ctx.return_type == Some(ZigType::JsAny)
145                    {
146                        val = self.coerce_jsany_result_type(val);
147                    }
148                    val
149                });
150                crate::zigir::types::IrStmt::Return { value }
151            }
152            Statement::BreakStatement(bs) => crate::zigir::types::IrStmt::Break {
153                label: bs.label.as_ref().map(|l| l.name.to_string()),
154            },
155            Statement::ContinueStatement(cs) => crate::zigir::types::IrStmt::Continue {
156                label: cs.label.as_ref().map(|l| l.name.to_string()),
157            },
158
159            // ©¤©¤ Block ©¤©¤©¤©¤©¤©¤©¤©¤©¤©¤©¤©¤©¤©¤©¤©¤©¤©¤©¤©¤©¤©¤©¤©¤©¤©¤©¤©¤©¤©¤©¤©¤©¤©¤©¤©¤©¤©¤
160            Statement::BlockStatement(bs) => {
161                self.name_mangler.push_shadow_scope();
162                let stmts: Vec<crate::zigir::types::IrStmt> =
163                    bs.body.iter().map(|s| self.lower_stmt(s)).collect();
164                self.name_mangler.pop_shadow_scope();
165                crate::zigir::types::IrStmt::Block(IrBlock::new(stmts))
166            }
167            Statement::LabeledStatement(ls) => self.lower_labeled(ls),
168
169            // ©¤©¤ Expression statement ©¤©¤©¤©¤©¤©¤©¤©¤©¤©¤©¤©¤©¤©¤©¤©¤©¤©¤©¤©¤©¤©¤©¤
170            Statement::ExpressionStatement(es) => {
171                // R8-C7: In a constructor body, `this.field = value` is
172                // rewritten to a `const field = value` binding that the
173                // Emitter uses to build the struct return. Because this arm
174                // is the shared statement-lowering path, the rewrite reaches
175                // this-field assignments nested inside if/loop/switch/try
176                // bodies (which lower via lower_stmt_as_block → lower_stmt).
177                // `this_rewrite_fields` is None outside constructors and is
178                // cleared inside nested functions (enter_fn), so non-
179                // constructor and nested-fn `this` are unaffected.
180                // Clone the field list to release the immutable borrow on
181                // `self` before the mutable `try_rewrite_*` call (the list is
182                // small — a handful of class fields per constructor).
183                if let Some(fields) = self.this_rewrite_fields.clone()
184                    && let Some(rewritten) =
185                        self.try_rewrite_this_field_assignment(&es.expression, &fields)
186                {
187                    return rewritten;
188                }
189                // Check if this is an assignment to a JS-const variable.
190                // In JS, `const x = 1; x = 2` throws TypeError at runtime.
191                // We detect this and emit a Throw with error.ConstReassignment
192                // instead of performing the assignment.
193                if let Some(throw_value) = self.make_const_reassign_throw(&es.expression) {
194                    crate::zigir::types::IrStmt::Throw {
195                        value: throw_value,
196                        error_name: Some("ConstReassignment".to_string()),
197                    }
198                } else {
199                    // Save/restore the old flag value rather than unconditionally
200                    // resetting to false. If the lowered expression contains a
201                    // nested function/closure, lowering that body may itself
202                    // touch in_expr_stmt; restoring the saved value keeps the
203                    // outer context consistent instead of clobbering it.
204                    let prev_in_expr_stmt = self.in_expr_stmt;
205                    self.in_expr_stmt = true;
206                    let expr = self.lower_expr(&es.expression);
207                    self.in_expr_stmt = prev_in_expr_stmt;
208                    crate::zigir::types::IrStmt::Expr(expr)
209                }
210            }
211
212            // ©¤©¤ Function declaration (nested) ©¤©¤©¤©¤©¤©¤©¤©¤©¤©¤©¤©¤©¤©¤
213            Statement::FunctionDeclaration(fd) => {
214                self.lower_nested_fn_decl(fd)
215            }
216
217            // ©¤©¤ With statement (unsupported) ©¤©¤©¤©¤©¤©¤©¤©¤©¤©¤©¤©¤©¤©¤©¤
218            Statement::WithStatement(ws) => {
219                let span = self.span_to_source_span(ws.span);
220                self.add_error(span, "with statement is not supported");
221                crate::zigir::types::IrStmt::CompileError {
222                    span: SourceSpan::default(),
223                    msg: "with statement is not supported".to_string(),
224                }
225            }
226
227            // ©¤©¤ Skippable ©¤©¤©¤©¤©¤©¤©¤©¤©¤©¤©¤©¤©¤©¤©¤©¤©¤©¤©¤©¤©¤©¤©¤©¤©¤©¤©¤©¤©¤©¤©¤©¤©¤©¤
228            Statement::EmptyStatement(_) => crate::zigir::types::IrStmt::Comment("".to_string()),
229            Statement::DebuggerStatement(ds) => {
230                crate::zigir::types::IrStmt::CompileError {
231                    span: self.span_to_source_span(ds.span),
232                    msg: "debugger statement is not supported (debugging is not available in compiled Zig)".to_string(),
233                }
234            }
235
236            // ©¤©¤ Descriptive unsupported ©¤©¤©¤©¤©¤©¤©¤©¤©¤©¤©¤©¤©¤©¤©¤©¤©¤©¤©¤
237            Statement::ClassDeclaration(cd) => {
238                let name = cd
239                    .id
240                    .as_ref()
241                    .map(|id| id.name.as_str())
242                    .unwrap_or("<anonymous>");
243                crate::zigir::types::IrStmt::CompileError {
244                    span: self.span_to_source_span(oxc_span::GetSpan::span(stmt)),
245                    msg: format!("nested class declaration '{}' is not supported", name),
246                }
247            }
248            Statement::ExportDefaultDeclaration(_) => crate::zigir::types::IrStmt::CompileError {
249                span: self.span_to_source_span(oxc_span::GetSpan::span(stmt)),
250                msg: "export default is not supported".to_string(),
251            },
252            Statement::ImportDeclaration(_) => crate::zigir::types::IrStmt::CompileError {
253                span: self.span_to_source_span(oxc_span::GetSpan::span(stmt)),
254                msg: "import declaration is not supported".to_string(),
255            },
256
257            // ©¤©¤ Unsupported ©¤©¤©¤©¤©¤©¤©¤©¤©¤©¤©¤©¤©¤©¤©¤©¤©¤©¤©¤©¤©¤©¤©¤©¤©¤©¤©¤©¤©¤©¤©¤©¤
258            _ => {
259                let span = oxc_span::GetSpan::span(stmt);
260                crate::zigir::types::IrStmt::CompileError {
261                    span: self.span_to_source_span(span),
262                    msg: "Unsupported statement type".to_string(),
263                }
264            }
265        }
266    }
267
268    /// Lower a statement into an IrBlock (used for loop bodies, etc.).
269    ///
270    /// For `BlockStatement`, emits inner statements directly.
271    /// For single statements, wraps in a single-element block.
272    pub(super) fn lower_stmt_as_block(
273        &mut self,
274        stmt: &Statement,
275        label: Option<String>,
276    ) -> IrBlock {
277        let stmts = match stmt {
278            Statement::BlockStatement(bs) => {
279                self.name_mangler.push_shadow_scope();
280                let stmts: Vec<crate::zigir::types::IrStmt> =
281                    bs.body.iter().map(|s| self.lower_stmt(s)).collect();
282                self.name_mangler.pop_shadow_scope();
283                stmts
284            }
285            _ => vec![self.lower_stmt(stmt)],
286        };
287        IrBlock {
288            stmts,
289            label,
290            transparent: false,
291        }
292    }
293
294    /// Lower an if statement (including else-if chains).
295    pub(super) fn lower_if(&mut self, is: &IfStatement) -> crate::zigir::types::IrStmt {
296        let cond = self.lower_expr(&is.test);
297        let then = self.lower_stmt_as_block(&is.consequent, None);
298        let else_ = is
299            .alternate
300            .as_ref()
301            .map(|alt| self.lower_stmt_as_block(alt, None));
302        crate::zigir::types::IrStmt::If { cond, then, else_ }
303    }
304
305    /// Lower a for statement.
306    ///
307    /// JS `for(init; test; update) { body }` maps to
308    /// Zig `{ init; while (test) : (update) { body } }`.
309    pub(super) fn lower_for(&mut self, fs: &ForStatement) -> crate::zigir::types::IrStmt {
310        let label = self.current_loop_label();
311
312        let init = fs.init.as_ref().map(|init| match init {
313            ForStatementInit::VariableDeclaration(vd) => {
314                // Lower ALL declarations (handle `for (let i = 0, j = 10; ...)`)
315                let is_const = vd.kind.is_const();
316                let stmts: Vec<crate::zigir::types::IrStmt> = vd
317                    .declarations
318                    .iter()
319                    .filter_map(|d| {
320                        let decl = self.lower_var_decl(d, is_const);
321                        match decl {
322                            IrDecl::Var(v) => Some(crate::zigir::types::IrStmt::VarDecl(v)),
323                            _ => None,
324                        }
325                    })
326                    .collect();
327                if stmts.len() == 1 {
328                    Box::new(
329                        stmts
330                            .into_iter()
331                            .next()
332                            .expect("stmts.len()==1 guarantees one element"),
333                    )
334                } else {
335                    // Transparent block: emits flat without {} braces so that
336                    // `for (let i = 0, j = 10; ...)` doesn't create a new Zig scope.
337                    // A non-transparent block would hide i/j from the while condition.
338                    Box::new(crate::zigir::types::IrStmt::Block(
339                        IrBlock::new_transparent(stmts),
340                    ))
341                }
342            }
343            _ => {
344                // Expression init: lower as expression statement.
345                // In a constructor, `this.field = value` in the init
346                // position is rewritten to a local assignment.
347                if let Some(expr) = init.as_expression() {
348                    let ctor_fields = self.this_rewrite_fields.clone();
349                    if let Some(fields) = &ctor_fields
350                        && let Some(rewritten) =
351                            self.try_rewrite_this_field_assignment(expr, fields)
352                    {
353                        Box::new(rewritten)
354                    } else {
355                        Box::new(crate::zigir::types::IrStmt::Expr(self.lower_expr(expr)))
356                    }
357                } else {
358                    Box::new(crate::zigir::types::IrStmt::Comment(
359                        "// skipped init".to_string(),
360                    ))
361                }
362            }
363        });
364
365        let cond = fs.test.as_ref().map(|expr| self.lower_expr(expr));
366        let update = fs.update.as_ref().map(|expr| {
367            // C9: In a constructor, `this.field++` / `this.field += val`
368            // in the update position must be rewritten to local mutations.
369            let ctor_fields = self.this_rewrite_fields.clone();
370            if let Some(fields) = &ctor_fields
371                && let Some(rewritten) = self.try_rewrite_this_field_assignment(expr, fields)
372            {
373                Box::new(rewritten)
374            } else {
375                Box::new(crate::zigir::types::IrStmt::Expr(self.lower_expr(expr)))
376            }
377        });
378        let body = self.lower_stmt_as_block(&fs.body, None);
379
380        crate::zigir::types::IrStmt::For {
381            init,
382            cond,
383            update,
384            body,
385            label,
386        }
387    }
388
389    /// Lower a for-of statement.
390    ///
391    /// JS `for (const x of iterable) { ... }`
392    /// - Array/ArrayList: Zig `for (iterable) |x| { ... }` or `for (iterable.items) |x| { ... }`
393    /// - Map/Set: Zig `var __it = obj.inner.iterator(); while (__it.next()) |__kv| { const x = __kv.key_ptr.*; ... }`
394    pub(super) fn lower_for_of(&mut self, fos: &ForOfStatement) -> crate::zigir::types::IrStmt {
395        let label = self.current_loop_label();
396
397        // for await...of is not supported
398        if fos.r#await {
399            let span = self.span_to_source_span(fos.span);
400            self.add_error(
401                span,
402                "for await...of is not supported. Use synchronous for...of instead.",
403            );
404            return crate::zigir::types::IrStmt::CompileError {
405                span: SourceSpan::default(),
406                msg: "for await...of is not supported".to_string(),
407            };
408        }
409
410        // Extract loop variable name(s)
411        let (var, destructure_vars) = self.extract_for_of_vars(&fos.left);
412
413        // Determine iteration kind
414        let (kind, iterable_is_arraylist) = self.detect_for_of_kind(&fos.right);
415
416        if matches!(kind, IrForOfKind::AsyncUnsupported) {
417            return crate::zigir::types::IrStmt::CompileError {
418                span: SourceSpan::default(),
419                msg: "for await...of is not supported".to_string(),
420            };
421        }
422
423        // Save old var_types entries for loop-scoped variables to restore after body lowering.
424        // Without this, Map/Set (JsAny) and String (I64) types leak to code after the loop.
425        let loop_var_keys: Vec<String> = if matches!(kind, IrForOfKind::MapSetIter { .. }) {
426            if destructure_vars.is_empty() {
427                vec![var.js_name.clone()]
428            } else {
429                destructure_vars
430                    .iter()
431                    .map(|dv| dv.js_name.clone())
432                    .collect()
433            }
434        } else if let IrForOfKind::Str { .. } = &kind {
435            vec![var.js_name.clone()]
436        } else {
437            Vec::new()
438        };
439        let saved_types: Vec<(String, Option<ZigType>)> = loop_var_keys
440            .iter()
441            .map(|k| (k.clone(), self.type_info.var_types.get(k).cloned()))
442            .collect();
443
444        // For Map/Set iteration, destructure variables and the primary variable
445        // are JsAny (from __kv.key_ptr.* / __kv.value_ptr.*). Set var_types so
446        // the body's binary expressions have correct type info.
447        if matches!(kind, IrForOfKind::MapSetIter { .. }) {
448            if destructure_vars.is_empty() {
449                self.type_info
450                    .var_types
451                    .insert(var.js_name.clone(), ZigType::JsAny);
452            } else {
453                for dv in &destructure_vars {
454                    self.type_info
455                        .var_types
456                        .insert(dv.js_name.clone(), ZigType::JsAny);
457                }
458            }
459        }
460
461        // For String iteration, set var type to I64 so binary expressions work.
462        // The emit layer casts the u8 capture to i64.
463        if let IrForOfKind::Str { .. } = &kind {
464            self.type_info
465                .var_types
466                .insert(var.js_name.clone(), ZigType::I64);
467        }
468
469        let iterable = self.lower_expr(&fos.right);
470        let body = self.lower_stmt_as_block(&fos.body, None);
471
472        // Restore var_types to pre-loop state (loop variables are not visible outside)
473        for (key, old_type) in &saved_types {
474            if let Some(t) = old_type {
475                self.type_info.var_types.insert(key.clone(), t.clone());
476            } else {
477                self.type_info.var_types.remove(key);
478            }
479        }
480
481        // For String for-of, determine if the loop variable is actually used
482        // in the body. If not, emit |_| to avoid Zig 0.16 unused-capture error.
483        let kind = if let IrForOfKind::Str { .. } = &kind {
484            let var_used = match &fos.body {
485                Statement::BlockStatement(b) => b
486                    .body
487                    .iter()
488                    .any(|s| Self::ast_stmt_uses_ident(&var.js_name, s)),
489                other => Self::ast_stmt_uses_ident(&var.js_name, other),
490            };
491            IrForOfKind::Str { var_used }
492        } else {
493            kind
494        };
495
496        crate::zigir::types::IrStmt::ForOf {
497            var,
498            destructure_vars,
499            iterable,
500            iterable_is_arraylist,
501            body,
502            kind,
503            is_async: fos.r#await,
504            label,
505        }
506    }
507
508    /// Lower a for-in statement.
509    ///
510    /// JS `for (const key in obj) { ... }`
511    /// - HashMap/dynamic: `var __it = obj.iterator(); while (__it.next()) |__kv| { const key = __kv.key_ptr.*; ... }`
512    /// - Static struct: unrolled loop ¡ª one block per field with `const key = "fieldName"`
513    pub(super) fn lower_for_in(&mut self, fis: &ForInStatement) -> crate::zigir::types::IrStmt {
514        let label = self.current_loop_label();
515
516        // Extract loop variable name
517        let var = self.extract_for_in_var(&fis.left);
518
519        // Determine iteration kind
520        let kind = self.detect_for_in_kind(&fis.right);
521
522        if matches!(kind, IrForInKind::Unsupported) {
523            let obj_name = match &fis.right {
524                Expression::Identifier(id) => id.name.to_string(),
525                _ => "<expression>".to_string(),
526            };
527            let span = self.span_to_source_span(fis.span);
528            self.add_error(
529                span,
530                format!("for-in: '{}' is not a dynamic object", obj_name),
531            );
532        }
533
534        // For StructUnroll, the iterable is not used at runtime (fields are
535        // hardcoded as string literals), so we use Null to avoid false
536        // "parameter used" detection. For HashMapIter/MapIter, we need the actual
537        // iterable expression at runtime.
538        //
539        // However, for unused-param detection, we still need to track that
540        // the iterable expression references identifiers (e.g., the param `cfg`
541        // in `for (const key in cfg)`), even though it's replaced by Null.
542
543        // Register loop variable type so body expressions have correct type info.
544        // - MapIter: key is JsAny (from std.HashMap(JsAny, JsAny, ...))
545        // - HashMapIter: key is []const u8 (from JsObjectMap = StringArrayHashMap(JsAny))
546        match &kind {
547            IrForInKind::MapIter => {
548                self.type_info
549                    .var_types
550                    .insert(var.js_name.clone(), ZigType::JsAny);
551            }
552            IrForInKind::HashMapIter => {
553                self.type_info
554                    .var_types
555                    .insert(var.js_name.clone(), ZigType::Str);
556            }
557            _ => {}
558        }
559
560        let iterable = if matches!(kind, IrForInKind::StructUnroll { .. }) {
561            // Track identifiers from the iterable for unused-param detection
562            let mut idents = HashSet::new();
563            Self::collect_ast_expr_idents(&fis.right, &mut idents);
564            if let Some(ctx) = self.fn_ctx.as_mut() {
565                ctx.compile_time_referenced_idents.extend(idents);
566            }
567            crate::zigir::types::IrExpr::Null
568        } else {
569            self.lower_expr(&fis.right)
570        };
571        let body = self.lower_stmt_as_block(&fis.body, None);
572
573        crate::zigir::types::IrStmt::ForIn {
574            var,
575            iterable,
576            body,
577            kind,
578            label,
579        }
580    }
581
582    /// Extract variable name from for-of left side.
583    /// Returns (primary_var, destructure_vars) where destructure_vars is
584    /// non-empty for ArrayPattern destructure like `[key, val]`.
585    pub(super) fn extract_for_of_vars(&self, left: &ForStatementLeft) -> (IrIdent, Vec<IrIdent>) {
586        match left {
587            ForStatementLeft::VariableDeclaration(vd) => {
588                if let Some(decl) = vd.declarations.first() {
589                    // Check for ArrayPattern destructure: [key, val]
590                    if let BindingPattern::ArrayPattern(ap) = &decl.id {
591                        let names: Vec<IrIdent> = ap
592                            .elements
593                            .iter()
594                            .filter_map(|elem| {
595                                elem.as_ref().and_then(|pat| {
596                                    crate::infer::binding_name(pat).map(IrIdent::new)
597                                })
598                            })
599                            .collect();
600                        let primary = names
601                            .first()
602                            .cloned()
603                            .unwrap_or_else(|| IrIdent::new("item"));
604                        return (primary, names);
605                    }
606                    // Simple identifier
607                    if let Some(name) = crate::infer::binding_name(&decl.id) {
608                        return (IrIdent::new(name), vec![]);
609                    }
610                }
611                (IrIdent::new("item"), vec![])
612            }
613            _ => (IrIdent::new("item"), vec![]),
614        }
615    }
616
617    /// Extract variable name from for-in left side.
618    pub(super) fn extract_for_in_var(&self, left: &ForStatementLeft) -> IrIdent {
619        match left {
620            ForStatementLeft::VariableDeclaration(vd) => vd
621                .declarations
622                .first()
623                .and_then(|decl| crate::infer::binding_name(&decl.id))
624                .map(IrIdent::new)
625                .unwrap_or_else(|| IrIdent::new("key")),
626            ForStatementLeft::AssignmentTargetIdentifier(id) => IrIdent::new(id.name.as_str()),
627            _ => IrIdent::new("key"),
628        }
629    }
630
631    /// Detect for-of iteration kind based on the right-hand expression type.
632    pub(super) fn detect_for_of_kind(&self, right: &Expression) -> (IrForOfKind, bool) {
633        match right {
634            Expression::Identifier(id) => {
635                if let Some(zig_type) = self.type_info.var_types.get(id.name.as_str()) {
636                    // Map → iterator pattern
637                    if let ZigType::NamedStruct(name) = zig_type {
638                        if name == "Map" {
639                            return (IrForOfKind::MapSetIter { is_map: true }, false);
640                        }
641                        if name == "Set" {
642                            return (IrForOfKind::MapSetIter { is_map: false }, false);
643                        }
644                    }
645                    // ArrayList → use .items
646                    if matches!(zig_type, ZigType::ArrayList(_)) {
647                        return (IrForOfKind::Array, true);
648                    }
649                    // String → byte iteration
650                    if matches!(zig_type, ZigType::Str) {
651                        // Check if the loop variable is used in the body
652                        // (we can't check here since we don't have the body;
653                        //  the var_used flag is set in lower_for_of via a re-check)
654                        return (IrForOfKind::Str { var_used: true }, false);
655                    }
656                }
657                // Default: array iteration
658                (IrForOfKind::Array, false)
659            }
660            Expression::StringLiteral(_) => (IrForOfKind::Str { var_used: true }, false),
661            _ => (IrForOfKind::Array, false),
662        }
663    }
664
665    /// Detect for-in iteration kind based on the right-hand expression type.
666    pub(super) fn detect_for_in_kind(&self, right: &Expression) -> IrForInKind {
667        match right {
668            Expression::Identifier(id) => {
669                if let Some(zig_type) = self.type_info.var_types.get(id.name.as_str()) {
670                    // Map (NamedStruct("Map")) → iterator via .inner.iterator()
671                    if let ZigType::NamedStruct(name) = zig_type
672                        && name == "Map"
673                    {
674                        return IrForInKind::MapIter;
675                    }
676                    // HashMap/dynamic object → iterator-based
677                    if matches!(zig_type, ZigType::Anytype) {
678                        return IrForInKind::HashMapIter;
679                    }
680                    // Static struct with known fields → unroll
681                    if let ZigType::Struct(fields) = zig_type
682                        && !fields.is_empty()
683                    {
684                        return IrForInKind::StructUnroll {
685                            fields: fields.iter().map(|(n, _)| n.clone()).collect(),
686                        };
687                    }
688                    // Named struct (e.g., JSDoc @typedef) → resolve to StructUnroll
689                    if let ZigType::NamedStruct(name) = zig_type
690                        && let Some(typedef) = self.jsdoc_data.typedefs.get(name)
691                        && !typedef.fields.is_empty()
692                    {
693                        let fields: Vec<String> =
694                            typedef.fields.iter().map(|f| f.name.clone()).collect();
695                        return IrForInKind::StructUnroll { fields };
696                    }
697                }
698                IrForInKind::Unsupported
699            }
700            _ => IrForInKind::Unsupported,
701        }
702    }
703
704    /// Lower a switch statement.
705    pub(super) fn lower_switch(&mut self, ss: &SwitchStatement) -> crate::zigir::types::IrStmt {
706        let expr = self.lower_expr(&ss.discriminant);
707
708        // Pre-compute fall-through ranges: for each case i, determine which
709        // cases' consequents must be merged into case i's body.
710        // A case falls through to the next if its consequent has no top-level
711        // break statement.
712        let n = ss.cases.len();
713        let mut body_ranges: Vec<(usize, usize)> = Vec::with_capacity(n);
714        for i in 0..n {
715            let mut end = i + 1;
716            while end <= n {
717                // Only unlabeled `break;` terminates switch fall-through.
718                // Labeled `break outerLabel;` must be preserved for outer loops.
719                let has_break = ss.cases[end - 1]
720                    .consequent
721                    .iter()
722                    .any(|s| matches!(s, Statement::BreakStatement(bs) if bs.label.is_none()));
723                if has_break {
724                    break;
725                }
726                if end < n {
727                    end += 1;
728                } else {
729                    break;
730                }
731            }
732            body_ranges.push((i, end));
733        }
734
735        // Lower each case: merge fall-through bodies, strip break statements.
736        let mut cases: Vec<crate::zigir::types::IrSwitchCase> = Vec::with_capacity(n);
737        for (i, case) in ss.cases.iter().enumerate() {
738            let test = case.test.as_ref().map(|e| self.lower_expr(e));
739            let (start, end) = body_ranges[i];
740            let mut body: Vec<crate::zigir::types::IrStmt> = Vec::new();
741            for j in start..end {
742                for s in &ss.cases[j].consequent {
743                    // Only strip unlabeled `break;` (switch break).
744                    // Labeled `break outerLabel;` must be lowered normally.
745                    if matches!(s, Statement::BreakStatement(bs) if bs.label.is_none()) {
746                        break;
747                    }
748                    body.push(self.lower_stmt(s));
749                }
750            }
751            cases.push(crate::zigir::types::IrSwitchCase { test, body });
752        }
753
754        crate::zigir::types::IrStmt::Switch { expr, cases }
755    }
756
757    /// Lower a try-catch statement.
758    pub(super) fn lower_try(&mut self, ts: &TryStatement) -> crate::zigir::types::IrStmt {
759        // Lower try block first, then inspect the resulting IR for throws.
760        // This catches implicit throws like const-reassignment guards that
761        // `stmt_has_throw_any` (AST-level) cannot detect.
762
763        // Record catchable_error state before lowering try body.
764        // If it changes from false to true, the try body contains operations
765        // that emit `catch return error.JsThrow` (JSON.parse, BigInt div/mod, etc.)
766        // — these need the labeled block pattern so the emit layer can use
767        // `break :label` instead of `return error.JsThrow`.
768        let catchable_before = self
769            .fn_ctx
770            .as_ref()
771            .is_some_and(|ctx| ctx.has_catchable_error);
772
773        let try_block = {
774            let stmts = ts.block.body.iter().map(|s| self.lower_stmt(s)).collect();
775            IrBlock::new(stmts)
776        };
777
778        let catchable_after = self
779            .fn_ctx
780            .as_ref()
781            .is_some_and(|ctx| ctx.has_catchable_error);
782        let has_catchable_error_in_try = catchable_after && !catchable_before;
783
784        // Reset has_catchable_error to its pre-try state.
785        // Without this reset, the flag is sticky: once any catchable operation
786        // (JSON.parse, BigInt div/mod, BigInt **) sets it to true, it stays true
787        // for all subsequent try blocks in the same function. Since lower_try
788        // detects catchable errors via the DIFFERENCE between catchable_before
789        // and catchable_after, a sticky true makes has_catchable_error_in_try =
790        // true && !true = false for every try after the first — silently
791        // skipping the labeled-block emit pattern and producing invalid Zig
792        // (catch return error.JsThrow inside a non-error-returning function).
793        // Catch/finally blocks below may set the flag again, which is correct:
794        // those errors are outside the try body and need function-level can_throw.
795        if let Some(ctx) = self.fn_ctx.as_mut() {
796            ctx.has_catchable_error = catchable_before;
797        }
798
799        // AST-level throw detection (for nested try exclusion)
800        let has_nested_try = ts
801            .block
802            .body
803            .iter()
804            .any(|s| matches!(s, Statement::TryStatement(_)));
805
806        // IR-level throw detection: scan lowered try_block for any IrStmt::Throw.
807        fn ir_stmt_has_throw(s: &crate::zigir::types::IrStmt) -> bool {
808            match s {
809                crate::zigir::types::IrStmt::Throw { .. } => true,
810                // Recurse into nested blocks (if, while, for, switch, etc.)
811                crate::zigir::types::IrStmt::If { then, else_, .. } => {
812                    ir_block_has_throw(then) || else_.as_ref().is_some_and(ir_block_has_throw)
813                }
814                crate::zigir::types::IrStmt::While { body, .. }
815                | crate::zigir::types::IrStmt::DoWhile { body, .. }
816                | crate::zigir::types::IrStmt::For { body, .. }
817                | crate::zigir::types::IrStmt::ForOf { body, .. }
818                | crate::zigir::types::IrStmt::ForIn { body, .. } => ir_block_has_throw(body),
819                crate::zigir::types::IrStmt::Switch { cases, .. } => {
820                    cases.iter().any(|c| c.body.iter().any(ir_stmt_has_throw))
821                }
822                crate::zigir::types::IrStmt::Block(b) => ir_block_has_throw(b),
823                // Recurse into nested try: throws in the try body, catch, or
824                // finally all propagate to the outer try's has_throw flag
825                // (conservative — even throws caught by the inner catch count,
826                //  which only makes the outer emit use the more general path).
827                crate::zigir::types::IrStmt::Try {
828                    try_block,
829                    catch_block,
830                    finally,
831                    ..
832                } => {
833                    ir_block_has_throw(try_block)
834                        || ir_block_has_throw(catch_block)
835                        || finally.as_ref().is_some_and(ir_block_has_throw)
836                }
837                _ => false,
838            }
839        }
840        fn ir_block_has_throw(block: &IrBlock) -> bool {
841            block.stmts.iter().any(ir_stmt_has_throw)
842        }
843        let has_throw = ir_block_has_throw(&try_block) || has_catchable_error_in_try;
844
845        // Check if a finally block contains break/continue that would escape
846        // the defer block (which is how finally is emitted). Break/continue
847        // inside nested loops are valid — they target the loop. Only
848        // break/continue in If/Block/Switch/Try (not inside a loop) would
849        // target a loop outside the defer, producing invalid Zig.
850        fn ir_finally_has_escaping_break_or_continue(
851            stmts: &[crate::zigir::types::IrStmt],
852        ) -> bool {
853            fn check(s: &crate::zigir::types::IrStmt) -> bool {
854                use crate::zigir::types::IrStmt;
855                match s {
856                    IrStmt::Break { .. } | IrStmt::Continue { .. } => true,
857                    IrStmt::If { then, else_, .. } => {
858                        check_block(&then.stmts)
859                            || else_.as_ref().is_some_and(|e| check_block(&e.stmts))
860                    }
861                    IrStmt::Block(b) => check_block(&b.stmts),
862                    IrStmt::Switch { cases, .. } => cases.iter().any(|c| c.body.iter().any(check)),
863                    IrStmt::Try {
864                        try_block,
865                        catch_block,
866                        finally,
867                        ..
868                    } => {
869                        check_block(&try_block.stmts)
870                            || check_block(&catch_block.stmts)
871                            || finally.as_ref().is_some_and(|f| check_block(&f.stmts))
872                    }
873                    // Loops: break/continue inside these target the loop — valid
874                    IrStmt::While { .. }
875                    | IrStmt::DoWhile { .. }
876                    | IrStmt::For { .. }
877                    | IrStmt::ForOf { .. }
878                    | IrStmt::ForIn { .. } => false,
879                    _ => false,
880                }
881            }
882            fn check_block(stmts: &[crate::zigir::types::IrStmt]) -> bool {
883                stmts.iter().any(check)
884            }
885            check_block(stmts)
886        }
887
888        let (catch_var, catch_var_referenced, catch_block) = if let Some(handler) = &ts.handler {
889            let var = handler
890                .param
891                .as_ref()
892                .and_then(|p| crate::infer::binding_name(&p.pattern))
893                .map(|name| self.make_ident(name));
894            // Register catch variable type as JsError so member access
895            // (e.name, e.message, e.stack) works correctly.
896            if let Some(ref v) = var {
897                self.type_info
898                    .var_types
899                    .insert(v.zig_name.clone(), ZigType::JsError);
900            }
901            let stmts = handler
902                .body
903                .body
904                .iter()
905                .map(|s| self.lower_stmt(s))
906                .collect();
907            // Check if catch variable is referenced in the catch body
908            let catch_var_referenced = if let Some(ref cv) = var {
909                let js_name = &cv.js_name;
910                handler
911                    .body
912                    .body
913                    .iter()
914                    .any(|s| Self::stmt_references_name(s, js_name))
915            } else {
916                false
917            };
918            (var, catch_var_referenced, IrBlock::new(stmts))
919        } else {
920            (None, false, IrBlock::new(vec![]))
921        };
922
923        let finally = ts.finalizer.as_ref().map(|f| {
924            let stmts = f.body.iter().map(|s| self.lower_stmt(s)).collect();
925            IrBlock::new(stmts)
926        });
927
928        // Detect break/continue in finally that would escape the defer.
929        // The emit layer already catches return/throw via block_has_return_or_throw,
930        // but break/continue are not checked there — producing invalid Zig that
931        // fails at compile time with an unhelpful error. Catch it here instead.
932        // Also call add_error so the message surfaces in TranspileResult.errors
933        // (not just compile_errors / emitted @compileError).
934        if let Some(ref fin) = finally
935            && ir_finally_has_escaping_break_or_continue(&fin.stmts)
936        {
937            let span = self.span_to_source_span(ts.span);
938            let msg = "break/continue in finally block is not supported";
939            self.add_error(span.clone(), msg);
940            return crate::zigir::types::IrStmt::CompileError {
941                span,
942                msg: msg.to_string(),
943            };
944        }
945
946        crate::zigir::types::IrStmt::Try {
947            try_block,
948            catch_var,
949            catch_var_referenced,
950            catch_block,
951            finally,
952            has_throw,
953            has_nested_try,
954        }
955    }
956
957    /// Check if a statement references a given identifier name.
958    /// Used to detect whether a catch variable is actually used in the catch body.
959    pub(super) fn stmt_references_name(stmt: &Statement, name: &str) -> bool {
960        match stmt {
961            Statement::ExpressionStatement(es) => Self::expr_references_name(&es.expression, name),
962            Statement::ReturnStatement(rs) => rs
963                .argument
964                .as_ref()
965                .is_some_and(|a| Self::expr_references_name(a, name)),
966            Statement::VariableDeclaration(vd) => vd.declarations.iter().any(|d| {
967                d.init
968                    .as_ref()
969                    .is_some_and(|init| Self::expr_references_name(init, name))
970            }),
971            Statement::BlockStatement(bs) => {
972                bs.body.iter().any(|s| Self::stmt_references_name(s, name))
973            }
974            Statement::ThrowStatement(ts) => Self::expr_references_name(&ts.argument, name),
975            Statement::IfStatement(ifs) => {
976                Self::stmt_references_name(&ifs.consequent, name)
977                    || ifs
978                        .alternate
979                        .as_ref()
980                        .is_some_and(|a| Self::stmt_references_name(a, name))
981            }
982            Statement::WhileStatement(ws) => {
983                Self::expr_references_name(&ws.test, name)
984                    || Self::stmt_references_name(&ws.body, name)
985            }
986            Statement::DoWhileStatement(dws) => {
987                Self::stmt_references_name(&dws.body, name)
988                    || Self::expr_references_name(&dws.test, name)
989            }
990            Statement::ForStatement(fs) => {
991                Self::stmt_references_name(&fs.body, name)
992                    || fs
993                        .test
994                        .as_ref()
995                        .is_some_and(|e| Self::expr_references_name(e, name))
996                    || fs
997                        .update
998                        .as_ref()
999                        .is_some_and(|e| Self::expr_references_name(e, name))
1000            }
1001            Statement::ForOfStatement(fos) => {
1002                Self::expr_references_name(&fos.right, name)
1003                    || Self::stmt_references_name(&fos.body, name)
1004            }
1005            Statement::ForInStatement(fis) => {
1006                Self::expr_references_name(&fis.right, name)
1007                    || Self::stmt_references_name(&fis.body, name)
1008            }
1009            Statement::LabeledStatement(ls) => Self::stmt_references_name(&ls.body, name),
1010            Statement::SwitchStatement(ss) => ss.cases.iter().any(|c| {
1011                c.consequent
1012                    .iter()
1013                    .any(|s| Self::stmt_references_name(s, name))
1014            }),
1015            Statement::TryStatement(ts) => {
1016                ts.block
1017                    .body
1018                    .iter()
1019                    .any(|s| Self::stmt_references_name(s, name))
1020                    || ts.handler.as_ref().is_some_and(|h| {
1021                        h.body
1022                            .body
1023                            .iter()
1024                            .any(|s| Self::stmt_references_name(s, name))
1025                    })
1026                    || ts
1027                        .finalizer
1028                        .as_ref()
1029                        .is_some_and(|f| f.body.iter().any(|s| Self::stmt_references_name(s, name)))
1030            }
1031            _ => false,
1032        }
1033    }
1034
1035    pub(super) fn expr_references_name(expr: &Expression, name: &str) -> bool {
1036        match expr {
1037            Expression::Identifier(id) => id.name.as_str() == name,
1038            Expression::BinaryExpression(be) => {
1039                Self::expr_references_name(&be.left, name)
1040                    || Self::expr_references_name(&be.right, name)
1041            }
1042            Expression::LogicalExpression(le) => {
1043                Self::expr_references_name(&le.left, name)
1044                    || Self::expr_references_name(&le.right, name)
1045            }
1046            Expression::UnaryExpression(ue) => Self::expr_references_name(&ue.argument, name),
1047            Expression::UpdateExpression(ue) => {
1048                Self::simple_assign_target_references_name(&ue.argument, name)
1049            }
1050            Expression::AssignmentExpression(ae) => {
1051                Self::assign_target_references_name(&ae.left, name)
1052                    || Self::expr_references_name(&ae.right, name)
1053            }
1054            Expression::ConditionalExpression(ce) => {
1055                Self::expr_references_name(&ce.test, name)
1056                    || Self::expr_references_name(&ce.consequent, name)
1057                    || Self::expr_references_name(&ce.alternate, name)
1058            }
1059            Expression::CallExpression(ce) => {
1060                Self::expr_references_name(&ce.callee, name)
1061                    || ce
1062                        .arguments
1063                        .iter()
1064                        .any(|a| Self::arg_references_name(a, name))
1065            }
1066            Expression::NewExpression(ne) => {
1067                Self::expr_references_name(&ne.callee, name)
1068                    || ne
1069                        .arguments
1070                        .iter()
1071                        .any(|a| Self::arg_references_name(a, name))
1072            }
1073            Expression::StaticMemberExpression(sme) => {
1074                Self::expr_references_name(&sme.object, name)
1075            }
1076            Expression::ComputedMemberExpression(cme) => {
1077                Self::expr_references_name(&cme.object, name)
1078                    || Self::expr_references_name(&cme.expression, name)
1079            }
1080            Expression::ArrayExpression(ae) => ae.elements.iter().any(|e| match e {
1081                ArrayExpressionElement::SpreadElement(se) => {
1082                    Self::expr_references_name(&se.argument, name)
1083                }
1084                other => other
1085                    .as_expression()
1086                    .is_some_and(|e| Self::expr_references_name(e, name)),
1087            }),
1088            Expression::ObjectExpression(oe) => oe.properties.iter().any(|p| match p {
1089                ObjectPropertyKind::ObjectProperty(op) => {
1090                    Self::expr_references_name(&op.value, name)
1091                }
1092                ObjectPropertyKind::SpreadProperty(sp) => {
1093                    Self::expr_references_name(&sp.argument, name)
1094                }
1095            }),
1096            Expression::SequenceExpression(se) => se
1097                .expressions
1098                .iter()
1099                .any(|e| Self::expr_references_name(e, name)),
1100            Expression::TemplateLiteral(tl) => tl
1101                .expressions
1102                .iter()
1103                .any(|e| Self::expr_references_name(e, name)),
1104            Expression::ChainExpression(ce) => {
1105                Self::chain_element_references_name(&ce.expression, name)
1106            }
1107            Expression::AwaitExpression(ae) => Self::expr_references_name(&ae.argument, name),
1108            Expression::TaggedTemplateExpression(tte) => {
1109                Self::expr_references_name(&tte.tag, name)
1110                    || tte
1111                        .quasi
1112                        .expressions
1113                        .iter()
1114                        .any(|e| Self::expr_references_name(e, name))
1115            }
1116            _ => false,
1117        }
1118    }
1119
1120    /// Recursively check whether an assignment target references the given name.
1121    fn assign_target_references_name(target: &AssignmentTarget, name: &str) -> bool {
1122        match target {
1123            AssignmentTarget::AssignmentTargetIdentifier(id) => id.name.as_str() == name,
1124            // Destructuring / member targets: identifiers inside the
1125            // destructure pattern still count as references to `name`.
1126            AssignmentTarget::ArrayAssignmentTarget(_)
1127            | AssignmentTarget::ObjectAssignmentTarget(_) => {
1128                // Conservative: assume destructuring patterns may reference
1129                // the name rather than missing it. Catch-variable usage is
1130                // intentionally over-reported here to avoid silently
1131                // dropping the variable binding.
1132                true
1133            }
1134            _ => false,
1135        }
1136    }
1137
1138    /// Recursively check whether a simple assignment target references the given name.
1139    fn simple_assign_target_references_name(target: &SimpleAssignmentTarget, name: &str) -> bool {
1140        match target {
1141            SimpleAssignmentTarget::AssignmentTargetIdentifier(id) => id.name.as_str() == name,
1142            _ => false,
1143        }
1144    }
1145
1146    /// Check whether an optional chain element references the given name.
1147    fn chain_element_references_name(elem: &ChainElement, name: &str) -> bool {
1148        match elem {
1149            ChainElement::StaticMemberExpression(sme) => {
1150                Self::expr_references_name(&sme.object, name)
1151            }
1152            ChainElement::ComputedMemberExpression(cme) => {
1153                Self::expr_references_name(&cme.object, name)
1154                    || Self::expr_references_name(&cme.expression, name)
1155            }
1156            ChainElement::CallExpression(ce) => {
1157                Self::expr_references_name(&ce.callee, name)
1158                    || ce
1159                        .arguments
1160                        .iter()
1161                        .any(|a| Self::arg_references_name(a, name))
1162            }
1163            _ => false,
1164        }
1165    }
1166
1167    /// Check if a call argument references a given identifier name.
1168    fn arg_references_name(arg: &Argument, name: &str) -> bool {
1169        match arg {
1170            Argument::SpreadElement(se) => Self::expr_references_name(&se.argument, name),
1171            // All other variants are inherited from Expression — use as_expression()
1172            other => {
1173                if let Some(expr) = other.as_expression() {
1174                    Self::expr_references_name(expr, name)
1175                } else {
1176                    false
1177                }
1178            }
1179        }
1180    }
1181
1182    /// Lower a labeled statement.
1183    ///
1184    /// For loops, the label is attached to the loop body.
1185    /// For blocks, the label is attached only if a `break :label` exists
1186    /// inside the body.
1187    pub(super) fn lower_labeled(&mut self, ls: &LabeledStatement) -> crate::zigir::types::IrStmt {
1188        let label_str = ls.label.name.to_string();
1189
1190        match &ls.body {
1191            // Loops: label attaches to the loop (handled by lower_stmt_for_loop)
1192            Statement::WhileStatement(_)
1193            | Statement::DoWhileStatement(_)
1194            | Statement::ForStatement(_)
1195            | Statement::ForOfStatement(_)
1196            | Statement::ForInStatement(_) => {
1197                // Set pending label for the loop to pick up
1198                self.pending_label = Some(label_str);
1199                self.lower_stmt(&ls.body)
1200            }
1201            // Other statements: only add label if body contains `break :label`
1202            _ => {
1203                let ir_stmt = self.lower_stmt(&ls.body);
1204                // Check if body contains break to this label
1205                let has_break = Self::stmt_has_break_to_label(&ls.body, &label_str);
1206                if has_break {
1207                    // Wrap in a labeled block
1208                    crate::zigir::types::IrStmt::Block(IrBlock::with_label(
1209                        if let crate::zigir::types::IrStmt::Block(b) = ir_stmt {
1210                            b.stmts
1211                        } else {
1212                            vec![ir_stmt]
1213                        },
1214                        label_str,
1215                    ))
1216                } else {
1217                    ir_stmt
1218                }
1219            }
1220        }
1221    }
1222
1223    /// Pre-scan: check if a statement tree contains `break :label_name`.
1224    pub(super) fn stmt_has_break_to_label(stmt: &Statement, label_name: &str) -> bool {
1225        match stmt {
1226            Statement::BreakStatement(bs) => bs
1227                .label
1228                .as_ref()
1229                .is_some_and(|l| l.name.as_str() == label_name),
1230            Statement::BlockStatement(bs) => bs
1231                .body
1232                .iter()
1233                .any(|s| Self::stmt_has_break_to_label(s, label_name)),
1234            Statement::IfStatement(is) => {
1235                Self::stmt_has_break_to_label(&is.consequent, label_name)
1236                    || is
1237                        .alternate
1238                        .as_ref()
1239                        .is_some_and(|a| Self::stmt_has_break_to_label(a, label_name))
1240            }
1241            Statement::LabeledStatement(ls) => Self::stmt_has_break_to_label(&ls.body, label_name),
1242            Statement::TryStatement(ts) => {
1243                ts.block
1244                    .body
1245                    .iter()
1246                    .any(|s| Self::stmt_has_break_to_label(s, label_name))
1247                    || ts.handler.as_ref().is_some_and(|h| {
1248                        h.body
1249                            .body
1250                            .iter()
1251                            .any(|s| Self::stmt_has_break_to_label(s, label_name))
1252                    })
1253                    || ts.finalizer.as_ref().is_some_and(|f| {
1254                        f.body
1255                            .iter()
1256                            .any(|s| Self::stmt_has_break_to_label(s, label_name))
1257                    })
1258            }
1259            Statement::SwitchStatement(ss) => ss.cases.iter().any(|c| {
1260                c.consequent
1261                    .iter()
1262                    .any(|s| Self::stmt_has_break_to_label(s, label_name))
1263            }),
1264            Statement::ForStatement(fs) => Self::stmt_has_break_to_label(&fs.body, label_name),
1265            Statement::ForOfStatement(fos) => Self::stmt_has_break_to_label(&fos.body, label_name),
1266            Statement::ForInStatement(fis) => Self::stmt_has_break_to_label(&fis.body, label_name),
1267            Statement::WhileStatement(ws) => Self::stmt_has_break_to_label(&ws.body, label_name),
1268            Statement::DoWhileStatement(dws) => {
1269                Self::stmt_has_break_to_label(&dws.body, label_name)
1270            }
1271            _ => false,
1272        }
1273    }
1274
1275    /// If the expression is an assignment to a JS-const variable, return Some(value)
1276    /// where `value` is the lowered right-hand side of the assignment. This ensures
1277    /// that variables referenced in the RHS (e.g., `y` in `x %= y`) are still
1278    /// considered "used" by the Zig compiler, avoiding "unused local constant" errors.
1279    /// Returns None if the expression is not a const-reassignment.
1280    fn make_const_reassign_throw(
1281        &mut self,
1282        expr: &Expression,
1283    ) -> Option<crate::zigir::types::IrExpr> {
1284        if let Expression::AssignmentExpression(ae) = expr {
1285            // All assignment operators (simple `=` and compound `+=`, `-=`, etc.)
1286            if let AssignmentTarget::AssignmentTargetIdentifier(id) = &ae.left {
1287                // Check if the identifier is in js_const_reassigned
1288                let is_const_reassign = self
1289                    .fn_ctx
1290                    .as_ref()
1291                    .is_some_and(|ctx| ctx.js_const_reassigned.contains(id.name.as_str()));
1292                if is_const_reassign {
1293                    // Lower the RHS only (not the full assignment, since Zig
1294                    // assignment is a statement, not an expression).
1295                    // This preserves references to variables in the RHS (e.g., `y`
1296                    // in `x %= y`) so they are not marked as unused.
1297                    return Some(self.lower_expr(&ae.right));
1298                }
1299            }
1300        }
1301        None
1302    }
1303
1304    /// Get and consume the pending loop label (set by lower_labeled).
1305    pub(super) fn current_loop_label(&mut self) -> Option<String> {
1306        self.pending_label.take()
1307    }
1308
1309    /// Lower a block of statements.
1310    pub(super) fn lower_block(&mut self, stmts: &[Statement]) -> IrBlock {
1311        let ir_stmts: Vec<crate::zigir::types::IrStmt> =
1312            stmts.iter().map(|s| self.lower_stmt(s)).collect();
1313        IrBlock::new(ir_stmts)
1314    }
1315
1316    /// When an i64-returning function contains a `return expr` where `expr`
1317    /// is a RemExpr, DivExpr, PowExpr, or a BuiltinCall returning f64, ensure
1318    /// the emitter wraps the f64 result in `@as(i64, @intFromFloat(...))`.
1319    ///
1320    /// For RemExpr/DivExpr/PowExpr: set `result_type` to `Some(I64)`.
1321    /// For BuiltinCall with F64 return type (e.g., Math.sqrt, parseFloat):
1322    /// wrap in a DivExpr with divisor 1 and `result_type: Some(I64)`.
1323    /// `x / 1.0` is the IEEE 754 identity for all f64 values (including NaN,
1324    /// Infinity, -0), so Zig optimizes the division away at comptime.
1325    ///
1326    /// Also recurses into Conditional and Sequence expressions to find
1327    /// nested expressions in value-producing positions
1328    /// (e.g., `return cond ? a % b : 0`).
1329    fn coerce_i64_result_type(
1330        &self,
1331        expr: crate::zigir::types::IrExpr,
1332    ) -> crate::zigir::types::IrExpr {
1333        use crate::zigir::types::IrExpr;
1334        match expr {
1335            // Direct matches: coerce result_type to I64
1336            IrExpr::RemExpr {
1337                left,
1338                right,
1339                left_type,
1340                right_type,
1341                result_type: None,
1342            } => IrExpr::RemExpr {
1343                left,
1344                right,
1345                left_type,
1346                right_type,
1347                result_type: Some(ZigType::I64),
1348            },
1349            IrExpr::DivExpr {
1350                left,
1351                right,
1352                left_type,
1353                right_type,
1354                result_type: None,
1355            } => IrExpr::DivExpr {
1356                left,
1357                right,
1358                left_type,
1359                right_type,
1360                result_type: Some(ZigType::I64),
1361            },
1362            IrExpr::PowExpr {
1363                base,
1364                exp,
1365                base_type,
1366                exp_type,
1367                result_type: None,
1368            } => IrExpr::PowExpr {
1369                base,
1370                exp,
1371                base_type,
1372                exp_type,
1373                result_type: Some(ZigType::I64),
1374            },
1375            // BuiltinCall returning JsAny (e.g., arr.pop(), arr.shift()):
1376            // wrap in .asI64() to extract the i64 value.
1377            IrExpr::BuiltinCall(bc) if bc.return_type == ZigType::JsAny => {
1378                Self::wrap_jsany_to_i64(IrExpr::BuiltinCall(bc))
1379            }
1380            // BuiltinCall returning F64 (e.g., Math.sqrt, parseFloat):
1381            // wrap in DivExpr with divisor 1 and result_type I64 to trigger
1382            // @as(i64, @intFromFloat(...)) in the emitter.
1383            // `x / 1.0` is the identity for all IEEE 754 f64 values.
1384            IrExpr::BuiltinCall(bc) if bc.return_type == ZigType::F64 => IrExpr::DivExpr {
1385                left: Box::new(IrExpr::BuiltinCall(bc)),
1386                right: Box::new(IrExpr::IntLiteral(1)),
1387                left_type: ZigType::F64,
1388                right_type: ZigType::I64,
1389                result_type: Some(ZigType::I64),
1390            },
1391            // HostCall returning F64: wrap in DivExpr, same as BuiltinCall above.
1392            IrExpr::HostCall(hc) if hc.return_type == ZigType::F64 => IrExpr::DivExpr {
1393                left: Box::new(IrExpr::HostCall(hc)),
1394                right: Box::new(IrExpr::IntLiteral(1)),
1395                left_type: ZigType::F64,
1396                right_type: ZigType::I64,
1397                result_type: Some(ZigType::I64),
1398            },
1399            // HostCall returning JsAny: wrap in .asI64() to extract the i64
1400            // value from the JsAny union, same as Call with JsAny return.
1401            IrExpr::HostCall(hc) if hc.return_type == ZigType::JsAny => {
1402                Self::wrap_jsany_to_i64(IrExpr::HostCall(hc))
1403            }
1404            // Call to a JsAny-returning function: wrap in .asI64() to
1405            // extract the i64 value from the JsAny union.
1406            IrExpr::Call(call) => {
1407                let returns_jsany = match &*call.callee {
1408                    IrExpr::Ident(ident) | IrExpr::TypedIdent { ident, .. } => {
1409                        self.type_info.fn_return_types.get(&ident.js_name) == Some(&ZigType::JsAny)
1410                    }
1411                    _ => false,
1412                };
1413                if returns_jsany {
1414                    Self::wrap_jsany_to_i64(IrExpr::Call(call))
1415                } else {
1416                    IrExpr::Call(call)
1417                }
1418            }
1419            // Conditional: recurse into both branches (value-producing).
1420            IrExpr::Conditional { cond, then, else_ } => IrExpr::Conditional {
1421                cond,
1422                then: Box::new(self.coerce_i64_result_type(*then)),
1423                else_: Box::new(self.coerce_i64_result_type(*else_)),
1424            },
1425            // Sequence: only the last element is the return value
1426            IrExpr::Sequence(mut exprs) => {
1427                if let Some(last) = exprs.pop() {
1428                    exprs.push(self.coerce_i64_result_type(last));
1429                }
1430                IrExpr::Sequence(exprs)
1431            }
1432            // Binary with f64 result → wrap in @intFromFloat
1433            IrExpr::Binary {
1434                ref left_type,
1435                ref right_type,
1436                ..
1437            } => {
1438                let is_f64 = left_type.as_ref() == Some(&ZigType::F64)
1439                    || right_type.as_ref() == Some(&ZigType::F64);
1440                if is_f64 {
1441                    Self::wrap_f64_to_i64(expr)
1442                } else {
1443                    expr
1444                }
1445            }
1446            // Unary with f64 operand → wrap
1447            IrExpr::Unary {
1448                ref operand_type, ..
1449            } => {
1450                if operand_type.as_ref() == Some(&ZigType::F64) {
1451                    Self::wrap_f64_to_i64(expr)
1452                } else {
1453                    expr
1454                }
1455            }
1456            // Logical with f64 same-type → wrap
1457            IrExpr::Logical {
1458                ref left_type,
1459                ref right_type,
1460                ..
1461            } => {
1462                let same_type =
1463                    left_type.is_some() && right_type.is_some() && left_type == right_type;
1464                if same_type && left_type.as_ref() == Some(&ZigType::F64) {
1465                    Self::wrap_f64_to_i64(expr)
1466                } else {
1467                    expr
1468                }
1469            }
1470            // Already-coerced or other expressions: pass through unchanged
1471            // TypedIdent with F64 → wrap to i64
1472            IrExpr::TypedIdent {
1473                ident,
1474                ty: ZigType::F64,
1475            } => Self::wrap_f64_to_i64(IrExpr::TypedIdent {
1476                ident,
1477                ty: ZigType::F64,
1478            }),
1479            // TypedIdent with JsAny → wrap via .asI64()
1480            IrExpr::TypedIdent {
1481                ident,
1482                ty: ZigType::JsAny,
1483            } => Self::wrap_jsany_to_i64(IrExpr::TypedIdent {
1484                ident,
1485                ty: ZigType::JsAny,
1486            }),
1487            // OptionalChain — recurse into body to coerce the non-null result to I64.
1488            // The else branch (null) will be handled by the surrounding context.
1489            IrExpr::OptionalChain {
1490                object,
1491                capture_var,
1492                body,
1493                needs_null_check,
1494            } => IrExpr::OptionalChain {
1495                object,
1496                capture_var,
1497                body: Box::new(self.coerce_i64_result_type(*body)),
1498                needs_null_check,
1499            },
1500            other => other,
1501        }
1502    }
1503
1504    /// Coerce an I64 expression to f64 when the function's return type is f64.
1505    /// This is the inverse of `coerce_i64_result_type`: it wraps I64-producing
1506    /// expressions in a DivExpr with divisor 1, which the emitter renders as
1507    /// `(@as(f64, @floatFromInt(expr)) / @as(f64, @floatFromInt(1)))`.
1508    /// Zig optimizes `/ 1.0` at comptime, leaving just the `@floatFromInt` cast.
1509    fn coerce_f64_result_type(
1510        &self,
1511        expr: crate::zigir::types::IrExpr,
1512    ) -> crate::zigir::types::IrExpr {
1513        use crate::zigir::kinds::{CallKind, MethodObjectKind};
1514        use crate::zigir::types::IrExpr;
1515
1516        // I64-returning Date methods (from infer layer)
1517        const I64_DATE_METHODS: &[&str] = &[
1518            "getTime",
1519            "getFullYear",
1520            "getMonth",
1521            "getDate",
1522            "getDay",
1523            "getHours",
1524            "getMinutes",
1525            "getSeconds",
1526            "getMilliseconds",
1527            "getTimezoneOffset",
1528            "valueOf",
1529            "getUTCFullYear",
1530            "getUTCMonth",
1531            "getUTCDate",
1532            "getUTCDay",
1533            "getUTCHours",
1534            "getUTCMinutes",
1535            "getUTCSeconds",
1536            "getUTCMilliseconds",
1537            "setFullYear",
1538            "setMonth",
1539            "setDate",
1540            "setHours",
1541            "setMinutes",
1542            "setSeconds",
1543            "setMilliseconds",
1544            "setUTCFullYear",
1545            "setUTCMonth",
1546            "setUTCDate",
1547            "setUTCHours",
1548            "setUTCMinutes",
1549            "setUTCSeconds",
1550            "setUTCMilliseconds",
1551            "setTime",
1552        ];
1553
1554        match expr {
1555            // Already F64 — pass through
1556            IrExpr::FloatLiteral(_) => expr,
1557            IrExpr::DivExpr { .. } | IrExpr::RemExpr { .. } | IrExpr::PowExpr { .. } => expr,
1558            IrExpr::BuiltinCall(bc) if bc.return_type == ZigType::F64 => IrExpr::BuiltinCall(bc),
1559            IrExpr::HostCall(hc) if hc.return_type == ZigType::F64 => IrExpr::HostCall(hc),
1560
1561            // I64 BuiltinCall — wrap
1562            IrExpr::BuiltinCall(bc) if bc.return_type == ZigType::I64 => {
1563                Self::wrap_i64_to_f64(IrExpr::BuiltinCall(bc))
1564            }
1565            // I64 HostCall — wrap
1566            IrExpr::HostCall(hc) if hc.return_type == ZigType::I64 => {
1567                Self::wrap_i64_to_f64(IrExpr::HostCall(hc))
1568            }
1569
1570            // Date method call returning I64 — wrap
1571            IrExpr::Call(call) => {
1572                let is_date_method = matches!(
1573                    call.call_kind,
1574                    CallKind::Method {
1575                        object_type: MethodObjectKind::Date
1576                    }
1577                );
1578                let method_name = match &*call.callee {
1579                    IrExpr::FieldAccess { field, .. } => Some(field.as_str()),
1580                    _ => None,
1581                };
1582                let needs_wrap = is_date_method
1583                    && method_name.is_some_and(|name| I64_DATE_METHODS.contains(&name));
1584
1585                if needs_wrap {
1586                    Self::wrap_i64_to_f64(IrExpr::Call(call))
1587                } else {
1588                    IrExpr::Call(call)
1589                }
1590            }
1591
1592            // Ident — check variable type in type_info
1593            IrExpr::Ident(ident) => {
1594                let needs_wrap =
1595                    self.type_info.var_types.get(&ident.js_name) == Some(&ZigType::I64);
1596                if needs_wrap {
1597                    Self::wrap_i64_to_f64(IrExpr::Ident(ident))
1598                } else {
1599                    IrExpr::Ident(ident)
1600                }
1601            }
1602
1603            // TypedIdent — use embedded ty field directly (no lookup needed)
1604            IrExpr::TypedIdent { ident, ty } => {
1605                if ty == ZigType::I64 {
1606                    Self::wrap_i64_to_f64(IrExpr::TypedIdent { ident, ty })
1607                } else {
1608                    IrExpr::TypedIdent { ident, ty }
1609                }
1610            }
1611
1612            // IntLiteral — always I64, wrap
1613            IrExpr::IntLiteral(_) => Self::wrap_i64_to_f64(expr),
1614
1615            // Conditional — recurse into both branches
1616            IrExpr::Conditional { cond, then, else_ } => IrExpr::Conditional {
1617                cond,
1618                then: Box::new(self.coerce_f64_result_type(*then)),
1619                else_: Box::new(self.coerce_f64_result_type(*else_)),
1620            },
1621
1622            // Sequence — only the last element is the return value
1623            IrExpr::Sequence(mut exprs) => {
1624                if let Some(last) = exprs.pop() {
1625                    exprs.push(self.coerce_f64_result_type(last));
1626                }
1627                IrExpr::Sequence(exprs)
1628            }
1629
1630            // Binary: wrap only if definitely I64 (known numeric type, not F64, not Anytype).
1631            // Unknown/Anytype types → pass through (Zig handles coercion).
1632            IrExpr::Binary {
1633                ref left_type,
1634                ref right_type,
1635                ..
1636            } => {
1637                let is_f64 = left_type.as_ref() == Some(&ZigType::F64)
1638                    || right_type.as_ref() == Some(&ZigType::F64);
1639                let is_known_i64 = left_type.as_ref() == Some(&ZigType::I64)
1640                    || right_type.as_ref() == Some(&ZigType::I64);
1641                if is_f64 || !is_known_i64 {
1642                    expr
1643                } else {
1644                    Self::wrap_i64_to_f64(expr)
1645                }
1646            }
1647            // Unary: wrap only if operand type is known I64
1648            IrExpr::Unary {
1649                ref operand_type, ..
1650            } => {
1651                if operand_type.as_ref() == Some(&ZigType::I64) {
1652                    Self::wrap_i64_to_f64(expr)
1653                } else {
1654                    expr
1655                }
1656            }
1657            // Logical: wrap only if known I64 same-type
1658            IrExpr::Logical {
1659                ref left_type,
1660                ref right_type,
1661                ..
1662            } => {
1663                let same_type =
1664                    left_type.is_some() && right_type.is_some() && left_type == right_type;
1665                if same_type && left_type.as_ref() == Some(&ZigType::I64) {
1666                    Self::wrap_i64_to_f64(expr)
1667                } else {
1668                    expr
1669                }
1670            }
1671
1672            // OptionalChain — recurse into body to coerce the non-null result to f64.
1673            IrExpr::OptionalChain {
1674                object,
1675                capture_var,
1676                body,
1677                needs_null_check,
1678            } => IrExpr::OptionalChain {
1679                object,
1680                capture_var,
1681                body: Box::new(self.coerce_f64_result_type(*body)),
1682                needs_null_check,
1683            },
1684
1685            // Other expressions — pass through unchanged
1686            other => other,
1687        }
1688    }
1689
1690    /// Wrap an I64 expression in a DivExpr that converts it to f64.
1691    /// The emitter generates `(@as(f64, @floatFromInt(expr)) / @as(f64, @floatFromInt(1)))`.
1692    fn wrap_i64_to_f64(expr: crate::zigir::types::IrExpr) -> crate::zigir::types::IrExpr {
1693        crate::zigir::types::IrExpr::DivExpr {
1694            left: Box::new(expr),
1695            right: Box::new(crate::zigir::types::IrExpr::IntLiteral(1)),
1696            left_type: ZigType::I64,
1697            right_type: ZigType::I64,
1698            result_type: None,
1699        }
1700    }
1701
1702    /// Wrap an f64-producing expression so the result is `i64`.
1703    /// The emitter generates `@as(i64, @intFromFloat((expr / @as(f64, @floatFromInt(1)))))`.
1704    /// The `/ 1.0` is a no-op for IEEE 754 floats; Zig optimizes it away at comptime.
1705    fn wrap_f64_to_i64(expr: crate::zigir::types::IrExpr) -> crate::zigir::types::IrExpr {
1706        crate::zigir::types::IrExpr::DivExpr {
1707            left: Box::new(expr),
1708            right: Box::new(crate::zigir::types::IrExpr::IntLiteral(1)),
1709            left_type: ZigType::F64,
1710            right_type: ZigType::I64,
1711            result_type: Some(ZigType::I64),
1712        }
1713    }
1714
1715    /// Wrap a JsAny-producing expression in `.asI64()` so the result is `i64`.
1716    /// The emitter renders `Call(FieldAccess(object, "asI64"), [])` as
1717    /// `object.asI64()`.
1718    fn wrap_jsany_to_i64(expr: crate::zigir::types::IrExpr) -> crate::zigir::types::IrExpr {
1719        use crate::zigir::kinds::CallKind;
1720        use crate::zigir::types::{IrCallExpr, IrExpr};
1721        IrExpr::Call(IrCallExpr {
1722            callee: Box::new(IrExpr::FieldAccess {
1723                object: Box::new(expr),
1724                field: "asI64".to_string(),
1725                field_kind: crate::zigir::kinds::FieldKind::StructField,
1726            }),
1727            args: vec![],
1728            call_kind: CallKind::Direct,
1729        })
1730    }
1731
1732    /// Wrap an expression in `JsAny.from(...)` so the result is `JsAny`.
1733    /// The emitter renders `Call(FieldAccess(Ident("JsAny"), "from"), [expr])`
1734    /// as `JsAny.from(expr)`.
1735    fn wrap_in_jsany_from(expr: crate::zigir::types::IrExpr) -> crate::zigir::types::IrExpr {
1736        use crate::zigir::kinds::{CallKind, FieldKind};
1737        use crate::zigir::types::{IrCallExpr, IrExpr};
1738        IrExpr::Call(IrCallExpr {
1739            callee: Box::new(IrExpr::FieldAccess {
1740                object: Box::new(IrExpr::Ident(crate::zigir::ident::IrIdent::new("JsAny"))),
1741                field: "from".to_string(),
1742                field_kind: FieldKind::StructField,
1743            }),
1744            args: vec![expr],
1745            call_kind: CallKind::Direct,
1746        })
1747    }
1748
1749    /// Coerce a return expression to `JsAny` when the function's return type
1750    /// is `JsAny` (e.g., P1-B7 default for non-export functions without JSDoc).
1751    /// Wraps non-JsAny expressions in `JsAny.from(...)`.
1752    fn coerce_jsany_result_type(
1753        &self,
1754        expr: crate::zigir::types::IrExpr,
1755    ) -> crate::zigir::types::IrExpr {
1756        use crate::zigir::types::IrExpr;
1757
1758        match expr {
1759            // Already JsAny — pass through
1760            IrExpr::Call(call) => {
1761                let returns_jsany = match &*call.callee {
1762                    IrExpr::Ident(ident) | IrExpr::TypedIdent { ident, .. } => {
1763                        self.type_info.fn_return_types.get(&ident.js_name) == Some(&ZigType::JsAny)
1764                    }
1765                    _ => false,
1766                };
1767                if returns_jsany {
1768                    IrExpr::Call(call)
1769                } else {
1770                    // Non-JsAny-returning call — wrap
1771                    Self::wrap_in_jsany_from(IrExpr::Call(call))
1772                }
1773            }
1774            IrExpr::BuiltinCall(bc) if bc.return_type == ZigType::JsAny => IrExpr::BuiltinCall(bc),
1775            IrExpr::HostCall(hc) if hc.return_type == ZigType::JsAny => IrExpr::HostCall(hc),
1776
1777            // Ident — check variable type in type_info
1778            IrExpr::Ident(ident) => {
1779                let is_jsany =
1780                    self.type_info.var_types.get(&ident.js_name) == Some(&ZigType::JsAny);
1781                if is_jsany {
1782                    IrExpr::Ident(ident)
1783                } else {
1784                    Self::wrap_in_jsany_from(IrExpr::Ident(ident))
1785                }
1786            }
1787
1788            // TypedIdent — use embedded ty field directly
1789            IrExpr::TypedIdent { ident, ty } => {
1790                if ty == ZigType::JsAny {
1791                    IrExpr::TypedIdent { ident, ty }
1792                } else {
1793                    Self::wrap_in_jsany_from(IrExpr::TypedIdent { ident, ty })
1794                }
1795            }
1796
1797            // Primitives and typed expressions — wrap in JsAny.from()
1798            IrExpr::IntLiteral(_)
1799            | IrExpr::FloatLiteral(_)
1800            | IrExpr::BoolLiteral(_)
1801            | IrExpr::StringLiteral(_) => Self::wrap_in_jsany_from(expr),
1802            IrExpr::BuiltinCall(bc)
1803                if matches!(
1804                    bc.return_type,
1805                    ZigType::I64 | ZigType::F64 | ZigType::Bool | ZigType::Str
1806                ) =>
1807            {
1808                Self::wrap_in_jsany_from(IrExpr::BuiltinCall(bc))
1809            }
1810            IrExpr::HostCall(hc)
1811                if matches!(
1812                    hc.return_type,
1813                    ZigType::I64 | ZigType::F64 | ZigType::Bool | ZigType::Str
1814                ) =>
1815            {
1816                Self::wrap_in_jsany_from(IrExpr::HostCall(hc))
1817            }
1818            // BuiltinCall/HostCall with other return types (ArrayList, NamedStruct, etc.)
1819            // — wrap in JsAny.from() for safety
1820            IrExpr::BuiltinCall(_) | IrExpr::HostCall(_) => Self::wrap_in_jsany_from(expr),
1821            IrExpr::Binary { .. } | IrExpr::Unary { .. } => Self::wrap_in_jsany_from(expr),
1822            IrExpr::FieldAccess { .. } => Self::wrap_in_jsany_from(expr),
1823            IrExpr::IndexAccess { .. } => Self::wrap_in_jsany_from(expr),
1824            // Arithmetic expressions producing f64 or i64 — wrap
1825            IrExpr::RemExpr { .. } | IrExpr::DivExpr { .. } | IrExpr::PowExpr { .. } => {
1826                Self::wrap_in_jsany_from(expr)
1827            }
1828            // Logical expressions (same_type path produces operand type)
1829            IrExpr::Logical { .. } => Self::wrap_in_jsany_from(expr),
1830            // Update (++, --) and assignment expressions produce i64/f64
1831            IrExpr::Update { .. } | IrExpr::Assign { .. } => Self::wrap_in_jsany_from(expr),
1832            // Literals — wrap
1833            IrExpr::ArrayLiteral(_) | IrExpr::ObjectLiteral(_) => Self::wrap_in_jsany_from(expr),
1834            IrExpr::TemplateLiteral { .. } | IrExpr::AllocPrint { .. } => {
1835                Self::wrap_in_jsany_from(expr)
1836            }
1837            IrExpr::BigIntLiteral(_) => Self::wrap_in_jsany_from(expr),
1838            // New(Error) already emits JsAny (fromError) — pass through.
1839            // Other New types (Map, Set, Date, …) would need JsAny.from()
1840            // but trigger @compileError for unsupported struct types.
1841            // Pass through and let the emitter produce the correct value.
1842            IrExpr::New(ref ne) if ne.result_type == ZigType::JsAny => expr,
1843            IrExpr::New(_) => Self::wrap_in_jsany_from(expr),
1844            IrExpr::BlockExpr { .. } => Self::wrap_in_jsany_from(expr),
1845            // Null/Undefined already emit as JsAny — pass through
1846            IrExpr::Null | IrExpr::Undefined => expr,
1847
1848            // OptionalChain — the else branch is always null (JsAny compatible),
1849            // but the then branch might produce a non-JsAny type. Wrap the whole
1850            // expression to ensure the result is always JsAny.
1851            IrExpr::OptionalChain { .. } => Self::wrap_in_jsany_from(expr),
1852
1853            // Await — the awaited value might be a non-JsAny type; wrap to ensure
1854            // the result is JsAny when the function returns JsAny.
1855            IrExpr::Await(_) => Self::wrap_in_jsany_from(expr),
1856
1857            // Array callback/method inline — produces ArrayList or specific element
1858            // type. Wrap to convert to JsAny when function returns JsAny.
1859            IrExpr::ArrayCallbackInline(_) | IrExpr::ArrayMethodInline(_) => {
1860                Self::wrap_in_jsany_from(expr)
1861            }
1862
1863            // ComputedField — produces a value that may not be JsAny. Wrap.
1864            IrExpr::ComputedField { .. } => Self::wrap_in_jsany_from(expr),
1865
1866            // Paren — recurse into the inner expression
1867            IrExpr::Paren(inner) => self.coerce_jsany_result_type(*inner),
1868
1869            // Typeof returns []const u8 — wrap in JsAny.from()
1870            IrExpr::Typeof(_) => Self::wrap_in_jsany_from(expr),
1871
1872            // Void returns JsAny (fromUndefined) — pass through
1873            IrExpr::Void(_) => expr,
1874
1875            // Spread is always non-JsAny — wrap
1876            IrExpr::Spread(_) => Self::wrap_in_jsany_from(expr),
1877
1878            // FnExpr produces a struct name — wrap
1879            IrExpr::FnExpr(_) => Self::wrap_in_jsany_from(expr),
1880
1881            // This — depends on context, wrap to be safe
1882            IrExpr::This => Self::wrap_in_jsany_from(expr),
1883
1884            // ArrowFn/Closure — produce struct types, wrap
1885            IrExpr::ArrowFn(_) | IrExpr::Closure(_) => Self::wrap_in_jsany_from(expr),
1886
1887            // CompileError — pass through (will fail at Zig compile time anyway)
1888            IrExpr::CompileError { .. } => expr,
1889
1890            // Conditional — recurse into both branches
1891            IrExpr::Conditional { cond, then, else_ } => IrExpr::Conditional {
1892                cond,
1893                then: Box::new(self.coerce_jsany_result_type(*then)),
1894                else_: Box::new(self.coerce_jsany_result_type(*else_)),
1895            },
1896
1897            // Sequence — only the last element is the return value
1898            IrExpr::Sequence(mut exprs) => {
1899                if let Some(last) = exprs.pop() {
1900                    exprs.push(self.coerce_jsany_result_type(last));
1901                }
1902                IrExpr::Sequence(exprs)
1903            }
1904        }
1905    }
1906}