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