1use oxc_ast::ast::*;
5
6use crate::native_builtins::BuiltinCall;
7use crate::types::ZigType;
8use crate::zigir::builtins::BuiltinModule;
9use crate::zigir::ident::IrIdent;
10use crate::zigir::kinds::{CallKind, FieldKind};
11
12use super::super::cabi::builtin_call_to_ir;
13use super::Lowerer;
14
15impl Lowerer {
16 pub(super) fn check_unsupported_call(&self, ce: &CallExpression) -> Option<String> {
19 match &ce.callee {
21 Expression::StaticMemberExpression(mem) => {
22 if let Expression::Identifier(id) = &mem.object {
23 let obj_name = id.name.as_str();
24 let method_name = mem.property.name.as_str();
25 match obj_name {
26 "Atomics" => Some(format!(
27 "Atomics.{}() is not supported (shared memory atomics are not available in Zig)",
28 method_name
29 )),
30 "Reflect" => Some(format!(
31 "Reflect.{}() is not supported (meta-programming API is not available)",
32 method_name
33 )),
34 "Object" => match method_name {
35 "getOwnPropertySymbols" => Some(
36 "Object.getOwnPropertySymbols() is not supported (Symbol keys are not available in js2zig)".to_string(),
37 ),
38 _ => None,
39 },
40 "Map" if method_name == "groupBy" => Some(
41 "Map.groupBy() is not supported (requires iterable grouping)".to_string(),
42 ),
43 "Promise" => Some(format!(
44 "Promise.{}() is not supported (use async/await + host functions instead)",
45 method_name
46 )),
47 "Intl" => Some(format!(
48 "Intl.{}() is not supported (use Zig/C library for internationalization)",
49 method_name
50 )),
51 _ => None,
52 }
53 } else {
54 None
55 }
56 }
57 Expression::Identifier(id) => match id.name.as_str() {
58 name @ "Atomics" | name @ "Reflect" | name @ "Promise" | name @ "Intl" => {
59 Some(format!("{} is not supported in js2zig", name))
60 }
61 _ => None,
62 },
63 _ => None,
64 }
65 }
66
67 pub(super) fn lower_call(&mut self, ce: &CallExpression) -> crate::zigir::types::IrExpr {
77 use crate::zigir::types::IrExpr;
78
79 if let Some(err_msg) = self.check_unsupported_call(ce) {
81 return self.compile_error_expr(ce.span, err_msg);
82 }
83
84 if let Some(builtin) = crate::native_builtins::detect_builtin_call(ce) {
86 if let Some(inlined) = self.try_inline_array_callback(ce, &builtin) {
99 return inlined;
100 }
101
102 let args = self.lower_args(&ce.arguments);
104
105 if let Some(inlined) = self.try_inline_array_method(ce, &builtin, &args) {
107 return inlined;
108 }
109
110 if matches!(builtin, crate::native_builtins::BuiltinCall::Eval) {
112 return self.compile_error_expr(ce.span, "eval() is not supported (security risk, cannot dynamically execute at compile time)");
113 }
114
115 if matches!(
117 builtin,
118 crate::native_builtins::BuiltinCall::SetUnion
119 | crate::native_builtins::BuiltinCall::SetIntersection
120 | crate::native_builtins::BuiltinCall::SetDifference
121 | crate::native_builtins::BuiltinCall::SetSymmetricDifference
122 | crate::native_builtins::BuiltinCall::SetIsSubsetOf
123 | crate::native_builtins::BuiltinCall::SetIsSupersetOf
124 | crate::native_builtins::BuiltinCall::SetIsDisjointFrom
125 ) {
126 let method_name = match &builtin {
127 crate::native_builtins::BuiltinCall::SetUnion => "union",
128 crate::native_builtins::BuiltinCall::SetIntersection => "intersection",
129 crate::native_builtins::BuiltinCall::SetDifference => "difference",
130 crate::native_builtins::BuiltinCall::SetSymmetricDifference => {
131 "symmetricDifference"
132 }
133 crate::native_builtins::BuiltinCall::SetIsSubsetOf => "isSubsetOf",
134 crate::native_builtins::BuiltinCall::SetIsSupersetOf => "isSupersetOf",
135 crate::native_builtins::BuiltinCall::SetIsDisjointFrom => "isDisjointFrom",
136 _ => "unknown",
140 };
141 return self.compile_error_expr(
142 ce.span,
143 format!(
144 "Set.prototype.{}() is not supported (ES2025 Set operation)",
145 method_name
146 ),
147 );
148 }
149
150 let (module, method, return_type) = builtin_call_to_ir(&builtin);
151
152 if matches!(builtin, crate::native_builtins::BuiltinCall::JsonParse)
155 && let Some(ctx) = self.fn_ctx.as_mut()
156 {
157 ctx.has_catchable_error = true;
158 }
159 let obj_name = Self::extract_callee_object_name_static(&ce.callee);
160
161 let (module, method, return_type) = if let Some(name) = &obj_name {
165 if let Some(var_type) = self.type_info.var_types.get(name.as_str()) {
166 if matches!(var_type, ZigType::Str) && module == BuiltinModule::JsArray {
167 match method.as_str() {
168 "at" => (BuiltinModule::JsString, "at".into(), ZigType::Str),
169 "indexOf" => (BuiltinModule::JsString, "indexOf".into(), ZigType::I64),
170 "includes" => {
171 (BuiltinModule::JsString, "includes".into(), ZigType::Bool)
172 }
173 "lastIndexOf" => {
174 (BuiltinModule::JsString, "lastIndexOf".into(), ZigType::I64)
175 }
176 "slice" => (BuiltinModule::JsString, "slice".into(), ZigType::Str),
177 _ => (module, method, return_type),
178 }
179 } else if matches!(var_type, ZigType::F64 | ZigType::I64)
180 && module == BuiltinModule::JsDate
181 && method == "toString"
182 {
183 (BuiltinModule::JsNumber, "toString".into(), ZigType::Str)
192 } else if matches!(var_type, ZigType::BigInt)
193 && module == BuiltinModule::JsDate
194 && (method == "toString" || method == "toLocaleString")
195 {
196 (BuiltinModule::JsBigInt, method, ZigType::Str)
208 } else if let ZigType::NamedStruct(n) = var_type {
209 if Self::is_typedarray_type(n) {
210 let ta_mod = BuiltinModule::JsTypedArray;
211 match method.as_str() {
212 "set" => (ta_mod, "set".into(), ZigType::Void),
213 "get" => (ta_mod, "get".into(), ZigType::I64),
214 "fill" => (ta_mod, "fill".into(), ZigType::Void),
215 "slice" => {
216 (ta_mod, "slice".into(), ZigType::NamedStruct(n.clone()))
217 }
218 "copyWithin" => (ta_mod, "copyWithin".into(), ZigType::Void),
219 _ => (module, method, return_type),
220 }
221 } else {
222 (module, method, return_type)
223 }
224 } else {
225 (module, method, return_type)
226 }
227 } else {
228 (module, method, return_type)
229 }
230 } else {
231 (module, method, return_type)
232 };
233
234 let regex_info = Self::extract_regex_info(ce, &builtin);
236
237 if matches!(builtin, BuiltinCall::StringMatchAll)
242 && let Some(ref ri) = regex_info
243 && !ri.is_var_ref
244 && !ri.has_global
245 {
246 return self.compile_error_expr(
247 ce.span,
248 "String.prototype.matchAll called with a non-global RegExp argument (TypeError)",
249 );
250 }
251
252 if matches!(builtin, BuiltinCall::StringReplaceAll)
256 && let Some(ref ri) = regex_info
257 && !ri.is_var_ref
258 && !ri.has_global
259 {
260 return self.compile_error_expr(
261 ce.span,
262 "String.prototype.replaceAll called with a non-global RegExp argument (TypeError)",
263 );
264 }
265
266 let ta_type_suffix = if module == BuiltinModule::JsTypedArray {
268 obj_name.as_ref().and_then(|name| {
269 self.type_info.var_types.get(name.as_str()).and_then(|zt| {
270 if let ZigType::NamedStruct(n) = zt {
271 Self::typedarray_type_suffix(n).map(|s| s.to_string())
272 } else {
273 None
274 }
275 })
276 })
277 } else {
278 None
279 };
280
281 let method = if module == BuiltinModule::JsObject
286 && (method == "keys" || method == "getOwnPropertyNames")
287 {
288 let ident_name = match args.first() {
289 Some(IrExpr::Ident(ident)) => Some(ident.zig_name.as_str()),
290 Some(IrExpr::TypedIdent { ident, .. }) => Some(ident.zig_name.as_str()),
291 _ => None,
292 };
293 if let Some(name) = ident_name {
294 if let Some(var_type) = self.type_info.var_types.get(name) {
295 if matches!(var_type, ZigType::Struct(_)) {
296 if method == "keys" {
297 "keysStruct".into()
298 } else {
299 "getOwnPropertyNamesStruct".into()
300 }
301 } else {
302 method
303 }
304 } else {
305 method
306 }
307 } else {
308 method
309 }
310 } else {
311 method
312 };
313
314 let mut inner_expr = if obj_name.is_none() {
319 if let Expression::StaticMemberExpression(sme) = &ce.callee {
320 match &sme.object {
321 Expression::CallExpression(_) | Expression::NewExpression(_) => {
324 Some(self.lower_expr(&sme.object))
325 }
326 _ => None,
327 }
328 } else {
329 None
330 }
331 } else {
332 None
333 };
334
335 if let Some(inner) = inner_expr.take() {
342 let chain_elem_type = match &inner {
343 IrExpr::ArrayCallbackInline(cb) => Some(cb.elem_type.clone()),
344 IrExpr::ArrayMethodInline(mm) => Some(mm.elem_type.clone()),
345 _ => None,
346 };
347
348 if let Some(elem_type) = chain_elem_type {
349 if let Some(inlined) =
351 self.try_inline_array_callback_with_chain(ce, &builtin, &elem_type, &inner)
352 {
353 return inlined;
354 }
355
356 if let Some(inlined) = self
358 .try_inline_array_method_with_chain(ce, &builtin, &args, &elem_type, &inner)
359 {
360 return inlined;
361 }
362
363 inner_expr = Some(inner);
365 } else {
366 inner_expr = Some(inner);
367 }
368 }
369
370 let obj_expr = inner_expr.map(Box::new);
371
372 return IrExpr::BuiltinCall(crate::zigir::types::IrBuiltinCall {
373 module,
374 method,
375 obj_name,
376 obj_expr,
377 args,
378 return_type,
379 regex_info,
380 ta_type_suffix,
381 });
382 }
383
384 let args = self.lower_args(&ce.arguments);
388
389 if let Expression::StaticMemberExpression(sme) = &ce.callee
394 && let Expression::Identifier(id) = &sme.object
395 {
396 let var_name = id.name.as_str();
397 let var_type = self.type_info.var_types.get(var_name).cloned().or_else(|| {
398 self.fn_ctx
399 .as_ref()
400 .and_then(|ctx| ctx.fn_local_types.get(var_name).cloned())
401 });
402 if let Some(ZigType::BigInt) = var_type {
403 let method = sme.property.name.as_str();
404 match method {
405 "toString" => {
406 return IrExpr::BuiltinCall(crate::zigir::types::IrBuiltinCall {
407 module: BuiltinModule::JsBigInt,
408 method: "toString".into(),
409 obj_name: Some(var_name.to_string()),
410 obj_expr: None,
411 args,
412 return_type: ZigType::Str,
413 regex_info: None,
414 ta_type_suffix: None,
415 });
416 }
417 "valueOf" => {
418 return IrExpr::BuiltinCall(crate::zigir::types::IrBuiltinCall {
419 module: BuiltinModule::JsBigInt,
420 method: "valueOf".into(),
421 obj_name: Some(var_name.to_string()),
422 obj_expr: None,
423 args,
424 return_type: ZigType::BigInt,
425 regex_info: None,
426 ta_type_suffix: None,
427 });
428 }
429 "toLocaleString" => {
430 return IrExpr::BuiltinCall(crate::zigir::types::IrBuiltinCall {
431 module: BuiltinModule::JsBigInt,
432 method: "toLocaleString".into(),
433 obj_name: Some(var_name.to_string()),
434 obj_expr: None,
435 args,
436 return_type: ZigType::Str,
437 regex_info: None,
438 ta_type_suffix: None,
439 });
440 }
441 _ => {} }
443 }
444 }
445
446 if let Expression::StaticMemberExpression(sme) = &ce.callee
451 && let Expression::Identifier(id) = &sme.object
452 {
453 let var_name = id.name.as_str();
454 if let Some(ctx) = &self.fn_ctx
455 && ctx.regexp_vars.contains(var_name)
456 {
457 let method = sme.property.name.as_str();
458 match method {
459 "test" => {
460 return IrExpr::BuiltinCall(crate::zigir::types::IrBuiltinCall {
461 module: BuiltinModule::JsRegExp,
462 method: "test".into(),
463 obj_name: Some(var_name.to_string()),
464 obj_expr: None,
465 args,
466 return_type: ZigType::Bool,
467 regex_info: Some(crate::zigir::types::IrRegexInfo {
468 pattern: None,
469 has_global: false,
470 is_var_ref: true,
471 var_name: Some(var_name.to_string()),
472 }),
473 ta_type_suffix: None,
474 });
475 }
476 "exec" => {
477 return IrExpr::BuiltinCall(crate::zigir::types::IrBuiltinCall {
478 module: BuiltinModule::JsRegExp,
479 method: "exec".into(),
480 obj_name: Some(var_name.to_string()),
481 obj_expr: None,
482 args,
483 return_type: ZigType::JsAny,
484 regex_info: Some(crate::zigir::types::IrRegexInfo {
485 pattern: None,
486 has_global: false,
487 is_var_ref: true,
488 var_name: Some(var_name.to_string()),
489 }),
490 ta_type_suffix: None,
491 });
492 }
493 _ => {} }
495 }
496 }
497
498 match &ce.callee {
500 Expression::Identifier(id) => {
502 let name = id.name.as_str();
503
504 if let Some(host_name) = name.strip_prefix("host_") {
506 let is_async = self.async_host_fns.contains(name);
507 let return_type = self.infer_host_return_type(host_name);
508 return IrExpr::HostCall(crate::zigir::types::IrHostCall {
509 name: host_name.to_string(),
510 args,
511 return_type,
512 is_async,
513 });
514 }
515
516 if self
518 .closure_mgr
519 .current_captured
520 .iter()
521 .any(|(n, _, _)| n.as_str() == name)
522 || self.is_closure_instance(name)
523 {
524 return IrExpr::Call(crate::zigir::types::IrCallExpr {
525 callee: Box::new(IrExpr::Ident(IrIdent::new(name))),
526 args,
527 call_kind: CallKind::Closure,
528 });
529 }
530
531 if let Some(ctx) = &self.fn_ctx
533 && ctx.is_nested_fn(name)
534 {
535 let callee_ident = self.make_ident(name);
536 return IrExpr::Call(crate::zigir::types::IrCallExpr {
537 callee: Box::new(IrExpr::Ident(callee_ident)),
538 args,
539 call_kind: CallKind::Closure,
540 });
541 }
542
543 let args = self.pack_rest_args_if_needed(name, args);
545 IrExpr::Call(crate::zigir::types::IrCallExpr {
546 callee: Box::new(IrExpr::Ident(IrIdent::new(name))),
547 args,
548 call_kind: CallKind::Direct,
549 })
550 }
551
552 Expression::StaticMemberExpression(mem) => {
554 let method_name = mem.property.name.as_str();
555 let obj_expr = self.lower_expr(&mem.object);
556
557 let object_type = self.infer_method_object_kind(&mem.object);
559
560 IrExpr::Call(crate::zigir::types::IrCallExpr {
561 callee: Box::new(IrExpr::FieldAccess {
562 object: Box::new(obj_expr),
563 field: method_name.to_string(),
564 field_kind: FieldKind::StructField,
565 }),
566 args,
567 call_kind: CallKind::Method { object_type },
568 })
569 }
570
571 Expression::FunctionExpression(_) | Expression::ArrowFunctionExpression(_) => {
573 let callee = self.lower_expr(&ce.callee);
575 IrExpr::Call(crate::zigir::types::IrCallExpr {
576 callee: Box::new(callee),
577 args,
578 call_kind: CallKind::Closure,
579 })
580 }
581
582 Expression::ParenthesizedExpression(_) => {
584 let callee = self.lower_expr(&ce.callee);
585 IrExpr::Call(crate::zigir::types::IrCallExpr {
586 callee: Box::new(callee),
587 args,
588 call_kind: CallKind::Closure,
589 })
590 }
591
592 _ => {
594 let callee = self.lower_expr(&ce.callee);
595 IrExpr::Call(crate::zigir::types::IrCallExpr {
596 callee: Box::new(callee),
597 args,
598 call_kind: CallKind::Direct,
599 })
600 }
601 }
602 }
603
604 pub(super) fn infer_method_object_kind(
606 &self,
607 obj: &Expression,
608 ) -> crate::zigir::kinds::MethodObjectKind {
609 use crate::zigir::kinds::MethodObjectKind;
610
611 match obj {
612 Expression::Identifier(id) => {
613 if let Some(zig_type) = self.type_info.var_types.get(id.name.as_str()) {
614 match zig_type {
615 ZigType::ArrayList(_) => MethodObjectKind::ArrayList,
616 ZigType::Str => MethodObjectKind::String,
617 ZigType::NamedStruct(name) => match name.as_str() {
618 "Map" => MethodObjectKind::Map,
619 "Set" => MethodObjectKind::Set,
620 "Date" => MethodObjectKind::Date,
621 other => {
622 if self.class_names.contains(other) {
623 MethodObjectKind::Class(other.to_string())
624 } else {
625 MethodObjectKind::Unknown
626 }
627 }
628 },
629 ZigType::JsAny | ZigType::Anytype => MethodObjectKind::JsAny,
630 _ => MethodObjectKind::Unknown,
631 }
632 } else {
633 MethodObjectKind::Unknown
634 }
635 }
636 _ => MethodObjectKind::Unknown,
637 }
638 }
639
640 pub(super) fn is_closure_instance(&self, name: &str) -> bool {
642 self.closure_mgr.closure_instances.contains(name)
643 }
644
645 pub(super) fn infer_host_return_type(&self, host_name: &str) -> ZigType {
650 let full_name = format!("host_{}", host_name);
652 self.type_info
653 .host_return_types
654 .get(&full_name)
655 .cloned()
656 .unwrap_or(ZigType::JsAny)
657 }
658
659 pub(super) fn lower_await(&mut self, ae: &AwaitExpression) -> crate::zigir::types::IrExpr {
661 let task_var = IrIdent::new(&self.name_mangler.next_name("_t"));
662 let block_label = format!("blk_{}", self.name_mangler.peek_count("_t"));
663
664 if let Expression::CallExpression(call) = &ae.argument {
666 let args: Vec<_> = call
667 .arguments
668 .iter()
669 .filter_map(|a| a.as_expression().map(|e| self.lower_expr(e)))
670 .collect();
671
672 if let Expression::Identifier(id) = &call.callee {
674 let name = id.name.as_str();
675 if self.async_host_fns.contains(name) {
676 return crate::zigir::types::IrExpr::Await(crate::zigir::types::IrAwaitExpr {
677 task_var,
678 callee: Box::new(crate::zigir::types::IrExpr::Ident(IrIdent::new(name))),
679 args,
680 is_host_async: true,
681 block_label,
682 });
683 }
684 }
685
686 let callee = self.lower_expr(&call.callee);
688 return crate::zigir::types::IrExpr::Await(crate::zigir::types::IrAwaitExpr {
689 task_var,
690 callee: Box::new(callee),
691 args,
692 is_host_async: false,
693 block_label,
694 });
695 }
696
697 let argument = self.lower_expr(&ae.argument);
699 crate::zigir::types::IrExpr::Await(crate::zigir::types::IrAwaitExpr {
700 task_var,
701 callee: Box::new(argument),
702 args: vec![],
703 is_host_async: false,
704 block_label,
705 })
706 }
707
708 pub(super) fn lower_new(&mut self, ne: &NewExpression) -> crate::zigir::types::IrExpr {
710 use crate::zigir::kinds::NewConstructor;
711
712 let constructor = match &ne.callee {
714 Expression::Identifier(id) => match id.name.as_str() {
715 "Map" => NewConstructor::Map,
716 "Set" => NewConstructor::Set,
717 "Date" => {
718 let kind = if ne.arguments.is_empty() {
720 crate::zigir::kinds::DateConstructorKind::Now
721 } else if ne.arguments.len() >= 2 {
722 crate::zigir::kinds::DateConstructorKind::FromComponents
723 } else if let Some(first_arg) = ne.arguments.first()
724 && let Some(expr) = first_arg.as_expression()
725 {
726 let is_string = matches!(expr, Expression::StringLiteral(_));
728 if is_string {
729 crate::zigir::kinds::DateConstructorKind::FromString
730 } else {
731 crate::zigir::kinds::DateConstructorKind::FromMillis
732 }
733 } else {
734 crate::zigir::kinds::DateConstructorKind::Now
735 };
736 NewConstructor::Date(kind)
737 }
738 "RegExp" => NewConstructor::RegExp,
739 "Int8Array" | "Uint8Array" | "Uint8ClampedArray" | "Int16Array" | "Uint16Array"
740 | "Int32Array" | "Uint32Array" | "Float32Array" | "Float64Array"
741 | "BigInt64Array" | "BigUint64Array" => {
742 let kind = match id.name.as_str() {
743 "Int8Array" => crate::zigir::kinds::TypedArrayKind::Int8Array,
744 "Uint8Array" => crate::zigir::kinds::TypedArrayKind::Uint8Array,
745 "Uint8ClampedArray" => {
746 crate::zigir::kinds::TypedArrayKind::Uint8ClampedArray
747 }
748 "Int16Array" => crate::zigir::kinds::TypedArrayKind::Int16Array,
749 "Uint16Array" => crate::zigir::kinds::TypedArrayKind::Uint16Array,
750 "Int32Array" => crate::zigir::kinds::TypedArrayKind::Int32Array,
751 "Uint32Array" => crate::zigir::kinds::TypedArrayKind::Uint32Array,
752 "Float32Array" => crate::zigir::kinds::TypedArrayKind::Float32Array,
753 "Float64Array" => crate::zigir::kinds::TypedArrayKind::Float64Array,
754 "BigInt64Array" => crate::zigir::kinds::TypedArrayKind::BigInt64Array,
755 "BigUint64Array" => crate::zigir::kinds::TypedArrayKind::BigUint64Array,
756 _ => crate::zigir::kinds::TypedArrayKind::Float64Array,
757 };
758 NewConstructor::TypedArray(kind)
759 }
760 "Error" => NewConstructor::Error("Error".to_string()),
761 "TypeError" => NewConstructor::Error("TypeError".to_string()),
762 "RangeError" => NewConstructor::Error("RangeError".to_string()),
763 "String" => {
765 return if let Some(first_arg) = ne.arguments.first()
766 && let Some(expr) = first_arg.as_expression()
767 {
768 self.lower_expr(expr)
769 } else {
770 crate::zigir::types::IrExpr::StringLiteral("".to_string())
771 };
772 }
773 "Number" => {
774 return if let Some(first_arg) = ne.arguments.first()
775 && let Some(expr) = first_arg.as_expression()
776 {
777 self.lower_expr(expr)
778 } else {
779 crate::zigir::types::IrExpr::IntLiteral(0)
780 };
781 }
782 "Boolean" => {
783 return if let Some(first_arg) = ne.arguments.first()
784 && let Some(expr) = first_arg.as_expression()
785 {
786 self.lower_expr(expr)
787 } else {
788 crate::zigir::types::IrExpr::BoolLiteral(false)
789 };
790 }
791 name if self.class_names.contains(name) => NewConstructor::Class(name.to_string()),
792 "ArrayBuffer" | "SharedArrayBuffer" | "Function" | "Promise" | "WeakMap"
794 | "WeakSet" | "DataView" => {
795 NewConstructor::Unsupported(id.name.as_str().to_string())
796 }
797 other => {
798 let span = oxc_span::GetSpan::span(ne);
799 return self.compile_error_expr(
800 span,
801 format!("Unsupported NewExpression: new {}()", other),
802 );
803 }
804 },
805 Expression::StaticMemberExpression(mem) => {
806 if let Expression::Identifier(id) = &mem.object {
807 let obj_name = id.name.as_str();
808 let method_name = mem.property.name.as_str();
809 match obj_name {
810 "Intl" => {
811 let span = oxc_span::GetSpan::span(ne);
812 return self.compile_error_expr(
813 span,
814 format!(
815 "Intl.{}() is not supported (use Zig/C library for internationalization)",
816 method_name
817 ),
818 );
819 }
820 _ => {
821 let span = oxc_span::GetSpan::span(ne);
822 return self.compile_error_expr(span, "Unsupported NewExpression");
823 }
824 }
825 } else {
826 let span = oxc_span::GetSpan::span(ne);
827 return self.compile_error_expr(span, "Unsupported NewExpression");
828 }
829 }
830 _ => {
831 let span = oxc_span::GetSpan::span(ne);
832 return self.compile_error_expr(span, "Unsupported NewExpression");
833 }
834 };
835
836 let args = self.lower_args(&ne.arguments);
837
838 let result_type = match &constructor {
839 NewConstructor::Map => ZigType::NamedStruct("Map".to_string()),
840 NewConstructor::Set => ZigType::NamedStruct("Set".to_string()),
841 NewConstructor::Date(_) => ZigType::NamedStruct("Date".to_string()),
842 NewConstructor::RegExp => ZigType::NamedStruct("JsRegExp".to_string()),
843 NewConstructor::TypedArray(_) => ZigType::NamedStruct("TypedArray".to_string()),
844 NewConstructor::Class(name) => ZigType::NamedStruct(name.clone()),
845 NewConstructor::Error(_) => ZigType::JsAny,
846 _ => ZigType::JsAny,
847 };
848
849 crate::zigir::types::IrExpr::New(crate::zigir::types::IrNewExpr {
850 constructor,
851 args,
852 result_type,
853 })
854 }
855
856 fn pack_rest_args_if_needed(
866 &self,
867 callee_name: &str,
868 args: Vec<crate::zigir::types::IrExpr>,
869 ) -> Vec<crate::zigir::types::IrExpr> {
870 use crate::zigir::types::{IrArrayLiteral, IrCallExpr, IrExpr};
871
872 if !self
873 .type_info
874 .functions_needing_synthetic_rest
875 .contains(callee_name)
876 {
877 return args;
878 }
879
880 let is_async = self
882 .type_info
883 .is_async
884 .get(callee_name)
885 .copied()
886 .unwrap_or(false);
887 let declared_count = self
888 .type_info
889 .fn_param_types
890 .get(callee_name)
891 .map(|params| params.len())
892 .unwrap_or(0)
893 + if is_async { 1 } else { 0 };
894
895 if args.len() <= declared_count {
896 let mut result = args;
898 result.push(IrExpr::Spread(Box::new(IrExpr::ArrayLiteral(
899 IrArrayLiteral {
900 elements: vec![],
901 spread_indices: vec![],
902 },
903 ))));
904 return result;
905 }
906
907 let mut regular_args = args;
909 let rest_args = regular_args.split_off(declared_count);
910
911 if rest_args.len() == 1 && matches!(rest_args[0], IrExpr::Spread(_)) {
913 regular_args.extend(rest_args);
914 return regular_args;
915 }
916
917 let rest_elements: Vec<IrExpr> = rest_args
919 .into_iter()
920 .map(|arg| {
921 IrExpr::Call(IrCallExpr {
922 callee: Box::new(IrExpr::FieldAccess {
923 object: Box::new(IrExpr::Ident(IrIdent::new("JsAny"))),
924 field: "from".to_string(),
925 field_kind: FieldKind::StructField,
926 }),
927 args: vec![arg],
928 call_kind: CallKind::Direct,
929 })
930 })
931 .collect();
932
933 regular_args.push(IrExpr::Spread(Box::new(IrExpr::ArrayLiteral(
934 IrArrayLiteral {
935 elements: rest_elements,
936 spread_indices: vec![],
937 },
938 ))));
939 regular_args
940 }
941}