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