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 _ => None,
43 }
44 } else {
45 None
46 }
47 }
48 Expression::Identifier(id) => match id.name.as_str() {
49 name @ "Atomics" | name @ "Reflect" => {
50 Some(format!("{} is not supported in js2zig", name))
51 }
52 _ => None,
53 },
54 _ => None,
55 }
56 }
57
58 pub(super) fn lower_call(&mut self, ce: &CallExpression) -> crate::zigir::types::IrExpr {
68 use crate::zigir::types::IrExpr;
69
70 if let Some(err_msg) = self.check_unsupported_call(ce) {
72 return self.compile_error_expr(ce.span, err_msg);
73 }
74
75 let args = self.lower_args(&ce.arguments);
76
77 if let Some(builtin) = crate::native_builtins::detect_builtin_call(ce) {
79 if let Some(inlined) = self.try_inline_array_callback(ce, &builtin) {
81 return inlined;
82 }
83
84 if let Some(inlined) = self.try_inline_array_method(ce, &builtin, &args) {
86 return inlined;
87 }
88
89 if matches!(builtin, crate::native_builtins::BuiltinCall::Eval) {
91 return self.compile_error_expr(ce.span, "eval() is not supported (security risk, cannot dynamically execute at compile time)");
92 }
93
94 let (module, method, return_type) = builtin_call_to_ir(&builtin);
95 let obj_name = Self::extract_callee_object_name_static(&ce.callee);
96
97 let (module, method, return_type) = if let Some(name) = &obj_name {
101 if let Some(var_type) = self.type_info.var_types.get(name.as_str()) {
102 if matches!(var_type, ZigType::Str) && module == BuiltinModule::JsArray {
103 match method.as_str() {
104 "at" => (BuiltinModule::JsString, "at".into(), ZigType::Str),
105 "indexOf" => (BuiltinModule::JsString, "indexOf".into(), ZigType::I64),
106 "includes" => {
107 (BuiltinModule::JsString, "includes".into(), ZigType::Bool)
108 }
109 "lastIndexOf" => {
110 (BuiltinModule::JsString, "lastIndexOf".into(), ZigType::I64)
111 }
112 "slice" => (BuiltinModule::JsString, "slice".into(), ZigType::Str),
113 _ => (module, method, return_type),
114 }
115 } else if let ZigType::NamedStruct(n) = var_type {
116 if Self::is_typedarray_type(n) {
117 let ta_mod = BuiltinModule::JsTypedArray;
118 match method.as_str() {
119 "set" => (ta_mod, "set".into(), ZigType::Void),
120 "get" => (ta_mod, "get".into(), ZigType::I64),
121 "fill" => (ta_mod, "fill".into(), ZigType::Void),
122 "slice" => {
123 (ta_mod, "slice".into(), ZigType::NamedStruct(n.clone()))
124 }
125 "copyWithin" => (ta_mod, "copyWithin".into(), ZigType::Void),
126 _ => (module, method, return_type),
127 }
128 } else {
129 (module, method, return_type)
130 }
131 } else {
132 (module, method, return_type)
133 }
134 } else {
135 (module, method, return_type)
136 }
137 } else {
138 (module, method, return_type)
139 };
140
141 let regex_info = Self::extract_regex_info(ce, &builtin);
143
144 let ta_type_suffix = if module == BuiltinModule::JsTypedArray {
146 obj_name.as_ref().and_then(|name| {
147 self.type_info.var_types.get(name.as_str()).and_then(|zt| {
148 if let ZigType::NamedStruct(n) = zt {
149 Self::typedarray_type_suffix(n).map(|s| s.to_string())
150 } else {
151 None
152 }
153 })
154 })
155 } else {
156 None
157 };
158
159 let method = if module == BuiltinModule::JsObject
164 && (method == "keys" || method == "getOwnPropertyNames")
165 {
166 if let Some(IrExpr::Ident(ident)) = args.first() {
167 if let Some(var_type) = self.type_info.var_types.get(ident.zig_name.as_str()) {
168 if matches!(var_type, ZigType::Struct(_)) {
169 if method == "keys" {
170 "keysStruct".into()
171 } else {
172 "getOwnPropertyNamesStruct".into()
173 }
174 } else {
175 method
176 }
177 } else {
178 method
179 }
180 } else {
181 method
182 }
183 } else {
184 method
185 };
186
187 let mut inner_expr = if obj_name.is_none() {
192 if let Expression::StaticMemberExpression(sme) = &ce.callee {
193 match &sme.object {
194 Expression::CallExpression(_) | Expression::NewExpression(_) => {
197 Some(self.lower_expr(&sme.object))
198 }
199 _ => None,
200 }
201 } else {
202 None
203 }
204 } else {
205 None
206 };
207
208 if let Some(inner) = inner_expr.take() {
215 let chain_elem_type = match &inner {
216 IrExpr::ArrayCallbackInline(cb) => Some(cb.elem_type.clone()),
217 IrExpr::ArrayMethodInline(mm) => Some(mm.elem_type.clone()),
218 _ => None,
219 };
220
221 if let Some(elem_type) = chain_elem_type {
222 if let Some(inlined) =
224 self.try_inline_array_callback_with_chain(ce, &builtin, &elem_type, &inner)
225 {
226 return inlined;
227 }
228
229 if let Some(inlined) = self
231 .try_inline_array_method_with_chain(ce, &builtin, &args, &elem_type, &inner)
232 {
233 return inlined;
234 }
235
236 inner_expr = Some(inner);
238 } else {
239 inner_expr = Some(inner);
240 }
241 }
242
243 let obj_expr = inner_expr.map(Box::new);
244
245 return IrExpr::BuiltinCall(crate::zigir::types::IrBuiltinCall {
246 module,
247 method,
248 obj_name,
249 obj_expr,
250 args,
251 return_type,
252 regex_info,
253 ta_type_suffix,
254 });
255 }
256
257 if let Expression::StaticMemberExpression(sme) = &ce.callee
262 && let Expression::Identifier(id) = &sme.object
263 {
264 let var_name = id.name.as_str();
265 let var_type = self.type_info.var_types.get(var_name).cloned().or_else(|| {
266 self.fn_ctx
267 .as_ref()
268 .and_then(|ctx| ctx.fn_local_types.get(var_name).cloned())
269 });
270 if let Some(ZigType::BigInt) = var_type {
271 let method = sme.property.name.as_str();
272 match method {
273 "toString" => {
274 return IrExpr::BuiltinCall(crate::zigir::types::IrBuiltinCall {
275 module: BuiltinModule::JsBigInt,
276 method: "toString".into(),
277 obj_name: Some(var_name.to_string()),
278 obj_expr: None,
279 args,
280 return_type: ZigType::Str,
281 regex_info: None,
282 ta_type_suffix: None,
283 });
284 }
285 "valueOf" => {
286 return IrExpr::BuiltinCall(crate::zigir::types::IrBuiltinCall {
287 module: BuiltinModule::JsBigInt,
288 method: "valueOf".into(),
289 obj_name: Some(var_name.to_string()),
290 obj_expr: None,
291 args,
292 return_type: ZigType::BigInt,
293 regex_info: None,
294 ta_type_suffix: None,
295 });
296 }
297 "toLocaleString" => {
298 return IrExpr::BuiltinCall(crate::zigir::types::IrBuiltinCall {
299 module: BuiltinModule::JsBigInt,
300 method: "toLocaleString".into(),
301 obj_name: Some(var_name.to_string()),
302 obj_expr: None,
303 args,
304 return_type: ZigType::Str,
305 regex_info: None,
306 ta_type_suffix: None,
307 });
308 }
309 _ => {} }
311 }
312 }
313
314 if let Expression::StaticMemberExpression(sme) = &ce.callee
319 && let Expression::Identifier(id) = &sme.object
320 {
321 let var_name = id.name.as_str();
322 if let Some(ctx) = &self.fn_ctx
323 && ctx.regexp_vars.contains(var_name)
324 {
325 let method = sme.property.name.as_str();
326 match method {
327 "test" => {
328 return IrExpr::BuiltinCall(crate::zigir::types::IrBuiltinCall {
329 module: BuiltinModule::JsRegExp,
330 method: "test".into(),
331 obj_name: Some(var_name.to_string()),
332 obj_expr: None,
333 args,
334 return_type: ZigType::Bool,
335 regex_info: Some(crate::zigir::types::IrRegexInfo {
336 pattern: None,
337 has_global: false,
338 is_var_ref: true,
339 var_name: Some(var_name.to_string()),
340 }),
341 ta_type_suffix: None,
342 });
343 }
344 "exec" => {
345 return IrExpr::BuiltinCall(crate::zigir::types::IrBuiltinCall {
346 module: BuiltinModule::JsRegExp,
347 method: "exec".into(),
348 obj_name: Some(var_name.to_string()),
349 obj_expr: None,
350 args,
351 return_type: ZigType::JsAny,
352 regex_info: Some(crate::zigir::types::IrRegexInfo {
353 pattern: None,
354 has_global: false,
355 is_var_ref: true,
356 var_name: Some(var_name.to_string()),
357 }),
358 ta_type_suffix: None,
359 });
360 }
361 _ => {} }
363 }
364 }
365
366 match &ce.callee {
368 Expression::Identifier(id) => {
370 let name = id.name.as_str();
371
372 if let Some(host_name) = name.strip_prefix("host_") {
374 let is_async = self.async_host_fns.contains(name);
375 let return_type = self.infer_host_return_type(host_name);
376 return IrExpr::HostCall(crate::zigir::types::IrHostCall {
377 name: host_name.to_string(),
378 args,
379 return_type,
380 is_async,
381 });
382 }
383
384 if self
386 .closure_mgr
387 .current_captured
388 .iter()
389 .any(|(n, _, _)| n.as_str() == name)
390 || self.is_closure_instance(name)
391 {
392 return IrExpr::Call(crate::zigir::types::IrCallExpr {
393 callee: Box::new(IrExpr::Ident(IrIdent::new(name))),
394 args,
395 call_kind: CallKind::Closure,
396 });
397 }
398
399 if let Some(ctx) = &self.fn_ctx
401 && ctx.is_nested_fn(name)
402 {
403 let callee_ident = self.make_ident(name);
404 return IrExpr::Call(crate::zigir::types::IrCallExpr {
405 callee: Box::new(IrExpr::Ident(callee_ident)),
406 args,
407 call_kind: CallKind::Closure,
408 });
409 }
410
411 IrExpr::Call(crate::zigir::types::IrCallExpr {
413 callee: Box::new(IrExpr::Ident(IrIdent::new(name))),
414 args,
415 call_kind: CallKind::Direct,
416 })
417 }
418
419 Expression::StaticMemberExpression(mem) => {
421 let method_name = mem.property.name.as_str();
422 let obj_expr = self.lower_expr(&mem.object);
423
424 let object_type = self.infer_method_object_kind(&mem.object);
426
427 IrExpr::Call(crate::zigir::types::IrCallExpr {
428 callee: Box::new(IrExpr::FieldAccess {
429 object: Box::new(obj_expr),
430 field: method_name.to_string(),
431 field_kind: FieldKind::StructField,
432 }),
433 args,
434 call_kind: CallKind::Method { object_type },
435 })
436 }
437
438 Expression::FunctionExpression(_) | Expression::ArrowFunctionExpression(_) => {
440 let callee = self.lower_expr(&ce.callee);
442 IrExpr::Call(crate::zigir::types::IrCallExpr {
443 callee: Box::new(callee),
444 args,
445 call_kind: CallKind::Closure,
446 })
447 }
448
449 Expression::ParenthesizedExpression(_) => {
451 let callee = self.lower_expr(&ce.callee);
452 IrExpr::Call(crate::zigir::types::IrCallExpr {
453 callee: Box::new(callee),
454 args,
455 call_kind: CallKind::Closure,
456 })
457 }
458
459 _ => {
461 let callee = self.lower_expr(&ce.callee);
462 IrExpr::Call(crate::zigir::types::IrCallExpr {
463 callee: Box::new(callee),
464 args,
465 call_kind: CallKind::Direct,
466 })
467 }
468 }
469 }
470
471 pub(super) fn infer_method_object_kind(
473 &self,
474 obj: &Expression,
475 ) -> crate::zigir::kinds::MethodObjectKind {
476 use crate::zigir::kinds::MethodObjectKind;
477
478 match obj {
479 Expression::Identifier(id) => {
480 if let Some(zig_type) = self.type_info.var_types.get(id.name.as_str()) {
481 match zig_type {
482 ZigType::ArrayList(_) => MethodObjectKind::ArrayList,
483 ZigType::Str => MethodObjectKind::String,
484 ZigType::NamedStruct(name) => match name.as_str() {
485 "Map" => MethodObjectKind::Map,
486 "Set" => MethodObjectKind::Set,
487 "Date" | "JsDate" => MethodObjectKind::Date,
488 other => {
489 if self.class_names.contains(other) {
490 MethodObjectKind::Class(other.to_string())
491 } else {
492 MethodObjectKind::Unknown
493 }
494 }
495 },
496 ZigType::JsAny | ZigType::Anytype => MethodObjectKind::JsAny,
497 _ => MethodObjectKind::Unknown,
498 }
499 } else {
500 MethodObjectKind::Unknown
501 }
502 }
503 _ => MethodObjectKind::Unknown,
504 }
505 }
506
507 pub(super) fn is_closure_instance(&self, name: &str) -> bool {
509 self.closure_mgr.closure_instances.contains(name)
510 }
511
512 pub(super) fn infer_host_return_type(&self, host_name: &str) -> ZigType {
517 let full_name = format!("host_{}", host_name);
519 self.type_info
520 .host_return_types
521 .get(&full_name)
522 .cloned()
523 .unwrap_or(ZigType::JsAny)
524 }
525
526 pub(super) fn lower_await(&mut self, ae: &AwaitExpression) -> crate::zigir::types::IrExpr {
528 let task_var = IrIdent::new(&self.name_mangler.next_name("_t"));
529 let block_label = format!("blk_{}", self.name_mangler.peek_count("_t"));
530
531 if let Expression::CallExpression(call) = &ae.argument {
533 let args: Vec<_> = call
534 .arguments
535 .iter()
536 .filter_map(|a| a.as_expression().map(|e| self.lower_expr(e)))
537 .collect();
538
539 if let Expression::Identifier(id) = &call.callee {
541 let name = id.name.as_str();
542 if self.async_host_fns.contains(name) {
543 return crate::zigir::types::IrExpr::Await(crate::zigir::types::IrAwaitExpr {
544 task_var,
545 callee: Box::new(crate::zigir::types::IrExpr::Ident(IrIdent::new(name))),
546 args,
547 is_host_async: true,
548 block_label,
549 });
550 }
551 }
552
553 let callee = self.lower_expr(&call.callee);
555 return crate::zigir::types::IrExpr::Await(crate::zigir::types::IrAwaitExpr {
556 task_var,
557 callee: Box::new(callee),
558 args,
559 is_host_async: false,
560 block_label,
561 });
562 }
563
564 let argument = self.lower_expr(&ae.argument);
566 crate::zigir::types::IrExpr::Await(crate::zigir::types::IrAwaitExpr {
567 task_var,
568 callee: Box::new(argument),
569 args: vec![],
570 is_host_async: false,
571 block_label,
572 })
573 }
574
575 pub(super) fn lower_new(&mut self, ne: &NewExpression) -> crate::zigir::types::IrExpr {
577 use crate::zigir::kinds::NewConstructor;
578
579 let constructor = match &ne.callee {
581 Expression::Identifier(id) => match id.name.as_str() {
582 "Map" => NewConstructor::Map,
583 "Set" => NewConstructor::Set,
584 "Date" => {
585 let kind = if ne.arguments.is_empty() {
587 crate::zigir::kinds::DateConstructorKind::Now
588 } else if ne.arguments.len() >= 2 {
589 crate::zigir::kinds::DateConstructorKind::FromComponents
590 } else if let Some(first_arg) = ne.arguments.first()
591 && let Some(expr) = first_arg.as_expression()
592 {
593 let is_string = matches!(expr, Expression::StringLiteral(_));
595 if is_string {
596 crate::zigir::kinds::DateConstructorKind::FromString
597 } else {
598 crate::zigir::kinds::DateConstructorKind::FromMillis
599 }
600 } else {
601 crate::zigir::kinds::DateConstructorKind::Now
602 };
603 NewConstructor::Date(kind)
604 }
605 "RegExp" => NewConstructor::RegExp,
606 "Int8Array" | "Uint8Array" | "Uint8ClampedArray" | "Int16Array" | "Uint16Array"
607 | "Int32Array" | "Uint32Array" | "Float32Array" | "Float64Array"
608 | "BigInt64Array" | "BigUint64Array" => {
609 let kind = match id.name.as_str() {
610 "Int8Array" => crate::zigir::kinds::TypedArrayKind::Int8Array,
611 "Uint8Array" => crate::zigir::kinds::TypedArrayKind::Uint8Array,
612 "Uint8ClampedArray" => {
613 crate::zigir::kinds::TypedArrayKind::Uint8ClampedArray
614 }
615 "Int16Array" => crate::zigir::kinds::TypedArrayKind::Int16Array,
616 "Uint16Array" => crate::zigir::kinds::TypedArrayKind::Uint16Array,
617 "Int32Array" => crate::zigir::kinds::TypedArrayKind::Int32Array,
618 "Uint32Array" => crate::zigir::kinds::TypedArrayKind::Uint32Array,
619 "Float32Array" => crate::zigir::kinds::TypedArrayKind::Float32Array,
620 "Float64Array" => crate::zigir::kinds::TypedArrayKind::Float64Array,
621 "BigInt64Array" => crate::zigir::kinds::TypedArrayKind::BigInt64Array,
622 "BigUint64Array" => crate::zigir::kinds::TypedArrayKind::BigUint64Array,
623 _ => crate::zigir::kinds::TypedArrayKind::Float64Array,
624 };
625 NewConstructor::TypedArray(kind)
626 }
627 "Error" => NewConstructor::Error("Error".to_string()),
628 "TypeError" => NewConstructor::Error("TypeError".to_string()),
629 "RangeError" => NewConstructor::Error("RangeError".to_string()),
630 "String" => {
632 return if let Some(first_arg) = ne.arguments.first()
633 && let Some(expr) = first_arg.as_expression()
634 {
635 self.lower_expr(expr)
636 } else {
637 crate::zigir::types::IrExpr::StringLiteral("".to_string())
638 };
639 }
640 "Number" => {
641 return if let Some(first_arg) = ne.arguments.first()
642 && let Some(expr) = first_arg.as_expression()
643 {
644 self.lower_expr(expr)
645 } else {
646 crate::zigir::types::IrExpr::IntLiteral(0)
647 };
648 }
649 "Boolean" => {
650 return if let Some(first_arg) = ne.arguments.first()
651 && let Some(expr) = first_arg.as_expression()
652 {
653 self.lower_expr(expr)
654 } else {
655 crate::zigir::types::IrExpr::BoolLiteral(false)
656 };
657 }
658 name if self.class_names.contains(name) => NewConstructor::Class(name.to_string()),
659 "ArrayBuffer" | "SharedArrayBuffer" | "Function" | "Promise" | "WeakMap"
661 | "WeakSet" | "DataView" => {
662 NewConstructor::Unsupported(id.name.as_str().to_string())
663 }
664 other => {
665 let span = oxc_span::GetSpan::span(ne);
666 return self.compile_error_expr(
667 span,
668 format!("Unsupported NewExpression: new {}()", other),
669 );
670 }
671 },
672 _ => {
673 let span = oxc_span::GetSpan::span(ne);
674 return self.compile_error_expr(span, "Unsupported NewExpression");
675 }
676 };
677
678 let args = self.lower_args(&ne.arguments);
679
680 let result_type = match &constructor {
681 NewConstructor::Map => ZigType::NamedStruct("Map".to_string()),
682 NewConstructor::Set => ZigType::NamedStruct("Set".to_string()),
683 NewConstructor::Date(_) => ZigType::NamedStruct("JsDate".to_string()),
684 NewConstructor::RegExp => ZigType::JsAny,
685 NewConstructor::TypedArray(_) => ZigType::NamedStruct("TypedArray".to_string()),
686 NewConstructor::Class(name) => ZigType::NamedStruct(name.clone()),
687 NewConstructor::Error(_) => ZigType::JsAny,
688 _ => ZigType::JsAny,
689 };
690
691 crate::zigir::types::IrExpr::New(crate::zigir::types::IrNewExpr {
692 constructor,
693 args,
694 result_type,
695 })
696 }
697}