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