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::ops::{AssignOp, BinOp, UnaOp, UpdateOp};
12
13use super::Lowerer;
14
15impl Lowerer {
16 pub(super) fn lower_binary(&mut self, be: &BinaryExpression) -> crate::zigir::types::IrExpr {
18 use crate::zigir::types::IrExpr;
19
20 if be.operator == BinaryOperator::Addition {
24 let left_is_str = self.expr_is_string(&be.left);
25 let right_is_str = self.expr_is_string(&be.right);
26 if left_is_str || right_is_str {
27 return self.lower_string_concat(be);
28 }
29 }
30
31 match be.operator {
33 BinaryOperator::Instanceof => {
34 if let Expression::Identifier(ident) = &be.right {
37 let name = ident.name.as_str();
38 if matches!(
39 name,
40 "Error"
41 | "URIError"
42 | "TypeError"
43 | "RangeError"
44 | "SyntaxError"
45 | "ReferenceError"
46 | "EvalError"
47 ) {
48 let left_expr = self.lower_expr(&be.left);
49 return IrExpr::Binary {
50 op: BinOp::Eq,
51 left: Box::new(IrExpr::FieldAccess {
52 object: Box::new(left_expr),
53 field: "name".to_string(),
54 field_kind: crate::zigir::kinds::FieldKind::StructField,
55 }),
56 right: Box::new(IrExpr::StringLiteral(name.to_string())),
57 left_type: Some(ZigType::Str),
58 right_type: Some(ZigType::Str),
59 };
60 }
61 }
62 return IrExpr::CompileError {
63 span: self.span_to_source_span(be.span),
64 msg: "instanceof operator is not supported in Zig".to_string(),
65 };
66 }
67 BinaryOperator::In => {
68 let right_expr = self.lower_expr(&be.right);
70 let left_expr = self.lower_expr(&be.left);
71 return IrExpr::Binary {
72 op: BinOp::In,
73 left: Box::new(left_expr),
74 right: Box::new(right_expr),
75 left_type: Some(ZigType::Str),
76 right_type: None,
77 };
78 }
79 _ => {}
80 }
81
82 let op = match be.operator {
83 BinaryOperator::Addition => BinOp::Add,
84 BinaryOperator::Subtraction => BinOp::Sub,
85 BinaryOperator::Multiplication => BinOp::Mul,
86 BinaryOperator::Division => BinOp::Div,
87 BinaryOperator::Remainder => BinOp::Mod,
88 BinaryOperator::Exponential => {
89 let left_type = self.infer_expr_type(&be.left).unwrap_or(ZigType::F64);
90 let right_type = self.infer_expr_type(&be.right).unwrap_or(ZigType::F64);
91 if left_type == ZigType::BigInt || right_type == ZigType::BigInt {
93 return IrExpr::Binary {
94 op: BinOp::Pow,
95 left: Box::new(self.lower_expr(&be.left)),
96 right: Box::new(self.lower_expr(&be.right)),
97 left_type: Some(left_type),
98 right_type: Some(right_type),
99 };
100 }
101 return IrExpr::PowExpr {
104 base: Box::new(self.lower_expr(&be.left)),
105 exp: Box::new(self.lower_expr(&be.right)),
106 base_type: left_type,
107 exp_type: right_type,
108 result_type: None, };
110 }
111 BinaryOperator::LessThan => BinOp::Lt,
112 BinaryOperator::GreaterThan => BinOp::Gt,
113 BinaryOperator::LessEqualThan => BinOp::Le,
114 BinaryOperator::GreaterEqualThan => BinOp::Ge,
115 BinaryOperator::Equality => BinOp::Eq,
116 BinaryOperator::Inequality => BinOp::Ne,
117 BinaryOperator::StrictEquality => BinOp::StrictEq,
118 BinaryOperator::StrictInequality => BinOp::StrictNe,
119 BinaryOperator::BitwiseAnd => BinOp::BitAnd,
120 BinaryOperator::BitwiseOR => BinOp::BitOr,
121 BinaryOperator::BitwiseXOR => BinOp::BitXor,
122 BinaryOperator::ShiftLeft => BinOp::Shl,
123 BinaryOperator::ShiftRight => BinOp::Shr,
124 BinaryOperator::ShiftRightZeroFill => BinOp::UrShr,
125 BinaryOperator::Instanceof | BinaryOperator::In => unreachable!(),
128 };
129
130 let left_type = self.infer_expr_type(&be.left);
131 let right_type = self.infer_expr_type(&be.right);
132
133 IrExpr::Binary {
134 op,
135 left: Box::new(self.lower_expr(&be.left)),
136 right: Box::new(self.lower_expr(&be.right)),
137 left_type,
138 right_type,
139 }
140 }
141
142 pub(super) fn lower_unary(&mut self, ue: &UnaryExpression) -> crate::zigir::types::IrExpr {
144 use crate::zigir::types::IrExpr;
145
146 match ue.operator {
147 UnaryOperator::UnaryNegation => {
148 if self.infer_expr_type(&ue.argument) == Some(ZigType::BigInt) {
150 return IrExpr::BuiltinCall(crate::zigir::types::IrBuiltinCall {
151 module: BuiltinModule::JsBigInt,
152 method: "bigIntNeg".to_string(),
153 obj_name: None,
154 obj_expr: Some(Box::new(self.lower_expr(&ue.argument))),
155 args: vec![],
156 return_type: ZigType::BigInt,
157 ta_type_suffix: None,
158 regex_info: None,
159 });
160 }
161 IrExpr::Unary {
162 op: UnaOp::Neg,
163 operand: Box::new(self.lower_expr(&ue.argument)),
164 }
165 }
166 UnaryOperator::UnaryPlus => {
167 self.lower_expr(&ue.argument)
169 }
170 UnaryOperator::LogicalNot => IrExpr::Unary {
171 op: UnaOp::Not,
172 operand: Box::new(self.lower_expr(&ue.argument)),
173 },
174 UnaryOperator::BitwiseNot => {
175 if self.infer_expr_type(&ue.argument) == Some(ZigType::BigInt) {
177 return IrExpr::BuiltinCall(crate::zigir::types::IrBuiltinCall {
178 module: BuiltinModule::JsBigInt,
179 method: "bigIntBitwiseNot".to_string(),
180 obj_name: None,
181 obj_expr: Some(Box::new(self.lower_expr(&ue.argument))),
182 args: vec![],
183 return_type: ZigType::BigInt,
184 ta_type_suffix: None,
185 regex_info: None,
186 });
187 }
188 IrExpr::Unary {
189 op: UnaOp::BitNot,
190 operand: Box::new(self.lower_expr(&ue.argument)),
191 }
192 }
193 UnaryOperator::Typeof => {
194 if let Some(ty) = self.infer_expr_type(&ue.argument) {
197 if let Some(js_typeof) = ty.to_js_typeof() {
198 let mut idents = HashSet::new();
202 Self::collect_ast_expr_idents(&ue.argument, &mut idents);
203 if let Some(ctx) = self.fn_ctx.as_mut() {
204 ctx.compile_time_referenced_idents.extend(idents);
205 }
206 IrExpr::StringLiteral(js_typeof.to_string())
207 } else {
208 IrExpr::BuiltinCall(crate::zigir::types::IrBuiltinCall {
209 module: BuiltinModule::JsRuntime,
210 method: "jsTypeof".to_string(),
211 obj_name: None,
212 obj_expr: None,
213 args: vec![self.lower_expr(&ue.argument)],
214 return_type: ZigType::Str,
215 regex_info: None,
216 ta_type_suffix: None,
217 })
218 }
219 } else {
220 IrExpr::BuiltinCall(crate::zigir::types::IrBuiltinCall {
221 module: BuiltinModule::JsRuntime,
222 method: "jsTypeof".to_string(),
223 obj_name: None,
224 obj_expr: None,
225 args: vec![self.lower_expr(&ue.argument)],
226 return_type: ZigType::Str,
227 regex_info: None,
228 ta_type_suffix: None,
229 })
230 }
231 }
232 UnaryOperator::Void => IrExpr::Void(Box::new(self.lower_expr(&ue.argument))),
233 UnaryOperator::Delete => {
234 match &ue.argument {
237 Expression::StaticMemberExpression(mem) => {
238 let obj_name = match &mem.object {
239 Expression::Identifier(id) => Some(id.name.as_str().to_string()),
240 _ => None,
241 };
242 IrExpr::BuiltinCall(crate::zigir::types::IrBuiltinCall {
243 module: BuiltinModule::JsRuntime,
244 method: "deleteKey".to_string(),
245 obj_name,
246 obj_expr: None,
247 args: vec![IrExpr::StringLiteral(
248 mem.property.name.as_str().to_string(),
249 )],
250 return_type: ZigType::Bool,
251 regex_info: None,
252 ta_type_suffix: None,
253 })
254 }
255 Expression::ComputedMemberExpression(mem) => {
256 let obj_name = if let Expression::Identifier(id) = &mem.object {
257 Some(id.name.as_str().to_string())
258 } else {
259 None
260 };
261 IrExpr::BuiltinCall(crate::zigir::types::IrBuiltinCall {
262 module: BuiltinModule::JsRuntime,
263 method: "deleteByKey".to_string(),
264 obj_name,
265 obj_expr: None,
266 args: vec![self.lower_expr(&mem.expression)],
267 return_type: ZigType::Bool,
268 regex_info: None,
269 ta_type_suffix: None,
270 })
271 }
272 _ => {
273 IrExpr::CompileError {
275 span: self.span_to_source_span(ue.span),
276 msg: "delete operator requires property access".to_string(),
277 }
278 }
279 }
280 }
281 }
282 }
283
284 pub(super) fn lower_update(&mut self, ue: &UpdateExpression) -> crate::zigir::types::IrExpr {
286 let op = if ue.operator == UpdateOperator::Increment {
287 UpdateOp::Increment
288 } else {
289 UpdateOp::Decrement
290 };
291 let target = Box::new(self.lower_simple_assign_target(&ue.argument));
292 crate::zigir::types::IrExpr::Update {
293 op,
294 target,
295 is_expr_stmt: self.in_expr_stmt,
296 }
297 }
298
299 pub(super) fn lower_assignment(
301 &mut self,
302 ae: &AssignmentExpression,
303 ) -> crate::zigir::types::IrExpr {
304 use crate::zigir::types::IrExpr;
305
306 if ae.operator == AssignmentOperator::Exponential {
309 let target = self.lower_assign_target(&ae.left);
310 let value = Box::new(self.lower_expr(&ae.right));
311 let target_type = self.infer_assign_target_type(&ae.left);
312 let base_ident = match &target {
314 crate::zigir::types::IrAssignTarget::Ident(name) => IrExpr::Ident(name.clone()),
315 _ => IrExpr::Ident(IrIdent::new("__target")),
316 };
317 if target_type == Some(ZigType::BigInt) {
320 let name_clone = match &target {
321 crate::zigir::types::IrAssignTarget::Ident(name) => name.clone(),
322 _ => IrIdent::new("__target"),
323 };
324 return IrExpr::Assign {
325 op: AssignOp::Assign,
326 target: Box::new(target),
327 value: Box::new(IrExpr::Binary {
328 op: BinOp::Pow,
329 left: Box::new(IrExpr::Ident(name_clone)),
330 right: value,
331 left_type: Some(ZigType::BigInt),
332 right_type: Some(ZigType::BigInt),
333 }),
334 };
335 }
336 let base_type = target_type.unwrap_or(crate::types::ZigType::F64);
338 let exp_type = self
339 .infer_expr_type(&ae.right)
340 .unwrap_or(crate::types::ZigType::F64);
341 let result_type = if base_type == crate::types::ZigType::I64 {
344 Some(crate::types::ZigType::I64)
345 } else {
346 None
347 };
348 return IrExpr::Assign {
349 op: AssignOp::Assign,
350 target: Box::new(target),
351 value: Box::new(IrExpr::PowExpr {
352 base: Box::new(base_ident),
353 exp: value,
354 base_type,
355 exp_type,
356 result_type,
357 }),
358 };
359 }
360 let is_compound = ae.operator != AssignmentOperator::Assign
367 && ae.operator != AssignmentOperator::LogicalAnd
368 && ae.operator != AssignmentOperator::LogicalOr
369 && ae.operator != AssignmentOperator::LogicalNullish;
370
371 if is_compound {
372 let target_type = self.infer_assign_target_type(&ae.left);
374 if target_type == Some(ZigType::BigInt) {
375 let target = self.lower_assign_target(&ae.left);
376 let value = Box::new(self.lower_expr(&ae.right));
377 if let crate::zigir::types::IrAssignTarget::Ident(name) = &target {
381 let bin_op = match ae.operator {
382 AssignmentOperator::Addition => BinOp::Add,
383 AssignmentOperator::Subtraction => BinOp::Sub,
384 AssignmentOperator::Multiplication => BinOp::Mul,
385 AssignmentOperator::Division => BinOp::Div,
386 AssignmentOperator::Remainder => BinOp::Mod,
387 AssignmentOperator::ShiftLeft => BinOp::Shl,
388 AssignmentOperator::ShiftRight => BinOp::Shr,
389 AssignmentOperator::ShiftRightZeroFill => BinOp::UrShr,
390 AssignmentOperator::BitwiseAnd => BinOp::BitAnd,
391 AssignmentOperator::BitwiseOR => BinOp::BitOr,
392 AssignmentOperator::BitwiseXOR => BinOp::BitXor,
393 _ => BinOp::Add, };
395 let name_clone = name.clone();
396 return IrExpr::Assign {
397 op: AssignOp::Assign,
398 target: Box::new(target),
399 value: Box::new(IrExpr::Binary {
400 op: bin_op,
401 left: Box::new(IrExpr::Ident(name_clone)),
402 right: value,
403 left_type: Some(ZigType::BigInt),
404 right_type: Some(ZigType::BigInt),
405 }),
406 };
407 }
408 }
411 }
412
413 let op = match ae.operator {
414 AssignmentOperator::Assign => AssignOp::Assign,
415 AssignmentOperator::Addition => AssignOp::Add,
416 AssignmentOperator::Subtraction => AssignOp::Sub,
417 AssignmentOperator::Multiplication => AssignOp::Mul,
418 AssignmentOperator::Division => AssignOp::Div,
419 AssignmentOperator::Remainder => AssignOp::Mod,
420 AssignmentOperator::ShiftLeft => AssignOp::Shl,
421 AssignmentOperator::ShiftRight => AssignOp::Shr,
422 AssignmentOperator::ShiftRightZeroFill => AssignOp::Shr,
423 AssignmentOperator::BitwiseAnd => AssignOp::BitAnd,
424 AssignmentOperator::BitwiseOR => AssignOp::BitOr,
425 AssignmentOperator::BitwiseXOR => AssignOp::BitXor,
426 AssignmentOperator::LogicalAnd => AssignOp::LogicAnd,
427 AssignmentOperator::LogicalOr => AssignOp::LogicOr,
428 AssignmentOperator::LogicalNullish => AssignOp::Nullish,
429 _ => AssignOp::Assign,
431 };
432 let target = Box::new(self.lower_assign_target(&ae.left));
433 let value = Box::new(self.lower_expr(&ae.right));
434 IrExpr::Assign { op, target, value }
435 }
436
437 pub(super) fn lower_simple_assign_target(
440 &mut self,
441 target: &SimpleAssignmentTarget,
442 ) -> crate::zigir::types::IrAssignTarget {
443 match target {
444 SimpleAssignmentTarget::AssignmentTargetIdentifier(id) => {
445 let var_name = id.name.as_str();
446
447 if let Some((_, _, is_mut)) = self
449 .closure_mgr
450 .current_captured
451 .iter()
452 .find(|(n, _, _)| n == var_name)
453 {
454 let field_name = self.make_ident(var_name).zig_name;
455 return crate::zigir::types::IrAssignTarget::Member {
456 object: Box::new(crate::zigir::types::IrExpr::Ident(IrIdent::new("self"))),
457 field: field_name,
458 is_pointer: *is_mut,
459 };
460 }
461
462 crate::zigir::types::IrAssignTarget::Ident(IrIdent::new(var_name))
463 }
464 SimpleAssignmentTarget::StaticMemberExpression(mem) => {
465 crate::zigir::types::IrAssignTarget::Member {
466 object: Box::new(self.lower_expr(&mem.object)),
467 field: mem.property.name.to_string(),
468 is_pointer: false,
469 }
470 }
471 SimpleAssignmentTarget::ComputedMemberExpression(mem) => {
472 crate::zigir::types::IrAssignTarget::Index {
473 object: Box::new(self.lower_expr(&mem.object)),
474 index: Box::new(self.lower_expr(&mem.expression)),
475 }
476 }
477 _ => crate::zigir::types::IrAssignTarget::Ident(IrIdent::new("__unsupported_target")),
478 }
479 }
480
481 pub(super) fn lower_maybe_default(
483 &mut self,
484 target: &AssignmentTargetMaybeDefault,
485 ) -> (IrIdent, Option<crate::zigir::types::IrExpr>) {
486 match target {
487 AssignmentTargetMaybeDefault::AssignmentTargetWithDefault(atwd) => {
488 let pattern = self.extract_target_ident(&atwd.binding);
489 let default = Some(self.lower_expr(&atwd.init));
490 (pattern, default)
491 }
492 AssignmentTargetMaybeDefault::AssignmentTargetIdentifier(id) => {
493 (IrIdent::new(id.name.as_str()), None)
494 }
495 _ => (IrIdent::new("_"), None),
496 }
497 }
498
499 pub(super) fn extract_target_ident(&self, target: &AssignmentTarget) -> IrIdent {
501 match target {
502 AssignmentTarget::AssignmentTargetIdentifier(id) => IrIdent::new(id.name.as_str()),
503 _ => IrIdent::new("_"),
504 }
505 }
506
507 pub(super) fn lower_assign_target(
509 &mut self,
510 target: &AssignmentTarget,
511 ) -> crate::zigir::types::IrAssignTarget {
512 match target {
513 AssignmentTarget::AssignmentTargetIdentifier(id) => {
514 let var_name = id.name.as_str();
515
516 if let Some((_, _, is_mut)) = self
519 .closure_mgr
520 .current_captured
521 .iter()
522 .find(|(n, _, _)| n == var_name)
523 {
524 let field_name = self.make_ident(var_name).zig_name;
525 return crate::zigir::types::IrAssignTarget::Member {
526 object: Box::new(crate::zigir::types::IrExpr::Ident(IrIdent::new("self"))),
527 field: field_name,
528 is_pointer: *is_mut,
529 };
530 }
531
532 crate::zigir::types::IrAssignTarget::Ident(IrIdent::new(var_name))
533 }
534 AssignmentTarget::StaticMemberExpression(mem) => {
535 crate::zigir::types::IrAssignTarget::Member {
536 object: Box::new(self.lower_expr(&mem.object)),
537 field: mem.property.name.to_string(),
538 is_pointer: false,
539 }
540 }
541 AssignmentTarget::ComputedMemberExpression(mem) => {
542 crate::zigir::types::IrAssignTarget::Index {
543 object: Box::new(self.lower_expr(&mem.object)),
544 index: Box::new(self.lower_expr(&mem.expression)),
545 }
546 }
547 AssignmentTarget::ObjectAssignmentTarget(ot) => {
548 let bindings: Vec<crate::zigir::types::IrDestructureBinding> = ot
549 .properties
550 .iter()
551 .map(|prop| {
552 match prop {
553 AssignmentTargetProperty::AssignmentTargetPropertyIdentifier(ap) => {
554 let pattern = IrIdent::new(ap.binding.name.as_str());
555 let default = ap.init.as_ref().map(|e| self.lower_expr(e));
556 crate::zigir::types::IrDestructureBinding { pattern, default }
557 }
558 AssignmentTargetProperty::AssignmentTargetPropertyProperty(ap) => {
559 let (pattern, default) = self.lower_maybe_default(&ap.binding);
561 crate::zigir::types::IrDestructureBinding { pattern, default }
562 }
563 }
564 })
565 .collect();
566 crate::zigir::types::IrAssignTarget::Destructure(bindings)
567 }
568 AssignmentTarget::ArrayAssignmentTarget(at) => {
569 let bindings: Vec<crate::zigir::types::IrDestructureBinding> = at
570 .elements
571 .iter()
572 .filter_map(|elem| {
573 elem.as_ref().map(|target| {
574 let (pattern, default) = self.lower_maybe_default(target);
575 crate::zigir::types::IrDestructureBinding { pattern, default }
576 })
577 })
578 .collect();
579 crate::zigir::types::IrAssignTarget::Destructure(bindings)
580 }
581 _ => crate::zigir::types::IrAssignTarget::Ident(IrIdent::new("__unsupported_target")),
582 }
583 }
584
585 pub(super) fn expr_is_string(&self, expr: &Expression) -> bool {
587 match expr {
588 Expression::StringLiteral(_) => true,
589 Expression::TemplateLiteral(_) => true,
590 Expression::Identifier(_id) => {
591 self.infer_expr_type(expr) == Some(ZigType::Str)
593 }
594 Expression::BinaryExpression(be) if be.operator == BinaryOperator::Addition => {
595 self.expr_is_string(&be.left) || self.expr_is_string(&be.right)
596 }
597 Expression::ParenthesizedExpression(pe) => self.expr_is_string(&pe.expression),
598 _ => self.infer_expr_type(expr) == Some(ZigType::Str),
599 }
600 }
601
602 pub(super) fn lower_string_concat(
605 &mut self,
606 be: &BinaryExpression,
607 ) -> crate::zigir::types::IrExpr {
608 use crate::zigir::types::IrExpr;
609
610 let mut operands: Vec<&Expression> = Vec::new();
611 Self::collect_concat_from_be(be, &mut operands);
612
613 let mut fmt = String::new();
614 let mut args: Vec<IrExpr> = Vec::new();
615
616 for op in &operands {
617 match op {
618 Expression::StringLiteral(sl) => {
619 for ch in sl.value.chars() {
621 match ch {
622 '\\' => fmt.push_str("\\\\"),
623 '"' => fmt.push_str("\\\""),
624 '\n' => fmt.push_str("\\n"),
625 '\r' => fmt.push_str("\\r"),
626 '\t' => fmt.push_str("\\t"),
627 '{' => fmt.push_str("{{"),
628 '}' => fmt.push_str("}}"),
629 c => fmt.push(c),
630 }
631 }
632 }
633 _ => {
634 let placeholder = if self.expr_is_string(op) {
636 "{s}"
637 } else {
638 match self.infer_expr_type(op) {
639 Some(ZigType::Str) => "{s}",
640 Some(ZigType::I64) => "{d}",
641 Some(ZigType::F64) => "{d:.15}",
642 Some(ZigType::Bool) => "{}",
643 _ => "{}",
644 }
645 };
646 fmt.push_str(placeholder);
647 let lowered = match op {
649 Expression::ParenthesizedExpression(pe) => self.lower_expr(&pe.expression),
650 _ => self.lower_expr(op),
651 };
652 args.push(lowered);
653 }
654 }
655 }
656
657 IrExpr::AllocPrint { fmt, args }
658 }
659
660 pub(super) fn collect_concat_from_be<'a>(
663 be: &'a BinaryExpression<'a>,
664 out: &mut Vec<&'a Expression<'a>>,
665 ) {
666 if let Expression::BinaryExpression(ref left_be) = be.left {
668 if left_be.operator == BinaryOperator::Addition {
669 Self::collect_concat_from_be(left_be, out);
670 } else {
671 out.push(&be.left);
672 }
673 } else {
674 out.push(&be.left);
675 }
676
677 if let Expression::BinaryExpression(ref right_be) = be.right {
679 if right_be.operator == BinaryOperator::Addition {
680 Self::collect_concat_from_be(right_be, out);
681 } else {
682 out.push(&be.right);
683 }
684 } else {
685 out.push(&be.right);
686 }
687 }
688}