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::{
11    EmitterHelpers, assign_op_to_zig, bin_op_to_zig, escape_zig_string, format_param_with_rest,
12    logical_op_to_zig, update_op_to_zig,
13};
14
15// ═══════════════════════════════════════════════════════
16//  Expression dispatch
17// ═══════════════════════════════════════════════════════
18
19impl Emitter {
20    pub(crate) fn emit_expr(&mut self, expr: &crate::zigir::types::IrExpr) {
21        match expr {
22            crate::zigir::types::IrExpr::IntLiteral(n) => {
23                self.write(&n.to_string());
24            }
25
26            crate::zigir::types::IrExpr::FloatLiteral(n) => {
27                if *n == -0.0 && n.is_sign_negative() {
28                    self.write("-0.0");
29                } else {
30                    self.write(&n.to_string());
31                }
32            }
33
34            crate::zigir::types::IrExpr::StringLiteral(s) => {
35                self.write(&format!("\"{}\"", escape_zig_string(s)));
36            }
37
38            crate::zigir::types::IrExpr::BoolLiteral(b) => {
39                self.write(if *b { "true" } else { "false" });
40            }
41
42            crate::zigir::types::IrExpr::BigIntLiteral(s) => {
43                // Wrap in parentheses: `catch` has lower precedence than `+`/`-`,
44                // so `BigInt.init(...) catch @panic(...) + x` would parse incorrectly.
45                self.write(&format!(
46                    "(js_bigint.JsBigInt.init(js_allocator.allocator(), \"{}\") catch @panic(\"OOM: BigInt init\"))",
47                    s
48                ));
49            }
50
51            crate::zigir::types::IrExpr::Null => {
52                self.write("JsAny.fromNull()");
53            }
54
55            crate::zigir::types::IrExpr::Undefined => {
56                self.write("JsAny.fromUndefined()");
57            }
58
59            crate::zigir::types::IrExpr::Ident(ident) => {
60                self.write(&ident.zig_name);
61            }
62
63            crate::zigir::types::IrExpr::This => {
64                self.write("self");
65            }
66
67            // ── Arithmetic / comparison ─────────────
68            crate::zigir::types::IrExpr::Binary {
69                op,
70                left,
71                right,
72                left_type,
73                right_type,
74            } => {
75                use crate::types::ZigType;
76                use crate::zigir::ops::BinOp;
77
78                // Determine if operands are BigInt, JsAny, String, or other
79                let lt = left_type.as_ref();
80                let rt = right_type.as_ref();
81                let left_is_bigint = lt == Some(&ZigType::BigInt);
82                let right_is_bigint = rt == Some(&ZigType::BigInt);
83                // Check both type inference AND the expression node itself.
84                // String literals like "5" often have `left_type = None` since they
85                // lack a JSDoc annotation, but `IrExpr::StringLiteral` is unambiguous.
86                let left_is_str = lt == Some(&ZigType::Str)
87                    || matches!(&**left, crate::zigir::types::IrExpr::StringLiteral(_));
88                let right_is_str = rt == Some(&ZigType::Str)
89                    || matches!(&**right, crate::zigir::types::IrExpr::StringLiteral(_));
90                let left_is_jsany = lt == Some(&ZigType::JsAny);
91                let right_is_jsany = rt == Some(&ZigType::JsAny);
92                let left_is_float = lt == Some(&ZigType::F64);
93                let right_is_float = rt == Some(&ZigType::F64);
94                // Pre-compute cross-type flags (needed for the if/else-if chain below)
95                // Anytype should not count as a distinct type — Zig resolves it at comptime.
96                let left_is_anytype = lt == Some(&ZigType::Anytype);
97                let right_is_anytype = rt == Some(&ZigType::Anytype);
98                let cross_type_known = lt.is_some()
99                    && rt.is_some()
100                    && lt != rt
101                    && !left_is_bigint
102                    && !right_is_bigint
103                    && !left_is_anytype
104                    && !right_is_anytype;
105                let str_vs_numeric = (left_is_str && !right_is_str && !right_is_bigint)
106                    || (right_is_str && !left_is_str && !left_is_bigint);
107
108                // ── BigInt arithmetic/comparison ──
109                if left_is_bigint && right_is_bigint {
110                    self.emit_bigint_binary(*op, left, right);
111                }
112                // ── BigInt ** non-BigInt (e.g. 2n ** 2) ──
113                // BigInt .pow() expects u64 exponent, not &JsBigInt.
114                else if left_is_bigint && *op == BinOp::Pow {
115                    self.write("(");
116                    self.emit_expr(left);
117                    self.write(".pow(");
118                    if right_is_bigint {
119                        self.emit_expr(right);
120                        self.write(".toU64() catch @panic(\"BigInt toU64 failed\")");
121                    } else {
122                        self.write("@as(u64, @intCast(");
123                        self.emit_expr(right);
124                        self.write("))");
125                    }
126                    self.write(", js_allocator.allocator()) catch @panic(\"BigInt pow OOM\"))");
127                }
128                // ── String equality/comparison ──
129                else if left_is_str && right_is_str {
130                    self.emit_string_comparison(*op, left, right);
131                }
132                // ── BigInt cross-type comparison (e.g. 0n === 0, bigint == 5) ──
133                // Convert the non-BigInt operand to JsBigInt and use .eq() / .order()
134                else if (left_is_bigint || right_is_bigint)
135                    && matches!(
136                        op,
137                        BinOp::Eq
138                            | BinOp::Ne
139                            | BinOp::StrictEq
140                            | BinOp::StrictNe
141                            | BinOp::Lt
142                            | BinOp::Le
143                            | BinOp::Gt
144                            | BinOp::Ge
145                    )
146                {
147                    self.emit_bigint_cross_comparison(
148                        *op,
149                        left,
150                        right,
151                        left_is_bigint,
152                        right_is_bigint,
153                    );
154                }
155                // ── Cross-type comparison (e.g. String vs Number, Bool vs I64) ──
156                // When both types are known but different, Zig's == / != / < etc.
157                // are type-mismatch errors. Route through JsAny comparison instead.
158                // EXCEPTION: exclude BigInt — JsAny.from() does not support BigInt,
159                // and BigInt cross-type comparisons need a different strategy.
160                //
161                // Also handle String vs numeric (even when numeric side type is unknown,
162                // e.g. "5" > 3 where 3 is a comptime_int literal).
163                else if (cross_type_known || str_vs_numeric)
164                    && matches!(
165                        op,
166                        BinOp::Eq
167                            | BinOp::Ne
168                            | BinOp::StrictEq
169                            | BinOp::StrictNe
170                            | BinOp::Lt
171                            | BinOp::Le
172                            | BinOp::Gt
173                            | BinOp::Ge
174                    )
175                {
176                    // Neither side is JsAny here (that branch is above),
177                    // but emit_jsany_comparison will wrap both in JsAny.from().
178                    self.emit_jsany_comparison(*op, left, right, false, false);
179                }
180                // ── JsAny comparison ──
181                else if (left_is_jsany || right_is_jsany)
182                    && matches!(
183                        op,
184                        BinOp::Eq
185                            | BinOp::Ne
186                            | BinOp::StrictEq
187                            | BinOp::StrictNe
188                            | BinOp::Lt
189                            | BinOp::Le
190                            | BinOp::Gt
191                            | BinOp::Ge
192                    )
193                {
194                    self.emit_jsany_comparison(*op, left, right, left_is_jsany, right_is_jsany);
195                }
196                // ── Division ──
197                else if *op == BinOp::Div {
198                    if left_is_float || right_is_float {
199                        self.write("(");
200                        self.emit_expr(left);
201                        self.write(" / ");
202                        self.emit_expr(right);
203                        self.write(")");
204                    } else {
205                        self.write("@divTrunc(");
206                        self.emit_expr(left);
207                        self.write(", ");
208                        self.emit_expr(right);
209                        self.write(")");
210                    }
211                }
212                // ── Remainder ──
213                else if *op == BinOp::Mod {
214                    if left_is_float || right_is_float {
215                        self.write("(");
216                        self.emit_expr(left);
217                        self.write(" % ");
218                        self.emit_expr(right);
219                        self.write(")");
220                    } else {
221                        self.write("@rem(");
222                        self.emit_expr(left);
223                        self.write(", ");
224                        self.emit_expr(right);
225                        self.write(")");
226                    }
227                }
228                // ── Unsigned right shift ──
229                else if *op == BinOp::UrShr {
230                    self.write("@as(i64, @intCast(@as(u32, @bitCast(@as(i32, @truncate(");
231                    self.emit_expr(left);
232                    self.write(")))) >> @intCast(");
233                    self.emit_expr(right);
234                    self.write(" & 31)))");
235                }
236                // ── `in` operator: key in obj → obj.contains(key) ──
237                else if *op == BinOp::In {
238                    // Right side is the object, left side is the key (operands swapped for .contains())
239                    self.emit_expr(right);
240                    self.write(".contains(");
241                    self.emit_expr(left);
242                    self.write(")");
243                }
244                // ── Default: direct operator ──
245                else {
246                    self.emit_expr(left);
247                    self.write(&format!(" {} ", bin_op_to_zig(*op)));
248                    self.emit_expr(right);
249                }
250            }
251
252            crate::zigir::types::IrExpr::PowExpr {
253                base,
254                exp,
255                base_type,
256                exp_type,
257                result_type,
258            } => {
259                // JS `**` always returns f64. Use std.math.pow(f64, ...) with
260                // temporary f64 variables in a labeled block.
261                let pow_id = self.peek_label_id();
262                let blk = self.next_label();
263                // If result_type is i64, wrap the entire block in @as(i64, @intFromFloat(...))
264                if let Some(crate::types::ZigType::I64) = result_type {
265                    self.write("@as(i64, @intFromFloat(");
266                }
267                self.write(&format!("({blk}: {{ "));
268                self.write(&format!("const _base_f64_{pow_id}: f64 = "));
269                self.emit_float_conversion(base, base_type);
270                self.write(&format!("; const _exp_f64_{pow_id}: f64 = "));
271                self.emit_float_conversion(exp, exp_type);
272                self.write(&format!(
273                    "; break :{blk} std.math.pow(f64, _base_f64_{pow_id}, _exp_f64_{pow_id}); }})",
274                ));
275                if let Some(crate::types::ZigType::I64) = result_type {
276                    self.write("))");
277                }
278            }
279
280            crate::zigir::types::IrExpr::Unary { op, operand } => {
281                match op {
282                    crate::zigir::ops::UnaOp::Neg => {
283                        self.write("-");
284                        self.emit_expr(operand);
285                    }
286                    crate::zigir::ops::UnaOp::Not => {
287                        self.write("!");
288                        // Coerce operand to bool first — JS `!x` works on any type,
289                        // but Zig `!` requires a bool operand.
290                        self.emit_expr_as_bool(operand);
291                    }
292                    crate::zigir::ops::UnaOp::BitNot => {
293                        // JS `~x` operates on 32-bit integer. Wrap in @as(i32, @intCast(..))
294                        // to handle comptime_int and ensure correct 32-bit semantics.
295                        self.write("~@as(i32, @intCast(");
296                        self.emit_expr(operand);
297                        self.write("))");
298                    }
299                    crate::zigir::ops::UnaOp::TypeOf => {
300                        // typeof expr → simplified; real impl depends on type
301                        self.write("\"undefined\""); // placeholder
302                        let _ = operand; // suppress warning
303                    }
304                    crate::zigir::ops::UnaOp::Void => {
305                        // void expr → evaluate and discard
306                        self.emit_expr(operand);
307                    }
308                    crate::zigir::ops::UnaOp::Delete => {
309                        // delete is a no-op in this context
310                        let _ = operand;
311                    }
312                }
313            }
314
315            crate::zigir::types::IrExpr::Logical { op, left, right } => {
316                // Zig `and`/`or` require bool operands. Coerce operands with
317                // truthiness if they are not already bool.
318                self.write("(");
319                self.emit_expr_as_bool(left);
320                self.write(&format!(" {} ", logical_op_to_zig(*op)));
321                self.emit_expr_as_bool(right);
322                self.write(")");
323            }
324
325            crate::zigir::types::IrExpr::Update {
326                op,
327                target,
328                is_expr_stmt,
329            } => {
330                if *is_expr_stmt {
331                    // Statement context: `i += 1` (no parens, no _ = prefix)
332                    self.emit_assign_target_inner(target);
333                    self.write(&format!(" {}", update_op_to_zig(*op)));
334                } else {
335                    // Expression context: `({blk}: { ... break :blk old_val })`
336                    self.write("(");
337                    self.emit_assign_target_inner(target);
338                    self.write(&format!(" {}", update_op_to_zig(*op)));
339                    self.write(")");
340                }
341            }
342
343            crate::zigir::types::IrExpr::Assign { op, target, value } => {
344                use crate::zigir::ops::AssignOp;
345                if *op == AssignOp::Mod {
346                    // Zig doesn't support % on signed integers; use x = @rem(x, y)
347                    self.emit_assign_target_inner(target);
348                    self.write(" = @rem(");
349                    self.emit_assign_target_inner(target);
350                    self.write(", ");
351                    self.emit_expr(value);
352                    self.write(")");
353                } else if *op == AssignOp::Div {
354                    // Zig signed integer division requires @divTrunc
355                    self.emit_assign_target_inner(target);
356                    self.write(" = @divTrunc(");
357                    self.emit_assign_target_inner(target);
358                    self.write(", ");
359                    self.emit_expr(value);
360                    self.write(")");
361                } else if *op == AssignOp::LogicAnd {
362                    // a &&= b → a = if (a.toBool()) b else a
363                    self.emit_assign_target_inner(target);
364                    self.write(" = if (");
365                    self.emit_assign_target_inner(target);
366                    self.write(".toBool()) ");
367                    self.emit_expr(value);
368                    self.write(" else ");
369                    self.emit_assign_target_inner(target);
370                } else if *op == AssignOp::LogicOr {
371                    // a ||= b → a = if (!a.toBool()) b else a
372                    self.emit_assign_target_inner(target);
373                    self.write(" = if (!");
374                    self.emit_assign_target_inner(target);
375                    self.write(".toBool()) ");
376                    self.emit_expr(value);
377                    self.write(" else ");
378                    self.emit_assign_target_inner(target);
379                } else if *op == AssignOp::Nullish {
380                    // a ??= b → a = if (a.isNullish()) b else a
381                    self.emit_assign_target_inner(target);
382                    self.write(" = if (");
383                    self.emit_assign_target_inner(target);
384                    self.write(".isNullish()) ");
385                    self.emit_expr(value);
386                    self.write(" else ");
387                    self.emit_assign_target_inner(target);
388                } else {
389                    self.emit_assign_target_inner(target);
390                    self.write(&format!(" {} ", assign_op_to_zig(*op)));
391                    self.emit_expr(value);
392                }
393            }
394
395            // ── Calls ───────────────────────────────
396            crate::zigir::types::IrExpr::Call(call) => {
397                self.emit_call_expr(call);
398            }
399
400            crate::zigir::types::IrExpr::BuiltinCall(bc) => {
401                self.emit_builtin_call(bc);
402            }
403
404            crate::zigir::types::IrExpr::HostCall(hc) => {
405                self.write(&format!("host.{}", hc.name));
406                self.emit_args(&hc.args);
407            }
408
409            // ── Member access ───────────────────────
410            crate::zigir::types::IrExpr::FieldAccess {
411                object,
412                field,
413                field_kind,
414            } => {
415                self.emit_field_access(object, field, field_kind);
416            }
417
418            crate::zigir::types::IrExpr::IndexAccess {
419                object,
420                index,
421                index_kind,
422            } => {
423                self.emit_index_access(object, index, index_kind);
424            }
425
426            crate::zigir::types::IrExpr::ComputedField {
427                object,
428                key,
429                key_kind,
430            } => {
431                self.emit_computed_field(object, key, key_kind);
432            }
433
434            // ── Object / Array ──────────────────────
435            crate::zigir::types::IrExpr::ArrayLiteral(arr) => {
436                self.emit_array_literal(arr);
437            }
438
439            crate::zigir::types::IrExpr::ObjectLiteral(obj) => {
440                self.emit_object_literal(obj);
441            }
442
443            // ── Function expressions ────────────────
444            // NOTE: Dead code path — Lowerer always converts ArrowFn to IrExpr::Ident
445            // + pending_arrow_structs. Kept as defensive fallback.
446            crate::zigir::types::IrExpr::ArrowFn(arrow) => {
447                // Arrow fn at expression level: emit inline struct
448                self.writeln(&format!("const {} = struct {{", arrow_name_placeholder()));
449                self.indent_push();
450                let ret = arrow.return_type.to_zig_type();
451                let mut sig = String::from("pub fn call(");
452                for (i, param) in arrow.params.iter().enumerate() {
453                    if i > 0 {
454                        sig.push_str(", ");
455                    }
456                    sig.push_str(&format_param_with_rest(
457                        &param.name,
458                        &param.zig_type,
459                        param.is_rest,
460                    ));
461                }
462                sig.push_str(&format!(") {} {{", ret));
463                self.writeln(&sig);
464                self.indent_push();
465                // Body
466                if arrow.is_concise {
467                    self.write_indent();
468                    self.write("return ");
469                    if let Some(stmt) = arrow.body.stmts.first()
470                        && let crate::zigir::types::IrStmt::Expr(e) = stmt
471                    {
472                        self.emit_expr(e);
473                    }
474                    self.write(";\n");
475                } else {
476                    for stmt in &arrow.body.stmts {
477                        self.emit_stmt(stmt);
478                    }
479                }
480                self.indent_pop();
481                self.writeln("}");
482                self.indent_pop();
483                self.writeln("};");
484            }
485
486            crate::zigir::types::IrExpr::Closure(closure) => {
487                // Closure instance: `StructName { .captured = val, ... }`
488                self.write(&closure.struct_name.zig_name);
489                self.write("{ ");
490                for (i, cap) in closure.captured.iter().enumerate() {
491                    if i > 0 {
492                        self.write(", ");
493                    }
494                    if cap.is_mut {
495                        self.write(&format!(".{} = &{}", cap.name.zig_name, cap.name.zig_name));
496                    } else {
497                        self.write(&format!(".{} = {}", cap.name.zig_name, cap.name.zig_name));
498                    }
499                }
500                self.write(" }");
501            }
502
503            crate::zigir::types::IrExpr::FnExpr(fn_expr) => {
504                // Function expression: emit as struct with call method
505                let name = fn_expr
506                    .name
507                    .as_ref()
508                    .map(|n| n.zig_name.clone())
509                    .unwrap_or_else(|| "_fn_expr".to_string());
510                self.write(&name);
511            }
512
513            // ── Conditional / template ───────────────
514            crate::zigir::types::IrExpr::Conditional { cond, then, else_ } => {
515                self.write("if (");
516                self.emit_expr_as_bool(cond);
517                self.write(") ");
518                self.emit_expr(then);
519                self.write(" else ");
520                self.emit_expr(else_);
521            }
522
523            crate::zigir::types::IrExpr::TemplateLiteral {
524                parts,
525                exprs,
526                format_specs,
527            } => {
528                self.emit_template_literal(parts, exprs, format_specs);
529            }
530
531            // ── Async ───────────────────────────────
532            crate::zigir::types::IrExpr::Await(await_expr) => {
533                // Emit: (blk: { var _tN = io.async(callee, .{ io, args... }); defer _ = _tN.cancel(io) catch undefined; break :blk try _tN.await(io); })
534                self.write(&format!("({}: {{\n", await_expr.block_label));
535                self.indent_push();
536                self.write_indent();
537                self.write(&format!("var {} = io.async(", await_expr.task_var.zig_name));
538
539                if await_expr.is_host_async {
540                    // For host async, callee is an Ident holding the host fn name
541                    if let crate::zigir::types::IrExpr::Ident(id) = &*await_expr.callee {
542                        self.write(&format!("host.{}_async", id.zig_name));
543                    } else {
544                        // Fallback
545                        self.emit_expr(&await_expr.callee);
546                    }
547                } else {
548                    self.emit_expr(&await_expr.callee);
549                }
550
551                self.write(", .{ io");
552                for arg in &await_expr.args {
553                    self.write(", ");
554                    self.emit_expr(arg);
555                }
556                self.write(" });\n");
557
558                self.write_indent();
559                self.write(&format!(
560                    "defer _ = {}.cancel(io) catch undefined;\n",
561                    await_expr.task_var.zig_name
562                ));
563
564                self.write_indent();
565                self.write(&format!(
566                    "break :{} try {}.await(io);\n",
567                    await_expr.block_label, await_expr.task_var.zig_name
568                ));
569
570                self.indent_pop();
571                self.write_indent();
572                self.write("})");
573            }
574
575            // ── Construction ────────────────────────
576            crate::zigir::types::IrExpr::New(new_expr) => {
577                self.emit_new_expr(new_expr);
578            }
579
580            // ── String formatting ──────────────────────
581            crate::zigir::types::IrExpr::AllocPrint { fmt, args } => {
582                if args.is_empty() {
583                    // Pure-text → plain string literal (no allocation)
584                    let unescaped = fmt.replace("{{", "{").replace("}}", "}");
585                    self.write(&format!("\"{}\"", unescaped));
586                } else {
587                    // Emit args by capturing each as a string
588                    let arg_strs: Vec<String> = args
589                        .iter()
590                        .map(|arg| {
591                            let saved = std::mem::take(self.output_mut());
592                            self.emit_expr(arg);
593                            let rendered = std::mem::take(self.output_mut());
594                            *self.output_mut() = saved;
595                            rendered
596                        })
597                        .collect();
598                    let args_str = format!(".{{{}}}", arg_strs.join(", "));
599                    self.write(&format!(
600                        "std.fmt.allocPrint(js_allocator.allocator(), \"{}\", {}) catch @panic(\"OOM: template literal allocPrint\")",
601                        fmt, args_str
602                    ));
603                }
604            }
605
606            // ── Block expression ────────────────────
607            crate::zigir::types::IrExpr::BlockExpr {
608                label,
609                body,
610                result,
611            } => {
612                self.write(&format!("({}: {{", label));
613                for stmt in body {
614                    self.emit_stmt(stmt);
615                }
616                self.write("break :");
617                self.write(label);
618                self.write(" ");
619                self.emit_expr(result);
620                self.write("}})");
621            }
622
623            // ── Special ─────────────────────────────
624            crate::zigir::types::IrExpr::Spread(inner) => {
625                self.emit_expr(inner);
626            }
627
628            crate::zigir::types::IrExpr::Typeof(inner) => {
629                // typeof on identifiers with known types is resolved at lower time
630                // to StringLiteral. This branch handles any remaining typeof
631                // expressions (shouldn't occur with current lowerer, but as fallback).
632                self.write("js_runtime.jsTypeof(");
633                self.emit_expr(inner);
634                self.write(")");
635            }
636
637            crate::zigir::types::IrExpr::Void(inner) => {
638                // void expr: evaluate expr for side effects, return undefined.
639                // Output: blk_N: { _ = expr; break :blk_N JsAny.fromUndefined(); }
640                let label = self.next_label();
641                self.write(&format!("{}: {{ _ = ", label));
642                self.emit_expr(inner);
643                self.write(&format!("; break :{} JsAny.fromUndefined(); }}", label));
644            }
645
646            crate::zigir::types::IrExpr::Paren(inner) => {
647                self.write("(");
648                self.emit_expr(inner);
649                self.write(")");
650            }
651
652            crate::zigir::types::IrExpr::Sequence(exprs) => {
653                for (i, e) in exprs.iter().enumerate() {
654                    if i > 0 {
655                        self.write(", ");
656                    }
657                    self.emit_expr(e);
658                }
659            }
660
661            crate::zigir::types::IrExpr::ArrayCallbackInline(inline_data) => {
662                self.emit_array_callback_inline(inline_data);
663            }
664
665            crate::zigir::types::IrExpr::ArrayMethodInline(inline_data) => {
666                self.emit_array_method_inline(inline_data);
667            }
668
669            crate::zigir::types::IrExpr::OptionalChain {
670                object,
671                capture_var,
672                body,
673                needs_null_check,
674            } => {
675                if *needs_null_check {
676                    self.write("(if (");
677                    self.emit_expr(object);
678                    self.write(") |");
679                    self.write(capture_var);
680                    self.write("| ");
681                    self.emit_expr(body);
682                    self.write(" else null)");
683                } else {
684                    self.emit_expr(body);
685                }
686            }
687
688            crate::zigir::types::IrExpr::CompileError { span, msg } => {
689                let loc = format!("{}:{}", span.js_line, span.js_col);
690                self.write(&format!(
691                    "@compileError(\"{} (at {})\")",
692                    escape_zig_string(msg),
693                    loc
694                ));
695            }
696        }
697    }
698
699    /// Convert an expression to a string without writing to the output buffer.
700    /// Used for contexts where we need the expression text as a value.
701    pub(crate) fn expr_to_string(&mut self, expr: &crate::zigir::types::IrExpr) -> String {
702        let saved_output = std::mem::take(&mut self.output);
703        self.emit_expr(expr);
704        let result = std::mem::take(&mut self.output);
705        self.output = saved_output;
706        result
707    }
708
709    // ── Internal helpers ───────────────────────────
710
711    pub(super) fn emit_assign_target_inner(
712        &mut self,
713        target: &crate::zigir::types::IrAssignTarget,
714    ) {
715        match target {
716            crate::zigir::types::IrAssignTarget::Ident(ident) => {
717                self.write(&ident.zig_name);
718            }
719            crate::zigir::types::IrAssignTarget::Member {
720                object,
721                field,
722                is_pointer,
723            } => {
724                self.emit_expr(object);
725                if *is_pointer {
726                    self.write(&format!(".{}.*", field));
727                } else {
728                    self.write(&format!(".{}", field));
729                }
730            }
731            crate::zigir::types::IrAssignTarget::Index { object, index } => {
732                self.emit_expr(object);
733                self.write("[");
734                self.emit_expr(index);
735                self.write("]");
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        }
750    }
751
752    pub(super) fn emit_args(&mut self, args: &[crate::zigir::types::IrExpr]) {
753        self.write("(");
754        for (i, arg) in args.iter().enumerate() {
755            if i > 0 {
756                self.write(", ");
757            }
758            // foo(...args) → foo(args.items)
759            if let crate::zigir::types::IrExpr::Spread(inner) = arg {
760                self.emit_expr(inner);
761                self.write(".items");
762            } else {
763                self.emit_expr(arg);
764            }
765        }
766        self.write(")");
767    }
768
769    /// Check if an IrExpr is definitely of type `bool`.
770    pub(super) fn ir_expr_is_bool(expr: &crate::zigir::types::IrExpr) -> bool {
771        use crate::zigir::ops::BinOp;
772        use crate::zigir::types::IrExpr;
773
774        match expr {
775            IrExpr::BoolLiteral(_) => true,
776            IrExpr::Logical { .. } => true,
777            IrExpr::Unary {
778                op: crate::zigir::ops::UnaOp::Not | crate::zigir::ops::UnaOp::Delete,
779                ..
780            } => true,
781            IrExpr::Binary { op, .. } => matches!(
782                op,
783                BinOp::Eq
784                    | BinOp::Ne
785                    | BinOp::StrictEq
786                    | BinOp::StrictNe
787                    | BinOp::Lt
788                    | BinOp::Le
789                    | BinOp::Gt
790                    | BinOp::Ge
791                    | BinOp::In
792                    | BinOp::InstanceOf
793            ),
794            _ => false,
795        }
796    }
797
798    /// Emit an expression with truthiness coercion for Zig `bool` context.
799    ///
800    /// When a non-bool expression appears in a position that Zig requires `bool`
801    /// (e.g. `if` condition, `while` condition), we coerce via `js_runtime.isTruthy()`
802    /// which handles all JS types correctly (bool, i64, f64, string, comptime_int, etc.).
803    pub(crate) fn emit_expr_as_bool(&mut self, expr: &crate::zigir::types::IrExpr) {
804        if Self::ir_expr_is_bool(expr) {
805            self.emit_expr(expr);
806        } else {
807            self.write("js_runtime.isTruthy(");
808            self.emit_expr(expr);
809            self.write(")");
810        }
811    }
812}
813
814/// Map TypedArrayKind to (module, init_fn) for construction.
815/// Uses fromI64AsI8/fromI64AsU8/.../fromF64 series instead of direct .init().
816pub(super) fn typed_array_init(
817    kind: &crate::zigir::kinds::TypedArrayKind,
818) -> (&'static str, &'static str) {
819    use crate::zigir::kinds::TypedArrayKind;
820    match kind {
821        TypedArrayKind::Int8Array => ("js_runtime.js_typedarray", "fromI64AsI8"),
822        TypedArrayKind::Uint8Array => ("js_runtime.js_typedarray", "fromI64AsU8"),
823        TypedArrayKind::Uint8ClampedArray => ("js_runtime.js_typedarray", "fromI64AsU8"),
824        TypedArrayKind::Int16Array => ("js_runtime.js_typedarray", "fromI64AsI16"),
825        TypedArrayKind::Uint16Array => ("js_runtime.js_typedarray", "fromI64AsU16"),
826        TypedArrayKind::Int32Array => ("js_runtime.js_typedarray", "fromI64AsI32"),
827        TypedArrayKind::Uint32Array => ("js_runtime.js_typedarray", "fromI64AsU32"),
828        TypedArrayKind::Float32Array => ("js_runtime.js_typedarray", "fromF64AsF32"),
829        TypedArrayKind::Float64Array => ("js_runtime.js_typedarray", "fromF64"),
830        TypedArrayKind::BigInt64Array => ("js_runtime.js_typedarray", "fromI64AsI64"),
831        TypedArrayKind::BigUint64Array => ("js_runtime.js_typedarray", "fromI64AsU64"),
832    }
833}
834
835fn arrow_name_placeholder() -> String {
836    "_arrow_fn".to_string()
837}