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 BigInt binary operation.
40    /// BigInt arithmetic uses method calls like `_a.add(&_b, alloc)`.
41    pub(super) fn emit_bigint_binary(
42        &mut self,
43        op: crate::zigir::ops::BinOp,
44        left: &crate::zigir::types::IrExpr,
45        right: &crate::zigir::types::IrExpr,
46    ) {
47        use crate::zigir::ops::BinOp;
48
49        match op {
50            // Arithmetic: _a.op(&_b, alloc) catch @panic("BigInt op OOM")
51            BinOp::Add => {
52                self.write("(");
53                self.emit_expr(left);
54                self.write(".add(&");
55                self.emit_expr(right);
56                self.write(", js_allocator.allocator()) catch @panic(\"BigInt add OOM\"))");
57            }
58            BinOp::Sub => {
59                self.write("(");
60                self.emit_expr(left);
61                self.write(".sub(&");
62                self.emit_expr(right);
63                self.write(", js_allocator.allocator()) catch @panic(\"BigInt sub OOM\"))");
64            }
65            BinOp::Mul => {
66                self.write("(");
67                self.emit_expr(left);
68                self.write(".mul(&");
69                self.emit_expr(right);
70                self.write(", js_allocator.allocator()) catch @panic(\"BigInt mul OOM\"))");
71            }
72            BinOp::Div => {
73                self.write("(");
74                self.emit_expr(left);
75                self.write(".div(&");
76                self.emit_expr(right);
77                self.write(", js_allocator.allocator()) catch |err| switch (err) { error.DivisionByZero => @panic(\"RangeError: BigInt division by zero\"), else => @panic(\"BigInt div OOM\") })");
78            }
79            BinOp::Mod => {
80                self.write("(");
81                self.emit_expr(left);
82                self.write(".rem(&");
83                self.emit_expr(right);
84                self.write(", js_allocator.allocator()) catch @panic(\"BigInt rem OOM\"))");
85            }
86            BinOp::Pow => {
87                self.write("(");
88                self.emit_expr(left);
89                self.write(".pow(");
90                self.emit_expr(right);
91                self.write(".toU64() catch @panic(\"BigInt toU64 failed\"), js_allocator.allocator()) catch @panic(\"BigInt pow OOM\"))");
92            }
93            BinOp::BitAnd => {
94                self.write("(");
95                self.emit_expr(left);
96                self.write(".bitwiseAnd(&");
97                self.emit_expr(right);
98                self.write(", js_allocator.allocator()) catch @panic(\"BigInt and OOM\"))");
99            }
100            BinOp::BitOr => {
101                self.write("(");
102                self.emit_expr(left);
103                self.write(".bitwiseOr(&");
104                self.emit_expr(right);
105                self.write(", js_allocator.allocator()) catch @panic(\"BigInt or OOM\"))");
106            }
107            BinOp::BitXor => {
108                self.write("(");
109                self.emit_expr(left);
110                self.write(".bitwiseXor(&");
111                self.emit_expr(right);
112                self.write(", js_allocator.allocator()) catch @panic(\"BigInt xor OOM\"))");
113            }
114            BinOp::Shl => {
115                self.write("(");
116                self.emit_expr(left);
117                self.write(".shiftLeft(@as(usize, @intCast(");
118                self.emit_expr(right);
119                self.write(".toU64() catch @panic(\"BigInt toU64 failed\"))), js_allocator.allocator()) catch @panic(\"BigInt shl OOM\"))");
120            }
121            BinOp::Shr => {
122                self.write("(");
123                self.emit_expr(left);
124                self.write(".shiftRight(@as(usize, @intCast(");
125                self.emit_expr(right);
126                self.write(".toU64() catch @panic(\"BigInt toU64 failed\"))), js_allocator.allocator()) catch @panic(\"BigInt shr OOM\"))");
127            }
128            // Equality
129            BinOp::Eq | BinOp::StrictEq => {
130                self.emit_expr(left);
131                self.write(".eq(&");
132                self.emit_expr(right);
133                self.write(")");
134            }
135            BinOp::Ne | BinOp::StrictNe => {
136                self.write("!");
137                self.emit_expr(left);
138                self.write(".eq(&");
139                self.emit_expr(right);
140                self.write(")");
141            }
142            // Ordering
143            BinOp::Lt => {
144                self.write("(");
145                self.emit_expr(left);
146                self.write(".order(&");
147                self.emit_expr(right);
148                self.write(") == .lt)");
149            }
150            BinOp::Le => {
151                self.write("(");
152                self.emit_expr(left);
153                self.write(".order(&");
154                self.emit_expr(right);
155                self.write(") != .gt)");
156            }
157            BinOp::Gt => {
158                self.write("(");
159                self.emit_expr(left);
160                self.write(".order(&");
161                self.emit_expr(right);
162                self.write(") == .gt)");
163            }
164            BinOp::Ge => {
165                self.write("(");
166                self.emit_expr(left);
167                self.write(".order(&");
168                self.emit_expr(right);
169                self.write(") != .lt)");
170            }
171            // >>> is not supported for BigInt (JS throws TypeError)
172            BinOp::UrShr => {
173                self.write("@compileError(\"BigInt does not support unsigned right shift\")");
174            }
175            _ => {
176                // Fallback: try direct operator
177                self.emit_expr(left);
178                self.write(&format!(
179                    " {} ",
180                    crate::zigir::emit::helpers::bin_op_to_zig(op)
181                ));
182                self.emit_expr(right);
183            }
184        }
185    }
186
187    /// Emit a String comparison operation.
188    pub(super) fn emit_string_comparison(
189        &mut self,
190        op: crate::zigir::ops::BinOp,
191        left: &crate::zigir::types::IrExpr,
192        right: &crate::zigir::types::IrExpr,
193    ) {
194        use crate::zigir::emit::helpers::bin_op_to_zig;
195        use crate::zigir::ops::BinOp;
196        match op {
197            BinOp::Eq | BinOp::StrictEq => {
198                self.write("std.mem.eql(u8, ");
199                self.emit_expr(left);
200                self.write(", ");
201                self.emit_expr(right);
202                self.write(")");
203            }
204            BinOp::Ne | BinOp::StrictNe => {
205                self.write("(!std.mem.eql(u8, ");
206                self.emit_expr(left);
207                self.write(", ");
208                self.emit_expr(right);
209                self.write("))");
210            }
211            BinOp::Lt => {
212                self.write("(std.mem.order(u8, ");
213                self.emit_expr(left);
214                self.write(", ");
215                self.emit_expr(right);
216                self.write(") == .lt)");
217            }
218            BinOp::Le => {
219                self.write("(std.mem.order(u8, ");
220                self.emit_expr(left);
221                self.write(", ");
222                self.emit_expr(right);
223                self.write(") != .gt)");
224            }
225            BinOp::Gt => {
226                self.write("(std.mem.order(u8, ");
227                self.emit_expr(left);
228                self.write(", ");
229                self.emit_expr(right);
230                self.write(") == .gt)");
231            }
232            BinOp::Ge => {
233                self.write("(std.mem.order(u8, ");
234                self.emit_expr(left);
235                self.write(", ");
236                self.emit_expr(right);
237                self.write(") != .lt)");
238            }
239            _ => {
240                // Other string operators (not expected)
241                self.emit_expr(left);
242                self.write(&format!(" {} ", bin_op_to_zig(op)));
243                self.emit_expr(right);
244            }
245        }
246    }
247
248    /// Emit a JsAny comparison operation.
249    /// JsAny equality uses .eq()/.strictEq(), ordering uses .asI64().
250    pub(super) fn emit_jsany_comparison(
251        &mut self,
252        op: crate::zigir::ops::BinOp,
253        left: &crate::zigir::types::IrExpr,
254        right: &crate::zigir::types::IrExpr,
255        left_is_jsany: bool,
256        right_is_jsany: bool,
257    ) {
258        use crate::zigir::emit::helpers::bin_op_to_zig;
259        use crate::zigir::ops::BinOp;
260
261        // Wrap non-JsAny operand with JsAny.from() if needed
262        let emit_left_as_jsany = |emitter: &mut Emitter| {
263            if left_is_jsany {
264                emitter.emit_expr(left);
265            } else {
266                emitter.write("JsAny.from(");
267                emitter.emit_expr(left);
268                emitter.write(")");
269            }
270        };
271        let emit_right_as_jsany = |emitter: &mut Emitter| {
272            if right_is_jsany {
273                emitter.emit_expr(right);
274            } else {
275                emitter.write("JsAny.from(");
276                emitter.emit_expr(right);
277                emitter.write(")");
278            }
279        };
280
281        match op {
282            BinOp::Eq => {
283                emit_left_as_jsany(self);
284                self.write(".eq(");
285                emit_right_as_jsany(self);
286                self.write(")");
287            }
288            BinOp::StrictEq => {
289                emit_left_as_jsany(self);
290                self.write(".strictEq(");
291                emit_right_as_jsany(self);
292                self.write(")");
293            }
294            BinOp::Ne => {
295                self.write("!(");
296                emit_left_as_jsany(self);
297                self.write(".eq(");
298                emit_right_as_jsany(self);
299                self.write("))");
300            }
301            BinOp::StrictNe => {
302                self.write("!(");
303                emit_left_as_jsany(self);
304                self.write(".strictEq(");
305                emit_right_as_jsany(self);
306                self.write("))");
307            }
308            // Ordering: use JsAny.from().asI64() for numeric comparison
309            BinOp::Lt | BinOp::Le | BinOp::Gt | BinOp::Ge => {
310                let zig_op = bin_op_to_zig(op);
311                // Both sides need to go through JsAny for consistent comparison.
312                // For already-JsAny sides, call .asI64() directly.
313                // For non-JsAny sides, wrap with JsAny.from() then .asI64().
314                if left_is_jsany {
315                    self.write("(");
316                    self.emit_expr(left);
317                    self.write(".asI64())");
318                } else {
319                    self.write("(JsAny.from(");
320                    self.emit_expr(left);
321                    self.write(").asI64())");
322                }
323                self.write(&format!(" {} ", zig_op));
324                if right_is_jsany {
325                    self.write("(");
326                    self.emit_expr(right);
327                    self.write(".asI64())");
328                } else {
329                    self.write("(JsAny.from(");
330                    self.emit_expr(right);
331                    self.write(").asI64())");
332                }
333            }
334            _ => {
335                // Fallback
336                self.emit_expr(left);
337                self.write(&format!(" {} ", bin_op_to_zig(op)));
338                self.emit_expr(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 => {
373                if left_is_bigint {
374                    self.emit_expr(left);
375                } else {
376                    emit_as_bigint(self, left);
377                }
378                self.write(".eq(&");
379                if right_is_bigint {
380                    self.emit_expr(right);
381                } else {
382                    emit_as_bigint(self, right);
383                }
384                self.write(")");
385            }
386            BinOp::Ne | BinOp::StrictNe => {
387                self.write("!");
388                if left_is_bigint {
389                    self.emit_expr(left);
390                } else {
391                    emit_as_bigint(self, left);
392                }
393                self.write(".eq(&");
394                if right_is_bigint {
395                    self.emit_expr(right);
396                } else {
397                    emit_as_bigint(self, right);
398                }
399                self.write(")");
400            }
401            BinOp::Lt | BinOp::Le | BinOp::Gt | BinOp::Ge => {
402                // Use .order() which returns std.math.Order (.lt, .eq, .gt)
403                let cmp_expr =
404                    |s: &mut Self, is_bigint: bool, expr: &crate::zigir::types::IrExpr| {
405                        if is_bigint {
406                            s.emit_expr(expr);
407                        } else {
408                            emit_as_bigint(s, expr);
409                        }
410                    };
411                // lhs.order(&rhs) compare to expected Order value
412                self.write("(");
413                cmp_expr(self, left_is_bigint, left);
414                self.write(".order(&");
415                cmp_expr(self, right_is_bigint, right);
416                self.write(") ");
417                match op {
418                    BinOp::Lt => self.write("== .lt"),
419                    BinOp::Le => self.write("!= .gt"),
420                    BinOp::Gt => self.write("== .gt"),
421                    BinOp::Ge => self.write("!= .lt"),
422                    _ => unreachable!(),
423                }
424                self.write(")");
425            }
426            _ => unreachable!(),
427        }
428    }
429}