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