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, 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 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 if left_type == ZigType::BigInt || right_type == ZigType::BigInt {
63 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 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 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, };
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 if left_type == ZigType::BigInt || right_type == ZigType::BigInt {
98 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 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, };
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 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 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 {
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; let is_bigint_urshr = op == BinOp::UrShr && (left_is_bigint || right_is_bigint);
162 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 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 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 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 pub(super) fn lower_update(&mut self, ue: &UpdateExpression) -> crate::zigir::types::IrExpr {
298 use crate::zigir::types::IrExpr;
299
300 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 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 pub(super) fn lower_assignment(
351 &mut self,
352 ae: &AssignmentExpression,
353 ) -> crate::zigir::types::IrExpr {
354 use crate::zigir::types::IrExpr;
355
356 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 let base_type = target_type.unwrap_or(ZigType::F64);
380 let exp_type = self.infer_expr_type(&ae.right).unwrap_or(ZigType::F64);
381 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 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 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 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 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 }
452 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 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, };
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 }
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 _ => 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 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 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 fn lower_ident_assign_target(&mut self, var_name: &str) -> crate::zigir::types::IrAssignTarget {
573 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 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 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 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 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 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 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 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 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 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 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 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 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 pub(super) fn collect_concat_from_be<'a>(
800 be: &'a BinaryExpression<'a>,
801 out: &mut Vec<&'a Expression<'a>>,
802 ) {
803 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 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 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 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 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 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 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 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 ZigType::ArrayList(_) => {
906 if type_name == "Array" || type_name == "Object" {
907 return Some(IrExpr::BoolLiteral(true));
908 }
909 Some(IrExpr::BoolLiteral(false))
910 }
911 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 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 ZigType::NamedStruct(class_name) => {
927 if class_name == type_name {
928 return Some(IrExpr::BoolLiteral(true));
929 }
930 if type_name == "Object" {
931 return Some(IrExpr::BoolLiteral(true));
933 }
934 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 ZigType::Str => Some(IrExpr::BoolLiteral(false)),
950 ZigType::I64 | ZigType::F64 | ZigType::Bool => Some(IrExpr::BoolLiteral(false)),
954 ZigType::JsAny | ZigType::Anytype => None,
956 _ => 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}