Skip to main content

js2zig_core/zigir/lower/expr/
operators.rs

1// zigir/lower/expr/operators.rs
2// Binary, unary, update, assignment expression lowering + string concatenation.
3
4use std::collections::HashSet;
5
6use oxc_ast::ast::*;
7
8use crate::types::ZigType;
9use crate::zigir::builtins::BuiltinModule;
10use crate::zigir::ident::IrIdent;
11use crate::zigir::kinds::{FieldKind, IndexKind};
12use crate::zigir::ops::{AssignOp, BinOp, LogicalOp, UnaOp, UpdateOp};
13
14use super::Lowerer;
15use crate::zigir::lower::helpers;
16
17impl Lowerer {
18    /// Lower a binary expression.
19    pub(super) fn lower_binary(&mut self, be: &BinaryExpression) -> crate::zigir::types::IrExpr {
20        use crate::zigir::types::IrExpr;
21
22        // String concatenation detection: if `+` has any string operand,
23        // flatten the chain and produce IrExpr::AllocPrint instead of
24        // a binary tree of IrExpr::Binary nodes.
25        if be.operator == BinaryOperator::Addition {
26            let left_is_str = self.expr_is_string(&be.left);
27            let right_is_str = self.expr_is_string(&be.right);
28            if left_is_str || right_is_str {
29                return self.lower_string_concat(be);
30            }
31        }
32
33        // ── Unsupported operators → compile error (or special handling) ──
34        match be.operator {
35            BinaryOperator::Instanceof => {
36                return self.lower_instanceof(be);
37            }
38            BinaryOperator::In => {
39                // `key in obj` → obj.has(key) for Map/Set, obj.contains(key) otherwise
40                let right_expr = self.lower_expr(&be.right);
41                let left_expr = self.lower_expr(&be.left);
42                let right_type = self.infer_expr_type(&be.right);
43                return IrExpr::Binary {
44                    op: BinOp::In,
45                    left: Box::new(left_expr),
46                    right: Box::new(right_expr),
47                    left_type: Some(ZigType::Str),
48                    right_type,
49                };
50            }
51            _ => {}
52        }
53
54        let op = match be.operator {
55            BinaryOperator::Addition => BinOp::Add,
56            BinaryOperator::Subtraction => BinOp::Sub,
57            BinaryOperator::Multiplication => BinOp::Mul,
58            BinaryOperator::Division => BinOp::Div,
59            BinaryOperator::Remainder => {
60                let left_type = self.infer_expr_type(&be.left).unwrap_or(ZigType::I64);
61                let right_type = self.infer_expr_type(&be.right).unwrap_or(ZigType::I64);
62                // BigInt % BigInt: use BinOp::Mod so emit_bigint_binary generates .rem() call.
63                if left_type == ZigType::BigInt || right_type == ZigType::BigInt {
64                    // BigInt modulo can throw RangeError — mark function as can_throw
65                    if let Some(ctx) = self.fn_ctx.as_mut() {
66                        ctx.has_bigint_div = true;
67                    }
68                    return IrExpr::Binary {
69                        op: BinOp::Mod,
70                        left: Box::new(self.lower_expr(&be.left)),
71                        right: Box::new(self.lower_expr(&be.right)),
72                        left_type: Some(left_type),
73                        right_type: Some(right_type),
74                    };
75                }
76                // Float % any: use BinOp::Mod so emit layer generates @rem(f64, f64).
77                if left_type == ZigType::F64 || right_type == ZigType::F64 {
78                    return IrExpr::Binary {
79                        op: BinOp::Mod,
80                        left: Box::new(self.lower_expr(&be.left)),
81                        right: Box::new(self.lower_expr(&be.right)),
82                        left_type: Some(left_type),
83                        right_type: Some(right_type),
84                    };
85                }
86                // Integer %: use RemExpr (jsRem returns f64, preserves signed zero).
87                // result_type is set later by lower_assignment when assigning to i64.
88                return IrExpr::RemExpr {
89                    left: Box::new(self.lower_expr(&be.left)),
90                    right: Box::new(self.lower_expr(&be.right)),
91                    result_type: None, // standalone `%` keeps f64 result
92                };
93            }
94            BinaryOperator::Exponential => {
95                let left_type = self.infer_expr_type(&be.left).unwrap_or(ZigType::F64);
96                let right_type = self.infer_expr_type(&be.right).unwrap_or(ZigType::F64);
97                // BigInt ** BigInt: use BinOp::Pow so emit_bigint_binary generates .pow() call.
98                if left_type == ZigType::BigInt || right_type == ZigType::BigInt {
99                    // BigInt ** can throw at runtime:
100                    // - Mixed BigInt (e.g., 2n ** 2): TypeError
101                    // - BigInt ** BigInt with negative exponent: RangeError (toU64 fails)
102                    if let Some(ctx) = self.fn_ctx.as_mut() {
103                        ctx.has_catchable_error = true;
104                    }
105                    return IrExpr::Binary {
106                        op: BinOp::Pow,
107                        left: Box::new(self.lower_expr(&be.left)),
108                        right: Box::new(self.lower_expr(&be.right)),
109                        left_type: Some(left_type),
110                        right_type: Some(right_type),
111                    };
112                }
113                // Non-BigInt: JS `**` always returns f64. Emit a PowExpr with type info
114                // so the Emitter can generate the correct f64 coercion.
115                return IrExpr::PowExpr {
116                    base: Box::new(self.lower_expr(&be.left)),
117                    exp: Box::new(self.lower_expr(&be.right)),
118                    base_type: left_type,
119                    exp_type: right_type,
120                    result_type: None, // standalone `**` always returns f64
121                };
122            }
123            BinaryOperator::LessThan => BinOp::Lt,
124            BinaryOperator::GreaterThan => BinOp::Gt,
125            BinaryOperator::LessEqualThan => BinOp::Le,
126            BinaryOperator::GreaterEqualThan => BinOp::Ge,
127            BinaryOperator::Equality => BinOp::Eq,
128            BinaryOperator::Inequality => BinOp::Ne,
129            BinaryOperator::StrictEquality => BinOp::StrictEq,
130            BinaryOperator::StrictInequality => BinOp::StrictNe,
131            BinaryOperator::BitwiseAnd => BinOp::BitAnd,
132            BinaryOperator::BitwiseOR => BinOp::BitOr,
133            BinaryOperator::BitwiseXOR => BinOp::BitXor,
134            BinaryOperator::ShiftLeft => BinOp::Shl,
135            BinaryOperator::ShiftRight => BinOp::Shr,
136            BinaryOperator::ShiftRightZeroFill => BinOp::UrShr,
137            // Instanceof is handled above (CompileError). In is also handled above (BinOp::In).
138            // These arms are unreachable but kept for exhaustiveness.
139            BinaryOperator::Instanceof | BinaryOperator::In => unreachable!(),
140        };
141
142        let left_type = self.infer_expr_type(&be.left);
143        let right_type = self.infer_expr_type(&be.right);
144
145        // BigInt division/modulo can throw RangeError — mark function as can_throw
146        if matches!(op, BinOp::Div | BinOp::Mod)
147            && (left_type.as_ref() == Some(&ZigType::BigInt)
148                || right_type.as_ref() == Some(&ZigType::BigInt))
149            && let Some(ctx) = self.fn_ctx.as_mut()
150        {
151            ctx.has_bigint_div = true;
152        }
153
154        // BigInt mixed-type ops, BigInt >>>, BigInt ** BigInt, and BigInt << >> BigInt
155        // throw or can throw at runtime. These are emitted as `return error.JsThrow`
156        // (not @panic) so JS try/catch can catch them.
157        // Mark the function as can_throw so the signature includes `!`.
158        {
159            let left_is_bigint = left_type.as_ref() == Some(&ZigType::BigInt);
160            let right_is_bigint = right_type.as_ref() == Some(&ZigType::BigInt);
161            let is_mixed_bigint = left_is_bigint != right_is_bigint; // XOR: exactly one is BigInt
162            let is_bigint_urshr = op == BinOp::UrShr && (left_is_bigint || right_is_bigint);
163            // BigInt << >> BigInt: toI64() can fail for very large shift amounts → error.JsThrow
164            let is_bigint_shift =
165                matches!(op, BinOp::Shl | BinOp::Shr) && left_is_bigint && right_is_bigint;
166            if ((is_mixed_bigint
167                && matches!(
168                    op,
169                    BinOp::Add
170                        | BinOp::Sub
171                        | BinOp::Mul
172                        | BinOp::Div
173                        | BinOp::Mod
174                        | BinOp::Pow
175                        | BinOp::BitAnd
176                        | BinOp::BitOr
177                        | BinOp::BitXor
178                        | BinOp::Shl
179                        | BinOp::Shr
180                ))
181                || is_bigint_urshr
182                || is_bigint_shift)
183                && let Some(ctx) = self.fn_ctx.as_mut()
184            {
185                ctx.has_catchable_error = true;
186            }
187        }
188
189        IrExpr::Binary {
190            op,
191            left: Box::new(self.lower_expr(&be.left)),
192            right: Box::new(self.lower_expr(&be.right)),
193            left_type,
194            right_type,
195        }
196    }
197
198    /// Lower a unary expression.
199    pub(super) fn lower_unary(&mut self, ue: &UnaryExpression) -> crate::zigir::types::IrExpr {
200        use crate::zigir::types::IrExpr;
201
202        match ue.operator {
203            UnaryOperator::UnaryNegation => {
204                if self.infer_expr_type(&ue.argument) == Some(ZigType::BigInt) {
205                    let operand = self.lower_expr(&ue.argument);
206                    return self.bigint_unary_builtin("bigIntNeg", operand);
207                }
208                IrExpr::Unary {
209                    op: UnaOp::Neg,
210                    operand: Box::new(self.lower_expr(&ue.argument)),
211                }
212            }
213            UnaryOperator::UnaryPlus => {
214                // Unary plus is a no-op in terms of IR; just lower the argument
215                self.lower_expr(&ue.argument)
216            }
217            UnaryOperator::LogicalNot => IrExpr::Unary {
218                op: UnaOp::Not,
219                operand: Box::new(self.lower_expr(&ue.argument)),
220            },
221            UnaryOperator::BitwiseNot => {
222                if self.infer_expr_type(&ue.argument) == Some(ZigType::BigInt) {
223                    let operand = self.lower_expr(&ue.argument);
224                    return self.bigint_unary_builtin("bigIntBitwiseNot", operand);
225                }
226                IrExpr::Unary {
227                    op: UnaOp::BitNot,
228                    operand: Box::new(self.lower_expr(&ue.argument)),
229                }
230            }
231            UnaryOperator::Typeof => {
232                if let Some(ty) = self.infer_expr_type(&ue.argument)
233                    && let Some(js_typeof) = ty.to_js_typeof()
234                {
235                    let mut idents = HashSet::new();
236                    Self::collect_ast_expr_idents(&ue.argument, &mut idents);
237                    if let Some(ctx) = self.fn_ctx.as_mut() {
238                        ctx.compile_time_referenced_idents.extend(idents);
239                    }
240                    return IrExpr::StringLiteral(js_typeof.to_string());
241                }
242                IrExpr::BuiltinCall(crate::zigir::types::IrBuiltinCall::simple(
243                    BuiltinModule::JsRuntime,
244                    "jsTypeof",
245                    None,
246                    None,
247                    vec![self.lower_expr(&ue.argument)],
248                    ZigType::Str,
249                ))
250            }
251            UnaryOperator::Void => IrExpr::Void(Box::new(self.lower_expr(&ue.argument))),
252            UnaryOperator::Delete => {
253                // delete obj.prop → IrBuiltinCall { JsRuntime, "deleteKey", obj, [prop] }
254                // delete obj[expr] → IrBuiltinCall { JsRuntime, "deleteByKey", obj, [expr] }
255                match &ue.argument {
256                    Expression::StaticMemberExpression(mem) => {
257                        let obj_name = match &mem.object {
258                            Expression::Identifier(id) => Some(id.name.as_str().to_string()),
259                            _ => None,
260                        };
261                        IrExpr::BuiltinCall(crate::zigir::types::IrBuiltinCall::simple(
262                            BuiltinModule::JsRuntime,
263                            "deleteKey",
264                            obj_name,
265                            None,
266                            vec![IrExpr::StringLiteral(
267                                mem.property.name.as_str().to_string(),
268                            )],
269                            ZigType::Bool,
270                        ))
271                    }
272                    Expression::ComputedMemberExpression(mem) => {
273                        let obj_name = if let Expression::Identifier(id) = &mem.object {
274                            Some(id.name.as_str().to_string())
275                        } else {
276                            None
277                        };
278                        IrExpr::BuiltinCall(crate::zigir::types::IrBuiltinCall::simple(
279                            BuiltinModule::JsRuntime,
280                            "deleteByKey",
281                            obj_name,
282                            None,
283                            vec![self.lower_expr(&mem.expression)],
284                            ZigType::Bool,
285                        ))
286                    }
287                    _ => {
288                        self.compile_error_expr(ue.span, "delete operator requires property access")
289                    }
290                }
291            }
292        }
293    }
294
295    /// Lower an update expression (++/--).
296    pub(super) fn lower_update(&mut self, ue: &UpdateExpression) -> crate::zigir::types::IrExpr {
297        use crate::zigir::types::IrExpr;
298
299        // Check if the target is BigInt — BigInt has no Zig +=, -=,
300        // so we must expand `x++` into `x = x + BigInt(1)` and
301        // `x--` into `x = x - BigInt(1)` using method calls.
302        let target_type = self.infer_simple_assign_target_type(&ue.argument);
303        if target_type == Some(ZigType::BigInt) {
304            let target = self.lower_simple_assign_target(&ue.argument);
305            let Some(read_expr) = target.to_read_expr() else {
306                return IrExpr::Update {
307                    op: if ue.operator == UpdateOperator::Increment {
308                        UpdateOp::Increment
309                    } else {
310                        UpdateOp::Decrement
311                    },
312                    target: Box::new(target),
313                    is_expr_stmt: self.in_expr_stmt,
314                };
315            };
316            let bin_op = if ue.operator == UpdateOperator::Increment {
317                BinOp::Add
318            } else {
319                BinOp::Sub
320            };
321            return IrExpr::Assign {
322                op: AssignOp::Assign,
323                target: Box::new(target),
324                value: Box::new(IrExpr::Binary {
325                    op: bin_op,
326                    left: Box::new(read_expr),
327                    right: Box::new(IrExpr::BigIntLiteral("1".to_string())),
328                    left_type: Some(ZigType::BigInt),
329                    right_type: Some(ZigType::BigInt),
330                }),
331            };
332        }
333
334        // Non-BigInt: emit standard ++/--
335        let op = if ue.operator == UpdateOperator::Increment {
336            UpdateOp::Increment
337        } else {
338            UpdateOp::Decrement
339        };
340        let target = Box::new(self.lower_simple_assign_target(&ue.argument));
341        IrExpr::Update {
342            op,
343            target,
344            is_expr_stmt: self.in_expr_stmt,
345        }
346    }
347
348    /// Lower an assignment expression.
349    pub(super) fn lower_assignment(
350        &mut self,
351        ae: &AssignmentExpression,
352    ) -> crate::zigir::types::IrExpr {
353        use crate::zigir::types::IrExpr;
354
355        // ── Special-case compound assignments that need expansion ──
356        // **= → a = a ** b
357        if ae.operator == AssignmentOperator::Exponential {
358            let target = self.lower_assign_target(&ae.left);
359            let value = Box::new(self.lower_expr(&ae.right));
360            let target_type = self.infer_assign_target_type(&ae.left);
361            let base_expr = target
362                .to_read_expr()
363                .unwrap_or_else(|| IrExpr::Ident(IrIdent::new("__target")));
364            if target_type == Some(ZigType::BigInt) {
365                return IrExpr::Assign {
366                    op: AssignOp::Assign,
367                    target: Box::new(target),
368                    value: Box::new(IrExpr::Binary {
369                        op: BinOp::Pow,
370                        left: Box::new(base_expr),
371                        right: value,
372                        left_type: Some(ZigType::BigInt),
373                        right_type: Some(ZigType::BigInt),
374                    }),
375                };
376            }
377            // Non-BigInt: a = std.math.pow(a, b) via PowExpr
378            let base_type = target_type.unwrap_or(ZigType::F64);
379            let exp_type = self.infer_expr_type(&ae.right).unwrap_or(ZigType::F64);
380            // When assigning pow result to an i64 variable, set result_type so
381            // the emit layer wraps in @as(i64, @intFromFloat(...))
382            let result_type = if base_type == ZigType::I64 {
383                Some(ZigType::I64)
384            } else {
385                None
386            };
387            return IrExpr::Assign {
388                op: AssignOp::Assign,
389                target: Box::new(target),
390                value: Box::new(IrExpr::PowExpr {
391                    base: Box::new(base_expr),
392                    exp: value,
393                    base_type,
394                    exp_type,
395                    result_type,
396                }),
397            };
398        }
399        // >>>= → a = a >>> b (unsigned right shift cannot use >>= which is signed)
400        // Expand early, same pattern as **=, so the emitter uses the UrShr path.
401        if ae.operator == AssignmentOperator::ShiftRightZeroFill {
402            let target = self.lower_assign_target(&ae.left);
403            let value = Box::new(self.lower_expr(&ae.right));
404            let target_type = self.infer_assign_target_type(&ae.left);
405            let base_type = target_type.unwrap_or(ZigType::I64);
406            let right_type = self.infer_expr_type(&ae.right).unwrap_or(ZigType::I64);
407            let base_expr = target
408                .to_read_expr()
409                .unwrap_or_else(|| IrExpr::Ident(IrIdent::new("__target")));
410            return IrExpr::Assign {
411                op: AssignOp::Assign,
412                target: Box::new(target),
413                value: Box::new(IrExpr::Binary {
414                    op: BinOp::UrShr,
415                    left: Box::new(base_expr),
416                    right: value,
417                    left_type: Some(base_type),
418                    right_type: Some(right_type),
419                }),
420            };
421        }
422        // %= → a = a % b  (non-BigInt: use RemExpr for jsRem with type conversion)
423        if ae.operator == AssignmentOperator::Remainder {
424            let target = self.lower_assign_target(&ae.left);
425            let target_type = self.infer_assign_target_type(&ae.left);
426            let value = Box::new(self.lower_expr(&ae.right));
427            // BigInt %= falls through to the BigInt compound expansion below
428            if target_type != Some(ZigType::BigInt) {
429                let base_expr = target
430                    .to_read_expr()
431                    .unwrap_or_else(|| IrExpr::Ident(IrIdent::new("__target")));
432                // When assigning % result to an i64 variable, set result_type so
433                // the emit layer wraps in @as(i64, @intFromFloat(jsRem(...)))
434                let result_type = if target_type == Some(ZigType::I64) {
435                    Some(ZigType::I64)
436                } else {
437                    None
438                };
439                return IrExpr::Assign {
440                    op: AssignOp::Assign,
441                    target: Box::new(target),
442                    value: Box::new(IrExpr::RemExpr {
443                        left: Box::new(base_expr),
444                        right: value,
445                        result_type,
446                    }),
447                };
448            }
449            // BigInt %=: fall through to BigInt compound expansion below
450        }
451        // &&= / ||= / ??= → expand into Assign + Logical
452        // This reuses the Logical emitter's type-aware JsAny.from() wrapping,
453        // avoiding type mismatches between comptime_int and JsAny branches.
454        // For &&/|| the emitter uses js_runtime.isTruthy() (anytype), so it works
455        // for i64 as well. For ?? the emitter uses .isNullish() (JsAny-only).
456        if matches!(
457            ae.operator,
458            AssignmentOperator::LogicalAnd
459                | AssignmentOperator::LogicalOr
460                | AssignmentOperator::LogicalNullish
461        ) {
462            let target_type = self
463                .infer_assign_target_type(&ae.left)
464                .unwrap_or(ZigType::JsAny);
465
466            // ??= on non-JsAny types is a no-op: the value can't be null/undefined
467            // in our type system (i64, bool, string, etc.). Evaluate RHS for side
468            // effects, keep target unchanged.
469            if ae.operator == AssignmentOperator::LogicalNullish && target_type != ZigType::JsAny {
470                let target = self.lower_assign_target(&ae.left);
471                let value = self.lower_expr(&ae.right);
472                if let Some(read) = target.to_read_expr() {
473                    return IrExpr::Sequence(vec![value, read]);
474                }
475                // Fall through for unsupported targets
476            } else {
477                let target = self.lower_assign_target(&ae.left);
478                let value = self.lower_expr(&ae.right);
479                let value_type = self.infer_expr_type(&ae.right).unwrap_or(ZigType::JsAny);
480                let logical_op = match ae.operator {
481                    AssignmentOperator::LogicalAnd => LogicalOp::And,
482                    AssignmentOperator::LogicalOr => LogicalOp::Or,
483                    AssignmentOperator::LogicalNullish => LogicalOp::Nullish,
484                    _ => unreachable!(),
485                };
486                if let Some(read) = target.to_read_expr() {
487                    return IrExpr::Assign {
488                        op: AssignOp::Assign,
489                        target: Box::new(target),
490                        value: Box::new(IrExpr::Logical {
491                            op: logical_op,
492                            left: Box::new(read),
493                            right: Box::new(value),
494                            left_type: Some(target_type),
495                            right_type: Some(value_type),
496                        }),
497                    };
498                }
499                // For unsupported targets (index, destructure), fall through to default path
500            }
501        }
502
503        // ── BigInt compound assignment expansion ──
504        // BigInt has no Zig +=, -=, etc. Expand `bigVar += expr` into
505        // `bigVar = bigVar + expr` (using IrExpr::Binary with BigInt type info
506        // so the Emitter generates .add() / .sub() / etc. method calls).
507        let is_compound = ae.operator != AssignmentOperator::Assign
508            && ae.operator != AssignmentOperator::LogicalAnd
509            && ae.operator != AssignmentOperator::LogicalOr
510            && ae.operator != AssignmentOperator::LogicalNullish;
511
512        if is_compound {
513            // Infer target type from the left-hand side
514            let target_type = self.infer_assign_target_type(&ae.left);
515            if target_type == Some(ZigType::BigInt) {
516                let target = self.lower_assign_target(&ae.left);
517                let value = Box::new(self.lower_expr(&ae.right));
518                if let Some(read) = target.to_read_expr() {
519                    let bin_op = match ae.operator {
520                        AssignmentOperator::Addition => BinOp::Add,
521                        AssignmentOperator::Subtraction => BinOp::Sub,
522                        AssignmentOperator::Multiplication => BinOp::Mul,
523                        AssignmentOperator::Division => BinOp::Div,
524                        AssignmentOperator::Remainder => BinOp::Mod,
525                        AssignmentOperator::ShiftLeft => BinOp::Shl,
526                        AssignmentOperator::ShiftRight => BinOp::Shr,
527                        AssignmentOperator::ShiftRightZeroFill => BinOp::UrShr,
528                        AssignmentOperator::BitwiseAnd => BinOp::BitAnd,
529                        AssignmentOperator::BitwiseOR => BinOp::BitOr,
530                        AssignmentOperator::BitwiseXOR => BinOp::BitXor,
531                        _ => BinOp::Add, // fallback, shouldn't reach here
532                    };
533                    return IrExpr::Assign {
534                        op: AssignOp::Assign,
535                        target: Box::new(target),
536                        value: Box::new(IrExpr::Binary {
537                            op: bin_op,
538                            left: Box::new(read),
539                            right: value,
540                            left_type: Some(ZigType::BigInt),
541                            right_type: Some(ZigType::BigInt),
542                        }),
543                    };
544                }
545                // For unsupported BigInt targets (index, destructure), fall through
546                // to default path (may produce invalid Zig but handles common cases)
547            }
548        }
549
550        let op = match ae.operator {
551            AssignmentOperator::Assign => AssignOp::Assign,
552            AssignmentOperator::Addition => AssignOp::Add,
553            AssignmentOperator::Subtraction => AssignOp::Sub,
554            AssignmentOperator::Multiplication => AssignOp::Mul,
555            AssignmentOperator::Division => AssignOp::Div,
556            AssignmentOperator::Remainder => AssignOp::Mod,
557            AssignmentOperator::ShiftLeft => AssignOp::Shl,
558            AssignmentOperator::ShiftRight => AssignOp::Shr,
559            AssignmentOperator::BitwiseAnd => AssignOp::BitAnd,
560            AssignmentOperator::BitwiseOR => AssignOp::BitOr,
561            AssignmentOperator::BitwiseXOR => AssignOp::BitXor,
562            AssignmentOperator::LogicalAnd => AssignOp::LogicAnd,
563            AssignmentOperator::LogicalOr => AssignOp::LogicOr,
564            AssignmentOperator::LogicalNullish => AssignOp::Nullish,
565            // Exponential handled above
566            _ => AssignOp::Assign,
567        };
568        let target = Box::new(self.lower_assign_target(&ae.left));
569        let value = Box::new(self.lower_expr(&ae.right));
570
571        // ── Detect `target = expr % expr2` where target is i64 ──
572        // If the value is a RemExpr (integer %) and the target is i64,
573        // set result_type so the emitter wraps in @intFromFloat.
574        if op == AssignOp::Assign {
575            let target_type = self.infer_assign_target_type(&ae.left);
576            if target_type == Some(ZigType::I64)
577                && let IrExpr::RemExpr {
578                    result_type: None,
579                    left,
580                    right,
581                } = value.as_ref()
582            {
583                return IrExpr::Assign {
584                    op,
585                    target,
586                    value: Box::new(IrExpr::RemExpr {
587                        left: left.clone(),
588                        right: right.clone(),
589                        result_type: Some(ZigType::I64),
590                    }),
591                };
592            }
593            // Same for PowExpr: `x = base ** exp` when target is i64
594            if target_type == Some(ZigType::I64)
595                && let IrExpr::PowExpr {
596                    result_type: None,
597                    base,
598                    exp,
599                    base_type,
600                    exp_type,
601                } = value.as_ref()
602            {
603                return IrExpr::Assign {
604                    op,
605                    target,
606                    value: Box::new(IrExpr::PowExpr {
607                        base: base.clone(),
608                        exp: exp.clone(),
609                        base_type: base_type.clone(),
610                        exp_type: exp_type.clone(),
611                        result_type: Some(ZigType::I64),
612                    }),
613                };
614            }
615        }
616
617        IrExpr::Assign { op, target, value }
618    }
619
620    /// Lower an identifier assignment target, handling captured closure variables.
621    fn lower_ident_assign_target(&mut self, var_name: &str) -> crate::zigir::types::IrAssignTarget {
622        // Check if this identifier is a captured closure variable.
623        if let Some((_, _, is_mut)) = self
624            .closure_mgr
625            .current_captured
626            .iter()
627            .find(|(n, _, _)| n == var_name)
628        {
629            let field_name = self.make_ident(var_name).zig_name;
630            return crate::zigir::types::IrAssignTarget::Member {
631                object: Box::new(crate::zigir::types::IrExpr::Ident(IrIdent::new("self"))),
632                field: field_name,
633                is_pointer: *is_mut,
634                field_kind: if *is_mut {
635                    FieldKind::PointerDeref
636                } else {
637                    FieldKind::StructField
638                },
639            };
640        }
641
642        crate::zigir::types::IrAssignTarget::Ident(IrIdent::new(var_name))
643    }
644
645    /// Lower a static member assignment target (obj.prop).
646    fn lower_static_member_assign_target(
647        &mut self,
648        object: &Expression,
649        property_name: &str,
650    ) -> crate::zigir::types::IrAssignTarget {
651        crate::zigir::types::IrAssignTarget::Member {
652            object: Box::new(self.lower_expr(object)),
653            field: property_name.to_string(),
654            is_pointer: false,
655            field_kind: self.infer_member_field_kind(object, property_name),
656        }
657    }
658
659    /// Lower a computed member assignment target (obj[expr]).
660    fn lower_computed_member_assign_target(
661        &mut self,
662        object: &Expression,
663        expression: &Expression,
664    ) -> crate::zigir::types::IrAssignTarget {
665        let obj_type = self.infer_expr_type(object);
666        let is_arraylist = obj_type
667            .as_ref()
668            .map(|t| matches!(t, ZigType::ArrayList(_)))
669            .unwrap_or(false);
670        crate::zigir::types::IrAssignTarget::Index {
671            object: Box::new(self.lower_expr(object)),
672            index: Box::new(self.lower_expr(expression)),
673            index_kind: if is_arraylist {
674                IndexKind::ArrayListItem
675            } else {
676                IndexKind::SliceIndex
677            },
678        }
679    }
680
681    /// Lower a simple assignment target (from UpdateExpression).
682    /// SimpleAssignmentTarget can be an identifier or member expression.
683    pub(super) fn lower_simple_assign_target(
684        &mut self,
685        target: &SimpleAssignmentTarget,
686    ) -> crate::zigir::types::IrAssignTarget {
687        match target {
688            SimpleAssignmentTarget::AssignmentTargetIdentifier(id) => {
689                self.lower_ident_assign_target(id.name.as_str())
690            }
691            SimpleAssignmentTarget::StaticMemberExpression(mem) => {
692                self.lower_static_member_assign_target(&mem.object, mem.property.name.as_str())
693            }
694            SimpleAssignmentTarget::ComputedMemberExpression(mem) => {
695                self.lower_computed_member_assign_target(&mem.object, &mem.expression)
696            }
697            SimpleAssignmentTarget::PrivateFieldExpression(pfe) => {
698                // Private field assignment (this.#field += ...) — treat as struct field access
699                self.lower_static_member_assign_target(&pfe.object, pfe.field.name.as_str())
700            }
701            _ => crate::zigir::types::IrAssignTarget::CompileError {
702                msg: "unsupported assignment target".to_string(),
703            },
704        }
705    }
706
707    /// Extract (pattern, default) from an AssignmentTargetMaybeDefault.
708    pub(super) fn lower_maybe_default(
709        &mut self,
710        target: &AssignmentTargetMaybeDefault,
711    ) -> (IrIdent, Option<crate::zigir::types::IrExpr>) {
712        match target {
713            AssignmentTargetMaybeDefault::AssignmentTargetWithDefault(atwd) => {
714                let pattern = self.extract_target_ident(&atwd.binding);
715                let default = Some(self.lower_expr(&atwd.init));
716                (pattern, default)
717            }
718            AssignmentTargetMaybeDefault::AssignmentTargetIdentifier(id) => {
719                (IrIdent::new(id.name.as_str()), None)
720            }
721            _ => (IrIdent::new("_"), None),
722        }
723    }
724
725    /// Extract an identifier name from an AssignmentTarget (best-effort).
726    pub(super) fn extract_target_ident(&self, target: &AssignmentTarget) -> IrIdent {
727        match target {
728            AssignmentTarget::AssignmentTargetIdentifier(id) => IrIdent::new(id.name.as_str()),
729            _ => IrIdent::new("_"),
730        }
731    }
732
733    /// Lower an assignment target (lhs).
734    pub(super) fn lower_assign_target(
735        &mut self,
736        target: &AssignmentTarget,
737    ) -> crate::zigir::types::IrAssignTarget {
738        match target {
739            AssignmentTarget::AssignmentTargetIdentifier(id) => {
740                self.lower_ident_assign_target(id.name.as_str())
741            }
742            AssignmentTarget::StaticMemberExpression(mem) => {
743                self.lower_static_member_assign_target(&mem.object, mem.property.name.as_str())
744            }
745            AssignmentTarget::ComputedMemberExpression(mem) => {
746                self.lower_computed_member_assign_target(&mem.object, &mem.expression)
747            }
748            AssignmentTarget::PrivateFieldExpression(pfe) => {
749                // Private field assignment (this.#field = ...) — treat as struct field access
750                self.lower_static_member_assign_target(&pfe.object, pfe.field.name.as_str())
751            }
752            AssignmentTarget::ObjectAssignmentTarget(ot) => {
753                let bindings: Vec<crate::zigir::types::IrDestructureBinding> = ot
754                    .properties
755                    .iter()
756                    .map(|prop| {
757                        match prop {
758                            AssignmentTargetProperty::AssignmentTargetPropertyIdentifier(ap) => {
759                                let pattern = IrIdent::new(ap.binding.name.as_str());
760                                let default = ap.init.as_ref().map(|e| self.lower_expr(e));
761                                crate::zigir::types::IrDestructureBinding { pattern, default }
762                            }
763                            AssignmentTargetProperty::AssignmentTargetPropertyProperty(ap) => {
764                                // e.g. { name: alias } — extract binding from value
765                                let (pattern, default) = self.lower_maybe_default(&ap.binding);
766                                crate::zigir::types::IrDestructureBinding { pattern, default }
767                            }
768                        }
769                    })
770                    .collect();
771                crate::zigir::types::IrAssignTarget::Destructure(bindings)
772            }
773            AssignmentTarget::ArrayAssignmentTarget(at) => {
774                let bindings: Vec<crate::zigir::types::IrDestructureBinding> = at
775                    .elements
776                    .iter()
777                    .filter_map(|elem| {
778                        elem.as_ref().map(|target| {
779                            let (pattern, default) = self.lower_maybe_default(target);
780                            crate::zigir::types::IrDestructureBinding { pattern, default }
781                        })
782                    })
783                    .collect();
784                crate::zigir::types::IrAssignTarget::Destructure(bindings)
785            }
786            _ => crate::zigir::types::IrAssignTarget::CompileError {
787                msg: "unsupported assignment target".to_string(),
788            },
789        }
790    }
791
792    /// Check if an expression is a string type (for string concatenation detection).
793    pub(super) fn expr_is_string(&self, expr: &Expression) -> bool {
794        match expr {
795            Expression::StringLiteral(_) => true,
796            Expression::TemplateLiteral(_) => true,
797            Expression::Identifier(_id) => {
798                // Use infer_expr_type which handles qualified name lookup
799                self.infer_expr_type(expr) == Some(ZigType::Str)
800            }
801            Expression::BinaryExpression(be) if be.operator == BinaryOperator::Addition => {
802                self.expr_is_string(&be.left) || self.expr_is_string(&be.right)
803            }
804            Expression::ParenthesizedExpression(pe) => self.expr_is_string(&pe.expression),
805            _ => self.infer_expr_type(expr) == Some(ZigType::Str),
806        }
807    }
808
809    /// Lower a string concatenation chain into IrExpr::AllocPrint.
810    /// Flattens nested `a + b + c` into a single format string + args list.
811    pub(super) fn lower_string_concat(
812        &mut self,
813        be: &BinaryExpression,
814    ) -> crate::zigir::types::IrExpr {
815        use crate::zigir::types::IrExpr;
816
817        let mut operands: Vec<&Expression> = Vec::new();
818        Self::collect_concat_from_be(be, &mut operands);
819
820        let mut fmt = String::new();
821        let mut args: Vec<IrExpr> = Vec::new();
822
823        for op in &operands {
824            match op {
825                Expression::StringLiteral(sl) => {
826                    fmt.push_str(&crate::zigir::emit::helpers::escape_zig_format_string(
827                        &sl.value,
828                    ));
829                }
830                _ => {
831                    // Pick placeholder based on inferred type
832                    let placeholder = if self.expr_is_string(op) {
833                        "{s}"
834                    } else {
835                        match self.infer_expr_type(op) {
836                            Some(ty) => helpers::format_specifier_for_type(&ty),
837                            None => "{any}",
838                        }
839                    };
840                    fmt.push_str(placeholder);
841                    // Unwrap parentheses before lowering
842                    let lowered = match op {
843                        Expression::ParenthesizedExpression(pe) => self.lower_expr(&pe.expression),
844                        _ => self.lower_expr(op),
845                    };
846                    args.push(lowered);
847                }
848            }
849        }
850
851        IrExpr::AllocPrint { fmt, args }
852    }
853
854    /// Recursively collect all operands in a string concatenation chain.
855    /// Only recurses into BinaryExpression(+); other nodes become leaves.
856    pub(super) fn collect_concat_from_be<'a>(
857        be: &'a BinaryExpression<'a>,
858        out: &mut Vec<&'a Expression<'a>>,
859    ) {
860        // Left side
861        if let Expression::BinaryExpression(ref left_be) = be.left {
862            if left_be.operator == BinaryOperator::Addition {
863                Self::collect_concat_from_be(left_be, out);
864            } else {
865                out.push(&be.left);
866            }
867        } else {
868            out.push(&be.left);
869        }
870
871        // Right side
872        if let Expression::BinaryExpression(ref right_be) = be.right {
873            if right_be.operator == BinaryOperator::Addition {
874                Self::collect_concat_from_be(right_be, out);
875            } else {
876                out.push(&be.right);
877            }
878        } else {
879            out.push(&be.right);
880        }
881    }
882
883    /// Lower `x instanceof Type` with prototype chain semantics.
884    ///
885    /// Three strategies:
886    /// 1. **Error types** → `e.name == "TypeName"` (existing efficient approach)
887    /// 2. **Compile-time type-aware** → known left type resolves at transpile time
888    /// 3. **Runtime** → emit `js_runtime.instanceOf(value, "TypeName")` for dynamic types
889    fn lower_instanceof(&mut self, be: &BinaryExpression) -> crate::zigir::types::IrExpr {
890        use crate::zigir::builtins::BuiltinModule;
891        use crate::zigir::kinds::FieldKind;
892        use crate::zigir::types::{IrBuiltinCall, IrExpr};
893
894        // Get the type name from the right operand
895        let type_name = if let Expression::Identifier(ident) = &be.right {
896            ident.name.to_string()
897        } else {
898            return self.compile_error_expr(
899                be.span,
900                "instanceof: right operand must be an identifier (constructor name)",
901            );
902        };
903
904        // ── Strategy 1: Error types → .name comparison ──
905        let error_types = [
906            "Error",
907            "URIError",
908            "TypeError",
909            "RangeError",
910            "SyntaxError",
911            "ReferenceError",
912            "EvalError",
913            "AggregateError",
914            "SuppressedError",
915        ];
916        if error_types.contains(&type_name.as_str()) {
917            let left_expr = self.lower_expr(&be.left);
918            return IrExpr::Binary {
919                op: BinOp::Eq,
920                left: Box::new(IrExpr::FieldAccess {
921                    object: Box::new(left_expr),
922                    field: "name".to_string(),
923                    field_kind: FieldKind::StructField,
924                }),
925                right: Box::new(IrExpr::StringLiteral(type_name)),
926                left_type: Some(ZigType::Str),
927                right_type: Some(ZigType::Str),
928            };
929        }
930
931        // ── Strategy 2: Compile-time type-aware instanceof ──
932        if let Some(left_ty) = self.infer_expr_type(&be.left)
933            && let Some(result) = self.resolve_instanceof_compile_time(&left_ty, &type_name)
934        {
935            return result;
936        }
937
938        // ── Strategy 3: Runtime instanceof check ──
939        let left_expr = self.lower_expr(&be.left);
940        IrExpr::BuiltinCall(IrBuiltinCall::simple(
941            BuiltinModule::JsRuntime,
942            "instanceOf",
943            None,
944            Some(Box::new(left_expr)),
945            vec![IrExpr::StringLiteral(type_name)],
946            ZigType::Bool,
947        ))
948    }
949
950    /// Resolve `instanceof` at compile time when the left operand's type is known.
951    ///
952    /// Returns `Some(IrExpr)` if resolved, `None` if we need runtime dispatch.
953    fn resolve_instanceof_compile_time(
954        &self,
955        left_ty: &ZigType,
956        type_name: &str,
957    ) -> Option<crate::zigir::types::IrExpr> {
958        use crate::zigir::types::IrExpr;
959
960        match left_ty {
961            // ArrayList matches Array
962            ZigType::ArrayList(_) => {
963                if type_name == "Array" || type_name == "Object" {
964                    return Some(IrExpr::BoolLiteral(true));
965                }
966                Some(IrExpr::BoolLiteral(false))
967            }
968            // Map matches Map and Object
969            ZigType::NamedStruct(name) if name == "Map" => {
970                if type_name == "Map" || type_name == "Object" {
971                    return Some(IrExpr::BoolLiteral(true));
972                }
973                Some(IrExpr::BoolLiteral(false))
974            }
975            // Set matches Set and Object
976            ZigType::NamedStruct(name) if name == "Set" => {
977                if type_name == "Set" || type_name == "Object" {
978                    return Some(IrExpr::BoolLiteral(true));
979                }
980                Some(IrExpr::BoolLiteral(false))
981            }
982            // Custom class: check direct match and prototype chain
983            ZigType::NamedStruct(class_name) => {
984                if class_name == type_name {
985                    return Some(IrExpr::BoolLiteral(true));
986                }
987                if type_name == "Object" {
988                    // All class instances are instanceof Object
989                    return Some(IrExpr::BoolLiteral(true));
990                }
991                // Walk prototype chain via class_extends_map
992                let mut current = class_name.as_str();
993                loop {
994                    if current == type_name {
995                        return Some(IrExpr::BoolLiteral(true));
996                    }
997                    if let Some(parent) = self.class_extends_map.get(current) {
998                        current = parent.as_str();
999                    } else {
1000                        break;
1001                    }
1002                }
1003                Some(IrExpr::BoolLiteral(false))
1004            }
1005            // String primitives: NOT instanceof String in JS (only String objects are)
1006            ZigType::Str => Some(IrExpr::BoolLiteral(false)),
1007            // Numeric/Boolean primitives are never `instanceof` their wrapper types
1008            // in JS (primitives lack [[Prototype]]).  Both branches always return false
1009            // regardless of the right-hand type_name.
1010            ZigType::I64 | ZigType::F64 | ZigType::Bool => Some(IrExpr::BoolLiteral(false)),
1011            // For JsAny / Anytype, we can't resolve at compile time
1012            ZigType::JsAny | ZigType::Anytype => None,
1013            // Other types: conservatively say we can't resolve
1014            _ => None,
1015        }
1016    }
1017
1018    fn bigint_unary_builtin(
1019        &mut self,
1020        method: &str,
1021        operand: crate::zigir::types::IrExpr,
1022    ) -> crate::zigir::types::IrExpr {
1023        crate::zigir::types::IrExpr::BuiltinCall(crate::zigir::types::IrBuiltinCall::simple(
1024            BuiltinModule::JsBigInt,
1025            method,
1026            None,
1027            Some(Box::new(operand)),
1028            vec![],
1029            ZigType::BigInt,
1030        ))
1031    }
1032}