Skip to main content

js2zig_core/zigir/emit/expr/
binary.rs

1// zigir/emit/expr/binary.rs
2// Binary operation helpers: float conversion, BigInt, String, and JsAny comparisons.
3
4use crate::zigir::emit::Emitter;
5use crate::zigir::emit::helpers::EmitterHelpers;
6
7// ═══════════════════════════════════════════════════════
8//  Float conversion helpers for PowExpr
9// ═══════════════════════════════════════════════════════
10
11impl Emitter {
12    /// Emit a float conversion for a `PowExpr` operand.
13    /// - F64: emit directly
14    /// - I64/BigInt: wrap in `@as(f64, @floatFromInt(...))`
15    /// - JsAny: call `.asF64()` (preserves the JsAny value's float payload)
16    /// - Other: wrap in `@as(f64, ...)` (comptime_int, bool, etc.)
17    pub(super) fn emit_float_conversion(
18        &mut self,
19        expr: &crate::zigir::types::IrExpr,
20        ty: &crate::types::ZigType,
21    ) {
22        match ty {
23            crate::types::ZigType::F64 => {
24                self.emit_expr(expr);
25            }
26            crate::types::ZigType::I64 | crate::types::ZigType::BigInt => {
27                self.write("@as(f64, @floatFromInt(");
28                self.emit_expr(expr);
29                self.write("))");
30            }
31            crate::types::ZigType::JsAny => {
32                self.emit_expr(expr);
33                self.write(".asF64()");
34            }
35            _ => {
36                // comptime_int, bool, or unknown — @as(f64, expr) works for comptime_int
37                self.write("@as(f64, ");
38                self.emit_expr(expr);
39                self.write(")");
40            }
41        }
42    }
43
44    /// Emit a default binary operator: `(left OP right)`.
45    /// Shared by bigint/string/jsany fallback and the main Binary dispatch in mod.rs.
46    ///
47    /// The outer parentheses are MANDATORY: JS and Zig disagree on operator
48    /// precedence for some operator pairs (most notably, JS `+` > `<<` but
49    /// Zig `<<` > `+`). Without wrapping each binary expression in parens,
50    /// flat emission like `a + b << c` would be re-parsed by Zig with
51    /// different grouping than the JS AST intended.
52    pub(super) fn emit_default_binop(
53        &mut self,
54        op: crate::zigir::ops::BinOp,
55        left: &crate::zigir::types::IrExpr,
56        right: &crate::zigir::types::IrExpr,
57    ) {
58        self.write("(");
59        self.emit_expr(left);
60        self.write(&format!(
61            " {} ",
62            crate::zigir::emit::helpers::bin_op_to_zig(op)
63        ));
64        self.emit_expr(right);
65        self.write(")");
66    }
67
68    /// Emit an ordering comparison: `(order_expr == .lt)` / `!= .gt` etc.
69    /// `order_expr_fn` emits the expression that yields `std.math.Order`.
70    pub(super) fn emit_order_cmp<F>(&mut self, op: crate::zigir::ops::BinOp, order_expr_fn: F)
71    where
72        F: FnOnce(&mut Self),
73    {
74        self.write("(");
75        order_expr_fn(self);
76        match op {
77            crate::zigir::ops::BinOp::Lt => self.write(" == .lt)"),
78            crate::zigir::ops::BinOp::Le => self.write(" != .gt)"),
79            crate::zigir::ops::BinOp::Gt => self.write(" == .gt)"),
80            crate::zigir::ops::BinOp::Ge => self.write(" != .lt)"),
81            _ => unreachable!("emit_order_cmp: expected Lt/Le/Gt/Ge, got {:?}", op),
82        }
83    }
84
85    /// BigInt arithmetic uses method calls like `_a.add(&_b, alloc)`.
86    pub(super) fn emit_bigint_binary(
87        &mut self,
88        op: crate::zigir::ops::BinOp,
89        left: &crate::zigir::types::IrExpr,
90        right: &crate::zigir::types::IrExpr,
91    ) {
92        use crate::zigir::ops::BinOp;
93
94        match op {
95            // Method calls: _a.op(&_b, alloc) catch ...
96            // Division/remainder may throw DivisionByZero; all others just panic on OOM.
97            BinOp::Add
98            | BinOp::Sub
99            | BinOp::Mul
100            | BinOp::BitAnd
101            | BinOp::BitOr
102            | BinOp::BitXor
103            | BinOp::Div
104            | BinOp::Mod => {
105                let (method, label) = match op {
106                    BinOp::Add => ("add", "add"),
107                    BinOp::Sub => ("sub", "sub"),
108                    BinOp::Mul => ("mul", "mul"),
109                    BinOp::BitAnd => ("bitwiseAnd", "and"),
110                    BinOp::BitOr => ("bitwiseOr", "or"),
111                    BinOp::BitXor => ("bitwiseXor", "xor"),
112                    BinOp::Div => ("div", "div"),
113                    BinOp::Mod => ("rem", "rem"),
114                    _ => unreachable!("emit_bigint_binary: unsupported BigInt op {:?}", op),
115                };
116                self.write("(");
117                self.emit_expr(left);
118                self.write(&format!(".{}(&", method));
119                self.emit_expr(right);
120                self.write(", js_allocator.allocator()) catch ");
121                if matches!(op, BinOp::Div | BinOp::Mod) {
122                    if let Some(try_label) = &self.inside_try_block {
123                        self.write(&format!(
124                            "|err| switch (err) {{ error.DivisionByZero => break :{} @as(anyerror!void, error.JsThrow), else => @panic(\"BigInt {} OOM\") }})",
125                            try_label, label
126                        ));
127                    } else {
128                        self.write(&format!(
129                            "|err| switch (err) {{ error.DivisionByZero => return error.JsThrow, else => @panic(\"BigInt {} OOM\") }})",
130                            label
131                        ));
132                    }
133                } else {
134                    self.write(&format!("@panic(\"BigInt {} OOM\"))", label));
135                }
136            }
137            BinOp::Pow => {
138                self.write("(");
139                self.emit_expr(left);
140                self.write(".pow(");
141                self.emit_expr(right);
142                // `BigInt.pow` returns `error.RangeError` when `exp > maxInt(u32)`
143                // (R8 P0-4); converting to `error.JsThrow` lets the surrounding
144                // try-catch machinery surface it as a JS TypeError instead of
145                // a Zig runtime panic.
146                if let Some(try_label) = &self.inside_try_block {
147                    self.write(&format!(
148                        ".toU64() catch break :{} @as(anyerror!void, error.JsThrow), js_allocator.allocator()) catch |err| switch (err) {{ error.RangeError => break :{} @as(anyerror!void, error.JsThrow), else => @panic(\"BigInt pow OOM\") }})",
149                        try_label, try_label
150                    ));
151                } else {
152                    self.write(".toU64() catch return error.JsThrow, js_allocator.allocator()) catch |err| switch (err) { error.RangeError => return error.JsThrow, else => @panic(\"BigInt pow OOM\") })");
153                }
154            }
155            BinOp::Shl | BinOp::Shr => {
156                let (method, label) = match op {
157                    BinOp::Shl => ("shiftLeft", "shl"),
158                    BinOp::Shr => ("shiftRight", "shr"),
159                    _ => unreachable!("emit_bigint_binary: unsupported shift op {:?}", op),
160                };
161                self.write("(");
162                self.emit_expr(left);
163                self.write(&format!(".{}(", method));
164                self.emit_expr(right);
165                if let Some(try_label) = &self.inside_try_block {
166                    self.write(&format!(
167                        ".toI64() catch break :{} @as(anyerror!void, error.JsThrow), js_allocator.allocator()) catch @panic(\"BigInt {} OOM\"))",
168                        try_label, label
169                    ));
170                } else {
171                    self.write(&format!(
172                        ".toI64() catch return error.JsThrow, js_allocator.allocator()) catch @panic(\"BigInt {} OOM\"))",
173                        label
174                    ));
175                }
176            }
177            // Equality
178            BinOp::Eq | BinOp::StrictEq | BinOp::Ne | BinOp::StrictNe => {
179                let negate = matches!(op, BinOp::Ne | BinOp::StrictNe);
180                if negate {
181                    self.write("!");
182                }
183                self.emit_expr(left);
184                self.write(".eq(&");
185                self.emit_expr(right);
186                self.write(")");
187            }
188            // Ordering
189            BinOp::Lt | BinOp::Le | BinOp::Gt | BinOp::Ge => {
190                let left_clone = left.clone();
191                let right_clone = right.clone();
192                self.emit_order_cmp(op, |emitter| {
193                    emitter.emit_expr(&left_clone);
194                    emitter.write(".order(&");
195                    emitter.emit_expr(&right_clone);
196                    emitter.write(")");
197                });
198            }
199            // >>> is not supported for BigInt (JS throws TypeError at runtime)
200            BinOp::UrShr => {
201                if let Some(label) = &self.inside_try_block {
202                    self.write(&format!(
203                        "({{ break :{} @as(anyerror!void, error.JsThrow); }})",
204                        label
205                    ));
206                } else {
207                    self.write("({ return error.JsThrow; })");
208                }
209            }
210            _ => {
211                self.emit_default_binop(op, left, right);
212            }
213        }
214    }
215
216    /// Emit a String comparison operation.
217    pub(super) fn emit_string_comparison(
218        &mut self,
219        op: crate::zigir::ops::BinOp,
220        left: &crate::zigir::types::IrExpr,
221        right: &crate::zigir::types::IrExpr,
222    ) {
223        use crate::zigir::ops::BinOp;
224        match op {
225            BinOp::Eq | BinOp::StrictEq | BinOp::Ne | BinOp::StrictNe => {
226                let negate = matches!(op, BinOp::Ne | BinOp::StrictNe);
227                if negate {
228                    self.write("(!");
229                }
230                self.write("std.mem.eql(u8, ");
231                self.emit_expr(left);
232                self.write(", ");
233                self.emit_expr(right);
234                self.write(")");
235                if negate {
236                    self.write(")");
237                }
238            }
239            BinOp::Lt | BinOp::Le | BinOp::Gt | BinOp::Ge => {
240                let left_clone = left.clone();
241                let right_clone = right.clone();
242                self.emit_order_cmp(op, |emitter| {
243                    emitter.write("std.mem.order(u8, ");
244                    emitter.emit_expr(&left_clone);
245                    emitter.write(", ");
246                    emitter.emit_expr(&right_clone);
247                    emitter.write(")");
248                });
249            }
250            _ => {
251                self.emit_default_binop(op, left, right);
252            }
253        }
254    }
255
256    /// Emit a JsAny comparison operation.
257    /// JsAny equality uses .eq()/.strictEq(), ordering uses .asF64() (preserves
258    /// float precision since JS numbers are doubles).
259    /// Emit an expression, optionally wrapping it in `JsAny.from()` if it
260    /// is not already a JsAny-typed value.
261    fn emit_expr_as_jsany(&mut self, expr: &crate::zigir::types::IrExpr, is_jsany: bool) {
262        if is_jsany {
263            self.emit_expr(expr);
264        } else {
265            self.write("JsAny.from(");
266            self.emit_expr(expr);
267            self.write(")");
268        }
269    }
270
271    /// Emit a JsAny arithmetic operation.
272    ///
273    /// Coerces JsAny side(s) via `.asI64()` by default (to match the inferred
274    /// integer result type for `i64 op JsAny` cases). However, when the OTHER
275    /// side has type F64, the JS result must be a float — use `.asF64()` in
276    /// that case to avoid Zig `i64 + f64` type errors AND to preserve float
277    /// precision (otherwise `5.0 + jsany` would compute `5 + jsany.asI64()`,
278    /// losing the float register and possibly truncating the JsAny value).
279    ///
280    /// The signature carries two extra type args (`left_type` / `right_type`)
281    /// so the emitter can decide `.asF64()` vs `.asI64()` based on the OTHER
282    /// side's type. Clippy's default 7-arg threshold is exceeded; suppressing
283    /// the lint here keeps the call-site (Binary dispatch in mod.rs) readable.
284    #[allow(clippy::too_many_arguments)]
285    pub(super) fn emit_jsany_arithmetic(
286        &mut self,
287        op: crate::zigir::ops::BinOp,
288        left: &crate::zigir::types::IrExpr,
289        right: &crate::zigir::types::IrExpr,
290        left_is_jsany: bool,
291        right_is_jsany: bool,
292        left_type: Option<&crate::types::ZigType>,
293        right_type: Option<&crate::types::ZigType>,
294    ) {
295        use crate::types::ZigType;
296        use crate::zigir::emit::helpers::bin_op_to_zig;
297
298        // Coercion decision: if the OTHER side is F64, use .asF64(); otherwise .asI64().
299        // The "other" side governs because Zig binary ops require both operands to
300        // share a type. If one side is f64, the other must be f64 too.
301        let left_coerce_f64 = left_is_jsany && right_type == Some(&ZigType::F64);
302        let right_coerce_f64 = right_is_jsany && left_type == Some(&ZigType::F64);
303
304        // Outer parens protect against JS/Zig operator precedence mismatches
305        // (e.g. nested `JsAny + JsAny << JsAny` would be re-grouped by Zig
306        // without the wrapping). They also ensure `.asI64()`/`.asF64()` appended
307        // after emit_expr binds to the entire sub-expression, not just the
308        // trailing token.
309        self.write("(");
310        // Left side
311        if left_is_jsany {
312            self.emit_expr(left);
313            if left_coerce_f64 {
314                self.write(".asF64()");
315            } else {
316                self.write(".asI64()");
317            }
318        } else {
319            self.emit_expr(left);
320        }
321        self.write(&format!(" {} ", bin_op_to_zig(op)));
322        // Right side
323        if right_is_jsany {
324            self.emit_expr(right);
325            if right_coerce_f64 {
326                self.write(".asF64()");
327            } else {
328                self.write(".asI64()");
329            }
330        } else {
331            self.emit_expr(right);
332        }
333        self.write(")");
334    }
335
336    pub(super) fn emit_jsany_comparison(
337        &mut self,
338        op: crate::zigir::ops::BinOp,
339        left: &crate::zigir::types::IrExpr,
340        right: &crate::zigir::types::IrExpr,
341        left_is_jsany: bool,
342        right_is_jsany: bool,
343    ) {
344        use crate::zigir::ops::BinOp;
345
346        match op {
347            // Equality: Eq/StrictEq and Ne/StrictNe share the same emit logic;
348            // only the method name (.eq vs .strictEq) and negation differ.
349            BinOp::Eq | BinOp::StrictEq | BinOp::Ne | BinOp::StrictNe => {
350                let method = match op {
351                    BinOp::StrictEq | BinOp::StrictNe => "strictEq",
352                    _ => "eq",
353                };
354                let negate = matches!(op, BinOp::Ne | BinOp::StrictNe);
355                if negate {
356                    self.write("!(");
357                }
358                self.emit_expr_as_jsany(left, left_is_jsany);
359                self.write(&format!(".{}(", method));
360                self.emit_expr_as_jsany(right, right_is_jsany);
361                self.write(")");
362                if negate {
363                    self.write(")");
364                }
365            }
366            // Ordering: delegate to JsAny runtime methods (lt/le/gt/ge).
367            // R8-P1-16: Previously inlined .asF64() which always compared
368            // numerically, making string<string always return false.
369            // The runtime methods now check isString() for lexicographic
370            // comparison before falling back to numeric asF64().
371            BinOp::Lt | BinOp::Le | BinOp::Gt | BinOp::Ge => {
372                let method = match op {
373                    BinOp::Lt => "lt",
374                    BinOp::Le => "le",
375                    BinOp::Gt => "gt",
376                    BinOp::Ge => "ge",
377                    _ => unreachable!(),
378                };
379                self.emit_expr_as_jsany(left, left_is_jsany);
380                self.write(&format!(".{}(", method));
381                self.emit_expr_as_jsany(right, right_is_jsany);
382                self.write(")");
383            }
384            _ => {
385                self.emit_default_binop(op, left, right);
386            }
387        }
388    }
389
390    /// Emit a comparison where one operand is BigInt and the other is a numeric type
391    /// (I64, F64, Bool) or StringLiteral. Convert the non-BigInt operand to JsBigInt
392    /// via fromI64 (for numeric) or JsBigInt.init (for string), then use .eq() / .order().
393    pub(super) fn emit_bigint_cross_comparison(
394        &mut self,
395        op: crate::zigir::ops::BinOp,
396        left: &crate::zigir::types::IrExpr,
397        right: &crate::zigir::types::IrExpr,
398        left_is_bigint: bool,
399        right_is_bigint: bool,
400    ) {
401        use crate::zigir::ops::BinOp;
402
403        // Emit a non-BigInt operand as JsBigInt.
404        // For StringLiteral: use JsBigInt.init(allocator, "value")
405        // For other types: use JsBigInt.fromI64(allocator, value)
406        let emit_as_bigint = |s: &mut Self, expr: &crate::zigir::types::IrExpr| {
407            if let crate::zigir::types::IrExpr::StringLiteral(val) = expr {
408                s.write("(js_bigint.JsBigInt.init(js_allocator.allocator(), \"");
409                s.write(&crate::zigir::emit::helpers::escape_zig_string(val));
410                s.write("\") catch @panic(\"OOM: BigInt init\"))");
411            } else {
412                s.write("(js_bigint.JsBigInt.fromI64(js_allocator.allocator(), ");
413                s.emit_expr(expr);
414                s.write(") catch @panic(\"BigInt fromI64 OOM\"))");
415            }
416        };
417
418        match op {
419            BinOp::Eq | BinOp::StrictEq | BinOp::Ne | BinOp::StrictNe => {
420                let negate = matches!(op, BinOp::Ne | BinOp::StrictNe);
421                if negate {
422                    self.write("!");
423                }
424                if left_is_bigint {
425                    self.emit_expr(left);
426                } else {
427                    emit_as_bigint(self, left);
428                }
429                self.write(".eq(&");
430                if right_is_bigint {
431                    self.emit_expr(right);
432                } else {
433                    emit_as_bigint(self, right);
434                }
435                self.write(")");
436            }
437            BinOp::Lt | BinOp::Le | BinOp::Gt | BinOp::Ge => {
438                let left_clone = left.clone();
439                let right_clone = right.clone();
440                self.emit_order_cmp(op, |emitter| {
441                    let cmp_expr =
442                        |s: &mut Self, is_bigint: bool, expr: &crate::zigir::types::IrExpr| {
443                            if is_bigint {
444                                s.emit_expr(expr);
445                            } else {
446                                emit_as_bigint(s, expr);
447                            }
448                        };
449                    cmp_expr(emitter, left_is_bigint, &left_clone);
450                    emitter.write(".order(&");
451                    cmp_expr(emitter, right_is_bigint, &right_clone);
452                    emitter.write(")");
453                });
454            }
455            _ => unreachable!("emit_binary: unsupported BinOp {:?}", op),
456        }
457    }
458
459    /// Emit a String + BigInt concatenation.
460    /// JS spec: `"hello" + 5n` → `"hello5"`, `5n + "hello"` → `"5hello"`.
461    /// Converts the BigInt operand to its decimal string representation,
462    /// then concatenates with the String operand using `std.fmt.allocPrint`.
463    pub(super) fn emit_bigint_string_concat(
464        &mut self,
465        left: &crate::zigir::types::IrExpr,
466        right: &crate::zigir::types::IrExpr,
467        left_is_str: bool,
468    ) {
469        // Determine which side is string and which is BigInt
470        let (str_expr, bigint_expr) = if left_is_str {
471            (left, right)
472        } else {
473            (right, left)
474        };
475        let str_on_left = left_is_str;
476
477        // Use a unique label rather than the hardcoded `blk:` so nested
478        // BigInt-string concatenations (e.g. `("a" + 1n) + 2n` if both `+`
479        // ops resolve to string concat) do not produce `redefinition of
480        // label 'blk'` in Zig.
481        let label = self.next_label();
482        self.write(&format!(
483            "({}: {{ var __buf = std.ArrayList(u8).init(js_allocator.allocator()); errdefer __buf.deinit(); ",
484            label
485        ));
486        // Write the first part
487        if str_on_left {
488            self.write("__buf.writer().print(\"{s}\", .{");
489            self.emit_expr(str_expr);
490            self.write("}) catch @panic(\"OOM: string concat\"); ");
491        } else {
492            self.write("__buf.writer().print(\"{f}\", .{");
493            self.emit_expr(bigint_expr);
494            self.write("}) catch @panic(\"OOM: bigint string concat\"); ");
495        }
496        // Write the second part
497        if str_on_left {
498            self.write("__buf.writer().print(\"{f}\", .{");
499            self.emit_expr(bigint_expr);
500            self.write("}) catch @panic(\"OOM: bigint string concat\"); ");
501        } else {
502            self.write("__buf.writer().print(\"{s}\", .{");
503            self.emit_expr(str_expr);
504            self.write("}) catch @panic(\"OOM: string concat\"); ");
505        }
506        self.write(&format!(
507            "break :{} __buf.toOwnedSlice() catch @panic(\"OOM: string concat\"); }})",
508            label
509        ));
510    }
511}