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