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 "getOwnPropertyNames" => Some(
38 "Object.getOwnPropertyNames() is not yet implemented in js2zig".to_string(),
39 ),
40 _ => None,
41 },
42 "Map" if method_name == "groupBy" => Some(
43 "Map.groupBy() is not supported (requires iterable grouping)".to_string(),
44 ),
45 _ => None,
46 }
47 } else {
48 None
49 }
50 }
51 Expression::Identifier(id) => match id.name.as_str() {
52 name @ "Atomics" | name @ "Reflect" => {
53 Some(format!("{} is not supported in js2zig", name))
54 }
55 _ => None,
56 },
57 _ => None,
58 }
59 }
60
61 pub(super) fn lower_call(&mut self, ce: &CallExpression) -> crate::zigir::types::IrExpr {
71 use crate::zigir::types::IrExpr;
72
73 if let Some(err_msg) = self.check_unsupported_call(ce) {
75 return IrExpr::CompileError {
76 span: self.span_to_source_span(ce.span),
77 msg: err_msg,
78 };
79 }
80
81 let args: Vec<IrExpr> = ce
82 .arguments
83 .iter()
84 .map(|arg| {
85 match arg {
86 Argument::SpreadElement(se) => {
87 IrExpr::Spread(Box::new(self.lower_expr(&se.argument)))
88 }
89 _ => {
91 let expr = arg.as_expression().unwrap();
93 self.lower_expr(expr)
94 }
95 }
96 })
97 .collect();
98
99 if let Some(builtin) = crate::native_builtins::detect_builtin_call(ce) {
101 if let Some(inlined) = self.try_inline_array_callback(ce, &builtin) {
103 return inlined;
104 }
105
106 if let Some(inlined) = self.try_inline_array_method(ce, &builtin, &args) {
108 return inlined;
109 }
110
111 if matches!(builtin, crate::native_builtins::BuiltinCall::Eval) {
113 return IrExpr::CompileError {
114 span: self.span_to_source_span(ce.span),
115 msg: "eval() is not supported (security risk, cannot dynamically execute at compile time)".to_string(),
116 };
117 }
118
119 let (module, method, return_type) = builtin_call_to_ir(&builtin);
120 let obj_name = Self::extract_callee_object_name_static(&ce.callee);
121
122 let (module, method, return_type) = if let Some(name) = &obj_name {
126 if let Some(var_type) = self.type_info.var_types.get(name.as_str()) {
127 if matches!(var_type, ZigType::Str)
128 && module == crate::zigir::builtins::BuiltinModule::JsArray
129 {
130 match method.as_str() {
131 "at" => (
132 crate::zigir::builtins::BuiltinModule::JsString,
133 "at".into(),
134 ZigType::Str,
135 ),
136 "indexOf" => (
137 crate::zigir::builtins::BuiltinModule::JsString,
138 "indexOf".into(),
139 ZigType::I64,
140 ),
141 "includes" => (
142 crate::zigir::builtins::BuiltinModule::JsString,
143 "includes".into(),
144 ZigType::Bool,
145 ),
146 "lastIndexOf" => (
147 crate::zigir::builtins::BuiltinModule::JsString,
148 "lastIndexOf".into(),
149 ZigType::I64,
150 ),
151 "slice" => (
152 crate::zigir::builtins::BuiltinModule::JsString,
153 "slice".into(),
154 ZigType::Str,
155 ),
156 _ => (module, method, return_type),
157 }
158 } else if let ZigType::NamedStruct(n) = var_type {
159 if Self::is_typedarray_type(n) {
160 let ta_mod = BuiltinModule::JsTypedArray;
161 match method.as_str() {
162 "set" => (ta_mod, "set".into(), ZigType::Void),
163 "get" => (ta_mod, "get".into(), ZigType::I64),
164 "fill" => (ta_mod, "fill".into(), ZigType::Void),
165 "slice" => {
166 (ta_mod, "slice".into(), ZigType::NamedStruct(n.clone()))
167 }
168 "copyWithin" => (ta_mod, "copyWithin".into(), ZigType::Void),
169 _ => (module, method, return_type),
170 }
171 } else {
172 (module, method, return_type)
173 }
174 } else {
175 (module, method, return_type)
176 }
177 } else {
178 (module, method, return_type)
179 }
180 } else {
181 (module, method, return_type)
182 };
183 let obj_name = Self::extract_callee_object_name_static(&ce.callee);
184
185 let regex_info = Self::extract_regex_info(ce, &builtin);
187
188 let ta_type_suffix = if module == BuiltinModule::JsTypedArray {
190 obj_name.as_ref().and_then(|name| {
191 self.type_info.var_types.get(name.as_str()).and_then(|zt| {
192 if let ZigType::NamedStruct(n) = zt {
193 Self::typedarray_type_suffix(n).map(|s| s.to_string())
194 } else {
195 None
196 }
197 })
198 })
199 } else {
200 None
201 };
202
203 let method = if module == BuiltinModule::JsObject && method == "keys" {
207 if let Some(crate::zigir::types::IrExpr::Ident(ident)) = args.first() {
208 if let Some(var_type) = self.type_info.var_types.get(ident.zig_name.as_str()) {
209 if matches!(var_type, ZigType::Struct(_)) {
210 "keysStruct".into()
211 } else {
212 method
213 }
214 } else {
215 method
216 }
217 } else {
218 method
219 }
220 } else {
221 method
222 };
223
224 let obj_expr = if obj_name.is_none() {
229 if let Expression::StaticMemberExpression(sme) = &ce.callee {
230 match &sme.object {
231 Expression::CallExpression(_) | Expression::NewExpression(_) => {
234 Some(Box::new(self.lower_expr(&sme.object)))
235 }
236 _ => None,
237 }
238 } else {
239 None
240 }
241 } else {
242 None
243 };
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 {
457 ZigType::JsAny
459 }
460
461 pub(super) fn lower_await(&mut self, ae: &AwaitExpression) -> crate::zigir::types::IrExpr {
463 let task_var = IrIdent::new(&self.name_mangler.next_name("_t"));
464 let block_label = format!("blk_{}", self.name_mangler.peek_count("_t"));
465
466 if let Expression::CallExpression(call) = &ae.argument {
468 if let Expression::Identifier(id) = &call.callee {
469 let name = id.name.as_str();
470 if self.async_host_fns.contains(name) {
471 let args: Vec<_> = call
473 .arguments
474 .iter()
475 .filter_map(|a| a.as_expression().map(|e| self.lower_expr(e)))
476 .collect();
477 return crate::zigir::types::IrExpr::Await(crate::zigir::types::IrAwaitExpr {
478 task_var,
479 callee: Box::new(crate::zigir::types::IrExpr::Ident(IrIdent::new(name))),
480 args,
481 is_host_async: true,
482 block_label,
483 });
484 }
485 }
486 let callee = self.lower_expr(&call.callee);
488 let args: Vec<_> = call
489 .arguments
490 .iter()
491 .filter_map(|a| a.as_expression().map(|e| self.lower_expr(e)))
492 .collect();
493 return crate::zigir::types::IrExpr::Await(crate::zigir::types::IrAwaitExpr {
494 task_var,
495 callee: Box::new(callee),
496 args,
497 is_host_async: false,
498 block_label,
499 });
500 }
501
502 let argument = self.lower_expr(&ae.argument);
504 crate::zigir::types::IrExpr::Await(crate::zigir::types::IrAwaitExpr {
505 task_var,
506 callee: Box::new(argument),
507 args: vec![],
508 is_host_async: false,
509 block_label,
510 })
511 }
512
513 pub(super) fn lower_new(&mut self, ne: &NewExpression) -> crate::zigir::types::IrExpr {
515 use crate::zigir::kinds::NewConstructor;
516
517 let constructor = match &ne.callee {
519 Expression::Identifier(id) => match id.name.as_str() {
520 "Map" => NewConstructor::Map,
521 "Set" => NewConstructor::Set,
522 "Date" => {
523 let kind = if ne.arguments.is_empty() {
525 crate::zigir::kinds::DateConstructorKind::Now
526 } else if ne.arguments.len() >= 2 {
527 crate::zigir::kinds::DateConstructorKind::FromComponents
528 } else if let Some(first_arg) = ne.arguments.first()
529 && let Some(expr) = first_arg.as_expression()
530 {
531 let is_string = matches!(expr, Expression::StringLiteral(_));
533 if is_string {
534 crate::zigir::kinds::DateConstructorKind::FromString
535 } else {
536 crate::zigir::kinds::DateConstructorKind::FromMillis
537 }
538 } else {
539 crate::zigir::kinds::DateConstructorKind::Now
540 };
541 NewConstructor::Date(kind)
542 }
543 "RegExp" => NewConstructor::RegExp,
544 "Int8Array" | "Uint8Array" | "Uint8ClampedArray" | "Int16Array" | "Uint16Array"
545 | "Int32Array" | "Uint32Array" | "Float32Array" | "Float64Array" => {
546 let kind = match id.name.as_str() {
547 "Int8Array" => crate::zigir::kinds::TypedArrayKind::Int8Array,
548 "Uint8Array" => crate::zigir::kinds::TypedArrayKind::Uint8Array,
549 "Uint8ClampedArray" => {
550 crate::zigir::kinds::TypedArrayKind::Uint8ClampedArray
551 }
552 "Int16Array" => crate::zigir::kinds::TypedArrayKind::Int16Array,
553 "Uint16Array" => crate::zigir::kinds::TypedArrayKind::Uint16Array,
554 "Int32Array" => crate::zigir::kinds::TypedArrayKind::Int32Array,
555 "Uint32Array" => crate::zigir::kinds::TypedArrayKind::Uint32Array,
556 "Float32Array" => crate::zigir::kinds::TypedArrayKind::Float32Array,
557 "Float64Array" => crate::zigir::kinds::TypedArrayKind::Float64Array,
558 _ => crate::zigir::kinds::TypedArrayKind::Float64Array,
559 };
560 NewConstructor::TypedArray(kind)
561 }
562 "Error" => NewConstructor::Error("Error".to_string()),
563 "TypeError" => NewConstructor::Error("TypeError".to_string()),
564 "RangeError" => NewConstructor::Error("RangeError".to_string()),
565 "String" => {
567 if let Some(first_arg) = ne.arguments.first()
568 && let Some(expr) = first_arg.as_expression()
569 {
570 return self.lower_expr(expr);
571 } else {
572 return crate::zigir::types::IrExpr::StringLiteral("".to_string());
573 }
574 }
575 "Number" => {
576 if let Some(first_arg) = ne.arguments.first()
577 && let Some(expr) = first_arg.as_expression()
578 {
579 return self.lower_expr(expr);
580 } else {
581 return crate::zigir::types::IrExpr::IntLiteral(0);
582 }
583 }
584 "Boolean" => {
585 if let Some(first_arg) = ne.arguments.first()
586 && let Some(expr) = first_arg.as_expression()
587 {
588 return self.lower_expr(expr);
589 } else {
590 return crate::zigir::types::IrExpr::BoolLiteral(false);
591 }
592 }
593 name if self.class_names.contains(name) => NewConstructor::Class(name.to_string()),
594 "ArrayBuffer" | "SharedArrayBuffer" | "Function" | "Promise" | "WeakMap"
596 | "WeakSet" | "DataView" => {
597 NewConstructor::Unsupported(id.name.as_str().to_string())
598 }
599 other => {
600 let span = oxc_span::GetSpan::span(ne);
601 return crate::zigir::types::IrExpr::CompileError {
602 span: self.span_to_source_span(span),
603 msg: format!("Unsupported NewExpression: new {}()", other),
604 };
605 }
606 },
607 _ => {
608 let span = oxc_span::GetSpan::span(ne);
609 return crate::zigir::types::IrExpr::CompileError {
610 span: self.span_to_source_span(span),
611 msg: "Unsupported NewExpression".to_string(),
612 };
613 }
614 };
615
616 let args: Vec<crate::zigir::types::IrExpr> = ne
617 .arguments
618 .iter()
619 .map(|arg| match arg {
620 Argument::SpreadElement(se) => {
621 crate::zigir::types::IrExpr::Spread(Box::new(self.lower_expr(&se.argument)))
622 }
623 _ => {
624 let expr = arg.as_expression().unwrap();
625 self.lower_expr(expr)
626 }
627 })
628 .collect();
629
630 let result_type = match &constructor {
631 NewConstructor::Map => ZigType::NamedStruct("Map".to_string()),
632 NewConstructor::Set => ZigType::NamedStruct("Set".to_string()),
633 NewConstructor::Date(_) => ZigType::NamedStruct("JsDate".to_string()),
634 NewConstructor::RegExp => ZigType::JsAny,
635 NewConstructor::TypedArray(_) => ZigType::NamedStruct("TypedArray".to_string()),
636 NewConstructor::Class(name) => ZigType::NamedStruct(name.clone()),
637 NewConstructor::Error(_) => ZigType::JsAny,
638 _ => ZigType::JsAny,
639 };
640
641 crate::zigir::types::IrExpr::New(crate::zigir::types::IrNewExpr {
642 constructor,
643 args,
644 result_type,
645 })
646 }
647}