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    /// - Other: wrap in `@as(f64, ...)` (comptime_int, bool, etc.)
16    pub(super) fn emit_float_conversion(
17        &mut self,
18        expr: &crate::zigir::types::IrExpr,
19        ty: &crate::types::ZigType,
20    ) {
21        match ty {
22            crate::types::ZigType::F64 => {
23                self.emit_expr(expr);
24            }
25            crate::types::ZigType::I64 | crate::types::ZigType::BigInt => {
26                self.write("@as(f64, @floatFromInt(");
27                self.emit_expr(expr);
28                self.write("))");
29            }
30            _ => {
31                // comptime_int, bool, or unknown — @as(f64, expr) works for comptime_int
32                self.write("@as(f64, ");
33                self.emit_expr(expr);
34                self.write(")");
35            }
36        }
37    }
38
39    /// Emit a default binary operator: `left OP right` (no parens).
40    /// Shared by bigint/string/jsany fallback and the main Binary dispatch in mod.rs.
41    pub(super) fn emit_default_binop(
42        &mut self,
43        op: crate::zigir::ops::BinOp,
44        left: &crate::zigir::types::IrExpr,
45        right: &crate::zigir::types::IrExpr,
46    ) {
47        self.emit_expr(left);
48        self.write(&format!(
49            " {} ",
50            crate::zigir::emit::helpers::bin_op_to_zig(op)
51        ));
52        self.emit_expr(right);
53    }
54
55    /// Emit an ordering comparison: `(order_expr == .lt)` / `!= .gt` etc.
56    /// `order_expr_fn` emits the expression that yields `std.math.Order`.
57    pub(super) fn emit_order_cmp<F>(&mut self, op: crate::zigir::ops::BinOp, order_expr_fn: F)
58    where
59        F: FnOnce(&mut Self),
60    {
61        self.write("(");
62        order_expr_fn(self);
63        match op {
64            crate::zigir::ops::BinOp::Lt => self.write(" == .lt)"),
65            crate::zigir::ops::BinOp::Le => self.write(" != .gt)"),
66            crate::zigir::ops::BinOp::Gt => self.write(" == .gt)"),
67            crate::zigir::ops::BinOp::Ge => self.write(" != .lt)"),
68            _ => unreachable!("emit_order_cmp: expected Lt/Le/Gt/Ge, got {:?}", op),
69        }
70    }
71
72    /// BigInt arithmetic uses method calls like `_a.add(&_b, alloc)`.
73    pub(super) fn emit_bigint_binary(
74        &mut self,
75        op: crate::zigir::ops::BinOp,
76        left: &crate::zigir::types::IrExpr,
77        right: &crate::zigir::types::IrExpr,
78    ) {
79        use crate::zigir::ops::BinOp;
80
81        match op {
82            // Method calls: _a.op(&_b, alloc) catch ...
83            // Division/remainder may throw DivisionByZero; all others just panic on OOM.
84            BinOp::Add
85            | BinOp::Sub
86            | BinOp::Mul
87            | BinOp::BitAnd
88            | BinOp::BitOr
89            | BinOp::BitXor
90            | BinOp::Div
91            | BinOp::Mod => {
92                let (method, label) = match op {
93                    BinOp::Add => ("add", "add"),
94                    BinOp::Sub => ("sub", "sub"),
95                    BinOp::Mul => ("mul", "mul"),
96                    BinOp::BitAnd => ("bitwiseAnd", "and"),
97                    BinOp::BitOr => ("bitwiseOr", "or"),
98                    BinOp::BitXor => ("bitwiseXor", "xor"),
99                    BinOp::Div => ("div", "div"),
100                    BinOp::Mod => ("rem", "rem"),
101                    _ => unreachable!("emit_bigint_binary: unsupported BigInt op {:?}", op),
102                };
103                self.write("(");
104                self.emit_expr(left);
105                self.write(&format!(".{}(&", method));
106                self.emit_expr(right);
107                self.write(", js_allocator.allocator()) catch ");
108                if matches!(op, BinOp::Div | BinOp::Mod) {
109                    self.write(&format!(
110                        "|err| switch (err) {{ error.DivisionByZero => return error.JsThrow, else => @panic(\"BigInt {} OOM\") }})",
111                        label
112                    ));
113                } else {
114                    self.write(&format!("@panic(\"BigInt {} OOM\"))", label));
115                }
116            }
117            BinOp::Pow => {
118                self.write("(");
119                self.emit_expr(left);
120                self.write(".pow(");
121                self.emit_expr(right);
122                self.write(".toU64() catch return error.JsThrow, js_allocator.allocator()) catch @panic(\"BigInt pow OOM\"))");
123            }
124            BinOp::Shl | BinOp::Shr => {
125                let (method, label) = match op {
126                    BinOp::Shl => ("shiftLeft", "shl"),
127                    BinOp::Shr => ("shiftRight", "shr"),
128                    _ => unreachable!("emit_bigint_binary: unsupported shift op {:?}", op),
129                };
130                self.write("(");
131                self.emit_expr(left);
132                self.write(&format!(".{}(", method));
133                self.emit_expr(right);
134                self.write(&format!(
135                    ".toI64() catch return error.JsThrow, js_allocator.allocator()) catch @panic(\"BigInt {} OOM\"))",
136                    label
137                ));
138            }
139            // Equality
140            BinOp::Eq | BinOp::StrictEq | BinOp::Ne | BinOp::StrictNe => {
141                let negate = matches!(op, BinOp::Ne | BinOp::StrictNe);
142                if negate {
143                    self.write("!");
144                }
145                self.emit_expr(left);
146                self.write(".eq(&");
147                self.emit_expr(right);
148                self.write(")");
149            }
150            // Ordering
151            BinOp::Lt | BinOp::Le | BinOp::Gt | BinOp::Ge => {
152                let left_clone = left.clone();
153                let right_clone = right.clone();
154                self.emit_order_cmp(op, |emitter| {
155                    emitter.emit_expr(&left_clone);
156                    emitter.write(".order(&");
157                    emitter.emit_expr(&right_clone);
158                    emitter.write(")");
159                });
160            }
161            // >>> is not supported for BigInt (JS throws TypeError at runtime)
162            BinOp::UrShr => {
163                self.write(
164                    "({ return error.JsThrow; })",
165                );
166            }
167            _ => {
168                self.emit_default_binop(op, left, right);
169            }
170        }
171    }
172
173    /// Emit a String comparison operation.
174    pub(super) fn emit_string_comparison(
175        &mut self,
176        op: crate::zigir::ops::BinOp,
177        left: &crate::zigir::types::IrExpr,
178        right: &crate::zigir::types::IrExpr,
179    ) {
180        use crate::zigir::ops::BinOp;
181        match op {
182            BinOp::Eq | BinOp::StrictEq | BinOp::Ne | BinOp::StrictNe => {
183                let negate = matches!(op, BinOp::Ne | BinOp::StrictNe);
184                if negate {
185                    self.write("(!");
186                }
187                self.write("std.mem.eql(u8, ");
188                self.emit_expr(left);
189                self.write(", ");
190                self.emit_expr(right);
191                self.write(")");
192                if negate {
193                    self.write(")");
194                }
195            }
196            BinOp::Lt | BinOp::Le | BinOp::Gt | BinOp::Ge => {
197                let left_clone = left.clone();
198                let right_clone = right.clone();
199                self.emit_order_cmp(op, |emitter| {
200                    emitter.write("std.mem.order(u8, ");
201                    emitter.emit_expr(&left_clone);
202                    emitter.write(", ");
203                    emitter.emit_expr(&right_clone);
204                    emitter.write(")");
205                });
206            }
207            _ => {
208                self.emit_default_binop(op, left, right);
209            }
210        }
211    }
212
213    /// Emit a JsAny comparison operation.
214    /// JsAny equality uses .eq()/.strictEq(), ordering uses .asI64().
215    /// Emit an expression, optionally wrapping it in `JsAny.from()` if it
216    /// is not already a JsAny-typed value.
217    fn emit_expr_as_jsany(&mut self, expr: &crate::zigir::types::IrExpr, is_jsany: bool) {
218        if is_jsany {
219            self.emit_expr(expr);
220        } else {
221            self.write("JsAny.from(");
222            self.emit_expr(expr);
223            self.write(")");
224        }
225    }
226
227    /// Emit an expression as `.asI64()`, wrapping with `JsAny.from()` first
228    /// if it is not already a JsAny-typed value.
229    fn emit_expr_as_i64(&mut self, expr: &crate::zigir::types::IrExpr, is_jsany: bool) {
230        self.write("(");
231        if is_jsany {
232            self.emit_expr(expr);
233            self.write(".asI64())");
234        } else {
235            self.write("JsAny.from(");
236            self.emit_expr(expr);
237            self.write(").asI64())");
238        }
239    }
240
241    pub(super) fn emit_jsany_comparison(
242        &mut self,
243        op: crate::zigir::ops::BinOp,
244        left: &crate::zigir::types::IrExpr,
245        right: &crate::zigir::types::IrExpr,
246        left_is_jsany: bool,
247        right_is_jsany: bool,
248    ) {
249        use crate::zigir::emit::helpers::bin_op_to_zig;
250        use crate::zigir::ops::BinOp;
251
252        match op {
253            // Equality: Eq/StrictEq and Ne/StrictNe share the same emit logic;
254            // only the method name (.eq vs .strictEq) and negation differ.
255            BinOp::Eq | BinOp::StrictEq | BinOp::Ne | BinOp::StrictNe => {
256                let method = match op {
257                    BinOp::StrictEq | BinOp::StrictNe => "strictEq",
258                    _ => "eq",
259                };
260                let negate = matches!(op, BinOp::Ne | BinOp::StrictNe);
261                if negate {
262                    self.write("!(");
263                }
264                self.emit_expr_as_jsany(left, left_is_jsany);
265                self.write(&format!(".{}(", method));
266                self.emit_expr_as_jsany(right, right_is_jsany);
267                self.write(")");
268                if negate {
269                    self.write(")");
270                }
271            }
272            // Ordering: use JsAny.from().asI64() for numeric comparison
273            BinOp::Lt | BinOp::Le | BinOp::Gt | BinOp::Ge => {
274                let zig_op = bin_op_to_zig(op);
275                // Both sides need to go through JsAny for consistent comparison.
276                // For already-JsAny sides, call .asI64() directly.
277                // For non-JsAny sides, wrap with JsAny.from() then .asI64().
278                self.emit_expr_as_i64(left, left_is_jsany);
279                self.write(&format!(" {} ", zig_op));
280                self.emit_expr_as_i64(right, right_is_jsany);
281            }
282            _ => {
283                self.emit_default_binop(op, left, right);
284            }
285        }
286    }
287
288    /// Emit a comparison where one operand is BigInt and the other is a numeric type
289    /// (I64, F64, Bool) or StringLiteral. Convert the non-BigInt operand to JsBigInt
290    /// via fromI64 (for numeric) or JsBigInt.init (for string), then use .eq() / .order().
291    pub(super) fn emit_bigint_cross_comparison(
292        &mut self,
293        op: crate::zigir::ops::BinOp,
294        left: &crate::zigir::types::IrExpr,
295        right: &crate::zigir::types::IrExpr,
296        left_is_bigint: bool,
297        right_is_bigint: bool,
298    ) {
299        use crate::zigir::ops::BinOp;
300
301        // Emit a non-BigInt operand as JsBigInt.
302        // For StringLiteral: use JsBigInt.init(allocator, "value")
303        // For other types: use JsBigInt.fromI64(allocator, value)
304        let emit_as_bigint = |s: &mut Self, expr: &crate::zigir::types::IrExpr| {
305            if let crate::zigir::types::IrExpr::StringLiteral(val) = expr {
306                s.write("(js_bigint.JsBigInt.init(js_allocator.allocator(), \"");
307                s.write(&crate::zigir::emit::helpers::escape_zig_string(val));
308                s.write("\") catch @panic(\"OOM: BigInt init\"))");
309            } else {
310                s.write("(js_bigint.JsBigInt.fromI64(js_allocator.allocator(), ");
311                s.emit_expr(expr);
312                s.write(") catch @panic(\"BigInt fromI64 OOM\"))");
313            }
314        };
315
316        match op {
317            BinOp::Eq | BinOp::StrictEq | BinOp::Ne | BinOp::StrictNe => {
318                let negate = matches!(op, BinOp::Ne | BinOp::StrictNe);
319                if negate {
320                    self.write("!");
321                }
322                if left_is_bigint {
323                    self.emit_expr(left);
324                } else {
325                    emit_as_bigint(self, left);
326                }
327                self.write(".eq(&");
328                if right_is_bigint {
329                    self.emit_expr(right);
330                } else {
331                    emit_as_bigint(self, right);
332                }
333                self.write(")");
334            }
335            BinOp::Lt | BinOp::Le | BinOp::Gt | BinOp::Ge => {
336                let left_clone = left.clone();
337                let right_clone = right.clone();
338                self.emit_order_cmp(op, |emitter| {
339                    let cmp_expr =
340                        |s: &mut Self, is_bigint: bool, expr: &crate::zigir::types::IrExpr| {
341                            if is_bigint {
342                                s.emit_expr(expr);
343                            } else {
344                                emit_as_bigint(s, expr);
345                            }
346                        };
347                    cmp_expr(emitter, left_is_bigint, &left_clone);
348                    emitter.write(".order(&");
349                    cmp_expr(emitter, right_is_bigint, &right_clone);
350                    emitter.write(")");
351                });
352            }
353            _ => unreachable!("emit_binary: unsupported BinOp {:?}", op),
354        }
355    }
356
357    /// Emit a String + BigInt concatenation.
358    /// JS spec: `"hello" + 5n` → `"hello5"`, `5n + "hello"` → `"5hello"`.
359    /// Converts the BigInt operand to its decimal string representation,
360    /// then concatenates with the String operand using `std.fmt.allocPrint`.
361    pub(super) fn emit_bigint_string_concat(
362        &mut self,
363        left: &crate::zigir::types::IrExpr,
364        right: &crate::zigir::types::IrExpr,
365        left_is_str: bool,
366    ) {
367        // Determine which side is string and which is BigInt
368        let (str_expr, bigint_expr) = if left_is_str {
369            (left, right)
370        } else {
371            (right, left)
372        };
373        let str_on_left = left_is_str;
374
375        self.write("(blk: { var __buf = std.ArrayList(u8).init(js_allocator.allocator()); errdefer __buf.deinit(); ");
376        // Write the first part
377        if str_on_left {
378            self.write("__buf.writer().print(\"{s}\", .{");
379            self.emit_expr(str_expr);
380            self.write("}) catch @panic(\"OOM: string concat\"); ");
381        } else {
382            self.write("__buf.writer().print(\"{f}\", .{");
383            self.emit_expr(bigint_expr);
384            self.write("}) catch @panic(\"OOM: bigint string concat\"); ");
385        }
386        // Write the second part
387        if str_on_left {
388            self.write("__buf.writer().print(\"{f}\", .{");
389            self.emit_expr(bigint_expr);
390            self.write("}) catch @panic(\"OOM: bigint string concat\"); ");
391        } else {
392            self.write("__buf.writer().print(\"{s}\", .{");
393            self.emit_expr(str_expr);
394            self.write("}) catch @panic(\"OOM: string concat\"); ");
395        }
396        self.write("break :blk __buf.toOwnedSlice() catch @panic(\"OOM: string concat\"); })");
397    }
398}