1use oxc_ast::ast::*;
5
6use crate::types::ZigType;
7use crate::zigir::builtins::BuiltinModule;
8use crate::zigir::ident::IrIdent;
9use crate::zigir::kinds::{CallKind, FieldKind};
10
11use super::super::cabi::builtin_call_to_ir;
12use super::Lowerer;
13
14impl Lowerer {
15 pub(super) fn check_unsupported_call(&self, ce: &CallExpression) -> Option<String> {
18 match &ce.callee {
20 Expression::StaticMemberExpression(mem) => {
21 if let Expression::Identifier(id) = &mem.object {
22 let obj_name = id.name.as_str();
23 let method_name = mem.property.name.as_str();
24 match obj_name {
25 "Atomics" => Some(format!(
26 "Atomics.{}() is not supported (shared memory atomics are not available in Zig)",
27 method_name
28 )),
29 "Reflect" => Some(format!(
30 "Reflect.{}() is not supported (meta-programming API is not available)",
31 method_name
32 )),
33 "Object" => match method_name {
34 "getOwnPropertySymbols" => Some(
35 "Object.getOwnPropertySymbols() is not supported (Symbol keys are not available in js2zig)".to_string(),
36 ),
37 _ => None,
38 },
39 "Map" if method_name == "groupBy" => Some(
40 "Map.groupBy() is not supported (requires iterable grouping)".to_string(),
41 ),
42 "Promise" => Some(format!(
43 "Promise.{}() is not supported (use async/await + host functions instead)",
44 method_name
45 )),
46 "Intl" => Some(format!(
47 "Intl.{}() is not supported (use Zig/C library for internationalization)",
48 method_name
49 )),
50 _ => None,
51 }
52 } else {
53 None
54 }
55 }
56 Expression::Identifier(id) => match id.name.as_str() {
57 name @ "Atomics" | name @ "Reflect" | name @ "Promise" | name @ "Intl" => {
58 Some(format!("{} is not supported in js2zig", name))
59 }
60 _ => None,
61 },
62 _ => None,
63 }
64 }
65
66 pub(super) fn lower_call(&mut self, ce: &CallExpression) -> crate::zigir::types::IrExpr {
76 use crate::zigir::types::IrExpr;
77
78 if let Some(err_msg) = self.check_unsupported_call(ce) {
80 return self.compile_error_expr(ce.span, err_msg);
81 }
82
83 let args = self.lower_args(&ce.arguments);
84
85 if let Some(builtin) = crate::native_builtins::detect_builtin_call(ce) {
87 if let Some(inlined) = self.try_inline_array_callback(ce, &builtin) {
89 return inlined;
90 }
91
92 if let Some(inlined) = self.try_inline_array_method(ce, &builtin, &args) {
94 return inlined;
95 }
96
97 if matches!(builtin, crate::native_builtins::BuiltinCall::Eval) {
99 return self.compile_error_expr(ce.span, "eval() is not supported (security risk, cannot dynamically execute at compile time)");
100 }
101
102 if matches!(
104 builtin,
105 crate::native_builtins::BuiltinCall::SetUnion
106 | crate::native_builtins::BuiltinCall::SetIntersection
107 | crate::native_builtins::BuiltinCall::SetDifference
108 | crate::native_builtins::BuiltinCall::SetSymmetricDifference
109 | crate::native_builtins::BuiltinCall::SetIsSubsetOf
110 | crate::native_builtins::BuiltinCall::SetIsSupersetOf
111 | crate::native_builtins::BuiltinCall::SetIsDisjointFrom
112 ) {
113 let method_name = match &builtin {
114 crate::native_builtins::BuiltinCall::SetUnion => "union",
115 crate::native_builtins::BuiltinCall::SetIntersection => "intersection",
116 crate::native_builtins::BuiltinCall::SetDifference => "difference",
117 crate::native_builtins::BuiltinCall::SetSymmetricDifference => {
118 "symmetricDifference"
119 }
120 crate::native_builtins::BuiltinCall::SetIsSubsetOf => "isSubsetOf",
121 crate::native_builtins::BuiltinCall::SetIsSupersetOf => "isSupersetOf",
122 crate::native_builtins::BuiltinCall::SetIsDisjointFrom => "isDisjointFrom",
123 _ => unreachable!(),
124 };
125 return self.compile_error_expr(
126 ce.span,
127 format!(
128 "Set.prototype.{}() is not supported (ES2025 Set operation)",
129 method_name
130 ),
131 );
132 }
133
134 let (module, method, return_type) = builtin_call_to_ir(&builtin);
135
136 if matches!(builtin, crate::native_builtins::BuiltinCall::JsonParse)
139 && let Some(ctx) = self.fn_ctx.as_mut()
140 {
141 ctx.has_catchable_error = true;
142 }
143 let obj_name = Self::extract_callee_object_name_static(&ce.callee);
144
145 let (module, method, return_type) = if let Some(name) = &obj_name {
149 if let Some(var_type) = self.type_info.var_types.get(name.as_str()) {
150 if matches!(var_type, ZigType::Str) && module == BuiltinModule::JsArray {
151 match method.as_str() {
152 "at" => (BuiltinModule::JsString, "at".into(), ZigType::Str),
153 "indexOf" => (BuiltinModule::JsString, "indexOf".into(), ZigType::I64),
154 "includes" => {
155 (BuiltinModule::JsString, "includes".into(), ZigType::Bool)
156 }
157 "lastIndexOf" => {
158 (BuiltinModule::JsString, "lastIndexOf".into(), ZigType::I64)
159 }
160 "slice" => (BuiltinModule::JsString, "slice".into(), ZigType::Str),
161 _ => (module, method, return_type),
162 }
163 } else if let ZigType::NamedStruct(n) = var_type {
164 if Self::is_typedarray_type(n) {
165 let ta_mod = BuiltinModule::JsTypedArray;
166 match method.as_str() {
167 "set" => (ta_mod, "set".into(), ZigType::Void),
168 "get" => (ta_mod, "get".into(), ZigType::I64),
169 "fill" => (ta_mod, "fill".into(), ZigType::Void),
170 "slice" => {
171 (ta_mod, "slice".into(), ZigType::NamedStruct(n.clone()))
172 }
173 "copyWithin" => (ta_mod, "copyWithin".into(), ZigType::Void),
174 _ => (module, method, return_type),
175 }
176 } else {
177 (module, method, return_type)
178 }
179 } else {
180 (module, method, return_type)
181 }
182 } else {
183 (module, method, return_type)
184 }
185 } else {
186 (module, method, return_type)
187 };
188
189 let regex_info = Self::extract_regex_info(ce, &builtin);
191
192 let ta_type_suffix = if module == BuiltinModule::JsTypedArray {
194 obj_name.as_ref().and_then(|name| {
195 self.type_info.var_types.get(name.as_str()).and_then(|zt| {
196 if let ZigType::NamedStruct(n) = zt {
197 Self::typedarray_type_suffix(n).map(|s| s.to_string())
198 } else {
199 None
200 }
201 })
202 })
203 } else {
204 None
205 };
206
207 let method = if module == BuiltinModule::JsObject
212 && (method == "keys" || method == "getOwnPropertyNames")
213 {
214 if let Some(IrExpr::Ident(ident)) = args.first() {
215 if let Some(var_type) = self.type_info.var_types.get(ident.zig_name.as_str()) {
216 if matches!(var_type, ZigType::Struct(_)) {
217 if method == "keys" {
218 "keysStruct".into()
219 } else {
220 "getOwnPropertyNamesStruct".into()
221 }
222 } else {
223 method
224 }
225 } else {
226 method
227 }
228 } else {
229 method
230 }
231 } else {
232 method
233 };
234
235 let mut inner_expr = if obj_name.is_none() {
240 if let Expression::StaticMemberExpression(sme) = &ce.callee {
241 match &sme.object {
242 Expression::CallExpression(_) | Expression::NewExpression(_) => {
245 Some(self.lower_expr(&sme.object))
246 }
247 _ => None,
248 }
249 } else {
250 None
251 }
252 } else {
253 None
254 };
255
256 if let Some(inner) = inner_expr.take() {
263 let chain_elem_type = match &inner {
264 IrExpr::ArrayCallbackInline(cb) => Some(cb.elem_type.clone()),
265 IrExpr::ArrayMethodInline(mm) => Some(mm.elem_type.clone()),
266 _ => None,
267 };
268
269 if let Some(elem_type) = chain_elem_type {
270 if let Some(inlined) =
272 self.try_inline_array_callback_with_chain(ce, &builtin, &elem_type, &inner)
273 {
274 return inlined;
275 }
276
277 if let Some(inlined) = self
279 .try_inline_array_method_with_chain(ce, &builtin, &args, &elem_type, &inner)
280 {
281 return inlined;
282 }
283
284 inner_expr = Some(inner);
286 } else {
287 inner_expr = Some(inner);
288 }
289 }
290
291 let obj_expr = inner_expr.map(Box::new);
292
293 return IrExpr::BuiltinCall(crate::zigir::types::IrBuiltinCall {
294 module,
295 method,
296 obj_name,
297 obj_expr,
298 args,
299 return_type,
300 regex_info,
301 ta_type_suffix,
302 });
303 }
304
305 if let Expression::StaticMemberExpression(sme) = &ce.callee
310 && let Expression::Identifier(id) = &sme.object
311 {
312 let var_name = id.name.as_str();
313 let var_type = self.type_info.var_types.get(var_name).cloned().or_else(|| {
314 self.fn_ctx
315 .as_ref()
316 .and_then(|ctx| ctx.fn_local_types.get(var_name).cloned())
317 });
318 if let Some(ZigType::BigInt) = var_type {
319 let method = sme.property.name.as_str();
320 match method {
321 "toString" => {
322 return IrExpr::BuiltinCall(crate::zigir::types::IrBuiltinCall {
323 module: BuiltinModule::JsBigInt,
324 method: "toString".into(),
325 obj_name: Some(var_name.to_string()),
326 obj_expr: None,
327 args,
328 return_type: ZigType::Str,
329 regex_info: None,
330 ta_type_suffix: None,
331 });
332 }
333 "valueOf" => {
334 return IrExpr::BuiltinCall(crate::zigir::types::IrBuiltinCall {
335 module: BuiltinModule::JsBigInt,
336 method: "valueOf".into(),
337 obj_name: Some(var_name.to_string()),
338 obj_expr: None,
339 args,
340 return_type: ZigType::BigInt,
341 regex_info: None,
342 ta_type_suffix: None,
343 });
344 }
345 "toLocaleString" => {
346 return IrExpr::BuiltinCall(crate::zigir::types::IrBuiltinCall {
347 module: BuiltinModule::JsBigInt,
348 method: "toLocaleString".into(),
349 obj_name: Some(var_name.to_string()),
350 obj_expr: None,
351 args,
352 return_type: ZigType::Str,
353 regex_info: None,
354 ta_type_suffix: None,
355 });
356 }
357 _ => {} }
359 }
360 }
361
362 if let Expression::StaticMemberExpression(sme) = &ce.callee
367 && let Expression::Identifier(id) = &sme.object
368 {
369 let var_name = id.name.as_str();
370 if let Some(ctx) = &self.fn_ctx
371 && ctx.regexp_vars.contains(var_name)
372 {
373 let method = sme.property.name.as_str();
374 match method {
375 "test" => {
376 return IrExpr::BuiltinCall(crate::zigir::types::IrBuiltinCall {
377 module: BuiltinModule::JsRegExp,
378 method: "test".into(),
379 obj_name: Some(var_name.to_string()),
380 obj_expr: None,
381 args,
382 return_type: ZigType::Bool,
383 regex_info: Some(crate::zigir::types::IrRegexInfo {
384 pattern: None,
385 has_global: false,
386 is_var_ref: true,
387 var_name: Some(var_name.to_string()),
388 }),
389 ta_type_suffix: None,
390 });
391 }
392 "exec" => {
393 return IrExpr::BuiltinCall(crate::zigir::types::IrBuiltinCall {
394 module: BuiltinModule::JsRegExp,
395 method: "exec".into(),
396 obj_name: Some(var_name.to_string()),
397 obj_expr: None,
398 args,
399 return_type: ZigType::JsAny,
400 regex_info: Some(crate::zigir::types::IrRegexInfo {
401 pattern: None,
402 has_global: false,
403 is_var_ref: true,
404 var_name: Some(var_name.to_string()),
405 }),
406 ta_type_suffix: None,
407 });
408 }
409 _ => {} }
411 }
412 }
413
414 match &ce.callee {
416 Expression::Identifier(id) => {
418 let name = id.name.as_str();
419
420 if let Some(host_name) = name.strip_prefix("host_") {
422 let is_async = self.async_host_fns.contains(name);
423 let return_type = self.infer_host_return_type(host_name);
424 return IrExpr::HostCall(crate::zigir::types::IrHostCall {
425 name: host_name.to_string(),
426 args,
427 return_type,
428 is_async,
429 });
430 }
431
432 if self
434 .closure_mgr
435 .current_captured
436 .iter()
437 .any(|(n, _, _)| n.as_str() == name)
438 || self.is_closure_instance(name)
439 {
440 return IrExpr::Call(crate::zigir::types::IrCallExpr {
441 callee: Box::new(IrExpr::Ident(IrIdent::new(name))),
442 args,
443 call_kind: CallKind::Closure,
444 });
445 }
446
447 if let Some(ctx) = &self.fn_ctx
449 && ctx.is_nested_fn(name)
450 {
451 let callee_ident = self.make_ident(name);
452 return IrExpr::Call(crate::zigir::types::IrCallExpr {
453 callee: Box::new(IrExpr::Ident(callee_ident)),
454 args,
455 call_kind: CallKind::Closure,
456 });
457 }
458
459 let args = self.pack_rest_args_if_needed(name, args);
461 IrExpr::Call(crate::zigir::types::IrCallExpr {
462 callee: Box::new(IrExpr::Ident(IrIdent::new(name))),
463 args,
464 call_kind: CallKind::Direct,
465 })
466 }
467
468 Expression::StaticMemberExpression(mem) => {
470 let method_name = mem.property.name.as_str();
471 let obj_expr = self.lower_expr(&mem.object);
472
473 let object_type = self.infer_method_object_kind(&mem.object);
475
476 IrExpr::Call(crate::zigir::types::IrCallExpr {
477 callee: Box::new(IrExpr::FieldAccess {
478 object: Box::new(obj_expr),
479 field: method_name.to_string(),
480 field_kind: FieldKind::StructField,
481 }),
482 args,
483 call_kind: CallKind::Method { object_type },
484 })
485 }
486
487 Expression::FunctionExpression(_) | Expression::ArrowFunctionExpression(_) => {
489 let callee = self.lower_expr(&ce.callee);
491 IrExpr::Call(crate::zigir::types::IrCallExpr {
492 callee: Box::new(callee),
493 args,
494 call_kind: CallKind::Closure,
495 })
496 }
497
498 Expression::ParenthesizedExpression(_) => {
500 let callee = self.lower_expr(&ce.callee);
501 IrExpr::Call(crate::zigir::types::IrCallExpr {
502 callee: Box::new(callee),
503 args,
504 call_kind: CallKind::Closure,
505 })
506 }
507
508 _ => {
510 let callee = self.lower_expr(&ce.callee);
511 IrExpr::Call(crate::zigir::types::IrCallExpr {
512 callee: Box::new(callee),
513 args,
514 call_kind: CallKind::Direct,
515 })
516 }
517 }
518 }
519
520 pub(super) fn infer_method_object_kind(
522 &self,
523 obj: &Expression,
524 ) -> crate::zigir::kinds::MethodObjectKind {
525 use crate::zigir::kinds::MethodObjectKind;
526
527 match obj {
528 Expression::Identifier(id) => {
529 if let Some(zig_type) = self.type_info.var_types.get(id.name.as_str()) {
530 match zig_type {
531 ZigType::ArrayList(_) => MethodObjectKind::ArrayList,
532 ZigType::Str => MethodObjectKind::String,
533 ZigType::NamedStruct(name) => match name.as_str() {
534 "Map" => MethodObjectKind::Map,
535 "Set" => MethodObjectKind::Set,
536 "Date" | "JsDate" => MethodObjectKind::Date,
537 other => {
538 if self.class_names.contains(other) {
539 MethodObjectKind::Class(other.to_string())
540 } else {
541 MethodObjectKind::Unknown
542 }
543 }
544 },
545 ZigType::JsAny | ZigType::Anytype => MethodObjectKind::JsAny,
546 _ => MethodObjectKind::Unknown,
547 }
548 } else {
549 MethodObjectKind::Unknown
550 }
551 }
552 _ => MethodObjectKind::Unknown,
553 }
554 }
555
556 pub(super) fn is_closure_instance(&self, name: &str) -> bool {
558 self.closure_mgr.closure_instances.contains(name)
559 }
560
561 pub(super) fn infer_host_return_type(&self, host_name: &str) -> ZigType {
566 let full_name = format!("host_{}", host_name);
568 self.type_info
569 .host_return_types
570 .get(&full_name)
571 .cloned()
572 .unwrap_or(ZigType::JsAny)
573 }
574
575 pub(super) fn lower_await(&mut self, ae: &AwaitExpression) -> crate::zigir::types::IrExpr {
577 let task_var = IrIdent::new(&self.name_mangler.next_name("_t"));
578 let block_label = format!("blk_{}", self.name_mangler.peek_count("_t"));
579
580 if let Expression::CallExpression(call) = &ae.argument {
582 let args: Vec<_> = call
583 .arguments
584 .iter()
585 .filter_map(|a| a.as_expression().map(|e| self.lower_expr(e)))
586 .collect();
587
588 if let Expression::Identifier(id) = &call.callee {
590 let name = id.name.as_str();
591 if self.async_host_fns.contains(name) {
592 return crate::zigir::types::IrExpr::Await(crate::zigir::types::IrAwaitExpr {
593 task_var,
594 callee: Box::new(crate::zigir::types::IrExpr::Ident(IrIdent::new(name))),
595 args,
596 is_host_async: true,
597 block_label,
598 });
599 }
600 }
601
602 let callee = self.lower_expr(&call.callee);
604 return crate::zigir::types::IrExpr::Await(crate::zigir::types::IrAwaitExpr {
605 task_var,
606 callee: Box::new(callee),
607 args,
608 is_host_async: false,
609 block_label,
610 });
611 }
612
613 let argument = self.lower_expr(&ae.argument);
615 crate::zigir::types::IrExpr::Await(crate::zigir::types::IrAwaitExpr {
616 task_var,
617 callee: Box::new(argument),
618 args: vec![],
619 is_host_async: false,
620 block_label,
621 })
622 }
623
624 pub(super) fn lower_new(&mut self, ne: &NewExpression) -> crate::zigir::types::IrExpr {
626 use crate::zigir::kinds::NewConstructor;
627
628 let constructor = match &ne.callee {
630 Expression::Identifier(id) => match id.name.as_str() {
631 "Map" => NewConstructor::Map,
632 "Set" => NewConstructor::Set,
633 "Date" => {
634 let kind = if ne.arguments.is_empty() {
636 crate::zigir::kinds::DateConstructorKind::Now
637 } else if ne.arguments.len() >= 2 {
638 crate::zigir::kinds::DateConstructorKind::FromComponents
639 } else if let Some(first_arg) = ne.arguments.first()
640 && let Some(expr) = first_arg.as_expression()
641 {
642 let is_string = matches!(expr, Expression::StringLiteral(_));
644 if is_string {
645 crate::zigir::kinds::DateConstructorKind::FromString
646 } else {
647 crate::zigir::kinds::DateConstructorKind::FromMillis
648 }
649 } else {
650 crate::zigir::kinds::DateConstructorKind::Now
651 };
652 NewConstructor::Date(kind)
653 }
654 "RegExp" => NewConstructor::RegExp,
655 "Int8Array" | "Uint8Array" | "Uint8ClampedArray" | "Int16Array" | "Uint16Array"
656 | "Int32Array" | "Uint32Array" | "Float32Array" | "Float64Array"
657 | "BigInt64Array" | "BigUint64Array" => {
658 let kind = match id.name.as_str() {
659 "Int8Array" => crate::zigir::kinds::TypedArrayKind::Int8Array,
660 "Uint8Array" => crate::zigir::kinds::TypedArrayKind::Uint8Array,
661 "Uint8ClampedArray" => {
662 crate::zigir::kinds::TypedArrayKind::Uint8ClampedArray
663 }
664 "Int16Array" => crate::zigir::kinds::TypedArrayKind::Int16Array,
665 "Uint16Array" => crate::zigir::kinds::TypedArrayKind::Uint16Array,
666 "Int32Array" => crate::zigir::kinds::TypedArrayKind::Int32Array,
667 "Uint32Array" => crate::zigir::kinds::TypedArrayKind::Uint32Array,
668 "Float32Array" => crate::zigir::kinds::TypedArrayKind::Float32Array,
669 "Float64Array" => crate::zigir::kinds::TypedArrayKind::Float64Array,
670 "BigInt64Array" => crate::zigir::kinds::TypedArrayKind::BigInt64Array,
671 "BigUint64Array" => crate::zigir::kinds::TypedArrayKind::BigUint64Array,
672 _ => crate::zigir::kinds::TypedArrayKind::Float64Array,
673 };
674 NewConstructor::TypedArray(kind)
675 }
676 "Error" => NewConstructor::Error("Error".to_string()),
677 "TypeError" => NewConstructor::Error("TypeError".to_string()),
678 "RangeError" => NewConstructor::Error("RangeError".to_string()),
679 "String" => {
681 return if let Some(first_arg) = ne.arguments.first()
682 && let Some(expr) = first_arg.as_expression()
683 {
684 self.lower_expr(expr)
685 } else {
686 crate::zigir::types::IrExpr::StringLiteral("".to_string())
687 };
688 }
689 "Number" => {
690 return if let Some(first_arg) = ne.arguments.first()
691 && let Some(expr) = first_arg.as_expression()
692 {
693 self.lower_expr(expr)
694 } else {
695 crate::zigir::types::IrExpr::IntLiteral(0)
696 };
697 }
698 "Boolean" => {
699 return if let Some(first_arg) = ne.arguments.first()
700 && let Some(expr) = first_arg.as_expression()
701 {
702 self.lower_expr(expr)
703 } else {
704 crate::zigir::types::IrExpr::BoolLiteral(false)
705 };
706 }
707 name if self.class_names.contains(name) => NewConstructor::Class(name.to_string()),
708 "ArrayBuffer" | "SharedArrayBuffer" | "Function" | "Promise" | "WeakMap"
710 | "WeakSet" | "DataView" => {
711 NewConstructor::Unsupported(id.name.as_str().to_string())
712 }
713 other => {
714 let span = oxc_span::GetSpan::span(ne);
715 return self.compile_error_expr(
716 span,
717 format!("Unsupported NewExpression: new {}()", other),
718 );
719 }
720 },
721 Expression::StaticMemberExpression(mem) => {
722 if let Expression::Identifier(id) = &mem.object {
723 let obj_name = id.name.as_str();
724 let method_name = mem.property.name.as_str();
725 match obj_name {
726 "Intl" => {
727 let span = oxc_span::GetSpan::span(ne);
728 return self.compile_error_expr(
729 span,
730 format!(
731 "Intl.{}() is not supported (use Zig/C library for internationalization)",
732 method_name
733 ),
734 );
735 }
736 _ => {
737 let span = oxc_span::GetSpan::span(ne);
738 return self.compile_error_expr(span, "Unsupported NewExpression");
739 }
740 }
741 } else {
742 let span = oxc_span::GetSpan::span(ne);
743 return self.compile_error_expr(span, "Unsupported NewExpression");
744 }
745 }
746 _ => {
747 let span = oxc_span::GetSpan::span(ne);
748 return self.compile_error_expr(span, "Unsupported NewExpression");
749 }
750 };
751
752 let args = self.lower_args(&ne.arguments);
753
754 let result_type = match &constructor {
755 NewConstructor::Map => ZigType::NamedStruct("Map".to_string()),
756 NewConstructor::Set => ZigType::NamedStruct("Set".to_string()),
757 NewConstructor::Date(_) => ZigType::NamedStruct("JsDate".to_string()),
758 NewConstructor::RegExp => ZigType::JsAny,
759 NewConstructor::TypedArray(_) => ZigType::NamedStruct("TypedArray".to_string()),
760 NewConstructor::Class(name) => ZigType::NamedStruct(name.clone()),
761 NewConstructor::Error(_) => ZigType::JsAny,
762 _ => ZigType::JsAny,
763 };
764
765 crate::zigir::types::IrExpr::New(crate::zigir::types::IrNewExpr {
766 constructor,
767 args,
768 result_type,
769 })
770 }
771
772 fn pack_rest_args_if_needed(
782 &self,
783 callee_name: &str,
784 args: Vec<crate::zigir::types::IrExpr>,
785 ) -> Vec<crate::zigir::types::IrExpr> {
786 use crate::zigir::types::{IrArrayLiteral, IrCallExpr, IrExpr};
787
788 if !self
789 .type_info
790 .functions_needing_synthetic_rest
791 .contains(callee_name)
792 {
793 return args;
794 }
795
796 let is_async = self
798 .type_info
799 .is_async
800 .get(callee_name)
801 .copied()
802 .unwrap_or(false);
803 let declared_count = self
804 .type_info
805 .fn_param_types
806 .get(callee_name)
807 .map(|params| params.len())
808 .unwrap_or(0)
809 + if is_async { 1 } else { 0 };
810
811 if args.len() <= declared_count {
812 let mut result = args;
814 result.push(IrExpr::Spread(Box::new(IrExpr::ArrayLiteral(
815 IrArrayLiteral {
816 elements: vec![],
817 spread_indices: vec![],
818 },
819 ))));
820 return result;
821 }
822
823 let mut regular_args = args;
825 let rest_args = regular_args.split_off(declared_count);
826
827 if rest_args.len() == 1 && matches!(rest_args[0], IrExpr::Spread(_)) {
829 regular_args.extend(rest_args);
830 return regular_args;
831 }
832
833 let rest_elements: Vec<IrExpr> = rest_args
835 .into_iter()
836 .map(|arg| {
837 IrExpr::Call(IrCallExpr {
838 callee: Box::new(IrExpr::FieldAccess {
839 object: Box::new(IrExpr::Ident(IrIdent::new("JsAny"))),
840 field: "from".to_string(),
841 field_kind: FieldKind::StructField,
842 }),
843 args: vec![arg],
844 call_kind: CallKind::Direct,
845 })
846 })
847 .collect();
848
849 regular_args.push(IrExpr::Spread(Box::new(IrExpr::ArrayLiteral(
850 IrArrayLiteral {
851 elements: rest_elements,
852 spread_indices: vec![],
853 },
854 ))));
855 regular_args
856 }
857}