Skip to main content

js2zig_core/zigir/emit/stmt/
control_flow.rs

1// zigir/emit/stmt/control_flow.rs
2// If, while, do-while, for, for-in, for-of, switch, and try statement emission.
3
4use crate::zigir::emit::Emitter;
5use crate::zigir::emit::helpers::EmitterHelpers;
6use crate::zigir::ident::IrIdent;
7use crate::zigir::types::{IrBlock, IrExpr, IrForInKind, IrForOfKind, IrStmt, IrSwitchCase};
8
9/// Parameters for `emit_for_of_stmt`, bundled to avoid too-many-arguments.
10pub(super) struct ForOfInfo<'a> {
11    pub var: &'a IrIdent,
12    pub destructure_vars: &'a [IrIdent],
13    pub iterable: &'a IrExpr,
14    pub iterable_is_arraylist: bool,
15    pub body: &'a IrBlock,
16    pub kind: &'a IrForOfKind,
17    pub is_async: bool,
18    pub label: &'a Option<String>,
19}
20
21/// Parameters for `emit_try_stmt`, bundled to avoid too-many-arguments.
22pub(super) struct TryInfo<'a> {
23    pub try_block: &'a IrBlock,
24    pub catch_var: &'a Option<IrIdent>,
25    pub catch_var_referenced: bool,
26    pub finally: &'a Option<IrBlock>,
27    pub has_throw: bool,
28    pub has_nested_try: bool,
29    pub catch_block: &'a IrBlock,
30}
31
32impl Emitter {
33    /// Emit label prefix if present: `lbl: ` (used by while/do-while/for/for-in/for-of).
34    fn emit_label_prefix(&mut self, label: &Option<String>) {
35        if let Some(lbl) = label {
36            self.write(&format!("{}: ", lbl));
37        }
38    }
39
40    /// Check if a block always exits (return/throw/break/continue).
41    fn block_always_exits(block: &IrBlock) -> bool {
42        block.stmts.last().is_some_and(|s| {
43            matches!(
44                s,
45                IrStmt::Return { .. }
46                    | IrStmt::Throw { .. }
47                    | IrStmt::Break { .. }
48                    | IrStmt::Continue { .. }
49            )
50        })
51    }
52
53    /// Recursively check if a block contains `return` or `throw` statements.
54    /// Used to detect finally blocks that can't be emitted as `defer { }`
55    /// (Zig doesn't allow return/throw inside defer).
56    fn block_has_return_or_throw(stmts: &[IrStmt]) -> bool {
57        fn ir_stmt_has_return_or_throw(stmt: &IrStmt) -> bool {
58            match stmt {
59                IrStmt::Return { .. } | IrStmt::Throw { .. } => true,
60                IrStmt::If { then, else_, .. } => {
61                    Emitter::block_has_return_or_throw(&then.stmts)
62                        || else_
63                            .as_ref()
64                            .is_some_and(|e| Emitter::block_has_return_or_throw(&e.stmts))
65                }
66                IrStmt::While { body, .. }
67                | IrStmt::DoWhile { body, .. }
68                | IrStmt::For { body, .. }
69                | IrStmt::ForOf { body, .. }
70                | IrStmt::ForIn { body, .. } => Emitter::block_has_return_or_throw(&body.stmts),
71                IrStmt::Block(b) => Emitter::block_has_return_or_throw(&b.stmts),
72                IrStmt::Switch { cases, .. } => cases
73                    .iter()
74                    .any(|c| Emitter::block_has_return_or_throw(&c.body)),
75                IrStmt::Try {
76                    try_block,
77                    catch_block,
78                    finally,
79                    ..
80                } => {
81                    Emitter::block_has_return_or_throw(&try_block.stmts)
82                        || Emitter::block_has_return_or_throw(&catch_block.stmts)
83                        || finally
84                            .as_ref()
85                            .is_some_and(|f| Emitter::block_has_return_or_throw(&f.stmts))
86                }
87                _ => false,
88            }
89        }
90        stmts.iter().any(ir_stmt_has_return_or_throw)
91    }
92
93    pub(super) fn emit_if_stmt(&mut self, cond: &IrExpr, then: &IrBlock, else_: &Option<IrBlock>) {
94        self.write_indent();
95        self.write("if (");
96        self.emit_expr_as_bool(cond);
97        self.write(") {\n");
98        self.indent_push();
99        self.emit_block_stmts_unlabeled(then);
100        self.indent_pop();
101        self.emit_else_chain(else_);
102    }
103
104    /// Recursively emit else / else-if chains.
105    pub(super) fn emit_else_chain(&mut self, else_: &Option<IrBlock>) {
106        if let Some(else_block) = else_ {
107            // Check for else-if chain
108            if else_block.stmts.len() == 1
109                && let IrStmt::If {
110                    cond: inner_cond,
111                    then: inner_then,
112                    else_: inner_else,
113                } = &else_block.stmts[0]
114            {
115                self.write_indent();
116                self.write("} else if (");
117                self.emit_expr_as_bool(inner_cond);
118                self.write(") {\n");
119                self.indent_push();
120                self.emit_block_stmts_unlabeled(inner_then);
121                self.indent_pop();
122                self.emit_else_chain(inner_else);
123                return;
124            }
125            self.writeln("} else {");
126            self.indent_push();
127            self.emit_block_stmts_unlabeled(else_block);
128            self.indent_pop();
129        }
130        self.writeln("}");
131    }
132
133    pub(super) fn emit_while_stmt(
134        &mut self,
135        cond: &IrExpr,
136        body: &IrBlock,
137        label: &Option<String>,
138    ) {
139        self.write_indent();
140        self.emit_label_prefix(label);
141        self.write("while (");
142        self.emit_expr_as_bool(cond);
143        self.write(") {\n");
144        self.indent_push();
145        self.emit_block_stmts_unlabeled(body);
146        self.indent_pop();
147        self.writeln("}");
148    }
149
150    pub(super) fn emit_do_while_stmt(
151        &mut self,
152        body: &IrBlock,
153        cond: &IrExpr,
154        label: &Option<String>,
155    ) {
156        // JS do-while: body always runs at least once, then cond is checked.
157        // `continue` must re-evaluate cond (not jump to loop top).
158        // Use a first-iteration flag as the while condition so that
159        // continue → continue expr (flag=false) → re-check cond.
160        //
161        // P1-10: Use a unique per-iteration flag name (`__dw_first_N`) instead
162        // of a hardcoded `__dw_first`. Zig 0.16 forbids local-variable
163        // shadowing across nesting scopes, so an inner do-while nested in
164        // the body of an outer do-while would otherwise fail ast-check
165        // ("local variable '__dw_first' shadows local variable from outer
166        // scope").
167        let flag = self.next_do_while_flag();
168        self.writeln("{");
169        self.indent_push();
170        self.writeln(&format!("var {flag}: bool = true;", flag = flag));
171        self.write_indent();
172        self.emit_label_prefix(label);
173        self.write("while (");
174        self.write(&format!("{flag} or (", flag = flag));
175        self.emit_expr_as_bool(cond);
176        self.write(&format!(")) : ({flag} = false) {{\n", flag = flag));
177        self.indent_push();
178        self.emit_block_stmts_unlabeled(body);
179        self.indent_pop();
180        self.writeln("}");
181        self.indent_pop();
182        self.writeln("}");
183    }
184
185    pub(super) fn emit_for_stmt(
186        &mut self,
187        init: &Option<Box<IrStmt>>,
188        cond: &Option<IrExpr>,
189        update: &Option<Box<IrStmt>>,
190        body: &IrBlock,
191        label: &Option<String>,
192    ) {
193        // Wrap the entire for loop in a block scope:
194        //   { init; label: while (cond) : ({ update; }) { body } }
195        // The label MUST be on the `while`, not on the enclosing block —
196        // Zig `continue :label` only targets a labeled loop, and a label on
197        // a plain block labels that block (which `continue` cannot target).
198        self.write_indent();
199        self.write("{\n");
200        self.indent_push();
201
202        // Emit init statement
203        if let Some(init_stmt) = init {
204            self.emit_stmt(init_stmt);
205        }
206
207        // While loop with optional update continuation
208        self.write_indent();
209        // Place the label directly before `while` so `continue :label`
210        // (and `break :label`) target this loop rather than the wrapping block.
211        self.emit_label_prefix(label);
212        self.write("while (");
213        if let Some(c) = cond {
214            self.emit_expr_as_bool(c);
215        } else {
216            self.write("true");
217        }
218        self.write(")");
219
220        // Zig while continuation syntax for the update expression.
221        // We emit the update inline inside a block expression: `: ({ update; })`
222        // NOTE: must NOT wrap in extra parentheses — `+=` is a statement in Zig,
223        // and `(i += 1)` is invalid. Use statement-level emission (no parens).
224        if let Some(update_stmt) = update {
225            self.write(" : ({ ");
226            match update_stmt.as_ref() {
227                IrStmt::Expr(expr) => {
228                    // For Update expressions (i++, i--), force statement-level
229                    // output (no wrapping parentheses).
230                    if let IrExpr::Update { op, target, .. } = expr {
231                        self.emit_assign_target_inner(target);
232                        self.write(&format!(
233                            " {}",
234                            crate::zigir::emit::helpers::update_op_to_zig(*op)
235                        ));
236                    } else {
237                        self.emit_expr(expr);
238                    }
239                }
240                IrStmt::Assign { target, op, value } => {
241                    // Use emit_assign_stmt logic but without indent/newline
242                    self.emit_assign_inline(target, *op, value);
243                }
244                _ => {
245                    // Fallback: emit the full statement (rare)
246                    self.emit_stmt(update_stmt);
247                }
248            }
249            self.write("; })");
250        }
251
252        self.write(" {\n");
253        self.indent_push();
254        self.emit_block_stmts_unlabeled(body);
255        self.indent_pop();
256
257        self.write_indent();
258        self.write("}\n");
259
260        // Close the enclosing block scope
261        self.indent_pop();
262        self.writeln("}");
263    }
264
265    pub(super) fn emit_for_in_stmt(
266        &mut self,
267        var: &IrIdent,
268        iterable: &IrExpr,
269        body: &IrBlock,
270        kind: &IrForInKind,
271        label: &Option<String>,
272    ) {
273        match kind {
274            IrForInKind::HashMapIter => {
275                // `var __it = obj.iterator(); label: while (__it.next()) |__kv| { ... }`
276                // Label goes directly on while (not a wrapping block) so that
277                // `continue :label` targets the loop, not a block.
278                self.write_indent();
279                let it_name = "__it";
280                self.write("var ");
281                self.write(it_name);
282                self.write(" = ");
283                self.emit_expr(iterable);
284                self.write(".iterator();\n");
285                self.write_indent();
286                if let Some(lbl) = label {
287                    self.write(&format!("{}: ", lbl));
288                }
289                self.write("while (");
290                self.write(it_name);
291                self.write(".next()) |__kv| {\n");
292                self.indent_push();
293                self.writeln(&format!("const {} = __kv.key_ptr.*;", var.zig_name));
294                self.emit_block_stmts_unlabeled(body);
295                self.indent_pop();
296                self.writeln("}");
297            }
298            IrForInKind::MapIter => {
299                // `var __it = obj.inner.iterator(); label: while (__it.next()) |__kv| { ... }`
300                self.write_indent();
301                let it_name = "__it";
302                self.write("var ");
303                self.write(it_name);
304                self.write(" = ");
305                self.emit_expr(iterable);
306                self.write(".inner.iterator();\n");
307                self.write_indent();
308                if let Some(lbl) = label {
309                    self.write(&format!("{}: ", lbl));
310                }
311                self.write("while (");
312                self.write(it_name);
313                self.write(".next()) |__kv| {\n");
314                self.indent_push();
315                self.writeln(&format!("const {} = __kv.key_ptr.*;", var.zig_name));
316                self.emit_block_stmts_unlabeled(body);
317                // Suppress unused-variable error when key is not referenced in body
318                self.writeln(&format!("_ = &{};", var.zig_name));
319                self.indent_pop();
320                self.writeln("}");
321            }
322            IrForInKind::StructUnroll { fields } => {
323                // Unrolled: one iteration per field. When a label is present
324                // we wrap ALL iterations in a single labeled block so that
325                // `break :label` exits the entire for-in (previously the label
326                // was attached only to the first iteration's block, so a break
327                // would skip just that iteration and silently fall through to
328                // the remaining ones).
329                if let Some(lbl) = label {
330                    self.write_indent();
331                    self.write(lbl);
332                    self.write(": {\n");
333                    self.indent_push();
334                }
335                for field_name in fields.iter() {
336                    self.write_indent();
337                    self.write("{\n");
338                    self.indent_push();
339                    self.writeln(&format!("const {} = \"{}\";", var.zig_name, field_name));
340                    self.emit_block_stmts_unlabeled(body);
341                    self.indent_pop();
342                    self.writeln("}");
343                }
344                if label.is_some() {
345                    self.indent_pop();
346                    self.writeln("}");
347                }
348            }
349            IrForInKind::Unsupported => {
350                if let Some(lbl) = label {
351                    self.write_indent();
352                    self.write(&format!(
353                        "{}: @compileError(\"for-in on this type is not supported\");\n",
354                        lbl
355                    ));
356                } else {
357                    self.writeln("@compileError(\"for-in on this type is not supported\");");
358                }
359            }
360        }
361    }
362
363    pub(super) fn emit_for_of_stmt(&mut self, info: &ForOfInfo<'_>) {
364        let var = info.var;
365        let destructure_vars = info.destructure_vars;
366        let iterable = info.iterable;
367        let iterable_is_arraylist = info.iterable_is_arraylist;
368        let body = info.body;
369        let kind = info.kind;
370        let is_async = info.is_async;
371        let label = info.label;
372
373        if is_async {
374            self.writeln("@compileError(\"for-await-of is not supported\");");
375            return;
376        }
377
378        match kind {
379            IrForOfKind::Array => {
380                self.write_indent();
381                self.emit_label_prefix(label);
382                self.write("for (");
383                self.emit_expr(iterable);
384                if iterable_is_arraylist {
385                    self.write(".items");
386                }
387                self.write(") |");
388                self.write(&var.zig_name);
389                self.write("| {\n");
390                self.indent_push();
391                self.emit_block_stmts_unlabeled(body);
392                self.indent_pop();
393                self.writeln("}");
394            }
395            IrForOfKind::MapSetIter { is_map } => {
396                // `var __it = obj.inner.iterator(); label: while (__it.next()) |__kv| { ... }`
397                // Label goes directly on while (not a wrapping block) so that
398                // `continue :label` targets the loop, not a block.
399                self.write_indent();
400                let it_name = "__it";
401                self.write("var ");
402                self.write(it_name);
403                self.write(" = ");
404                self.emit_expr(iterable);
405                self.write(".inner.iterator();\n");
406                self.write_indent();
407                if let Some(lbl) = label {
408                    self.write(&format!("{}: ", lbl));
409                }
410                self.write("while (");
411                self.write(it_name);
412                self.write(".next()) |__kv| {\n");
413                self.indent_push();
414                if *is_map && !destructure_vars.is_empty() {
415                    // Map destructure: const [key, val] = ...
416                    self.writeln(&format!(
417                        "const {} = __kv.key_ptr.*;",
418                        destructure_vars[0].zig_name
419                    ));
420                    if destructure_vars.len() > 1 {
421                        self.writeln(&format!(
422                            "const {} = __kv.value_ptr.*;",
423                            destructure_vars[1].zig_name
424                        ));
425                    }
426                } else {
427                    self.writeln(&format!("const {} = __kv.key_ptr.*;", var.zig_name));
428                }
429                self.emit_block_stmts_unlabeled(body);
430                // Suppress unused-variable errors for destructured vars that
431                // the body doesn't reference (e.g., `for (const [k, v] of m)`
432                // where only v is used). Taking the address marks it as "used".
433                if *is_map && !destructure_vars.is_empty() {
434                    for dv in destructure_vars {
435                        self.writeln(&format!("_ = &{};", dv.zig_name));
436                    }
437                } else {
438                    self.writeln(&format!("_ = &{};", var.zig_name));
439                }
440                self.indent_pop();
441                self.writeln("}");
442            }
443            IrForOfKind::Str { var_used } => {
444                // JS `for (x of str)` iterates over Unicode code points (UTF-8
445                // scalar values), not raw bytes. Zig's `for (str)` iterates u8
446                // bytes, so we emit a std.unicode.Utf8View while-loop instead.
447                self.write_indent();
448                self.write("var __iter = std.unicode.Utf8View.initUnchecked(");
449                self.emit_expr(iterable);
450                self.writeln(").iterator();");
451                self.write_indent();
452                self.emit_label_prefix(label);
453                self.write("while (__iter.nextCodepoint()) ");
454                if *var_used {
455                    // Bind to a temp var, then cast u21 → i64 for the user-facing name.
456                    self.write("|__cp| {\n");
457                    self.indent_push();
458                    self.writeln(&format!("const {} = @as(i64, __cp);", var.zig_name));
459                } else {
460                    // Unused capture: use |_| to avoid Zig 0.16 unused-capture error.
461                    self.write("|_| {\n");
462                    self.indent_push();
463                }
464                self.emit_block_stmts_unlabeled(body);
465                self.indent_pop();
466                self.writeln("}");
467            }
468            IrForOfKind::AsyncUnsupported => {
469                self.writeln("@compileError(\"for-await-of is not supported\");");
470            }
471        }
472    }
473
474    pub(super) fn emit_switch_stmt(&mut self, expr: &IrExpr, cases: &[IrSwitchCase]) {
475        // Detect a string-keyed switch: Zig's `switch` cannot operate on
476        // []const u8 (only integers/enums/bools/union tags). If any case's
477        // test lowers to `IrExpr::StringLiteral`, lower the whole switch as
478        // an `if`/`else if` chain using `std.mem.eql(u8, ...)` (R6-2).
479        let is_string_switch = cases.iter().any(|c| {
480            c.test
481                .as_ref()
482                .is_some_and(|t| matches!(t, crate::zigir::types::IrExpr::StringLiteral(_)))
483        });
484        if is_string_switch {
485            self.emit_string_switch(expr, cases);
486            return;
487        }
488
489        self.write_indent();
490        self.write("switch (");
491        self.emit_expr(expr);
492        self.write(") {\n");
493        self.indent_push();
494        let mut has_default = false;
495        for case in cases {
496            self.write_indent();
497            if let Some(test) = &case.test {
498                self.emit_expr(test);
499            } else {
500                has_default = true;
501                self.write("else");
502            }
503            self.write(" => {\n");
504            self.indent_push();
505            for stmt in &case.body {
506                self.emit_stmt(stmt);
507            }
508            self.indent_pop();
509            self.write_indent();
510            self.write("},\n");
511        }
512        // Zig switch must be exhaustive; add empty else if no default
513        if !has_default {
514            self.writeln("else => {},");
515        }
516        self.indent_pop();
517        self.writeln("}");
518    }
519
520    /// Emit a string-keyed switch as an if/else-if chain using std.mem.eql.
521    /// Used when any case test is a `StringLiteral` — Zig's `switch` cannot
522    /// operate on `[]const u8`.
523    fn emit_string_switch(&mut self, expr: &IrExpr, cases: &[IrSwitchCase]) {
524        // Bind the discriminant to a const so it is evaluated only once,
525        // avoiding repeated side-effects if the expression is non-trivial.
526        // `_ = &__sw;` suppresses "unused variable" when all cases are default.
527        self.write_indent();
528        self.write("const __sw = ");
529        self.emit_expr(expr);
530        self.write(";\n");
531        self.write_indent();
532        self.write("_ = &__sw;\n");
533
534        let mut written_first = false;
535        let mut has_default = false;
536        for case in cases {
537            match &case.test {
538                Some(test @ crate::zigir::types::IrExpr::StringLiteral(_)) => {
539                    self.write_indent();
540                    if !written_first {
541                        self.write("if (");
542                        written_first = true;
543                    } else {
544                        self.write("} else if (");
545                    }
546                    self.write("std.mem.eql(u8, __sw, ");
547                    self.emit_expr(test);
548                    self.write(")) {\n");
549                    // Body must be emitted INSIDE the string-literal arm —
550                    // otherwise the default case body leaks into the previous
551                    // case's scope (R6-2 follow-up: unreachable-code ast error).
552                    self.indent_push();
553                    for stmt in &case.body {
554                        self.emit_stmt(stmt);
555                    }
556                    self.indent_pop();
557                }
558                _ => {
559                    // default (test == None) — collect for the trailing else.
560                    // Body is emitted later from the `)} else {` block below.
561                    has_default = true;
562                }
563            }
564        }
565        if written_first {
566            self.write_indent();
567            if has_default {
568                self.write("} else {\n");
569                self.indent_push();
570                // find default body
571                for case in cases {
572                    if case.test.is_none() {
573                        for stmt in &case.body {
574                            self.emit_stmt(stmt);
575                        }
576                    }
577                }
578                self.indent_pop();
579                self.write_indent();
580                self.write("}\n");
581            } else {
582                self.write("}\n");
583            }
584        } else if has_default {
585            // All cases were default (no string tests) — just emit the default body inline.
586            for case in cases {
587                if case.test.is_none() {
588                    for stmt in &case.body {
589                        self.emit_stmt(stmt);
590                    }
591                }
592            }
593        }
594    }
595
596    pub(super) fn emit_try_stmt(&mut self, info: &TryInfo<'_>) {
597        let try_block = info.try_block;
598        let catch_var = info.catch_var;
599        let catch_var_referenced = info.catch_var_referenced;
600        let finally = info.finally;
601        let has_throw = info.has_throw;
602        let has_nested_try = info.has_nested_try;
603        let catch_block = info.catch_block;
604
605        let needs_catch = catch_var.is_some();
606
607        // ── B1: No throw, no catch, no nested try → inline body + finally ──
608        // Also applies when: no throw AND body always exits (catch is unreachable)
609        if !has_throw && (!needs_catch || Self::block_always_exits(try_block)) && !has_nested_try {
610            // Emit finally as defer BEFORE the body so it always runs,
611            // even if the body contains return/break/continue.
612            if let Some(finally_block) = finally {
613                if Self::block_has_return_or_throw(&finally_block.stmts) {
614                    self.writeln(
615                        "@compileError(\"return/throw in finally block is not yet supported\");",
616                    );
617                } else {
618                    self.writeln("defer {");
619                    self.indent_push();
620                    self.emit_block_stmts_unlabeled(finally_block);
621                    self.indent_pop();
622                    self.writeln("}");
623                }
624            }
625            self.emit_block_stmts_unlabeled(try_block);
626            return;
627        }
628
629        // ── Case A: Has catch (and catch may be reached), throw, or nested try
630        // → full labeled block pattern ──
631        // Double labeled-block pattern:
632        //   outer blk (_js_try_blk_N): scope for defer (finally) + catch dispatch
633        //   inner body blk (_js_try_body_blk_N): scope for throw → break to catch
634        let label_id = self.next_try_label();
635        let blk_label = format!("_js_try_blk_{}", label_id);
636        let result_var = format!("_js_try_{}", label_id);
637        let body_blk_label = format!("_js_try_body_blk_{}", label_id);
638        let body_result_var = format!("_js_try_body_{}", label_id);
639
640        // Save current inside_try_block so we can restore it later
641        let saved_inside = self.inside_try_block.clone();
642
643        // ── Outer labeled block ──
644        self.write_indent();
645        self.write(&format!(
646            "const {}: anyerror!void = {}: {{\n",
647            result_var, blk_label,
648        ));
649        self.indent_push();
650
651        // ── Finally as defer (always runs, inside labeled block) ──
652        if let Some(finally_block) = finally {
653            if Self::block_has_return_or_throw(&finally_block.stmts) {
654                self.writeln(
655                    "@compileError(\"return/throw in finally block is not yet supported\");",
656                );
657            } else {
658                self.writeln("defer {");
659                self.indent_push();
660                self.emit_block_stmts_unlabeled(finally_block);
661                self.indent_pop();
662                self.writeln("}");
663            }
664        }
665
666        // ── Inner body labeled block ──
667        self.write_indent();
668        self.write(&format!(
669            "const {}: anyerror!void = {}: {{\n",
670            body_result_var, body_blk_label,
671        ));
672        self.indent_push();
673
674        // Set inside_try_block so that throw/break statements emit
675        // break :body_blk_label or break :blk_label
676        self.inside_try_block = Some(body_blk_label.clone());
677
678        self.emit_block_stmts_unlabeled(try_block);
679
680        // Normal completion of try body (no throw).
681        // Skip if the try body ends with a return/break/continue/throw —
682        // execution never reaches this point.
683        let body_always_exits = Self::block_always_exits(try_block);
684        if !body_always_exits {
685            self.write_indent();
686            self.write(&format!("break :{} {{}};\n", body_blk_label));
687        }
688
689        self.indent_pop();
690        self.writeln("};");
691
692        // ── Catch dispatch ──
693        if needs_catch {
694            self.writeln(&format!("if ({}) |_| {{", body_result_var));
695            // success path: nothing to do
696            if catch_var_referenced {
697                self.writeln("} else |__catch_err| {");
698            } else {
699                self.writeln("} else |_| {");
700            }
701            self.indent_push();
702            if let Some(var) = catch_var
703                && catch_var_referenced
704            {
705                self.writeln(&format!(
706                    "const {} = js_error.JsError.fromError(__catch_err, js_allocator.allocator()) catch @panic(\"OOM: JsError\");",
707                    var.zig_name
708                ));
709            }
710            // When !catch_var_referenced: catch capture is |_| (discarded).
711            // Set inside_try_block to outer label so re-throw in catch body
712            // produces break :blk_label error.JsThrow
713            self.inside_try_block = Some(blk_label.clone());
714            self.emit_block_stmts_unlabeled(catch_block);
715            self.indent_pop();
716            self.writeln("}");
717        }
718
719        // Normal completion of outer block
720        // When `needs_catch == false` but `has_throw == true` (try-finally with
721        // no catch handler that can throw), propagate the inner body's error
722        // result to the outer block. Without this, a thrown error in the body
723        // is silently swallowed (R6-1).
724        self.write_indent();
725        if !needs_catch && has_throw {
726            self.write(&format!(
727                "break :{} if ({}) |_| @as(anyerror!void, {{}}) else |_| @as(anyerror!void, error.JsThrow);\n",
728                blk_label, body_result_var,
729            ));
730        } else {
731            self.write(&format!("break :{} {{}};\n", blk_label));
732        }
733
734        self.indent_pop();
735        self.writeln("};");
736
737        // ── Propagate unhandled re-throw ──
738        // If the result is an error (re-throw from catch, or a throw that
739        // escaped the body when there is no catch handler), propagate it.
740        // Pre-fix: guarded by `if needs_catch`, which meant a try-finally
741        // with NO catch handler silently dropped any throw from the body
742        // (body_result_var was error.JsThrow but never inspected).
743        // Post-fix: propagate whenever `needs_catch || has_throw`.
744        if needs_catch || has_throw {
745            if let Some(ref parent_label) = saved_inside {
746                // Inside another try block → break to parent
747                self.writeln(&format!(
748                    "if ({0}) |_| {{}} else |_| break :{1} @as(anyerror!void, error.JsThrow);",
749                    result_var, parent_label,
750                ));
751            } else {
752                // Top-level → return error
753                self.writeln(&format!(
754                    "if ({}) |_| {{}} else |_| return error.JsThrow;",
755                    result_var,
756                ));
757            }
758        }
759
760        // Restore saved inside_try_block
761        self.inside_try_block = saved_inside;
762    }
763}