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 if let Some(ctx) = &self.fn_ctx
266 && ctx.regexp_vars.contains(var_name)
267 {
268 let method = sme.property.name.as_str();
269 match method {
270 "test" => {
271 return IrExpr::BuiltinCall(crate::zigir::types::IrBuiltinCall {
272 module: BuiltinModule::JsRegExp,
273 method: "test".into(),
274 obj_name: Some(var_name.to_string()),
275 obj_expr: None,
276 args,
277 return_type: ZigType::Bool,
278 regex_info: Some(crate::zigir::types::IrRegexInfo {
279 pattern: None,
280 has_global: false,
281 is_var_ref: true,
282 var_name: Some(var_name.to_string()),
283 }),
284 ta_type_suffix: None,
285 });
286 }
287 "exec" => {
288 return IrExpr::BuiltinCall(crate::zigir::types::IrBuiltinCall {
289 module: BuiltinModule::JsRegExp,
290 method: "exec".into(),
291 obj_name: Some(var_name.to_string()),
292 obj_expr: None,
293 args,
294 return_type: ZigType::JsAny,
295 regex_info: Some(crate::zigir::types::IrRegexInfo {
296 pattern: None,
297 has_global: false,
298 is_var_ref: true,
299 var_name: Some(var_name.to_string()),
300 }),
301 ta_type_suffix: None,
302 });
303 }
304 _ => {} }
306 }
307 }
308
309 match &ce.callee {
311 Expression::Identifier(id) => {
313 let name = id.name.as_str();
314
315 if let Some(host_name) = name.strip_prefix("host_") {
317 let is_async = self.async_host_fns.contains(name);
318 let return_type = self.infer_host_return_type(host_name);
319 return IrExpr::HostCall(crate::zigir::types::IrHostCall {
320 name: host_name.to_string(),
321 args,
322 return_type,
323 is_async,
324 });
325 }
326
327 if self
329 .closure_mgr
330 .current_captured
331 .iter()
332 .any(|(n, _, _)| n.as_str() == name)
333 || self.is_closure_instance(name)
334 {
335 return IrExpr::Call(crate::zigir::types::IrCallExpr {
336 callee: Box::new(IrExpr::Ident(IrIdent::new(name))),
337 args,
338 call_kind: CallKind::Closure,
339 });
340 }
341
342 if let Some(ctx) = &self.fn_ctx
344 && ctx.is_nested_fn(name)
345 {
346 let callee_ident = self.make_ident(name);
347 return IrExpr::Call(crate::zigir::types::IrCallExpr {
348 callee: Box::new(IrExpr::Ident(callee_ident)),
349 args,
350 call_kind: CallKind::Closure,
351 });
352 }
353
354 IrExpr::Call(crate::zigir::types::IrCallExpr {
356 callee: Box::new(IrExpr::Ident(IrIdent::new(name))),
357 args,
358 call_kind: CallKind::Direct,
359 })
360 }
361
362 Expression::StaticMemberExpression(mem) => {
364 let method_name = mem.property.name.as_str();
365 let obj_expr = self.lower_expr(&mem.object);
366
367 let object_type = self.infer_method_object_kind(&mem.object);
369
370 IrExpr::Call(crate::zigir::types::IrCallExpr {
371 callee: Box::new(IrExpr::FieldAccess {
372 object: Box::new(obj_expr),
373 field: method_name.to_string(),
374 field_kind: FieldKind::StructField,
375 }),
376 args,
377 call_kind: CallKind::Method { object_type },
378 })
379 }
380
381 Expression::FunctionExpression(_) | Expression::ArrowFunctionExpression(_) => {
383 let callee = self.lower_expr(&ce.callee);
385 IrExpr::Call(crate::zigir::types::IrCallExpr {
386 callee: Box::new(callee),
387 args,
388 call_kind: CallKind::Closure,
389 })
390 }
391
392 Expression::ParenthesizedExpression(_) => {
394 let callee = self.lower_expr(&ce.callee);
395 IrExpr::Call(crate::zigir::types::IrCallExpr {
396 callee: Box::new(callee),
397 args,
398 call_kind: CallKind::Closure,
399 })
400 }
401
402 _ => {
404 let callee = self.lower_expr(&ce.callee);
405 IrExpr::Call(crate::zigir::types::IrCallExpr {
406 callee: Box::new(callee),
407 args,
408 call_kind: CallKind::Direct,
409 })
410 }
411 }
412 }
413
414 pub(super) fn infer_method_object_kind(
416 &self,
417 obj: &Expression,
418 ) -> crate::zigir::kinds::MethodObjectKind {
419 use crate::zigir::kinds::MethodObjectKind;
420
421 match obj {
422 Expression::Identifier(id) => {
423 if let Some(zig_type) = self.type_info.var_types.get(id.name.as_str()) {
424 match zig_type {
425 ZigType::ArrayList(_) => MethodObjectKind::ArrayList,
426 ZigType::Str => MethodObjectKind::String,
427 ZigType::NamedStruct(name) => match name.as_str() {
428 "Map" => MethodObjectKind::Map,
429 "Set" => MethodObjectKind::Set,
430 "Date" | "JsDate" => MethodObjectKind::Date,
431 other => {
432 if self.class_names.contains(other) {
433 MethodObjectKind::Class(other.to_string())
434 } else {
435 MethodObjectKind::Unknown
436 }
437 }
438 },
439 ZigType::JsAny | ZigType::Anytype => MethodObjectKind::JsAny,
440 _ => MethodObjectKind::Unknown,
441 }
442 } else {
443 MethodObjectKind::Unknown
444 }
445 }
446 _ => MethodObjectKind::Unknown,
447 }
448 }
449
450 pub(super) fn is_closure_instance(&self, name: &str) -> bool {
452 self.closure_mgr.closure_instances.contains(name)
453 }
454
455 pub(super) fn infer_host_return_type(&self, host_name: &str) -> ZigType {
460 let full_name = format!("host_{}", host_name);
462 self.type_info
463 .host_return_types
464 .get(&full_name)
465 .cloned()
466 .unwrap_or(ZigType::JsAny)
467 }
468
469 pub(super) fn lower_await(&mut self, ae: &AwaitExpression) -> crate::zigir::types::IrExpr {
471 let task_var = IrIdent::new(&self.name_mangler.next_name("_t"));
472 let block_label = format!("blk_{}", self.name_mangler.peek_count("_t"));
473
474 if let Expression::CallExpression(call) = &ae.argument {
476 let args: Vec<_> = call
477 .arguments
478 .iter()
479 .filter_map(|a| a.as_expression().map(|e| self.lower_expr(e)))
480 .collect();
481
482 if let Expression::Identifier(id) = &call.callee {
484 let name = id.name.as_str();
485 if self.async_host_fns.contains(name) {
486 return crate::zigir::types::IrExpr::Await(crate::zigir::types::IrAwaitExpr {
487 task_var,
488 callee: Box::new(crate::zigir::types::IrExpr::Ident(IrIdent::new(name))),
489 args,
490 is_host_async: true,
491 block_label,
492 });
493 }
494 }
495
496 let callee = self.lower_expr(&call.callee);
498 return crate::zigir::types::IrExpr::Await(crate::zigir::types::IrAwaitExpr {
499 task_var,
500 callee: Box::new(callee),
501 args,
502 is_host_async: false,
503 block_label,
504 });
505 }
506
507 let argument = self.lower_expr(&ae.argument);
509 crate::zigir::types::IrExpr::Await(crate::zigir::types::IrAwaitExpr {
510 task_var,
511 callee: Box::new(argument),
512 args: vec![],
513 is_host_async: false,
514 block_label,
515 })
516 }
517
518 pub(super) fn lower_new(&mut self, ne: &NewExpression) -> crate::zigir::types::IrExpr {
520 use crate::zigir::kinds::NewConstructor;
521
522 let constructor = match &ne.callee {
524 Expression::Identifier(id) => match id.name.as_str() {
525 "Map" => NewConstructor::Map,
526 "Set" => NewConstructor::Set,
527 "Date" => {
528 let kind = if ne.arguments.is_empty() {
530 crate::zigir::kinds::DateConstructorKind::Now
531 } else if ne.arguments.len() >= 2 {
532 crate::zigir::kinds::DateConstructorKind::FromComponents
533 } else if let Some(first_arg) = ne.arguments.first()
534 && let Some(expr) = first_arg.as_expression()
535 {
536 let is_string = matches!(expr, Expression::StringLiteral(_));
538 if is_string {
539 crate::zigir::kinds::DateConstructorKind::FromString
540 } else {
541 crate::zigir::kinds::DateConstructorKind::FromMillis
542 }
543 } else {
544 crate::zigir::kinds::DateConstructorKind::Now
545 };
546 NewConstructor::Date(kind)
547 }
548 "RegExp" => NewConstructor::RegExp,
549 "Int8Array" | "Uint8Array" | "Uint8ClampedArray" | "Int16Array" | "Uint16Array"
550 | "Int32Array" | "Uint32Array" | "Float32Array" | "Float64Array"
551 | "BigInt64Array" | "BigUint64Array" => {
552 let kind = match id.name.as_str() {
553 "Int8Array" => crate::zigir::kinds::TypedArrayKind::Int8Array,
554 "Uint8Array" => crate::zigir::kinds::TypedArrayKind::Uint8Array,
555 "Uint8ClampedArray" => {
556 crate::zigir::kinds::TypedArrayKind::Uint8ClampedArray
557 }
558 "Int16Array" => crate::zigir::kinds::TypedArrayKind::Int16Array,
559 "Uint16Array" => crate::zigir::kinds::TypedArrayKind::Uint16Array,
560 "Int32Array" => crate::zigir::kinds::TypedArrayKind::Int32Array,
561 "Uint32Array" => crate::zigir::kinds::TypedArrayKind::Uint32Array,
562 "Float32Array" => crate::zigir::kinds::TypedArrayKind::Float32Array,
563 "Float64Array" => crate::zigir::kinds::TypedArrayKind::Float64Array,
564 "BigInt64Array" => crate::zigir::kinds::TypedArrayKind::BigInt64Array,
565 "BigUint64Array" => crate::zigir::kinds::TypedArrayKind::BigUint64Array,
566 _ => crate::zigir::kinds::TypedArrayKind::Float64Array,
567 };
568 NewConstructor::TypedArray(kind)
569 }
570 "Error" => NewConstructor::Error("Error".to_string()),
571 "TypeError" => NewConstructor::Error("TypeError".to_string()),
572 "RangeError" => NewConstructor::Error("RangeError".to_string()),
573 "String" => {
575 return if let Some(first_arg) = ne.arguments.first()
576 && let Some(expr) = first_arg.as_expression()
577 {
578 self.lower_expr(expr)
579 } else {
580 crate::zigir::types::IrExpr::StringLiteral("".to_string())
581 };
582 }
583 "Number" => {
584 return if let Some(first_arg) = ne.arguments.first()
585 && let Some(expr) = first_arg.as_expression()
586 {
587 self.lower_expr(expr)
588 } else {
589 crate::zigir::types::IrExpr::IntLiteral(0)
590 };
591 }
592 "Boolean" => {
593 return if let Some(first_arg) = ne.arguments.first()
594 && let Some(expr) = first_arg.as_expression()
595 {
596 self.lower_expr(expr)
597 } else {
598 crate::zigir::types::IrExpr::BoolLiteral(false)
599 };
600 }
601 name if self.class_names.contains(name) => NewConstructor::Class(name.to_string()),
602 "ArrayBuffer" | "SharedArrayBuffer" | "Function" | "Promise" | "WeakMap"
604 | "WeakSet" | "DataView" => {
605 NewConstructor::Unsupported(id.name.as_str().to_string())
606 }
607 other => {
608 let span = oxc_span::GetSpan::span(ne);
609 return self.compile_error_expr(
610 span,
611 format!("Unsupported NewExpression: new {}()", other),
612 );
613 }
614 },
615 _ => {
616 let span = oxc_span::GetSpan::span(ne);
617 return self.compile_error_expr(span, "Unsupported NewExpression");
618 }
619 };
620
621 let args = self.lower_args(&ne.arguments);
622
623 let result_type = match &constructor {
624 NewConstructor::Map => ZigType::NamedStruct("Map".to_string()),
625 NewConstructor::Set => ZigType::NamedStruct("Set".to_string()),
626 NewConstructor::Date(_) => ZigType::NamedStruct("JsDate".to_string()),
627 NewConstructor::RegExp => ZigType::JsAny,
628 NewConstructor::TypedArray(_) => ZigType::NamedStruct("TypedArray".to_string()),
629 NewConstructor::Class(name) => ZigType::NamedStruct(name.clone()),
630 NewConstructor::Error(_) => ZigType::JsAny,
631 _ => ZigType::JsAny,
632 };
633
634 crate::zigir::types::IrExpr::New(crate::zigir::types::IrNewExpr {
635 constructor,
636 args,
637 result_type,
638 })
639 }
640}