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 => {
59                let left_type = self.infer_expr_type(&be.left).unwrap_or(ZigType::I64);
60                let right_type = self.infer_expr_type(&be.right).unwrap_or(ZigType::I64);
61                // BigInt / BigInt or mixed BigInt: use BinOp::Div so emit_bigint_binary
62                // (for pure BigInt) or error.JsThrow (for mixed) is generated at emit time.
63                if left_type == ZigType::BigInt || right_type == ZigType::BigInt {
64                    if let Some(ctx) = self.fn_ctx.as_mut() {
65                        ctx.has_bigint_div = true;
66                        // Mixed BigInt division throws TypeError at runtime
67                        if left_type != right_type {
68                            ctx.has_catchable_error = true;
69                        }
70                    }
71                    return IrExpr::Binary {
72                        op: BinOp::Div,
73                        left: Box::new(self.lower_expr(&be.left)),
74                        right: Box::new(self.lower_expr(&be.right)),
75                        left_type: Some(left_type),
76                        right_type: Some(right_type),
77                    };
78                }
79                // Non-BigInt: JS `/` always returns f64. Emit a DivExpr with type info
80                // so the Emitter can generate the correct f64 coercion and i64 wrapping
81                // (when result_type is later set to Some(I64) by coerce_i64_result_type).
82                return IrExpr::DivExpr {
83                    left: Box::new(self.lower_expr(&be.left)),
84                    right: Box::new(self.lower_expr(&be.right)),
85                    left_type,
86                    right_type,
87                    result_type: None, // standalone `/` keeps f64 result
88                };
89            }
90            BinaryOperator::Remainder => {
91                let left_type = self.infer_expr_type(&be.left).unwrap_or(ZigType::I64);
92                let right_type = self.infer_expr_type(&be.right).unwrap_or(ZigType::I64);
93                // BigInt % BigInt: use BinOp::Mod so emit_bigint_binary generates .rem() call.
94                if left_type == ZigType::BigInt || right_type == ZigType::BigInt {
95                    // BigInt modulo can throw RangeError — mark function as can_throw
96                    if let Some(ctx) = self.fn_ctx.as_mut() {
97                        ctx.has_bigint_div = true;
98                    }
99                    return IrExpr::Binary {
100                        op: BinOp::Mod,
101                        left: Box::new(self.lower_expr(&be.left)),
102                        right: Box::new(self.lower_expr(&be.right)),
103                        left_type: Some(left_type),
104                        right_type: Some(right_type),
105                    };
106                }
107                // Float % any: use BinOp::Mod so emit layer generates @rem(f64, f64).
108                if left_type == ZigType::F64 || right_type == ZigType::F64 {
109                    return IrExpr::Binary {
110                        op: BinOp::Mod,
111                        left: Box::new(self.lower_expr(&be.left)),
112                        right: Box::new(self.lower_expr(&be.right)),
113                        left_type: Some(left_type),
114                        right_type: Some(right_type),
115                    };
116                }
117                // Integer %: use RemExpr (jsRem returns f64, preserves signed zero).
118                // result_type is set later by lower_assignment when assigning to i64.
119                return IrExpr::RemExpr {
120                    left: Box::new(self.lower_expr(&be.left)),
121                    right: Box::new(self.lower_expr(&be.right)),
122                    left_type,
123                    right_type,
124                    result_type: None, // standalone `%` keeps f64 result
125                };
126            }
127            BinaryOperator::Exponential => {
128                let left_type = self.infer_expr_type(&be.left).unwrap_or(ZigType::F64);
129                let right_type = self.infer_expr_type(&be.right).unwrap_or(ZigType::F64);
130                // BigInt ** BigInt: use BinOp::Pow so emit_bigint_binary generates .pow() call.
131                if left_type == ZigType::BigInt || right_type == ZigType::BigInt {
132                    // BigInt ** can throw at runtime:
133                    // - Mixed BigInt (e.g., 2n ** 2): TypeError
134                    // - BigInt ** BigInt with negative exponent: RangeError (toU64 fails)
135                    if let Some(ctx) = self.fn_ctx.as_mut() {
136                        ctx.has_catchable_error = true;
137                    }
138                    return IrExpr::Binary {
139                        op: BinOp::Pow,
140                        left: Box::new(self.lower_expr(&be.left)),
141                        right: Box::new(self.lower_expr(&be.right)),
142                        left_type: Some(left_type),
143                        right_type: Some(right_type),
144                    };
145                }
146                // Non-BigInt: JS `**` always returns f64. Emit a PowExpr with type info
147                // so the Emitter can generate the correct f64 coercion.
148                return IrExpr::PowExpr {
149                    base: Box::new(self.lower_expr(&be.left)),
150                    exp: Box::new(self.lower_expr(&be.right)),
151                    base_type: left_type,
152                    exp_type: right_type,
153                    result_type: None, // standalone `**` always returns f64
154                };
155            }
156            BinaryOperator::LessThan => BinOp::Lt,
157            BinaryOperator::GreaterThan => BinOp::Gt,
158            BinaryOperator::LessEqualThan => BinOp::Le,
159            BinaryOperator::GreaterEqualThan => BinOp::Ge,
160            BinaryOperator::Equality => BinOp::Eq,
161            BinaryOperator::Inequality => BinOp::Ne,
162            BinaryOperator::StrictEquality => BinOp::StrictEq,
163            BinaryOperator::StrictInequality => BinOp::StrictNe,
164            BinaryOperator::BitwiseAnd => BinOp::BitAnd,
165            BinaryOperator::BitwiseOR => BinOp::BitOr,
166            BinaryOperator::BitwiseXOR => BinOp::BitXor,
167            BinaryOperator::ShiftLeft => BinOp::Shl,
168            BinaryOperator::ShiftRight => BinOp::Shr,
169            BinaryOperator::ShiftRightZeroFill => BinOp::UrShr,
170            // Instanceof/In are handled above (CompileError). Kept for
171            // exhaustiveness — use safe fallback instead of unreachable! (P0-9 fix).
172            BinaryOperator::Instanceof | BinaryOperator::In => BinOp::Add,
173        };
174
175        let left_type = self.infer_expr_type(&be.left);
176        let right_type = self.infer_expr_type(&be.right);
177
178        // BigInt division/modulo can throw RangeError — mark function as can_throw
179        if matches!(op, BinOp::Div | BinOp::Mod)
180            && (left_type.as_ref() == Some(&ZigType::BigInt)
181                || right_type.as_ref() == Some(&ZigType::BigInt))
182            && let Some(ctx) = self.fn_ctx.as_mut()
183        {
184            ctx.has_bigint_div = true;
185        }
186
187        // BigInt mixed-type ops, BigInt >>>, BigInt ** BigInt, and BigInt << >> BigInt
188        // throw or can throw at runtime. These are emitted as `return error.JsThrow`
189        // (not @panic) so JS try/catch can catch them.
190        // Mark the function as can_throw so the signature includes `!`.
191        {
192            let left_is_bigint = left_type.as_ref() == Some(&ZigType::BigInt);
193            let right_is_bigint = right_type.as_ref() == Some(&ZigType::BigInt);
194            let is_mixed_bigint = left_is_bigint != right_is_bigint; // XOR: exactly one is BigInt
195            let is_bigint_urshr = op == BinOp::UrShr && (left_is_bigint || right_is_bigint);
196            // BigInt << >> BigInt: toI64() can fail for very large shift amounts → error.JsThrow
197            let is_bigint_shift =
198                matches!(op, BinOp::Shl | BinOp::Shr) && left_is_bigint && right_is_bigint;
199            if ((is_mixed_bigint
200                && matches!(
201                    op,
202                    BinOp::Add
203                        | BinOp::Sub
204                        | BinOp::Mul
205                        | BinOp::Div
206                        | BinOp::Mod
207                        | BinOp::Pow
208                        | BinOp::BitAnd
209                        | BinOp::BitOr
210                        | BinOp::BitXor
211                        | BinOp::Shl
212                        | BinOp::Shr
213                ))
214                || is_bigint_urshr
215                || is_bigint_shift)
216                && let Some(ctx) = self.fn_ctx.as_mut()
217            {
218                ctx.has_catchable_error = true;
219            }
220        }
221
222        IrExpr::Binary {
223            op,
224            left: Box::new(self.lower_expr(&be.left)),
225            right: Box::new(self.lower_expr(&be.right)),
226            left_type,
227            right_type,
228        }
229    }
230
231    /// Lower a unary expression.
232    pub(super) fn lower_unary(&mut self, ue: &UnaryExpression) -> crate::zigir::types::IrExpr {
233        use crate::zigir::types::IrExpr;
234
235        match ue.operator {
236            UnaryOperator::UnaryNegation => {
237                // -0.0 must be lowered directly as FloatLiteral(-0.0) to
238                // preserve IEEE 754 signed zero. Otherwise the operand 0.0 is
239                // lowered as IntLiteral(0) (0.0 fits in i64), and constant
240                // folding collapses Neg(IntLiteral(0)) -> IntLiteral(0),
241                // losing the sign bit.
242                if let Expression::NumericLiteral(nl) = &ue.argument
243                    && nl.value == 0.0
244                {
245                    return IrExpr::FloatLiteral(-0.0);
246                }
247                if self.infer_expr_type(&ue.argument) == Some(ZigType::BigInt) {
248                    let operand = self.lower_expr(&ue.argument);
249                    return self.bigint_unary_builtin("bigIntNeg", operand);
250                }
251                IrExpr::Unary {
252                    op: UnaOp::Neg,
253                    operand: Box::new(self.lower_expr(&ue.argument)),
254                    operand_type: self.infer_expr_type(&ue.argument),
255                }
256            }
257            UnaryOperator::UnaryPlus => {
258                // JS unary `+` performs ToNumber conversion:
259                //   +true → 1, +false → 0, +null → 0, +undefined → NaN,
260                //   +"5" → 5, +5 → 5 (no-op for numbers).
261                // Previously this was a no-op for all types, leaving bool and
262                // string operands unconverted (R8-E1).
263                let arg = &ue.argument;
264                let ty = self.infer_expr_type(arg);
265                match ty {
266                    Some(ZigType::Bool) => {
267                        // Constant-fold boolean literals.
268                        if let Expression::BooleanLiteral(bl) = arg {
269                            return IrExpr::IntLiteral(if bl.value { 1 } else { 0 });
270                        }
271                        // For a bool variable, emit `(if (expr) 1 else 0)`
272                        // to coerce to i64 without needing a new IR node.
273                        IrExpr::Conditional {
274                            cond: Box::new(self.lower_expr(arg)),
275                            then: Box::new(IrExpr::IntLiteral(1)),
276                            else_: Box::new(IrExpr::IntLiteral(0)),
277                        }
278                    }
279                    Some(ZigType::Str) => {
280                        // String → f64 via js_number.constructor (matches
281                        // Number(str) semantics: parseFloat with NaN fallback).
282                        IrExpr::BuiltinCall(crate::zigir::types::IrBuiltinCall::simple(
283                            BuiltinModule::JsNumber,
284                            "constructor",
285                            None,
286                            None,
287                            vec![self.lower_expr(arg)],
288                            ZigType::F64,
289                        ))
290                    }
291                    // Already numeric or BigInt: no-op (BigInt + is a JS
292                    // TypeError, but we let Zig surface the type mismatch).
293                    _ => self.lower_expr(arg),
294                }
295            }
296            UnaryOperator::LogicalNot => IrExpr::Unary {
297                op: UnaOp::Not,
298                operand: Box::new(self.lower_expr(&ue.argument)),
299                operand_type: self.infer_expr_type(&ue.argument),
300            },
301            UnaryOperator::BitwiseNot => {
302                if self.infer_expr_type(&ue.argument) == Some(ZigType::BigInt) {
303                    let operand = self.lower_expr(&ue.argument);
304                    return self.bigint_unary_builtin("bigIntBitwiseNot", operand);
305                }
306                IrExpr::Unary {
307                    op: UnaOp::BitNot,
308                    operand: Box::new(self.lower_expr(&ue.argument)),
309                    operand_type: self.infer_expr_type(&ue.argument),
310                }
311            }
312            UnaryOperator::Typeof => {
313                if let Some(ty) = self.infer_expr_type(&ue.argument)
314                    && let Some(js_typeof) = ty.to_js_typeof()
315                {
316                    let mut idents = HashSet::new();
317                    Self::collect_ast_expr_idents(&ue.argument, &mut idents);
318                    if let Some(ctx) = self.fn_ctx.as_mut() {
319                        ctx.compile_time_referenced_idents.extend(idents);
320                    }
321                    return IrExpr::StringLiteral(js_typeof.to_string());
322                }
323                IrExpr::BuiltinCall(crate::zigir::types::IrBuiltinCall::simple(
324                    BuiltinModule::JsRuntime,
325                    "jsTypeof",
326                    None,
327                    None,
328                    vec![self.lower_expr(&ue.argument)],
329                    ZigType::Str,
330                ))
331            }
332            UnaryOperator::Void => IrExpr::Void(Box::new(self.lower_expr(&ue.argument))),
333            UnaryOperator::Delete => {
334                // delete obj.prop → IrBuiltinCall { JsRuntime, "deleteKey", obj, [prop] }
335                // delete obj[expr] → IrBuiltinCall { JsRuntime, "deleteByKey", obj, [expr] }
336                //
337                // Bug fix (Agent1 P1-6): When the receiver is a non-Identifier
338                // expression (e.g. `delete getObj().prop`, `delete arr[i].prop`,
339                // `delete obj.a.b`), the previous code set both `obj_name` and
340                // `obj_expr` to `None`, silently dropping the receiver —
341                // including its side effects. The emit layer would then produce
342                // invalid Zig like `_ = .deleteKey("prop")`. Now we lower the
343                // receiver expression and pass it via `obj_expr` so the Emitter
344                // renders it inline (`Self::emit_expr_inline`).
345                match &ue.argument {
346                    Expression::StaticMemberExpression(mem) => {
347                        let (obj_name, obj_expr) = match &mem.object {
348                            Expression::Identifier(id) => {
349                                (Some(id.name.as_str().to_string()), None)
350                            }
351                            other => {
352                                // Lower the receiver so its side effects happen
353                                // exactly once at the delete call site.
354                                (None, Some(Box::new(self.lower_expr(other))))
355                            }
356                        };
357                        IrExpr::BuiltinCall(crate::zigir::types::IrBuiltinCall::simple(
358                            BuiltinModule::JsRuntime,
359                            "deleteKey",
360                            obj_name,
361                            obj_expr,
362                            vec![IrExpr::StringLiteral(
363                                mem.property.name.as_str().to_string(),
364                            )],
365                            ZigType::Bool,
366                        ))
367                    }
368                    Expression::ComputedMemberExpression(mem) => {
369                        let (obj_name, obj_expr) = match &mem.object {
370                            Expression::Identifier(id) => {
371                                (Some(id.name.as_str().to_string()), None)
372                            }
373                            other => (None, Some(Box::new(self.lower_expr(other)))),
374                        };
375                        IrExpr::BuiltinCall(crate::zigir::types::IrBuiltinCall::simple(
376                            BuiltinModule::JsRuntime,
377                            "deleteByKey",
378                            obj_name,
379                            obj_expr,
380                            vec![self.lower_expr(&mem.expression)],
381                            ZigType::Bool,
382                        ))
383                    }
384                    _ => {
385                        self.compile_error_expr(ue.span, "delete operator requires property access")
386                    }
387                }
388            }
389        }
390    }
391
392    /// Lower an update expression (++/--).
393    pub(super) fn lower_update(&mut self, ue: &UpdateExpression) -> crate::zigir::types::IrExpr {
394        use crate::zigir::types::IrExpr;
395
396        // Check if the target is BigInt — BigInt has no Zig +=, -=,
397        // so we must expand `x++` into `x = x + BigInt(1)` and
398        // `x--` into `x = x - BigInt(1)` using method calls.
399        let target_type = self.infer_simple_assign_target_type(&ue.argument);
400        if target_type == Some(ZigType::BigInt) {
401            let target = self.lower_simple_assign_target(&ue.argument);
402            let Some(read_expr) = target.to_read_expr() else {
403                return IrExpr::Update {
404                    op: if ue.operator == UpdateOperator::Increment {
405                        UpdateOp::Increment
406                    } else {
407                        UpdateOp::Decrement
408                    },
409                    target: Box::new(target),
410                    is_expr_stmt: self.in_expr_stmt,
411                    prefix: ue.prefix,
412                };
413            };
414            let bin_op = if ue.operator == UpdateOperator::Increment {
415                BinOp::Add
416            } else {
417                BinOp::Sub
418            };
419
420            // For prefix `++x`: an `Assign` expression evaluates to the
421            // assigned (new) value, which matches JS semantics for prefix
422            // (the expression returns the value AFTER incrementing).
423            if ue.prefix {
424                return IrExpr::Assign {
425                    op: AssignOp::Assign,
426                    target: Box::new(target),
427                    value: Box::new(IrExpr::Binary {
428                        op: bin_op,
429                        left: Box::new(read_expr),
430                        right: Box::new(IrExpr::BigIntLiteral("1".to_string())),
431                        left_type: Some(ZigType::BigInt),
432                        right_type: Some(ZigType::BigInt),
433                    }),
434                };
435            }
436
437            // For postfix `x++`: JS spec returns the OLD value of `x`.
438            // An `Assign` expression alone would return the NEW value, so
439            // we capture the pre-increment value in a temp variable, then
440            // wrap the assign + temp in a BlockExpr so the expression
441            // result is the temp (old value):
442            //   (blk: {
443            //     const __bi_post_N = <read_expr>;
444            //     <target> = __bi_post_N + BigInt(1);
445            //     break :blk __bi_post_N;
446            //   })
447            use crate::zigir::types::{IrStmt, IrVarDecl};
448            let temp_name = self.name_mangler.next_name("__bi_post");
449            let blk_label = self.name_mangler.next_name("_bi_post_blk");
450            let temp_ident = IrExpr::Ident(IrIdent::new(&temp_name));
451            let var_decl = IrStmt::VarDecl(IrVarDecl {
452                name: IrIdent::new(&temp_name),
453                is_const: true,
454                zig_type: None,
455                init: Some(read_expr),
456                is_json_parse: false,
457                needs_var_suppression: false,
458                needs_deinit: false,
459            });
460            let assign_stmt = IrStmt::Expr(IrExpr::Assign {
461                op: AssignOp::Assign,
462                target: Box::new(target),
463                value: Box::new(IrExpr::Binary {
464                    op: bin_op,
465                    left: Box::new(temp_ident.clone()),
466                    right: Box::new(IrExpr::BigIntLiteral("1".to_string())),
467                    left_type: Some(ZigType::BigInt),
468                    right_type: Some(ZigType::BigInt),
469                }),
470            });
471            return IrExpr::BlockExpr {
472                label: blk_label,
473                body: vec![var_decl, assign_stmt],
474                result: Box::new(temp_ident),
475            };
476        }
477
478        // Non-BigInt: emit standard ++/--
479        let op = if ue.operator == UpdateOperator::Increment {
480            UpdateOp::Increment
481        } else {
482            UpdateOp::Decrement
483        };
484        let target = Box::new(self.lower_simple_assign_target(&ue.argument));
485        IrExpr::Update {
486            op,
487            target,
488            is_expr_stmt: self.in_expr_stmt,
489            prefix: ue.prefix,
490        }
491    }
492
493    /// Lower an assignment expression.
494    pub(super) fn lower_assignment(
495        &mut self,
496        ae: &AssignmentExpression,
497    ) -> crate::zigir::types::IrExpr {
498        use crate::zigir::types::IrExpr;
499
500        // ── Special-case compound assignments that need expansion ──
501        // **= → a = a ** b
502        if ae.operator == AssignmentOperator::Exponential {
503            let target = self.lower_assign_target(&ae.left);
504            let value = Box::new(self.lower_expr(&ae.right));
505            let target_type = self.infer_assign_target_type(&ae.left);
506            let (bind, target, base_expr) = self.maybe_bind_member_object_for_compound(target);
507            let break_value = base_expr.clone();
508            let assign = if target_type == Some(ZigType::BigInt) {
509                IrExpr::Assign {
510                    op: AssignOp::Assign,
511                    target: Box::new(target),
512                    value: Box::new(IrExpr::Binary {
513                        op: BinOp::Pow,
514                        left: Box::new(base_expr),
515                        right: value,
516                        left_type: Some(ZigType::BigInt),
517                        right_type: Some(ZigType::BigInt),
518                    }),
519                }
520            } else {
521                // Non-BigInt: a = std.math.pow(a, b) via PowExpr
522                let base_type = target_type.unwrap_or(ZigType::F64);
523                let exp_type = self.infer_expr_type(&ae.right).unwrap_or(ZigType::F64);
524                // When assigning pow result to an i64 variable, set result_type so
525                // the emit layer wraps in @as(i64, @intFromFloat(...))
526                let result_type = if base_type == ZigType::I64 {
527                    Some(ZigType::I64)
528                } else {
529                    None
530                };
531                IrExpr::Assign {
532                    op: AssignOp::Assign,
533                    target: Box::new(target),
534                    value: Box::new(IrExpr::PowExpr {
535                        base: Box::new(base_expr),
536                        exp: value,
537                        base_type,
538                        exp_type,
539                        result_type,
540                    }),
541                }
542            };
543            return self.wrap_compound_assign(bind, assign, break_value);
544        }
545        // >>>= → a = a >>> b (unsigned right shift cannot use >>= which is signed)
546        // Expand early, same pattern as **=, so the emitter uses the UrShr path.
547        if ae.operator == AssignmentOperator::ShiftRightZeroFill {
548            let target = self.lower_assign_target(&ae.left);
549            let value = Box::new(self.lower_expr(&ae.right));
550            let target_type = self.infer_assign_target_type(&ae.left);
551            let base_type = target_type.unwrap_or(ZigType::I64);
552            let right_type = self.infer_expr_type(&ae.right).unwrap_or(ZigType::I64);
553            let (bind, target, base_expr) = self.maybe_bind_member_object_for_compound(target);
554            let break_value = base_expr.clone();
555            let assign = IrExpr::Assign {
556                op: AssignOp::Assign,
557                target: Box::new(target),
558                value: Box::new(IrExpr::Binary {
559                    op: BinOp::UrShr,
560                    left: Box::new(base_expr),
561                    right: value,
562                    left_type: Some(base_type),
563                    right_type: Some(right_type),
564                }),
565            };
566            return self.wrap_compound_assign(bind, assign, break_value);
567        }
568        // %= → a = a % b  (non-BigInt: use RemExpr for jsRem with type conversion)
569        if ae.operator == AssignmentOperator::Remainder {
570            let target = self.lower_assign_target(&ae.left);
571            let target_type = self.infer_assign_target_type(&ae.left);
572            let value = Box::new(self.lower_expr(&ae.right));
573            // BigInt %= falls through to the BigInt compound expansion below
574            if target_type != Some(ZigType::BigInt) {
575                let (bind, target, base_expr) = self.maybe_bind_member_object_for_compound(target);
576                let break_value = base_expr.clone();
577                // When assigning % result to an i64 variable, set result_type so
578                // the emit layer wraps in @as(i64, @intFromFloat(jsRem(...)))
579                let result_type = if target_type == Some(ZigType::I64) {
580                    Some(ZigType::I64)
581                } else {
582                    None
583                };
584                let left_type = target_type.unwrap_or(ZigType::I64);
585                let right_type = self.infer_expr_type(&ae.right).unwrap_or(ZigType::I64);
586                let assign = IrExpr::Assign {
587                    op: AssignOp::Assign,
588                    target: Box::new(target),
589                    value: Box::new(IrExpr::RemExpr {
590                        left: Box::new(base_expr),
591                        right: value,
592                        left_type,
593                        right_type,
594                        result_type,
595                    }),
596                };
597                return self.wrap_compound_assign(bind, assign, break_value);
598            }
599            // BigInt %=: fall through to BigInt compound expansion below
600        }
601        // /= → a = a / b  (JS `/` always returns float; for i64 target, truncate back)
602        if ae.operator == AssignmentOperator::Division {
603            let target = self.lower_assign_target(&ae.left);
604            let target_type = self.infer_assign_target_type(&ae.left);
605            // BigInt /= falls through to the BigInt compound expansion below
606            if target_type != Some(ZigType::BigInt) {
607                let value = Box::new(self.lower_expr(&ae.right));
608                let (bind, target, base_expr) = self.maybe_bind_member_object_for_compound(target);
609                let break_value = base_expr.clone();
610                let left_type = target_type.unwrap_or(ZigType::I64);
611                let right_type = self.infer_expr_type(&ae.right).unwrap_or(ZigType::I64);
612                // When assigning / result to an i64 variable, set result_type so
613                // the emit layer wraps in @as(i64, @intFromFloat(...))
614                let result_type = if left_type == ZigType::I64 {
615                    Some(ZigType::I64)
616                } else {
617                    None
618                };
619                let assign = IrExpr::Assign {
620                    op: AssignOp::Assign,
621                    target: Box::new(target),
622                    value: Box::new(IrExpr::DivExpr {
623                        left: Box::new(base_expr),
624                        right: value,
625                        left_type,
626                        right_type,
627                        result_type,
628                    }),
629                };
630                return self.wrap_compound_assign(bind, assign, break_value);
631            }
632            // BigInt /=: fall through to BigInt compound expansion below
633        }
634        // &&= / ||= / ??= → expand into Assign + Logical
635        // This reuses the Logical emitter's type-aware JsAny.from() wrapping,
636        // avoiding type mismatches between comptime_int and JsAny branches.
637        // For &&/|| the emitter uses js_runtime.isTruthy() (anytype), so it works
638        // for i64 as well. For ??= on non-JsAny types, the value can't be
639        // null/undefined, so it's handled as a no-op (evaluate RHS, keep target).
640        if matches!(
641            ae.operator,
642            AssignmentOperator::LogicalAnd
643                | AssignmentOperator::LogicalOr
644                | AssignmentOperator::LogicalNullish
645        ) {
646            let target_type = self
647                .infer_assign_target_type(&ae.left)
648                .unwrap_or(ZigType::JsAny);
649
650            // ??= on non-JsAny types is a no-op: the value can't be null/undefined
651            // in our type system (i64, bool, string, etc.). Short-circuit: just
652            // return the target value without evaluating RHS (consistent with ??).
653            if ae.operator == AssignmentOperator::LogicalNullish && target_type != ZigType::JsAny {
654                let target = self.lower_assign_target(&ae.left);
655                if let Some(read) = target.to_read_expr() {
656                    return read;
657                }
658                // Fall through for unsupported targets
659            } else {
660                let target = self.lower_assign_target(&ae.left);
661                // Only expand for Member/Ident targets (to_read_expr returns Some).
662                // Index/Destructure fall through to the default path below.
663                if matches!(
664                    target,
665                    crate::zigir::types::IrAssignTarget::Member { .. }
666                        | crate::zigir::types::IrAssignTarget::Ident(_)
667                ) {
668                    let value = self.lower_expr(&ae.right);
669                    let value_type = self.infer_expr_type(&ae.right).unwrap_or(ZigType::JsAny);
670                    let logical_op = match ae.operator {
671                        AssignmentOperator::LogicalAnd => LogicalOp::And,
672                        AssignmentOperator::LogicalOr => LogicalOp::Or,
673                        AssignmentOperator::LogicalNullish => LogicalOp::Nullish,
674                        _ => LogicalOp::And, // safe fallback (P0-10 fix)
675                    };
676                    let (bind, target, read) = self.maybe_bind_member_object_for_compound(target);
677                    let break_value = read.clone();
678                    let assign = IrExpr::Assign {
679                        op: AssignOp::Assign,
680                        target: Box::new(target),
681                        value: Box::new(IrExpr::Logical {
682                            op: logical_op,
683                            left: Box::new(read),
684                            right: Box::new(value),
685                            left_type: Some(target_type),
686                            right_type: Some(value_type),
687                        }),
688                    };
689                    return self.wrap_compound_assign(bind, assign, break_value);
690                }
691                // For unsupported targets (index, destructure), fall through to default path
692            }
693        }
694
695        // ── BigInt compound assignment expansion ──
696        // BigInt has no Zig +=, -=, etc. Expand `bigVar += expr` into
697        // `bigVar = bigVar + expr` (using IrExpr::Binary with BigInt type info
698        // so the Emitter generates .add() / .sub() / etc. method calls).
699        let is_compound = ae.operator != AssignmentOperator::Assign
700            && ae.operator != AssignmentOperator::LogicalAnd
701            && ae.operator != AssignmentOperator::LogicalOr
702            && ae.operator != AssignmentOperator::LogicalNullish;
703
704        if is_compound {
705            // Infer target type from the left-hand side
706            let target_type = self.infer_assign_target_type(&ae.left);
707            if target_type == Some(ZigType::BigInt) {
708                let target = self.lower_assign_target(&ae.left);
709                // Only expand for Member/Ident targets (to_read_expr returns Some).
710                if matches!(
711                    target,
712                    crate::zigir::types::IrAssignTarget::Member { .. }
713                        | crate::zigir::types::IrAssignTarget::Ident(_)
714                ) {
715                    let value = Box::new(self.lower_expr(&ae.right));
716                    let (bind, target, read) = self.maybe_bind_member_object_for_compound(target);
717                    let break_value = read.clone();
718                    let bin_op = match ae.operator {
719                        AssignmentOperator::Addition => BinOp::Add,
720                        AssignmentOperator::Subtraction => BinOp::Sub,
721                        AssignmentOperator::Multiplication => BinOp::Mul,
722                        AssignmentOperator::Division => BinOp::Div,
723                        AssignmentOperator::Remainder => BinOp::Mod,
724                        AssignmentOperator::ShiftLeft => BinOp::Shl,
725                        AssignmentOperator::ShiftRight => BinOp::Shr,
726                        AssignmentOperator::ShiftRightZeroFill => BinOp::UrShr,
727                        AssignmentOperator::BitwiseAnd => BinOp::BitAnd,
728                        AssignmentOperator::BitwiseOR => BinOp::BitOr,
729                        AssignmentOperator::BitwiseXOR => BinOp::BitXor,
730                        _ => BinOp::Add, // fallback, shouldn't reach here
731                    };
732                    let assign = IrExpr::Assign {
733                        op: AssignOp::Assign,
734                        target: Box::new(target),
735                        value: Box::new(IrExpr::Binary {
736                            op: bin_op,
737                            left: Box::new(read),
738                            right: value,
739                            left_type: Some(ZigType::BigInt),
740                            right_type: Some(ZigType::BigInt),
741                        }),
742                    };
743                    return self.wrap_compound_assign(bind, assign, break_value);
744                }
745                // For unsupported BigInt targets (index, destructure), fall through
746                // to default path (may produce invalid Zig but handles common cases)
747            }
748        }
749
750        let op = match ae.operator {
751            AssignmentOperator::Assign => AssignOp::Assign,
752            AssignmentOperator::Addition => AssignOp::Add,
753            AssignmentOperator::Subtraction => AssignOp::Sub,
754            AssignmentOperator::Multiplication => AssignOp::Mul,
755            AssignmentOperator::Division => AssignOp::Div,
756            AssignmentOperator::Remainder => AssignOp::Mod,
757            AssignmentOperator::ShiftLeft => AssignOp::Shl,
758            AssignmentOperator::ShiftRight => AssignOp::Shr,
759            AssignmentOperator::BitwiseAnd => AssignOp::BitAnd,
760            AssignmentOperator::BitwiseOR => AssignOp::BitOr,
761            AssignmentOperator::BitwiseXOR => AssignOp::BitXor,
762            AssignmentOperator::LogicalAnd => AssignOp::LogicAnd,
763            AssignmentOperator::LogicalOr => AssignOp::LogicOr,
764            AssignmentOperator::LogicalNullish => AssignOp::Nullish,
765            // Exponential handled above
766            _ => AssignOp::Assign,
767        };
768        let target = Box::new(self.lower_assign_target(&ae.left));
769        let value = Box::new(self.lower_expr(&ae.right));
770
771        // ── Detect `target = expr % expr2` where target is i64 ──
772        // If the value is a RemExpr (integer %) and the target is i64,
773        // set result_type so the emitter wraps in @intFromFloat.
774        if op == AssignOp::Assign {
775            let target_type = self.infer_assign_target_type(&ae.left);
776            if target_type == Some(ZigType::I64)
777                && let IrExpr::RemExpr {
778                    result_type: None,
779                    left,
780                    right,
781                    left_type,
782                    right_type,
783                } = value.as_ref()
784            {
785                return IrExpr::Assign {
786                    op,
787                    target,
788                    value: Box::new(IrExpr::RemExpr {
789                        left: left.clone(),
790                        right: right.clone(),
791                        left_type: left_type.clone(),
792                        right_type: right_type.clone(),
793                        result_type: Some(ZigType::I64),
794                    }),
795                };
796            }
797            // Same for PowExpr: `x = base ** exp` when target is i64
798            if target_type == Some(ZigType::I64)
799                && let IrExpr::PowExpr {
800                    result_type: None,
801                    base,
802                    exp,
803                    base_type,
804                    exp_type,
805                } = value.as_ref()
806            {
807                return IrExpr::Assign {
808                    op,
809                    target,
810                    value: Box::new(IrExpr::PowExpr {
811                        base: base.clone(),
812                        exp: exp.clone(),
813                        base_type: base_type.clone(),
814                        exp_type: exp_type.clone(),
815                        result_type: Some(ZigType::I64),
816                    }),
817                };
818            }
819            // Same for DivExpr: `x = a / b` when target is i64
820            if target_type == Some(ZigType::I64)
821                && let IrExpr::DivExpr {
822                    result_type: None,
823                    left,
824                    right,
825                    left_type,
826                    right_type,
827                } = value.as_ref()
828            {
829                return IrExpr::Assign {
830                    op,
831                    target,
832                    value: Box::new(IrExpr::DivExpr {
833                        left: left.clone(),
834                        right: right.clone(),
835                        left_type: left_type.clone(),
836                        right_type: right_type.clone(),
837                        result_type: Some(ZigType::I64),
838                    }),
839                };
840            }
841        }
842
843        IrExpr::Assign { op, target, value }
844    }
845
846    /// For compound-assignment expansions (`**=`, `>>>=`, `%=`, `/=`, `&&=`,
847    /// `||=`, `??=`, BigInt compound), check if the Member target's object
848    /// expression might have side effects (e.g. `getObj().prop += 1`).
849    ///
850    /// If so, bind it to a temp variable `__co_N` so the object is only
851    /// evaluated once. Returns `(optional (var_decl, block_label),
852    /// possibly-rewritten target, read_expr)`. Callers should pass the
853    /// returned bind info and final Assign to `wrap_compound_assign`.
854    ///
855    /// For simple lvalue paths (`a`, `a.b`, `a[i]`) — no side effects — or
856    /// non-Member targets, returns `(None, original_target, to_read_expr)`.
857    fn maybe_bind_member_object_for_compound(
858        &mut self,
859        target: crate::zigir::types::IrAssignTarget,
860    ) -> (
861        Option<(crate::zigir::types::IrStmt, String)>,
862        crate::zigir::types::IrAssignTarget,
863        crate::zigir::types::IrExpr,
864    ) {
865        use crate::zigir::types::{IrAssignTarget, IrExpr, IrStmt, IrVarDecl};
866
867        let IrAssignTarget::Member {
868            object,
869            field,
870            is_pointer,
871            field_kind,
872        } = &target
873        else {
874            let read = target
875                .to_read_expr()
876                .unwrap_or_else(|| IrExpr::Ident(IrIdent::new("__target")));
877            return (None, target, read);
878        };
879
880        // Simple lvalue paths (Ident, FieldAccess chain, IndexAccess of simple)
881        // have no side effects — safe to evaluate twice without binding.
882        if self.ir_object_is_simple_lvalue(object) {
883            let read = target
884                .to_read_expr()
885                .unwrap_or_else(|| IrExpr::Ident(IrIdent::new("__target")));
886            return (None, target, read);
887        }
888
889        // Bind the object to a temp variable to ensure single evaluation.
890        let temp_name = self.name_mangler.next_name("__co");
891        let blk_label = format!("_co_blk{}", self.name_mangler.peek_count("__co"));
892        let temp_ident = IrExpr::Ident(IrIdent::new(&temp_name));
893
894        let var_decl = IrStmt::VarDecl(IrVarDecl {
895            name: IrIdent::new(&temp_name),
896            is_const: true,
897            zig_type: None,
898            init: Some((**object).clone()),
899            is_json_parse: false,
900            needs_var_suppression: false,
901            needs_deinit: false,
902        });
903
904        let new_target = IrAssignTarget::Member {
905            object: Box::new(temp_ident.clone()),
906            field: field.clone(),
907            is_pointer: *is_pointer,
908            field_kind: field_kind.clone(),
909        };
910        let read = IrExpr::FieldAccess {
911            object: Box::new(temp_ident),
912            field: field.clone(),
913            field_kind: field_kind.clone(),
914        };
915
916        (Some((var_decl, blk_label)), new_target, read)
917    }
918
919    /// Check if an IrExpr is a "simple lvalue path": an Ident, This, or a chain of
920    /// FieldAccess/IndexAccess over simple lvalue paths. Such expressions have
921    /// no side effects and can be safely evaluated twice without a temp binding.
922    fn ir_object_is_simple_lvalue(&self, expr: &crate::zigir::types::IrExpr) -> bool {
923        use crate::zigir::types::IrExpr;
924        match expr {
925            IrExpr::Ident(_) | IrExpr::TypedIdent { .. } | IrExpr::This => true,
926            IrExpr::FieldAccess { object, .. } => self.ir_object_is_simple_lvalue(object),
927            IrExpr::IndexAccess { object, index, .. } => {
928                self.ir_object_is_simple_lvalue(object) && self.ir_object_is_simple_lvalue(index)
929            }
930            _ => false,
931        }
932    }
933
934    /// Wrap a compound-assignment expansion in a BlockExpr if the target's
935    /// object was bound to a temp variable. The BlockExpr runs the temp
936    /// binding, executes the Assign as a statement, then breaks with the
937    /// `read_expr` (which re-reads the target field, yielding the NEW value).
938    /// This matches JS semantics where `a op= b` returns the assigned value,
939    /// and ensures single evaluation of side-effecting object expressions.
940    fn wrap_compound_assign(
941        &self,
942        bind: Option<(crate::zigir::types::IrStmt, String)>,
943        assign: crate::zigir::types::IrExpr,
944        read_expr: crate::zigir::types::IrExpr,
945    ) -> crate::zigir::types::IrExpr {
946        use crate::zigir::types::{IrExpr, IrStmt};
947        if let Some((var_decl, label)) = bind {
948            IrExpr::BlockExpr {
949                label,
950                body: vec![var_decl, IrStmt::Expr(assign)],
951                result: Box::new(read_expr),
952            }
953        } else {
954            assign
955        }
956    }
957
958    /// Lower an identifier assignment target, handling captured closure variables.
959    fn lower_ident_assign_target(&mut self, var_name: &str) -> crate::zigir::types::IrAssignTarget {
960        // Check if this identifier is a captured closure variable.
961        if let Some((_, _, is_mut)) = self
962            .closure_mgr
963            .current_captured
964            .iter()
965            .find(|(n, _, _)| n == var_name)
966        {
967            let field_name = self.make_ident(var_name).zig_name;
968            return crate::zigir::types::IrAssignTarget::Member {
969                object: Box::new(crate::zigir::types::IrExpr::Ident(IrIdent::new("self"))),
970                field: field_name,
971                is_pointer: *is_mut,
972                field_kind: if *is_mut {
973                    FieldKind::PointerDeref
974                } else {
975                    FieldKind::StructField
976                },
977            };
978        }
979
980        crate::zigir::types::IrAssignTarget::Ident(IrIdent::new(var_name))
981    }
982
983    /// Lower a static member assignment target (obj.prop).
984    fn lower_static_member_assign_target(
985        &mut self,
986        object: &Expression,
987        property_name: &str,
988    ) -> crate::zigir::types::IrAssignTarget {
989        crate::zigir::types::IrAssignTarget::Member {
990            object: Box::new(self.lower_expr(object)),
991            field: property_name.to_string(),
992            is_pointer: false,
993            field_kind: self.infer_member_field_kind(object, property_name),
994        }
995    }
996
997    /// Lower a computed member assignment target (obj[expr]).
998    fn lower_computed_member_assign_target(
999        &mut self,
1000        object: &Expression,
1001        expression: &Expression,
1002    ) -> crate::zigir::types::IrAssignTarget {
1003        let obj_type = self.infer_expr_type(object);
1004        let is_arraylist = obj_type
1005            .as_ref()
1006            .map(|t| matches!(t, ZigType::ArrayList(_)))
1007            .unwrap_or(false);
1008        crate::zigir::types::IrAssignTarget::Index {
1009            object: Box::new(self.lower_expr(object)),
1010            index: Box::new(self.lower_expr(expression)),
1011            index_kind: if is_arraylist {
1012                IndexKind::ArrayListItem
1013            } else {
1014                IndexKind::SliceIndex
1015            },
1016        }
1017    }
1018
1019    /// Lower a simple assignment target (from UpdateExpression).
1020    /// SimpleAssignmentTarget can be an identifier or member expression.
1021    pub(super) fn lower_simple_assign_target(
1022        &mut self,
1023        target: &SimpleAssignmentTarget,
1024    ) -> crate::zigir::types::IrAssignTarget {
1025        match target {
1026            SimpleAssignmentTarget::AssignmentTargetIdentifier(id) => {
1027                self.lower_ident_assign_target(id.name.as_str())
1028            }
1029            SimpleAssignmentTarget::StaticMemberExpression(mem) => {
1030                self.lower_static_member_assign_target(&mem.object, mem.property.name.as_str())
1031            }
1032            SimpleAssignmentTarget::ComputedMemberExpression(mem) => {
1033                self.lower_computed_member_assign_target(&mem.object, &mem.expression)
1034            }
1035            SimpleAssignmentTarget::PrivateFieldExpression(pfe) => {
1036                // Private field assignment (this.#field += ...) — treat as struct field access
1037                self.lower_static_member_assign_target(&pfe.object, pfe.field.name.as_str())
1038            }
1039            _ => crate::zigir::types::IrAssignTarget::CompileError {
1040                msg: "unsupported assignment target".to_string(),
1041            },
1042        }
1043    }
1044
1045    /// Extract (pattern, default) from an AssignmentTargetMaybeDefault.
1046    pub(super) fn lower_maybe_default(
1047        &mut self,
1048        target: &AssignmentTargetMaybeDefault,
1049    ) -> (IrIdent, Option<crate::zigir::types::IrExpr>) {
1050        match target {
1051            AssignmentTargetMaybeDefault::AssignmentTargetWithDefault(atwd) => {
1052                let pattern = self.extract_target_ident(&atwd.binding);
1053                let default = Some(self.lower_expr(&atwd.init));
1054                (pattern, default)
1055            }
1056            AssignmentTargetMaybeDefault::AssignmentTargetIdentifier(id) => {
1057                (IrIdent::new(id.name.as_str()), None)
1058            }
1059            _ => (IrIdent::new("_"), None),
1060        }
1061    }
1062
1063    /// Extract an identifier name from an AssignmentTarget (best-effort).
1064    pub(super) fn extract_target_ident(&self, target: &AssignmentTarget) -> IrIdent {
1065        match target {
1066            AssignmentTarget::AssignmentTargetIdentifier(id) => IrIdent::new(id.name.as_str()),
1067            _ => IrIdent::new("_"),
1068        }
1069    }
1070
1071    /// Lower an assignment target (lhs).
1072    pub(super) fn lower_assign_target(
1073        &mut self,
1074        target: &AssignmentTarget,
1075    ) -> crate::zigir::types::IrAssignTarget {
1076        match target {
1077            AssignmentTarget::AssignmentTargetIdentifier(id) => {
1078                self.lower_ident_assign_target(id.name.as_str())
1079            }
1080            AssignmentTarget::StaticMemberExpression(mem) => {
1081                self.lower_static_member_assign_target(&mem.object, mem.property.name.as_str())
1082            }
1083            AssignmentTarget::ComputedMemberExpression(mem) => {
1084                self.lower_computed_member_assign_target(&mem.object, &mem.expression)
1085            }
1086            AssignmentTarget::PrivateFieldExpression(pfe) => {
1087                // Private field assignment (this.#field = ...) — treat as struct field access
1088                self.lower_static_member_assign_target(&pfe.object, pfe.field.name.as_str())
1089            }
1090            AssignmentTarget::ObjectAssignmentTarget(ot) => {
1091                let bindings: Vec<crate::zigir::types::IrDestructureBinding> = ot
1092                    .properties
1093                    .iter()
1094                    .map(|prop| {
1095                        match prop {
1096                            AssignmentTargetProperty::AssignmentTargetPropertyIdentifier(ap) => {
1097                                let pattern = IrIdent::new(ap.binding.name.as_str());
1098                                let default = ap.init.as_ref().map(|e| self.lower_expr(e));
1099                                crate::zigir::types::IrDestructureBinding { pattern, default }
1100                            }
1101                            AssignmentTargetProperty::AssignmentTargetPropertyProperty(ap) => {
1102                                // e.g. { name: alias } — extract binding from value
1103                                let (pattern, default) = self.lower_maybe_default(&ap.binding);
1104                                crate::zigir::types::IrDestructureBinding { pattern, default }
1105                            }
1106                        }
1107                    })
1108                    .collect();
1109                crate::zigir::types::IrAssignTarget::Destructure(bindings)
1110            }
1111            AssignmentTarget::ArrayAssignmentTarget(at) => {
1112                let bindings: Vec<crate::zigir::types::IrDestructureBinding> = at
1113                    .elements
1114                    .iter()
1115                    .filter_map(|elem| {
1116                        elem.as_ref().map(|target| {
1117                            let (pattern, default) = self.lower_maybe_default(target);
1118                            crate::zigir::types::IrDestructureBinding { pattern, default }
1119                        })
1120                    })
1121                    .collect();
1122                crate::zigir::types::IrAssignTarget::Destructure(bindings)
1123            }
1124            _ => crate::zigir::types::IrAssignTarget::CompileError {
1125                msg: "unsupported assignment target".to_string(),
1126            },
1127        }
1128    }
1129
1130    /// Check if an expression is a string type (for string concatenation detection).
1131    ///
1132    /// NOTE: A parallel implementation exists on `TypeInferrer` (infer/expr.rs).
1133    /// The two are NOT merged because they use different type-lookup mechanisms:
1134    /// - `TypeInferrer` checks `self.var_types` (built during analysis pass)
1135    /// - `Lowerer` calls `self.infer_expr_type` (reads from TypeCheckResult snapshot)
1136    ///
1137    /// The match structure (literals, binary `+`, conditional, paren) is aligned
1138    /// between the two (P2-2).
1139    pub(super) fn expr_is_string(&self, expr: &Expression) -> bool {
1140        match expr {
1141            Expression::StringLiteral(_) => true,
1142            Expression::TemplateLiteral(_) => true,
1143            Expression::Identifier(_id) => {
1144                // Use infer_expr_type which handles qualified name lookup
1145                self.infer_expr_type(expr) == Some(ZigType::Str)
1146            }
1147            Expression::BinaryExpression(be) if be.operator == BinaryOperator::Addition => {
1148                self.expr_is_string(&be.left) || self.expr_is_string(&be.right)
1149            }
1150            // ConditionalExpression: result is string only if both branches are strings
1151            Expression::ConditionalExpression(ce) => {
1152                self.expr_is_string(&ce.consequent) && self.expr_is_string(&ce.alternate)
1153            }
1154            Expression::ParenthesizedExpression(pe) => self.expr_is_string(&pe.expression),
1155            _ => self.infer_expr_type(expr) == Some(ZigType::Str),
1156        }
1157    }
1158
1159    /// Lower a string concatenation chain into IrExpr::AllocPrint.
1160    /// Flattens nested `a + b + c` into a single format string + args list.
1161    pub(super) fn lower_string_concat(
1162        &mut self,
1163        be: &BinaryExpression,
1164    ) -> crate::zigir::types::IrExpr {
1165        use crate::zigir::types::IrExpr;
1166
1167        let mut operands: Vec<&Expression> = Vec::new();
1168        self.collect_concat_from_be(be, &mut operands);
1169
1170        let mut fmt = String::new();
1171        let mut args: Vec<IrExpr> = Vec::new();
1172
1173        for op in &operands {
1174            match op {
1175                Expression::StringLiteral(sl) => {
1176                    fmt.push_str(&crate::zigir::emit::helpers::escape_zig_format_string(
1177                        &sl.value,
1178                    ));
1179                }
1180                _ => {
1181                    // Lower the operand ONCE so we can wrap BigInt operands in
1182                    // a `.toString(allocator)` call (R6-4). Pre-fix the BigInt
1183                    // operand was lowered directly and formatted via `{any}`,
1184                    // which invoked `JsBigInt.format()` — and that method
1185                    // appends a trailing `"n"` (for Node.js console.log
1186                    // parity), producing `"12n"` instead of `"12"` for
1187                    // `"1" + 2n`.
1188                    //
1189                    // Unwrap parentheses before lowering.
1190                    let lowered = match op {
1191                        Expression::ParenthesizedExpression(pe) => self.lower_expr(&pe.expression),
1192                        _ => self.lower_expr(op),
1193                    };
1194
1195                    let operand_type = if self.expr_is_string(op) {
1196                        Some(ZigType::Str)
1197                    } else {
1198                        self.infer_expr_type(op)
1199                    };
1200
1201                    // Each arm pushes `lowered` to `args` exactly once. Moving
1202                    // `lowered` only inside the BigInt arm BuiltinCall used to
1203                    // break the borrow checker — the runtime
1204                    // `if !matches!(operand_type, …)` guard on a post-match
1205                    // `args.push(lowered)` couldn't narrow the move.
1206                    let placeholder = match operand_type {
1207                        Some(ZigType::BigInt) => {
1208                            // Wrap the lowered BigInt expression in
1209                            // `(.toString(allocator) catch @panic(...))` so the
1210                            // resulting slice formats as the decimal value
1211                            // (no trailing "n") via the `{s}` specifier.
1212                            args.push(IrExpr::BuiltinCall(
1213                                crate::zigir::types::IrBuiltinCall::simple(
1214                                    BuiltinModule::JsBigInt,
1215                                    "toString",
1216                                    None,
1217                                    Some(Box::new(lowered)),
1218                                    vec![],
1219                                    ZigType::Str,
1220                                ),
1221                            ));
1222                            "{s}"
1223                        }
1224                        Some(ZigType::Str) => {
1225                            args.push(lowered);
1226                            "{s}"
1227                        }
1228                        Some(ref ty) => {
1229                            args.push(lowered);
1230                            helpers::format_specifier_for_type(ty)
1231                        }
1232                        None => {
1233                            args.push(lowered);
1234                            "{any}"
1235                        }
1236                    };
1237                    fmt.push_str(placeholder);
1238                }
1239            }
1240        }
1241
1242        IrExpr::AllocPrint { fmt, args }
1243    }
1244
1245    /// Recursively collect all operands in a string concatenation chain.
1246    /// Only recurses into nested `+` when the sub-tree itself involves a
1247    /// string operand; this preserves JS left-to-right evaluation for
1248    /// purely numeric sub-expressions (e.g. `1 + 2 + "3"` must produce
1249    /// `"33"`, not `"123"`).
1250    pub(super) fn collect_concat_from_be<'a>(
1251        &self,
1252        be: &'a BinaryExpression<'a>,
1253        out: &mut Vec<&'a Expression<'a>>,
1254    ) {
1255        // Left side
1256        if let Expression::BinaryExpression(ref left_be) = be.left {
1257            if left_be.operator == BinaryOperator::Addition && self.expr_is_string(&be.left) {
1258                self.collect_concat_from_be(left_be, out);
1259            } else {
1260                out.push(&be.left);
1261            }
1262        } else {
1263            out.push(&be.left);
1264        }
1265
1266        // Right side
1267        if let Expression::BinaryExpression(ref right_be) = be.right {
1268            if right_be.operator == BinaryOperator::Addition && self.expr_is_string(&be.right) {
1269                self.collect_concat_from_be(right_be, out);
1270            } else {
1271                out.push(&be.right);
1272            }
1273        } else {
1274            out.push(&be.right);
1275        }
1276    }
1277
1278    /// Lower `x instanceof Type` with prototype chain semantics.
1279    ///
1280    /// Three strategies:
1281    /// 1. **Error types** → `e.name == "TypeName"` (existing efficient approach)
1282    /// 2. **Compile-time type-aware** → known left type resolves at transpile time
1283    /// 3. **Runtime** → emit `js_runtime.instanceOf(value, "TypeName")` for dynamic types
1284    fn lower_instanceof(&mut self, be: &BinaryExpression) -> crate::zigir::types::IrExpr {
1285        use crate::zigir::builtins::BuiltinModule;
1286        use crate::zigir::kinds::FieldKind;
1287        use crate::zigir::types::{IrBuiltinCall, IrExpr};
1288
1289        // Get the type name from the right operand
1290        let type_name = if let Expression::Identifier(ident) = &be.right {
1291            ident.name.to_string()
1292        } else {
1293            return self.compile_error_expr(
1294                be.span,
1295                "instanceof: right operand must be an identifier (constructor name)",
1296            );
1297        };
1298
1299        // ── Strategy 1: Error types → .name comparison ──
1300        let error_types = [
1301            "Error",
1302            "URIError",
1303            "TypeError",
1304            "RangeError",
1305            "SyntaxError",
1306            "ReferenceError",
1307            "EvalError",
1308            "AggregateError",
1309            "SuppressedError",
1310        ];
1311        if error_types.contains(&type_name.as_str()) {
1312            let left_expr = self.lower_expr(&be.left);
1313            return IrExpr::Binary {
1314                op: BinOp::Eq,
1315                left: Box::new(IrExpr::FieldAccess {
1316                    object: Box::new(left_expr),
1317                    field: "name".to_string(),
1318                    field_kind: FieldKind::StructField,
1319                }),
1320                right: Box::new(IrExpr::StringLiteral(type_name)),
1321                left_type: Some(ZigType::Str),
1322                right_type: Some(ZigType::Str),
1323            };
1324        }
1325
1326        // ── Strategy 2: Compile-time type-aware instanceof ──
1327        if let Some(left_ty) = self.infer_expr_type(&be.left)
1328            && let Some(result) = self.resolve_instanceof_compile_time(&left_ty, &type_name)
1329        {
1330            return result;
1331        }
1332
1333        // ── Strategy 3: Runtime instanceof check ──
1334        let left_expr = self.lower_expr(&be.left);
1335        IrExpr::BuiltinCall(IrBuiltinCall::simple(
1336            BuiltinModule::JsRuntime,
1337            "instanceOf",
1338            None,
1339            Some(Box::new(left_expr)),
1340            vec![IrExpr::StringLiteral(type_name)],
1341            ZigType::Bool,
1342        ))
1343    }
1344
1345    /// Resolve `instanceof` at compile time when the left operand's type is known.
1346    ///
1347    /// Returns `Some(IrExpr)` if resolved, `None` if we need runtime dispatch.
1348    fn resolve_instanceof_compile_time(
1349        &self,
1350        left_ty: &ZigType,
1351        type_name: &str,
1352    ) -> Option<crate::zigir::types::IrExpr> {
1353        use crate::zigir::types::IrExpr;
1354
1355        match left_ty {
1356            // ArrayList matches Array
1357            ZigType::ArrayList(_) => {
1358                if type_name == "Array" || type_name == "Object" {
1359                    return Some(IrExpr::BoolLiteral(true));
1360                }
1361                Some(IrExpr::BoolLiteral(false))
1362            }
1363            // Map matches Map and Object
1364            ZigType::NamedStruct(name) if name == "Map" => {
1365                if type_name == "Map" || type_name == "Object" {
1366                    return Some(IrExpr::BoolLiteral(true));
1367                }
1368                Some(IrExpr::BoolLiteral(false))
1369            }
1370            // Set matches Set and Object
1371            ZigType::NamedStruct(name) if name == "Set" => {
1372                if type_name == "Set" || type_name == "Object" {
1373                    return Some(IrExpr::BoolLiteral(true));
1374                }
1375                Some(IrExpr::BoolLiteral(false))
1376            }
1377            // Custom class: check direct match and prototype chain
1378            ZigType::NamedStruct(class_name) => {
1379                if class_name == type_name {
1380                    return Some(IrExpr::BoolLiteral(true));
1381                }
1382                if type_name == "Object" {
1383                    // All class instances are instanceof Object
1384                    return Some(IrExpr::BoolLiteral(true));
1385                }
1386                // Walk prototype chain via class_extends_map
1387                let mut current = class_name.as_str();
1388                loop {
1389                    if current == type_name {
1390                        return Some(IrExpr::BoolLiteral(true));
1391                    }
1392                    if let Some(parent) = self.class_extends_map.get(current) {
1393                        current = parent.as_str();
1394                    } else {
1395                        break;
1396                    }
1397                }
1398                Some(IrExpr::BoolLiteral(false))
1399            }
1400            // String primitives: NOT instanceof String in JS (only String objects are)
1401            ZigType::Str => Some(IrExpr::BoolLiteral(false)),
1402            // Numeric/Boolean primitives are never `instanceof` their wrapper types
1403            // in JS (primitives lack [[Prototype]]).  Both branches always return false
1404            // regardless of the right-hand type_name.
1405            ZigType::I64 | ZigType::F64 | ZigType::Bool => Some(IrExpr::BoolLiteral(false)),
1406            // For JsAny / Anytype, we can't resolve at compile time
1407            ZigType::JsAny | ZigType::Anytype => None,
1408            // Other types: conservatively say we can't resolve
1409            _ => None,
1410        }
1411    }
1412
1413    fn bigint_unary_builtin(
1414        &mut self,
1415        method: &str,
1416        operand: crate::zigir::types::IrExpr,
1417    ) -> crate::zigir::types::IrExpr {
1418        crate::zigir::types::IrExpr::BuiltinCall(crate::zigir::types::IrBuiltinCall::simple(
1419            BuiltinModule::JsBigInt,
1420            method,
1421            None,
1422            Some(Box::new(operand)),
1423            vec![],
1424            ZigType::BigInt,
1425        ))
1426    }
1427}