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