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                    if let Some(try_label) = &self.inside_try_block {
110                        self.write(&format!(
111                            "|err| switch (err) {{ error.DivisionByZero => break :{} @as(anyerror!void, error.JsThrow), else => @panic(\"BigInt {} OOM\") }})",
112                            try_label, label
113                        ));
114                    } else {
115                        self.write(&format!(
116                            "|err| switch (err) {{ error.DivisionByZero => return error.JsThrow, else => @panic(\"BigInt {} OOM\") }})",
117                            label
118                        ));
119                    }
120                } else {
121                    self.write(&format!("@panic(\"BigInt {} OOM\"))", label));
122                }
123            }
124            BinOp::Pow => {
125                self.write("(");
126                self.emit_expr(left);
127                self.write(".pow(");
128                self.emit_expr(right);
129                if let Some(try_label) = &self.inside_try_block {
130                    self.write(&format!(
131                        ".toU64() catch break :{} @as(anyerror!void, error.JsThrow), js_allocator.allocator()) catch @panic(\"BigInt pow OOM\"))",
132                        try_label
133                    ));
134                } else {
135                    self.write(".toU64() catch return error.JsThrow, js_allocator.allocator()) catch @panic(\"BigInt pow OOM\"))");
136                }
137            }
138            BinOp::Shl | BinOp::Shr => {
139                let (method, label) = match op {
140                    BinOp::Shl => ("shiftLeft", "shl"),
141                    BinOp::Shr => ("shiftRight", "shr"),
142                    _ => unreachable!("emit_bigint_binary: unsupported shift op {:?}", op),
143                };
144                self.write("(");
145                self.emit_expr(left);
146                self.write(&format!(".{}(", method));
147                self.emit_expr(right);
148                if let Some(try_label) = &self.inside_try_block {
149                    self.write(&format!(
150                        ".toI64() catch break :{} @as(anyerror!void, error.JsThrow), js_allocator.allocator()) catch @panic(\"BigInt {} OOM\"))",
151                        try_label, label
152                    ));
153                } else {
154                    self.write(&format!(
155                        ".toI64() catch return error.JsThrow, js_allocator.allocator()) catch @panic(\"BigInt {} OOM\"))",
156                        label
157                    ));
158                }
159            }
160            // Equality
161            BinOp::Eq | BinOp::StrictEq | BinOp::Ne | BinOp::StrictNe => {
162                let negate = matches!(op, BinOp::Ne | BinOp::StrictNe);
163                if negate {
164                    self.write("!");
165                }
166                self.emit_expr(left);
167                self.write(".eq(&");
168                self.emit_expr(right);
169                self.write(")");
170            }
171            // Ordering
172            BinOp::Lt | BinOp::Le | BinOp::Gt | BinOp::Ge => {
173                let left_clone = left.clone();
174                let right_clone = right.clone();
175                self.emit_order_cmp(op, |emitter| {
176                    emitter.emit_expr(&left_clone);
177                    emitter.write(".order(&");
178                    emitter.emit_expr(&right_clone);
179                    emitter.write(")");
180                });
181            }
182            // >>> is not supported for BigInt (JS throws TypeError at runtime)
183            BinOp::UrShr => {
184                if let Some(label) = &self.inside_try_block {
185                    self.write(&format!(
186                        "({{ break :{} @as(anyerror!void, error.JsThrow); }})",
187                        label
188                    ));
189                } else {
190                    self.write("({ return error.JsThrow; })");
191                }
192            }
193            _ => {
194                self.emit_default_binop(op, left, right);
195            }
196        }
197    }
198
199    /// Emit a String comparison operation.
200    pub(super) fn emit_string_comparison(
201        &mut self,
202        op: crate::zigir::ops::BinOp,
203        left: &crate::zigir::types::IrExpr,
204        right: &crate::zigir::types::IrExpr,
205    ) {
206        use crate::zigir::ops::BinOp;
207        match op {
208            BinOp::Eq | BinOp::StrictEq | BinOp::Ne | BinOp::StrictNe => {
209                let negate = matches!(op, BinOp::Ne | BinOp::StrictNe);
210                if negate {
211                    self.write("(!");
212                }
213                self.write("std.mem.eql(u8, ");
214                self.emit_expr(left);
215                self.write(", ");
216                self.emit_expr(right);
217                self.write(")");
218                if negate {
219                    self.write(")");
220                }
221            }
222            BinOp::Lt | BinOp::Le | BinOp::Gt | BinOp::Ge => {
223                let left_clone = left.clone();
224                let right_clone = right.clone();
225                self.emit_order_cmp(op, |emitter| {
226                    emitter.write("std.mem.order(u8, ");
227                    emitter.emit_expr(&left_clone);
228                    emitter.write(", ");
229                    emitter.emit_expr(&right_clone);
230                    emitter.write(")");
231                });
232            }
233            _ => {
234                self.emit_default_binop(op, left, right);
235            }
236        }
237    }
238
239    /// Emit a JsAny comparison operation.
240    /// JsAny equality uses .eq()/.strictEq(), ordering uses .asI64().
241    /// Emit an expression, optionally wrapping it in `JsAny.from()` if it
242    /// is not already a JsAny-typed value.
243    fn emit_expr_as_jsany(&mut self, expr: &crate::zigir::types::IrExpr, is_jsany: bool) {
244        if is_jsany {
245            self.emit_expr(expr);
246        } else {
247            self.write("JsAny.from(");
248            self.emit_expr(expr);
249            self.write(")");
250        }
251    }
252
253    /// Emit a JsAny arithmetic operation: convert JsAny side(s) to i64 via .asI64().
254    /// e.g., `sum + v` where v is JsAny → `sum + v.asI64()`
255    pub(super) fn emit_jsany_arithmetic(
256        &mut self,
257        op: crate::zigir::ops::BinOp,
258        left: &crate::zigir::types::IrExpr,
259        right: &crate::zigir::types::IrExpr,
260        left_is_jsany: bool,
261        right_is_jsany: bool,
262    ) {
263        use crate::zigir::emit::helpers::bin_op_to_zig;
264
265        // Left side
266        if left_is_jsany {
267            self.emit_expr(left);
268            self.write(".asI64()");
269        } else {
270            self.emit_expr(left);
271        }
272        self.write(&format!(" {} ", bin_op_to_zig(op)));
273        // Right side
274        if right_is_jsany {
275            self.emit_expr(right);
276            self.write(".asI64()");
277        } else {
278            self.emit_expr(right);
279        }
280    }
281
282    /// Emit an expression as `.asI64()`, wrapping with `JsAny.from()` first
283    /// if it is not already a JsAny-typed value.
284    fn emit_expr_as_i64(&mut self, expr: &crate::zigir::types::IrExpr, is_jsany: bool) {
285        self.write("(");
286        if is_jsany {
287            self.emit_expr(expr);
288            self.write(".asI64())");
289        } else {
290            self.write("JsAny.from(");
291            self.emit_expr(expr);
292            self.write(").asI64())");
293        }
294    }
295
296    pub(super) fn emit_jsany_comparison(
297        &mut self,
298        op: crate::zigir::ops::BinOp,
299        left: &crate::zigir::types::IrExpr,
300        right: &crate::zigir::types::IrExpr,
301        left_is_jsany: bool,
302        right_is_jsany: bool,
303    ) {
304        use crate::zigir::emit::helpers::bin_op_to_zig;
305        use crate::zigir::ops::BinOp;
306
307        match op {
308            // Equality: Eq/StrictEq and Ne/StrictNe share the same emit logic;
309            // only the method name (.eq vs .strictEq) and negation differ.
310            BinOp::Eq | BinOp::StrictEq | BinOp::Ne | BinOp::StrictNe => {
311                let method = match op {
312                    BinOp::StrictEq | BinOp::StrictNe => "strictEq",
313                    _ => "eq",
314                };
315                let negate = matches!(op, BinOp::Ne | BinOp::StrictNe);
316                if negate {
317                    self.write("!(");
318                }
319                self.emit_expr_as_jsany(left, left_is_jsany);
320                self.write(&format!(".{}(", method));
321                self.emit_expr_as_jsany(right, right_is_jsany);
322                self.write(")");
323                if negate {
324                    self.write(")");
325                }
326            }
327            // Ordering: use JsAny.from().asI64() for numeric comparison
328            BinOp::Lt | BinOp::Le | BinOp::Gt | BinOp::Ge => {
329                let zig_op = bin_op_to_zig(op);
330                // Both sides need to go through JsAny for consistent comparison.
331                // For already-JsAny sides, call .asI64() directly.
332                // For non-JsAny sides, wrap with JsAny.from() then .asI64().
333                self.emit_expr_as_i64(left, left_is_jsany);
334                self.write(&format!(" {} ", zig_op));
335                self.emit_expr_as_i64(right, right_is_jsany);
336            }
337            _ => {
338                self.emit_default_binop(op, left, right);
339            }
340        }
341    }
342
343    /// Emit a comparison where one operand is BigInt and the other is a numeric type
344    /// (I64, F64, Bool) or StringLiteral. Convert the non-BigInt operand to JsBigInt
345    /// via fromI64 (for numeric) or JsBigInt.init (for string), then use .eq() / .order().
346    pub(super) fn emit_bigint_cross_comparison(
347        &mut self,
348        op: crate::zigir::ops::BinOp,
349        left: &crate::zigir::types::IrExpr,
350        right: &crate::zigir::types::IrExpr,
351        left_is_bigint: bool,
352        right_is_bigint: bool,
353    ) {
354        use crate::zigir::ops::BinOp;
355
356        // Emit a non-BigInt operand as JsBigInt.
357        // For StringLiteral: use JsBigInt.init(allocator, "value")
358        // For other types: use JsBigInt.fromI64(allocator, value)
359        let emit_as_bigint = |s: &mut Self, expr: &crate::zigir::types::IrExpr| {
360            if let crate::zigir::types::IrExpr::StringLiteral(val) = expr {
361                s.write("(js_bigint.JsBigInt.init(js_allocator.allocator(), \"");
362                s.write(&crate::zigir::emit::helpers::escape_zig_string(val));
363                s.write("\") catch @panic(\"OOM: BigInt init\"))");
364            } else {
365                s.write("(js_bigint.JsBigInt.fromI64(js_allocator.allocator(), ");
366                s.emit_expr(expr);
367                s.write(") catch @panic(\"BigInt fromI64 OOM\"))");
368            }
369        };
370
371        match op {
372            BinOp::Eq | BinOp::StrictEq | BinOp::Ne | BinOp::StrictNe => {
373                let negate = matches!(op, BinOp::Ne | BinOp::StrictNe);
374                if negate {
375                    self.write("!");
376                }
377                if left_is_bigint {
378                    self.emit_expr(left);
379                } else {
380                    emit_as_bigint(self, left);
381                }
382                self.write(".eq(&");
383                if right_is_bigint {
384                    self.emit_expr(right);
385                } else {
386                    emit_as_bigint(self, right);
387                }
388                self.write(")");
389            }
390            BinOp::Lt | BinOp::Le | BinOp::Gt | BinOp::Ge => {
391                let left_clone = left.clone();
392                let right_clone = right.clone();
393                self.emit_order_cmp(op, |emitter| {
394                    let cmp_expr =
395                        |s: &mut Self, is_bigint: bool, expr: &crate::zigir::types::IrExpr| {
396                            if is_bigint {
397                                s.emit_expr(expr);
398                            } else {
399                                emit_as_bigint(s, expr);
400                            }
401                        };
402                    cmp_expr(emitter, left_is_bigint, &left_clone);
403                    emitter.write(".order(&");
404                    cmp_expr(emitter, right_is_bigint, &right_clone);
405                    emitter.write(")");
406                });
407            }
408            _ => unreachable!("emit_binary: unsupported BinOp {:?}", op),
409        }
410    }
411
412    /// Emit a String + BigInt concatenation.
413    /// JS spec: `"hello" + 5n` → `"hello5"`, `5n + "hello"` → `"5hello"`.
414    /// Converts the BigInt operand to its decimal string representation,
415    /// then concatenates with the String operand using `std.fmt.allocPrint`.
416    pub(super) fn emit_bigint_string_concat(
417        &mut self,
418        left: &crate::zigir::types::IrExpr,
419        right: &crate::zigir::types::IrExpr,
420        left_is_str: bool,
421    ) {
422        // Determine which side is string and which is BigInt
423        let (str_expr, bigint_expr) = if left_is_str {
424            (left, right)
425        } else {
426            (right, left)
427        };
428        let str_on_left = left_is_str;
429
430        self.write("(blk: { var __buf = std.ArrayList(u8).init(js_allocator.allocator()); errdefer __buf.deinit(); ");
431        // Write the first part
432        if str_on_left {
433            self.write("__buf.writer().print(\"{s}\", .{");
434            self.emit_expr(str_expr);
435            self.write("}) catch @panic(\"OOM: string concat\"); ");
436        } else {
437            self.write("__buf.writer().print(\"{f}\", .{");
438            self.emit_expr(bigint_expr);
439            self.write("}) catch @panic(\"OOM: bigint string concat\"); ");
440        }
441        // Write the second part
442        if str_on_left {
443            self.write("__buf.writer().print(\"{f}\", .{");
444            self.emit_expr(bigint_expr);
445            self.write("}) catch @panic(\"OOM: bigint string concat\"); ");
446        } else {
447            self.write("__buf.writer().print(\"{s}\", .{");
448            self.emit_expr(str_expr);
449            self.write("}) catch @panic(\"OOM: string concat\"); ");
450        }
451        self.write("break :blk __buf.toOwnedSlice() catch @panic(\"OOM: string concat\"); })");
452    }
453}