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