Skip to main content

js2zig_core/zigir/lower/expr/
call.rs

1// zigir/lower/expr/call.rs
2// Call, new, await expression lowering + helpers.
3
4use 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    /// Check for unsupported global object calls (Atomics, Reflect, etc.)
16    /// that should produce compile errors instead of silent code generation.
17    pub(super) fn check_unsupported_call(&self, ce: &CallExpression) -> Option<String> {
18        // Match patterns: Atomics.load(), Reflect.apply(), Map.groupBy(), etc.
19        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    /// Lower a call expression.
62    ///
63    /// Routing priority:
64    /// 1. Builtin detection → `IrBuiltinCall`
65    /// 2. Closure / nested function call → `IrCall { call_kind: Closure }`
66    /// 3. Host function call → `IrHostCall`
67    /// 4. Direct user function → `IrCall { call_kind: Direct }`
68    /// 5. Method call → `IrCall { call_kind: Method { .. } }`
69    /// 6. IIFE / expression callee → `IrCall { call_kind: Closure }`
70    pub(super) fn lower_call(&mut self, ce: &CallExpression) -> crate::zigir::types::IrExpr {
71        use crate::zigir::types::IrExpr;
72
73        // ── Step 0: Check for unsupported global objects ──
74        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                    // Argument inherits all Expression variants
90                    _ => {
91                        // All Expression variants are directly accessible
92                        let expr = arg.as_expression().unwrap();
93                        self.lower_expr(expr)
94                    }
95                }
96            })
97            .collect();
98
99        // ── Step 1: Builtin detection ──
100        if let Some(builtin) = crate::native_builtins::detect_builtin_call(ce) {
101            // ── Step 1a: Array callback inlining ──
102            if let Some(inlined) = self.try_inline_array_callback(ce, &builtin) {
103                return inlined;
104            }
105
106            // ── Step 1b: Array non-callback method inlining ──
107            if let Some(inlined) = self.try_inline_array_method(ce, &builtin, &args) {
108                return inlined;
109            }
110
111            // ── Step 1c: eval() → compile error ──
112            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            // ── Fix string-variable methods misidentified as array ──
123            // detect_builtin_call only checks if the callee object is a StringLiteral,
124            // not if it's a variable of type string. Fix up the module/method here.
125            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            // ── Extract regex metadata for match/matchAll/search ──
186            let regex_info = Self::extract_regex_info(ce, &builtin);
187
188            // ── Derive TypedArray type suffix for JsTypedArray calls ──
189            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            // ── Fix Object.keys for struct-typed arguments ──
204            // Object.keys(obj) where obj is a Zig struct (not HashMap) needs
205            // a different runtime function (keysStruct) that uses comptime reflection.
206            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            // ── Handle complex receiver expressions (method chaining) ──
225            // When the receiver is a CallExpression (e.g., encodeURIComponent(str).replace(...)),
226            // extract_callee_object_name_static returns None. We lower the receiver expression
227            // and store it in obj_expr so the Emitter can inline it.
228            let obj_expr = if obj_name.is_none() {
229                if let Expression::StaticMemberExpression(sme) = &ce.callee {
230                    match &sme.object {
231                        // Complex receivers: lower the entire expression so the Emitter
232                        // can inline it (e.g., new Date(0).getFullYear()).
233                        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        // ── Step 1.5: RegExp variable method interception ──
258        // `r.test(s)` or `r.exec(s)` where `r` is a known RegExp variable.
259        // detect_builtin_call only identifies RegExpTest/RegExpExec for RegExpLiteral receivers.
260        // For variable receivers, we intercept here using regexp_vars tracking.
261        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                    _ => {} // other methods fall through
305                }
306            }
307        }
308
309        // ── Step 2: Identify callee pattern ──
310        match &ce.callee {
311            // Identifier callee: direct function call, host call, or closure
312            Expression::Identifier(id) => {
313                let name = id.name.as_str();
314
315                // Host function call: starts with "host_"
316                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                // Closure / nested function call
328                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                // Nested function call: rewrite to name.call(args)
343                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                // Direct user function call
355                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            // Static member expression callee: obj.method()
363            Expression::StaticMemberExpression(mem) => {
364                let method_name = mem.property.name.as_str();
365                let obj_expr = self.lower_expr(&mem.object);
366
367                // Determine method object type for CallKind::Method
368                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            // Function expression / arrow function callee (IIFE)
382            Expression::FunctionExpression(_) | Expression::ArrowFunctionExpression(_) => {
383                // IIFE: emit the function then call it
384                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            // Parenthesized expression containing function
393            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            // Any other callee type (computed member, etc.)
403            _ => {
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    /// Determine the MethodObjectKind for a method call's receiver object.
415    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    /// Check if a name refers to a closure instance.
451    pub(super) fn is_closure_instance(&self, name: &str) -> bool {
452        self.closure_mgr.closure_instances.contains(name)
453    }
454
455    /// Infer the return type of a host function.
456    pub(super) fn infer_host_return_type(&self, _host_name: &str) -> ZigType {
457        // TODO: look up host function return type from type_info
458        ZigType::JsAny
459    }
460
461    /// Lower an await expression.
462    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        // Check if this is an async host function call
467        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                    // Host async function: emit as host.{name}_async
472                    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            // Regular async call (non-host)
487            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        // Non-call await (unusual but valid JS)
503        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    /// Lower a new expression.
514    pub(super) fn lower_new(&mut self, ne: &NewExpression) -> crate::zigir::types::IrExpr {
515        use crate::zigir::kinds::NewConstructor;
516
517        // Determine constructor kind from callee
518        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                    // Determine DateConstructorKind from arguments
524                    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                        // Detect if argument is a string literal
532                        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                // Wrapper constructors — emit argument value directly (no wrapper object in Zig)
566                "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                // Known-unsupported constructors → structured Unsupported (Emitter generates proper @compileError)
595                "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}