Skip to main content

js2zig_core/zigir/emit/expr/
mod.rs

1// zigir/emit/expr/mod.rs
2// Expression-level Zig emission from IrExpr nodes.
3
4pub mod binary;
5pub mod call_member;
6pub mod container;
7pub mod template_new;
8
9use crate::types::ZigType;
10use crate::zigir::emit::Emitter;
11use crate::zigir::emit::helpers as emit_helpers;
12use crate::zigir::emit::helpers::{EmitterHelpers, escape_zig_string, update_op_to_zig};
13
14// ═══════════════════════════════════════════════════════
15//  Expression dispatch
16// ═══════════════════════════════════════════════════════
17
18impl Emitter {
19    pub(crate) fn emit_expr(&mut self, expr: &crate::zigir::types::IrExpr) {
20        match expr {
21            crate::zigir::types::IrExpr::IntLiteral(n) => {
22                self.write(&n.to_string());
23            }
24
25            crate::zigir::types::IrExpr::FloatLiteral(n) => {
26                if *n == -0.0 && n.is_sign_negative() {
27                    self.write("-0.0");
28                } else {
29                    self.write(&n.to_string());
30                }
31            }
32
33            crate::zigir::types::IrExpr::StringLiteral(s) => {
34                self.write(&format!("\"{}\"", escape_zig_string(s)));
35            }
36
37            crate::zigir::types::IrExpr::BoolLiteral(b) => {
38                self.write(if *b { "true" } else { "false" });
39            }
40
41            crate::zigir::types::IrExpr::BigIntLiteral(s) => {
42                // Wrap in parentheses: `catch` has lower precedence than `+`/`-`,
43                // so `BigInt.init(...) catch @panic(...) + x` would parse incorrectly.
44                self.write(&format!(
45                    "(js_bigint.JsBigInt.init(js_allocator.allocator(), \"{}\") catch @panic(\"OOM: BigInt init\"))",
46                    escape_zig_string(s)
47                ));
48            }
49
50            crate::zigir::types::IrExpr::Null => {
51                self.write("JsAny.fromNull()");
52            }
53
54            crate::zigir::types::IrExpr::Undefined => {
55                self.write("JsAny.fromUndefined()");
56            }
57
58            crate::zigir::types::IrExpr::Ident(ident) => {
59                self.write(&ident.zig_name);
60            }
61
62            crate::zigir::types::IrExpr::TypedIdent { ident, .. } => {
63                self.write(&ident.zig_name);
64            }
65
66            crate::zigir::types::IrExpr::This => {
67                self.write("self");
68            }
69
70            // ── Arithmetic / comparison ─────────────
71            crate::zigir::types::IrExpr::Binary {
72                op,
73                left,
74                right,
75                left_type,
76                right_type,
77            } => {
78                use crate::types::ZigType;
79                use crate::zigir::ops::BinOp;
80
81                // Determine if operands are BigInt, JsAny, String, or other
82                let lt = left_type.as_ref();
83                let rt = right_type.as_ref();
84                let left_is_bigint = lt == Some(&ZigType::BigInt);
85                let right_is_bigint = rt == Some(&ZigType::BigInt);
86                // Check both type inference AND the expression node itself.
87                // String literals like "5" often have `left_type = None` since they
88                // lack a JSDoc annotation, but `IrExpr::StringLiteral` is unambiguous.
89                let left_is_str = lt == Some(&ZigType::Str)
90                    || matches!(&**left, crate::zigir::types::IrExpr::StringLiteral(_));
91                let right_is_str = rt == Some(&ZigType::Str)
92                    || matches!(&**right, crate::zigir::types::IrExpr::StringLiteral(_));
93                let left_is_jsany = lt == Some(&ZigType::JsAny);
94                let right_is_jsany = rt == Some(&ZigType::JsAny);
95                let left_is_float = lt == Some(&ZigType::F64);
96                let right_is_float = rt == Some(&ZigType::F64);
97                let left_is_symbol = lt == Some(&ZigType::JsSymbol);
98                let right_is_symbol = rt == Some(&ZigType::JsSymbol);
99                // Pre-compute cross-type flags (needed for the if/else-if chain below)
100                // Anytype should not count as a distinct type — Zig resolves it at comptime.
101                let left_is_anytype = lt == Some(&ZigType::Anytype);
102                let right_is_anytype = rt == Some(&ZigType::Anytype);
103                let cross_type_known = lt.is_some()
104                    && rt.is_some()
105                    && lt != rt
106                    && !left_is_bigint
107                    && !right_is_bigint
108                    && !left_is_anytype
109                    && !right_is_anytype;
110                let str_vs_numeric = (left_is_str && !right_is_str && !right_is_bigint)
111                    || (right_is_str && !left_is_str && !left_is_bigint);
112
113                // ── BigInt arithmetic/comparison ──
114                if left_is_bigint && right_is_bigint {
115                    self.emit_bigint_binary(*op, left, right);
116                }
117                // ── Symbol equality/comparison ──
118                // JsSymbol is a struct with slice fields; Zig doesn't support == on it.
119                // Use .eql() for equality, and .id for ordering (shouldn't occur in practice).
120                else if left_is_symbol
121                    && right_is_symbol
122                    && matches!(
123                        op,
124                        BinOp::Eq | BinOp::Ne | BinOp::StrictEq | BinOp::StrictNe
125                    )
126                {
127                    let negate = matches!(*op, BinOp::Ne | BinOp::StrictNe);
128                    if negate {
129                        self.write("!");
130                    }
131                    self.emit_expr(left);
132                    self.write(".eql(");
133                    self.emit_expr(right);
134                    self.write(")");
135                }
136                // ── String + BigInt concatenation ──
137                // JS spec: "hello" + 5n → "hello5", 5n + "hello" → "5hello"
138                // Only the Add operator allows String+BigInt; all other mixed ops throw TypeError.
139                else if *op == BinOp::Add
140                    && ((left_is_str && right_is_bigint) || (left_is_bigint && right_is_str))
141                {
142                    self.emit_bigint_string_concat(left, right, left_is_str);
143                }
144                // ── BigInt × Number non-comparison ops: JS throws TypeError ──
145                // e.g. 1n + 2, 3n & x, 2n ** 3 where x: number
146                // JS spec: "Cannot mix BigInt and other types, consider explicit conversions"
147                else if (left_is_bigint || right_is_bigint)
148                    && matches!(
149                        op,
150                        BinOp::Add
151                            | BinOp::Sub
152                            | BinOp::Mul
153                            | BinOp::Div
154                            | BinOp::Mod
155                            | BinOp::Pow
156                            | BinOp::BitAnd
157                            | BinOp::BitOr
158                            | BinOp::BitXor
159                            | BinOp::Shl
160                            | BinOp::Shr
161                    )
162                {
163                    if let Some(label) = &self.inside_try_block {
164                        self.write(&format!(
165                            "({{ break :{} @as(anyerror!void, error.JsThrow); }})",
166                            label
167                        ));
168                    } else {
169                        self.write("({ return error.JsThrow; })");
170                    }
171                }
172                // ── String equality/comparison ──
173                else if left_is_str && right_is_str {
174                    self.emit_string_comparison(*op, left, right);
175                }
176                // ── BigInt cross-type comparison (e.g. 0n === 0, bigint == 5) ──
177                // Convert the non-BigInt operand to JsBigInt and use .eq() / .order()
178                else if (left_is_bigint || right_is_bigint)
179                    && matches!(
180                        op,
181                        BinOp::Eq
182                            | BinOp::Ne
183                            | BinOp::StrictEq
184                            | BinOp::StrictNe
185                            | BinOp::Lt
186                            | BinOp::Le
187                            | BinOp::Gt
188                            | BinOp::Ge
189                    )
190                {
191                    self.emit_bigint_cross_comparison(
192                        *op,
193                        left,
194                        right,
195                        left_is_bigint,
196                        right_is_bigint,
197                    );
198                }
199                // ── Cross-type comparison (e.g. String vs Number, Bool vs I64) ──
200                // When both types are known but different, Zig's == / != / < etc.
201                // are type-mismatch errors. Route through JsAny comparison instead.
202                // EXCEPTION: exclude BigInt — JsAny.from() does not support BigInt,
203                // and BigInt cross-type comparisons need a different strategy.
204                //
205                // Also handle String vs numeric (even when numeric side type is unknown,
206                // e.g. "5" > 3 where 3 is a comptime_int literal).
207                else if (cross_type_known || str_vs_numeric)
208                    && matches!(
209                        op,
210                        BinOp::Eq
211                            | BinOp::Ne
212                            | BinOp::StrictEq
213                            | BinOp::StrictNe
214                            | BinOp::Lt
215                            | BinOp::Le
216                            | BinOp::Gt
217                            | BinOp::Ge
218                    )
219                {
220                    // Neither side is JsAny here (that branch is above),
221                    // but emit_jsany_comparison will wrap both in JsAny.from().
222                    self.emit_jsany_comparison(*op, left, right, false, false);
223                }
224                // ── JsAny comparison ──
225                else if (left_is_jsany || right_is_jsany)
226                    && matches!(
227                        op,
228                        BinOp::Eq
229                            | BinOp::Ne
230                            | BinOp::StrictEq
231                            | BinOp::StrictNe
232                            | BinOp::Lt
233                            | BinOp::Le
234                            | BinOp::Gt
235                            | BinOp::Ge
236                    )
237                {
238                    self.emit_jsany_comparison(*op, left, right, left_is_jsany, right_is_jsany);
239                }
240                // ── JsAny arithmetic: convert JsAny side to i64 via .asI64()
241                // (or to f64 via .asF64() when the other side is F64) ──
242                // This handles cases like `sum + mapValue` where mapValue is JsAny
243                // (e.g., from Map/Set for-of iteration or forEach callbacks).
244                else if (left_is_jsany || right_is_jsany)
245                    && matches!(
246                        op,
247                        BinOp::Add
248                            | BinOp::Sub
249                            | BinOp::Mul
250                            | BinOp::BitAnd
251                            | BinOp::BitOr
252                            | BinOp::BitXor
253                            | BinOp::Shl
254                            | BinOp::Shr
255                    )
256                {
257                    self.emit_jsany_arithmetic(
258                        *op,
259                        left,
260                        right,
261                        left_is_jsany,
262                        right_is_jsany,
263                        lt,
264                        rt,
265                    );
266                }
267                // ── Division / Remainder ──
268                // Note: Integer `%` is handled by RemExpr node, not Binary(Mod).
269                // Binary(Mod) is only reached for Float and BigInt operands.
270                else if *op == BinOp::Div || *op == BinOp::Mod {
271                    if left_is_float || right_is_float {
272                        if *op == BinOp::Mod {
273                            self.write("@rem(");
274                            self.emit_expr(left);
275                            self.write(", ");
276                            self.emit_expr(right);
277                            self.write(")");
278                        } else {
279                            self.write("(");
280                            self.emit_expr(left);
281                            self.write(" / ");
282                            self.emit_expr(right);
283                            self.write(")");
284                        }
285                    } else if *op == BinOp::Div {
286                        // JS `/` always returns float (5/2 === 2.5).
287                        // Convert integer operands to f64 before division.
288                        self.write("(@as(f64, @floatFromInt(");
289                        self.emit_expr(left);
290                        self.write(")) / @as(f64, @floatFromInt(");
291                        self.emit_expr(right);
292                        self.write(")))");
293                    } else {
294                        // BigInt %: emit via bigint binary method
295                        self.emit_bigint_binary(BinOp::Mod, left, right);
296                    }
297                }
298                // ── Unsigned right shift ──
299                // BigInt × any: JS throws TypeError at runtime
300                else if *op == BinOp::UrShr && (left_is_bigint || right_is_bigint) {
301                    if let Some(label) = &self.inside_try_block {
302                        self.write(&format!(
303                            "({{ break :{} @as(anyerror!void, error.JsThrow); }})",
304                            label
305                        ));
306                    } else {
307                        self.write("({ return error.JsThrow; })");
308                    }
309                }
310                // ── Unsigned right shift (non-BigInt) ──
311                else if *op == BinOp::UrShr {
312                    self.write("@as(i64, @intCast(@as(u32, @bitCast(@as(i32, @truncate(");
313                    self.emit_expr(left);
314                    self.write(")))) >> @intCast(");
315                    self.emit_expr(right);
316                    self.write(" & 31)))");
317                }
318                // ── `in` operator: key in obj → obj.has(JsAny.from(key)) for Map/Set, obj.contains(key) otherwise ──
319                else if *op == BinOp::In {
320                    // Right side is the object, left side is the key (operands swapped for .has()/.contains())
321                    let is_map_or_set = matches!(
322                        right_type,
323                        Some(ZigType::NamedStruct(n)) if n == "Map" || n == "Set"
324                    );
325                    self.emit_expr(right);
326                    if is_map_or_set {
327                        self.write(".has(JsAny.from(");
328                        self.emit_expr(left);
329                        self.write("))");
330                    } else {
331                        self.write(".contains(");
332                        self.emit_expr(left);
333                        self.write(")");
334                    }
335                }
336                // ── Default: direct operator ──
337                else {
338                    self.emit_default_binop(*op, left, right);
339                }
340            }
341
342            crate::zigir::types::IrExpr::PowExpr {
343                base,
344                exp,
345                base_type,
346                exp_type,
347                result_type,
348            } => {
349                // JS `**` always returns f64. Use std.math.pow(f64, ...) with
350                // temporary f64 variables in a labeled block.
351                let pow_id = self.peek_label_id();
352                let blk = self.next_label();
353                // If result_type is i64, wrap the entire block in @as(i64, @intFromFloat(...))
354                if let Some(crate::types::ZigType::I64) = result_type {
355                    self.write("@as(i64, @intFromFloat(");
356                }
357                self.write(&format!("({blk}: {{ "));
358                self.write(&format!("const _base_f64_{pow_id}: f64 = "));
359                self.emit_float_conversion(base, base_type);
360                self.write(&format!("; const _exp_f64_{pow_id}: f64 = "));
361                self.emit_float_conversion(exp, exp_type);
362                self.write(&format!(
363                    "; break :{blk} std.math.pow(f64, _base_f64_{pow_id}, _exp_f64_{pow_id}); }})",
364                ));
365                if let Some(crate::types::ZigType::I64) = result_type {
366                    self.write("))");
367                }
368            }
369
370            crate::zigir::types::IrExpr::RemExpr {
371                left,
372                right,
373                left_type,
374                right_type,
375                result_type,
376            } => {
377                // JS `%` for integer operands: always uses jsRem which returns f64
378                // (preserves signed zero -0). When result_type is i64, wrap in
379                // @as(i64, @intFromFloat(...)) for assignment to i64 variable.
380                //
381                // For JsAny operands, route through `@rem(f64, f64)` with
382                // `.asF64()` coercion — this preserves the float payload
383                // (e.g. `JsAny.from(5.7) % 2` must give 1.7, not 5 % 2 = 1).
384                // Mirrors the DivExpr JsAny path. @rem on f64 preserves IEEE
385                // 754 signed-zero (-0) semantics just like jsRem does for i64.
386                //
387                // BigInt and F64 are routed to `Binary(Mod)` by the lowerer
388                // and never reach this node. comptime_int operands emit
389                // directly as comptime_int and are accepted by jsRem's i64
390                // parameter via comptime coercion.
391                use crate::types::ZigType;
392                let left_is_jsany = *left_type == ZigType::JsAny;
393                let right_is_jsany = *right_type == ZigType::JsAny;
394
395                if let Some(ZigType::I64) = result_type {
396                    self.write("@as(i64, @intFromFloat(");
397                }
398                if left_is_jsany || right_is_jsany {
399                    // At least one operand is JsAny: use @rem(f64, f64) to
400                    // preserve the float payload. emit_float_conversion maps
401                    // F64 → direct, I64/BigInt → @floatFromInt, JsAny →
402                    // .asF64(), comptime_int → @as(f64, ...).
403                    self.write("@rem(");
404                    self.emit_float_conversion(left, left_type);
405                    self.write(", ");
406                    self.emit_float_conversion(right, right_type);
407                    self.write(")");
408                } else {
409                    // Pure integer operands (I64, comptime_int, BigInt-only
410                    // here because lowerer routes BigInt to Binary(Mod) — so
411                    // we actually only see I64/comptime_int at this point).
412                    // Use jsRem(i64, i64)→f64 for signed-zero preservation.
413                    self.write("js_runtime.jsRem(");
414                    self.emit_expr(left);
415                    self.write(", ");
416                    self.emit_expr(right);
417                    self.write(")");
418                }
419                if let Some(ZigType::I64) = result_type {
420                    self.write("))");
421                }
422            }
423
424            crate::zigir::types::IrExpr::DivExpr {
425                left,
426                right,
427                left_type,
428                right_type,
429                result_type,
430            } => {
431                // JS `/` always returns float. For integer operands, convert to f64 first.
432                // For JsAny operands, .asF64() preserves the float payload.
433                // When result_type is i64, wrap in @as(i64, @intFromFloat(...)).
434                use crate::types::ZigType;
435                let left_is_float = *left_type == ZigType::F64;
436                let right_is_float = *right_type == ZigType::F64;
437                let left_is_jsany = *left_type == ZigType::JsAny;
438                let right_is_jsany = *right_type == ZigType::JsAny;
439
440                if let Some(ZigType::I64) = result_type {
441                    self.write("@as(i64, @intFromFloat(");
442                }
443                if left_is_float || right_is_float || left_is_jsany || right_is_jsany {
444                    // At least one operand is F64 (already float) or JsAny (.asF64()):
445                    // route both through emit_float_conversion which handles each
446                    // case appropriately (no @floatFromInt needed on already-numeric).
447                    self.write("(");
448                    self.emit_float_conversion(left, left_type);
449                    self.write(" / ");
450                    self.emit_float_conversion(right, right_type);
451                    self.write(")");
452                } else {
453                    // Both operands are integer-ish (I64, BigInt, comptime_int,
454                    // Anytype-int-coercible). Wrap both in @as(f64, @floatFromInt(...)).
455                    // This matches the pre-Round-4 behavior and works for anytype params.
456                    self.write("(@as(f64, @floatFromInt(");
457                    self.emit_expr(left);
458                    self.write(")) / @as(f64, @floatFromInt(");
459                    self.emit_expr(right);
460                    self.write(")))");
461                }
462                if let Some(ZigType::I64) = result_type {
463                    self.write("))");
464                }
465            }
466
467            crate::zigir::types::IrExpr::Unary {
468                op,
469                operand,
470                operand_type,
471            } => {
472                match op {
473                    crate::zigir::ops::UnaOp::Neg => {
474                        self.write("-");
475                        self.emit_expr(operand);
476                    }
477                    crate::zigir::ops::UnaOp::Not => {
478                        self.write("!");
479                        // Coerce operand to bool first — JS `!x` works on any type,
480                        // but Zig `!` requires a bool operand.
481                        self.emit_expr_as_bool(operand);
482                    }
483                    crate::zigir::ops::UnaOp::BitNot => {
484                        // JS `~x` operates on 32-bit integer. Convert operand to i32 first.
485                        // For f64 operands: @intFromFloat → i64, then @intCast → i32.
486                        // For integer/comptime operands: @intCast works directly.
487                        if let Some(crate::types::ZigType::F64) = operand_type {
488                            self.write("~@as(i32, @intCast(@as(i64, @intFromFloat(");
489                            self.emit_expr(operand);
490                            self.write("))))");
491                        } else {
492                            self.write("~@as(i32, @intCast(");
493                            self.emit_expr(operand);
494                            self.write("))");
495                        }
496                    }
497                    crate::zigir::ops::UnaOp::Void => {
498                        // void expr → evaluate and discard
499                        self.emit_expr(operand);
500                    }
501                    // TypeOf and Delete are resolved by the lowerer into
502                    // StringLiteral / BuiltinCall / CompileError before
503                    // reaching the emit layer.  These arms are unreachable
504                    // but must exist for exhaustive match coverage.
505                    _ => unreachable!("typeof/delete should be resolved at lower time"),
506                }
507            }
508
509            crate::zigir::types::IrExpr::Logical {
510                op,
511                left,
512                right,
513                left_type,
514                right_type,
515            } => {
516                // Value-returning logical operators (JS semantics):
517                //   a && b → returns a if falsy, else b
518                //   a || b → returns a if truthy, else b
519                //   a ?? b → returns a if not null/undefined, else b
520                //
521                // Emitted as a Zig labeled-block if-expression so the result
522                // preserves the operand type instead of flattening to bool.
523                let id = self.peek_label_id();
524                let blk = self.next_label();
525                let lt = left_type.as_ref();
526                let rt = right_type.as_ref();
527                let same_type = lt.is_some() && rt.is_some() && lt == rt;
528
529                // When same_type, add an explicit type annotation to the temp var
530                // so that comptime_int / comptime_float values are materialized
531                // as proper runtime types (e.g., i64, f64). Without this, Zig
532                // rejects comptime-only values in runtime control flow branches.
533                self.write(&format!("({blk}: {{ const _lv_{id}"));
534                if same_type && let Some(lt_val) = lt {
535                    self.write(&format!(": {}", lt_val.to_zig_type()));
536                }
537                self.write(" = ");
538                self.emit_expr(left);
539                self.write("; ");
540
541                match op {
542                    crate::zigir::ops::LogicalOp::And => {
543                        // a && b: if truthy(a) → b, else → a
544                        self.write("if (js_runtime.isTruthy(_lv_");
545                        self.write(&format!("{id}))"));
546                        self.write(&format!(" break :{blk} "));
547                        if same_type {
548                            self.emit_expr(right);
549                        } else {
550                            self.write("JsAny.from(");
551                            self.emit_expr(right);
552                            self.write(")");
553                        }
554                        self.write(&format!(" else break :{blk} "));
555                        if same_type {
556                            self.write(&format!("_lv_{id}"));
557                        } else {
558                            self.write(&format!("JsAny.from(_lv_{id})"));
559                        }
560                    }
561                    crate::zigir::ops::LogicalOp::Or => {
562                        // a || b: if truthy(a) → a, else → b
563                        self.write("if (js_runtime.isTruthy(_lv_");
564                        self.write(&format!("{id}))"));
565                        self.write(&format!(" break :{blk} "));
566                        if same_type {
567                            self.write(&format!("_lv_{id}"));
568                        } else {
569                            self.write(&format!("JsAny.from(_lv_{id})"));
570                        }
571                        self.write(&format!(" else break :{blk} "));
572                        if same_type {
573                            self.emit_expr(right);
574                        } else {
575                            self.write("JsAny.from(");
576                            self.emit_expr(right);
577                            self.write(")");
578                        }
579                    }
580                    crate::zigir::ops::LogicalOp::Nullish => {
581                        // a ?? b: if a is not null/undefined → a, else → b.
582                        // When same_type is true but the type is a concrete
583                        // non-nullable scalar (I64/F64/Str/Bool etc.), the
584                        // value can never be nullish, so skip the check and
585                        // just return the left value directly. Only JsAny
586                        // values (or unknown types) need the runtime
587                        // isNullish() check.
588                        let is_jsany = lt == Some(&ZigType::JsAny);
589                        if same_type && !is_jsany {
590                            // Non-nullable concrete type — left is always
591                            // the result; right expression is never evaluated.
592                            self.write(&format!("break :{blk} _lv_{id}"));
593                        } else {
594                            // JsAny or unknown type — runtime nullish check
595                            self.write(&format!("if (!_lv_{id}.isNullish())"));
596                            self.write(&format!(" break :{blk} "));
597                            if same_type {
598                                self.write(&format!("_lv_{id}"));
599                            } else {
600                                self.write(&format!("JsAny.from(_lv_{id})"));
601                            }
602                            self.write(&format!(" else break :{blk} "));
603                            if same_type {
604                                self.emit_expr(right);
605                            } else {
606                                self.write("JsAny.from(");
607                                self.emit_expr(right);
608                                self.write(")");
609                            }
610                        }
611                    }
612                }
613                self.write("; })");
614            }
615
616            crate::zigir::types::IrExpr::Update {
617                op,
618                target,
619                is_expr_stmt,
620                prefix,
621            } => {
622                if *is_expr_stmt {
623                    // Statement context: `i += 1` (no parens, no _ = prefix)
624                    self.emit_assign_target_inner(target);
625                    self.write(&format!(" {}", update_op_to_zig(*op)));
626                } else if *prefix {
627                    // Prefix `++x` in expression context: returns NEW value.
628                    // (_blk: { x += 1; break :_blk x; })
629                    let blk = self.next_label();
630                    self.write(&format!("({}: {{ ", blk));
631                    self.emit_assign_target_inner(target);
632                    self.write(&format!(" {}; ", update_op_to_zig(*op)));
633                    self.write("break :");
634                    self.write(&blk);
635                    self.write(" ");
636                    self.emit_assign_target_inner(target);
637                    self.write("; })");
638                } else {
639                    // Postfix `x++` in expression context: returns OLD value.
640                    // (_blk: { const _old = x; x += 1; break :_blk _old; })
641                    let blk = self.next_label();
642                    self.write(&format!("({}: {{ const _old = ", blk));
643                    self.emit_assign_target_inner(target);
644                    self.write("; ");
645                    self.emit_assign_target_inner(target);
646                    self.write(&format!(" {}; ", update_op_to_zig(*op)));
647                    self.write(&format!("break :{} _old; }})", blk));
648                }
649            }
650
651            crate::zigir::types::IrExpr::Assign { op, target, value } => {
652                self.emit_compound_assign(target, *op, value);
653            }
654
655            // ── Calls ───────────────────────────────
656            crate::zigir::types::IrExpr::Call(call) => {
657                self.emit_call_expr(call);
658            }
659
660            crate::zigir::types::IrExpr::BuiltinCall(bc) => {
661                self.emit_builtin_call(bc);
662            }
663
664            crate::zigir::types::IrExpr::HostCall(hc) => {
665                self.write(&format!("host.{}", hc.name));
666                self.emit_args(&hc.args);
667            }
668
669            // ── Member access ───────────────────────
670            crate::zigir::types::IrExpr::FieldAccess {
671                object,
672                field,
673                field_kind,
674            } => {
675                self.emit_field_access(object, field, field_kind);
676            }
677
678            crate::zigir::types::IrExpr::IndexAccess {
679                object,
680                index,
681                index_kind,
682            } => {
683                self.emit_index_access(object, index, index_kind);
684            }
685
686            crate::zigir::types::IrExpr::ComputedField {
687                object,
688                key,
689                key_kind,
690            } => {
691                self.emit_computed_field(object, key, key_kind);
692            }
693
694            // ── Object / Array ──────────────────────
695            crate::zigir::types::IrExpr::ArrayLiteral(arr) => {
696                self.emit_array_literal(arr);
697            }
698
699            crate::zigir::types::IrExpr::ObjectLiteral(obj) => {
700                self.emit_object_literal(obj);
701            }
702
703            // ── Function expressions ────────────────
704            crate::zigir::types::IrExpr::ArrowFn(_arrow) => {
705                unreachable!("ArrowFn should be lowered to Closure before emit")
706            }
707
708            crate::zigir::types::IrExpr::Closure(closure) => {
709                // Closure instance: `StructName { .captured = val, ... }`
710                // When a capture has init_expr, use that as the init value
711                // (e.g. `__self` capture uses `self` instead of `__self`).
712                self.write(&closure.struct_name.zig_name);
713                self.write("{ ");
714                for (i, cap) in closure.captured.iter().enumerate() {
715                    if i > 0 {
716                        self.write(", ");
717                    }
718                    let init_val = cap.init_expr.as_deref().unwrap_or(&cap.name.zig_name);
719                    if cap.is_mut {
720                        self.write(&format!(".{} = &{}", cap.name.zig_name, init_val));
721                    } else {
722                        self.write(&format!(".{} = {}", cap.name.zig_name, init_val));
723                    }
724                }
725                self.write(" }");
726            }
727
728            crate::zigir::types::IrExpr::FnExpr(fn_expr) => {
729                // Function expression: emit as struct with call method
730                let name = fn_expr
731                    .name
732                    .as_ref()
733                    .map(|n| n.zig_name.clone())
734                    .unwrap_or_else(|| "_fn_expr".to_string());
735                self.write(&name);
736            }
737
738            // ── Conditional / template ───────────────
739            crate::zigir::types::IrExpr::Conditional { cond, then, else_ } => {
740                // Wrap in parentheses for defensive safety: when this expression
741                // is nested inside a larger expression (e.g. `a + (b ? c : d)`),
742                // unparenthesized `if ... else ...` is invalid Zig syntax in
743                // expression position. All sibling multi-token expressions
744                // (BlockExpr, Await, Sequence, OptionalChain) also wrap in (..).
745                self.write("(if (");
746                self.emit_expr_as_bool(cond);
747                self.write(") ");
748                self.emit_expr(then);
749                self.write(" else ");
750                self.emit_expr(else_);
751                self.write(")");
752            }
753
754            crate::zigir::types::IrExpr::TemplateLiteral {
755                parts,
756                exprs,
757                format_specs,
758            } => {
759                self.emit_template_literal(parts, exprs, format_specs);
760            }
761
762            // ── Async ───────────────────────────────
763            crate::zigir::types::IrExpr::Await(await_expr) => {
764                // Emit: (blk: { var _tN = io.async(callee, .{ io, args... }); defer _ = _tN.cancel(io) catch undefined; break :blk try _tN.await(io); })
765                self.write(&format!("({}: {{\n", await_expr.block_label));
766                self.indent_push();
767                self.write_indent();
768                self.write(&format!("var {} = io.async(", await_expr.task_var.zig_name));
769
770                if await_expr.is_host_async {
771                    // For host async, callee is an Ident holding the host fn name
772                    if let crate::zigir::types::IrExpr::Ident(id) = &*await_expr.callee {
773                        self.write(&format!("host.{}_async", id.zig_name));
774                    } else {
775                        // Fallback
776                        self.emit_expr(&await_expr.callee);
777                    }
778                } else {
779                    self.emit_expr(&await_expr.callee);
780                }
781
782                self.write(", .{ io");
783                for arg in &await_expr.args {
784                    self.write(", ");
785                    self.emit_expr(arg);
786                }
787                self.write(" });\n");
788
789                self.write_indent();
790                self.write(&format!(
791                    "defer _ = {}.cancel(io) catch undefined;\n",
792                    await_expr.task_var.zig_name
793                ));
794
795                self.write_indent();
796                self.write(&format!(
797                    "break :{} try {}.await(io);\n",
798                    await_expr.block_label, await_expr.task_var.zig_name
799                ));
800
801                self.indent_pop();
802                self.write_indent();
803                self.write("})");
804            }
805
806            // ── Construction ────────────────────────
807            crate::zigir::types::IrExpr::New(new_expr) => {
808                self.emit_new_expr(new_expr);
809            }
810
811            // ── String formatting ──────────────────────
812            crate::zigir::types::IrExpr::AllocPrint { fmt, args } => {
813                if args.is_empty() {
814                    // Pure-text → plain string literal (no allocation)
815                    let unescaped = fmt.replace("{{", "{").replace("}}", "}");
816                    self.write(&format!("\"{}\"", unescaped));
817                } else {
818                    // Emit args by capturing each as a string
819                    self.emit_alloc_print(fmt, args);
820                }
821            }
822
823            // ── Block expression ────────────────────
824            crate::zigir::types::IrExpr::BlockExpr {
825                label,
826                body,
827                result,
828            } => {
829                self.write(&format!("({}: {{", label));
830                for stmt in body {
831                    self.emit_stmt(stmt);
832                }
833                self.write("break :");
834                self.write(label);
835                self.write(" ");
836                self.emit_expr(result);
837                // Close: `; })` — `;` ends the break STMT (Zig requires `;`
838                // after `break :label value`), `}` closes the labeled block,
839                // `)` closes the wrapping paren.
840                // Pre-fix typo wrote `}})` (two `}`, no `;`) which produced
841                // invalid Zig: `expected ';' after statement` on the `}`.
842                self.write("; })");
843            }
844
845            // ── Special ─────────────────────────────
846            crate::zigir::types::IrExpr::Spread(inner) => {
847                self.emit_expr(inner);
848            }
849
850            crate::zigir::types::IrExpr::Typeof(inner) => {
851                // typeof on identifiers with known types is resolved at lower time
852                // to StringLiteral. This branch handles any remaining typeof
853                // expressions (shouldn't occur with current lowerer, but as fallback).
854                self.write("js_runtime.jsTypeof(");
855                self.emit_expr(inner);
856                self.write(")");
857            }
858
859            crate::zigir::types::IrExpr::Void(inner) => {
860                // void expr: evaluate expr for side effects, return undefined.
861                // Output: blk_N: { _ = expr; break :blk_N JsAny.fromUndefined(); }
862                let label = self.next_label();
863                self.write(&format!("{}: {{ _ = ", label));
864                self.emit_expr(inner);
865                self.write(&format!("; break :{} JsAny.fromUndefined(); }}", label));
866            }
867
868            crate::zigir::types::IrExpr::Paren(inner) => {
869                self.write("(");
870                self.emit_expr(inner);
871                self.write(")");
872            }
873
874            crate::zigir::types::IrExpr::Sequence(exprs) => {
875                // JS comma operator: evaluate all expressions, return the last.
876                // Zig has no comma operator, so use a labeled block.
877                // `a, b, c` → `blk: { _ = a; _ = b; break :blk c; }`
878                if exprs.len() == 1 {
879                    self.emit_expr(&exprs[0]);
880                } else {
881                    let blk = self.next_label();
882                    self.write(&format!("({blk}: {{ "));
883                    for e in &exprs[..exprs.len() - 1] {
884                        self.write("_ = ");
885                        self.emit_expr(e);
886                        self.write("; ");
887                    }
888                    self.write(&format!("break :{blk} "));
889                    self.emit_expr(&exprs[exprs.len() - 1]);
890                    self.write("; })");
891                }
892            }
893
894            crate::zigir::types::IrExpr::ArrayCallbackInline(inline_data) => {
895                self.emit_array_callback_inline(inline_data);
896            }
897
898            crate::zigir::types::IrExpr::ArrayMethodInline(inline_data) => {
899                self.emit_array_method_inline(inline_data);
900            }
901
902            crate::zigir::types::IrExpr::OptionalChain {
903                object,
904                capture_var,
905                body,
906                needs_null_check,
907            } => {
908                if *needs_null_check {
909                    self.write("(if (");
910                    self.emit_expr(object);
911                    self.write(") |");
912                    self.write(capture_var);
913                    self.write("| ");
914                    self.emit_expr(body);
915                    self.write(" else null)");
916                } else {
917                    self.emit_expr(body);
918                }
919            }
920
921            crate::zigir::types::IrExpr::CompileError { span, msg } => {
922                let loc = format!("{}:{}", span.js_line, span.js_col);
923                self.write(&emit_helpers::compile_error(&format!(
924                    "{} (at {})",
925                    msg, loc
926                )));
927            }
928        }
929    }
930
931    /// Convert an expression to a string without writing to the output buffer.
932    /// Used for contexts where we need the expression text as a value.
933    pub(crate) fn expr_to_string(&mut self, expr: &crate::zigir::types::IrExpr) -> String {
934        let saved_output = std::mem::take(&mut self.output);
935        self.emit_expr(expr);
936        let result = std::mem::take(&mut self.output);
937        self.output = saved_output;
938        result
939    }
940
941    // ── Internal helpers ───────────────────────────
942
943    pub(super) fn emit_assign_target_inner(
944        &mut self,
945        target: &crate::zigir::types::IrAssignTarget,
946    ) {
947        match target {
948            crate::zigir::types::IrAssignTarget::Ident(ident) => {
949                self.write(&ident.zig_name);
950            }
951            crate::zigir::types::IrAssignTarget::Member {
952                object,
953                field,
954                is_pointer,
955                field_kind,
956            } => {
957                use crate::zigir::kinds::FieldKind;
958                match field_kind {
959                    FieldKind::StaticField { class_name } => {
960                        self.emit_static_field(class_name, field);
961                    }
962                    _ => {
963                        self.emit_expr(object);
964                        if *is_pointer {
965                            self.write(&format!(".{}.*", field));
966                        } else {
967                            self.write(&format!(".{}", field));
968                        }
969                    }
970                }
971            }
972            crate::zigir::types::IrAssignTarget::Index {
973                object,
974                index,
975                index_kind,
976            } => {
977                use crate::zigir::kinds::IndexKind;
978                match index_kind {
979                    IndexKind::ArrayListItem => {
980                        self.emit_arraylist_item(object, index);
981                    }
982                    IndexKind::SliceIndex => {
983                        self.emit_slice_index(object, index);
984                    }
985                }
986            }
987            crate::zigir::types::IrAssignTarget::Destructure(bindings) => {
988                for (i, binding) in bindings.iter().enumerate() {
989                    if i > 0 {
990                        self.write("; ");
991                    }
992                    self.write(&binding.pattern.zig_name);
993                    if let Some(default) = &binding.default {
994                        self.write(" orelse ");
995                        self.emit_expr(default);
996                    }
997                }
998            }
999            crate::zigir::types::IrAssignTarget::CompileError { msg } => {
1000                self.write(&format!("@compileError(\"{}\")", msg));
1001            }
1002        }
1003    }
1004
1005    /// Emit a compound assignment (LogicAnd/LogicOr/Nullish or simple op).
1006    /// Shared by IrExpr::Assign (expression context) and emit_assign_inline (statement context).
1007    /// Note: Mod (%) is expanded to RemExpr and Div (/) to DivExpr in the lowerer.
1008    pub(super) fn emit_compound_assign(
1009        &mut self,
1010        target: &crate::zigir::types::IrAssignTarget,
1011        op: crate::zigir::ops::AssignOp,
1012        value: &crate::zigir::types::IrExpr,
1013    ) {
1014        use crate::zigir::ops::AssignOp;
1015        if op == AssignOp::LogicAnd {
1016            // a &&= b → a = if (js_runtime.isTruthy(a)) b else a
1017            // Use isTruthy (works for anytype: i64, f64, bool, JsAny, string, ...)
1018            // instead of .toBool() which only exists on JsAny.
1019            self.emit_assign_target_inner(target);
1020            self.write(" = if (js_runtime.isTruthy(");
1021            self.emit_assign_target_inner(target);
1022            self.write(")) ");
1023            self.emit_expr(value);
1024            self.write(" else ");
1025            self.emit_assign_target_inner(target);
1026        } else if op == AssignOp::LogicOr {
1027            // a ||= b → a = if (!js_runtime.isTruthy(a)) b else a
1028            self.emit_assign_target_inner(target);
1029            self.write(" = if (!js_runtime.isTruthy(");
1030            self.emit_assign_target_inner(target);
1031            self.write(")) ");
1032            self.emit_expr(value);
1033            self.write(" else ");
1034            self.emit_assign_target_inner(target);
1035        } else if op == AssignOp::Nullish {
1036            // a ??= b → a = if (js_runtime.isNullish(a)) b else a
1037            // Use js_runtime.isNullish (anytype) so it works for JsAny,
1038            // optionals (?i64), and primitives (i64, f64, … → always false).
1039            self.emit_assign_target_inner(target);
1040            self.write(" = if (js_runtime.isNullish(");
1041            self.emit_assign_target_inner(target);
1042            self.write(")) ");
1043            self.emit_expr(value);
1044            self.write(" else ");
1045            self.emit_assign_target_inner(target);
1046        } else {
1047            self.emit_assign_target_inner(target);
1048            self.write(&format!(" {} ", op.to_zig_str()));
1049            self.emit_expr(value);
1050        }
1051    }
1052
1053    /// Emit a `std.fmt.allocPrint(allocator, fmt, .{args})` call.
1054    /// Shared by IrExpr::AllocPrint and emit_template_literal.
1055    pub(super) fn emit_alloc_print(&mut self, fmt: &str, args: &[crate::zigir::types::IrExpr]) {
1056        let arg_strs: Vec<String> = args.iter().map(|arg| self.expr_to_string(arg)).collect();
1057        let args_str = format!(".{{{}}}", arg_strs.join(", "));
1058        self.write(&format!(
1059            "std.fmt.allocPrint(js_allocator.allocator(), \"{}\", {}) catch @panic(\"OOM: template literal allocPrint\")",
1060            fmt, args_str
1061        ));
1062    }
1063
1064    /// Emit a single call argument, handling spread elements.
1065    /// Shared by `emit_args` (function calls, with parens) and `emit_new_expr`
1066    /// (class constructors, parens managed by caller) so that
1067    /// `new Foo(...args)` gets the same spread treatment as `foo(...args)`.
1068    ///
1069    /// foo(...args) → foo(args.items)  [ArrayList spread]
1070    /// foo(...restParam) → foo(restParam)  [rest param: already []const JsAny]
1071    /// foo(...[1,2,3]) → foo(&[_]JsAny{ JsAny.from(1), ... })  [literal spread]
1072    pub(super) fn emit_one_arg(&mut self, arg: &crate::zigir::types::IrExpr) {
1073        use crate::zigir::types::IrExpr;
1074        if let IrExpr::Spread(inner) = arg {
1075            match inner.as_ref() {
1076                // Rest param spread: pass slice directly (no .items)
1077                IrExpr::Ident(ident) if self.rest_param_names.contains(&ident.zig_name) => {
1078                    self.emit_expr(inner);
1079                }
1080                IrExpr::TypedIdent { ident, .. }
1081                    if self.rest_param_names.contains(&ident.zig_name) =>
1082                {
1083                    self.emit_expr(inner);
1084                }
1085                // Array literal spread: emit as &[_]JsAny{ ... }
1086                // Each element must be wrapped in JsAny.from() since the
1087                // array literal type is explicitly JsAny.
1088                IrExpr::ArrayLiteral(arr) => {
1089                    self.write("&[_]JsAny{ ");
1090                    for (j, elem) in arr.elements.iter().enumerate() {
1091                        if j > 0 {
1092                            self.write(", ");
1093                        }
1094                        if arr.spread_indices.contains(&j) {
1095                            // Nested spread inside array literal spread:
1096                            // not supported in &[_]JsAny{} syntax.
1097                            self.write(
1098                                "@compileError(\"nested spread in call args not supported\")",
1099                            );
1100                        } else {
1101                            // The lowerer's pack_rest_args_if_needed already
1102                            // wraps each element in JsAny.from() at the IR level.
1103                            // Check if already wrapped to avoid double-wrapping
1104                            // (JsAny.from(JsAny.from(x))).
1105                            let already_wrapped = is_jsany_from_call(elem);
1106                            if !already_wrapped {
1107                                self.write("JsAny.from(");
1108                            }
1109                            self.emit_expr(elem);
1110                            if !already_wrapped {
1111                                self.write(")");
1112                            }
1113                        }
1114                    }
1115                    self.write(" }");
1116                }
1117                // Default: ArrayList spread → .items
1118                _ => {
1119                    self.emit_expr(inner);
1120                    self.write(".items");
1121                }
1122            }
1123        } else {
1124            self.emit_expr(arg);
1125        }
1126    }
1127
1128    pub(super) fn emit_args(&mut self, args: &[crate::zigir::types::IrExpr]) {
1129        self.write("(");
1130        for (i, arg) in args.iter().enumerate() {
1131            if i > 0 {
1132                self.write(", ");
1133            }
1134            self.emit_one_arg(arg);
1135        }
1136        self.write(")");
1137    }
1138
1139    /// Check if an IrExpr is definitely of type `bool`.
1140    pub(super) fn ir_expr_is_bool(expr: &crate::zigir::types::IrExpr) -> bool {
1141        use crate::zigir::ops::BinOp;
1142        use crate::zigir::types::IrExpr;
1143
1144        match expr {
1145            IrExpr::BoolLiteral(_) => true,
1146            // Logical expressions are value-returning in JS, not bool.
1147            // They use if-expressions at emit time, producing the operand type or JsAny.
1148            IrExpr::Logical { .. } => false,
1149            IrExpr::Unary {
1150                op: crate::zigir::ops::UnaOp::Not,
1151                ..
1152            } => true,
1153            IrExpr::Binary { op, .. } => matches!(
1154                op,
1155                BinOp::Eq
1156                    | BinOp::Ne
1157                    | BinOp::StrictEq
1158                    | BinOp::StrictNe
1159                    | BinOp::Lt
1160                    | BinOp::Le
1161                    | BinOp::Gt
1162                    | BinOp::Ge
1163                    | BinOp::In
1164                    | BinOp::InstanceOf
1165            ),
1166            _ => false,
1167        }
1168    }
1169
1170    /// Emit an expression with truthiness coercion for Zig `bool` context.
1171    ///
1172    /// When a non-bool expression appears in a position that Zig requires `bool`
1173    /// (e.g. `if` condition, `while` condition), we coerce via `js_runtime.isTruthy()`
1174    /// which handles all JS types correctly (bool, i64, f64, string, comptime_int, etc.).
1175    pub(crate) fn emit_expr_as_bool(&mut self, expr: &crate::zigir::types::IrExpr) {
1176        if Self::ir_expr_is_bool(expr) {
1177            self.emit_expr(expr);
1178        } else {
1179            self.write("js_runtime.isTruthy(");
1180            self.emit_expr(expr);
1181            self.write(")");
1182        }
1183    }
1184}
1185
1186/// Map TypedArrayKind to (module, init_fn) for construction.
1187/// Uses fromI64AsI8/fromI64AsU8/.../fromF64 series instead of direct .init().
1188pub(super) fn typed_array_init(
1189    kind: &crate::zigir::kinds::TypedArrayKind,
1190) -> (&'static str, &'static str) {
1191    use crate::zigir::kinds::TypedArrayKind;
1192    match kind {
1193        TypedArrayKind::Int8Array => ("js_runtime.js_typedarray", "fromI64AsI8"),
1194        TypedArrayKind::Uint8Array => ("js_runtime.js_typedarray", "fromI64AsU8"),
1195        TypedArrayKind::Uint8ClampedArray => ("js_runtime.js_typedarray", "fromI64AsU8"),
1196        TypedArrayKind::Int16Array => ("js_runtime.js_typedarray", "fromI64AsI16"),
1197        TypedArrayKind::Uint16Array => ("js_runtime.js_typedarray", "fromI64AsU16"),
1198        TypedArrayKind::Int32Array => ("js_runtime.js_typedarray", "fromI64AsI32"),
1199        TypedArrayKind::Uint32Array => ("js_runtime.js_typedarray", "fromI64AsU32"),
1200        TypedArrayKind::Float32Array => ("js_runtime.js_typedarray", "fromF64AsF32"),
1201        TypedArrayKind::Float64Array => ("js_runtime.js_typedarray", "fromF64"),
1202        TypedArrayKind::BigInt64Array => ("js_runtime.js_typedarray", "fromI64AsI64"),
1203        TypedArrayKind::BigUint64Array => ("js_runtime.js_typedarray", "fromI64AsU64"),
1204    }
1205}
1206
1207/// Check if an IrExpr is a `JsAny.from(...)` call — used to avoid double-wrapping
1208/// in `emit_one_arg`'s array literal spread path.
1209fn is_jsany_from_call(expr: &crate::zigir::types::IrExpr) -> bool {
1210    use crate::zigir::types::{IrCallExpr, IrExpr};
1211    if let IrExpr::Call(IrCallExpr { callee, .. }) = expr
1212        && let IrExpr::FieldAccess { object, field, .. } = &**callee
1213        && let IrExpr::Ident(ident) | IrExpr::TypedIdent { ident, .. } = &**object
1214    {
1215        return ident.zig_name == "JsAny" && field == "from";
1216    }
1217    false
1218}