1use 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 pub(super) fn lower_binary(&mut self, be: &BinaryExpression) -> crate::zigir::types::IrExpr {
20 use crate::zigir::types::IrExpr;
21
22 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 match be.operator {
35 BinaryOperator::Instanceof => {
36 return self.lower_instanceof(be);
37 }
38 BinaryOperator::In => {
39 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 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 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 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, };
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 if left_type == ZigType::BigInt || right_type == ZigType::BigInt {
95 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 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 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, };
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 if left_type == ZigType::BigInt || right_type == ZigType::BigInt {
132 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 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, };
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 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 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 {
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; let is_bigint_urshr = op == BinOp::UrShr && (left_is_bigint || right_is_bigint);
196 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 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 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 let arg = &ue.argument;
264 let ty = self.infer_expr_type(arg);
265 match ty {
266 Some(ZigType::Bool) => {
267 if let Expression::BooleanLiteral(bl) = arg {
269 return IrExpr::IntLiteral(if bl.value { 1 } else { 0 });
270 }
271 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 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 _ => 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 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 (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 pub(super) fn lower_update(&mut self, ue: &UpdateExpression) -> crate::zigir::types::IrExpr {
394 use crate::zigir::types::IrExpr;
395
396 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 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 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 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 pub(super) fn lower_assignment(
495 &mut self,
496 ae: &AssignmentExpression,
497 ) -> crate::zigir::types::IrExpr {
498 use crate::zigir::types::IrExpr;
499
500 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 let base_type = target_type.unwrap_or(ZigType::F64);
523 let exp_type = self.infer_expr_type(&ae.right).unwrap_or(ZigType::F64);
524 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 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 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 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 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 }
601 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 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 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 }
634 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 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 } else {
660 let target = self.lower_assign_target(&ae.left);
661 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, };
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 }
693 }
694
695 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 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 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, };
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 }
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 _ => 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 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 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 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 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 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 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 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 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 fn lower_ident_assign_target(&mut self, var_name: &str) -> crate::zigir::types::IrAssignTarget {
960 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 let placeholder = match operand_type {
1207 Some(ZigType::BigInt) => {
1208 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 pub(super) fn collect_concat_from_be<'a>(
1251 &self,
1252 be: &'a BinaryExpression<'a>,
1253 out: &mut Vec<&'a Expression<'a>>,
1254 ) {
1255 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 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 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 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 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 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 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 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 ZigType::ArrayList(_) => {
1358 if type_name == "Array" || type_name == "Object" {
1359 return Some(IrExpr::BoolLiteral(true));
1360 }
1361 Some(IrExpr::BoolLiteral(false))
1362 }
1363 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 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 ZigType::NamedStruct(class_name) => {
1379 if class_name == type_name {
1380 return Some(IrExpr::BoolLiteral(true));
1381 }
1382 if type_name == "Object" {
1383 return Some(IrExpr::BoolLiteral(true));
1385 }
1386 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 ZigType::Str => Some(IrExpr::BoolLiteral(false)),
1402 ZigType::I64 | ZigType::F64 | ZigType::Bool => Some(IrExpr::BoolLiteral(false)),
1406 ZigType::JsAny | ZigType::Anytype => None,
1408 _ => 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}