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::native_builtins::BuiltinCall;
7use crate::types::ZigType;
8use crate::zigir::builtins::BuiltinModule;
9use crate::zigir::ident::IrIdent;
10use crate::zigir::kinds::{CallKind, FieldKind};
11
12use super::super::cabi::builtin_call_to_ir;
13use super::Lowerer;
14
15impl Lowerer {
16    /// Check for unsupported global object calls (Atomics, Reflect, etc.)
17    /// that should produce compile errors instead of silent code generation.
18    pub(super) fn check_unsupported_call(&self, ce: &CallExpression) -> Option<String> {
19        // Match patterns: Atomics.load(), Reflect.apply(), Map.groupBy(), etc.
20        match &ce.callee {
21            Expression::StaticMemberExpression(mem) => {
22                if let Expression::Identifier(id) = &mem.object {
23                    let obj_name = id.name.as_str();
24                    let method_name = mem.property.name.as_str();
25                    match obj_name {
26                        "Atomics" => Some(format!(
27                            "Atomics.{}() is not supported (shared memory atomics are not available in Zig)",
28                            method_name
29                        )),
30                        "Reflect" => Some(format!(
31                            "Reflect.{}() is not supported (meta-programming API is not available)",
32                            method_name
33                        )),
34                        "Object" => match method_name {
35                            "getOwnPropertySymbols" => Some(
36                                "Object.getOwnPropertySymbols() is not supported (Symbol keys are not available in js2zig)".to_string(),
37                            ),
38                            _ => None,
39                        },
40                        "Map" if method_name == "groupBy" => Some(
41                            "Map.groupBy() is not supported (requires iterable grouping)".to_string(),
42                        ),
43                        "Promise" => Some(format!(
44                            "Promise.{}() is not supported (use async/await + host functions instead)",
45                            method_name
46                        )),
47                        "Intl" => Some(format!(
48                            "Intl.{}() is not supported (use Zig/C library for internationalization)",
49                            method_name
50                        )),
51                        _ => None,
52                    }
53                } else {
54                    None
55                }
56            }
57            Expression::Identifier(id) => match id.name.as_str() {
58                name @ "Atomics" | name @ "Reflect" | name @ "Promise" | name @ "Intl" => {
59                    Some(format!("{} is not supported in js2zig", name))
60                }
61                _ => None,
62            },
63            _ => None,
64        }
65    }
66
67    /// Lower a call expression.
68    ///
69    /// Routing priority:
70    /// 1. Builtin detection → `IrBuiltinCall`
71    /// 2. Closure / nested function call → `IrCall { call_kind: Closure }`
72    /// 3. Host function call → `IrHostCall`
73    /// 4. Direct user function → `IrCall { call_kind: Direct }`
74    /// 5. Method call → `IrCall { call_kind: Method { .. } }`
75    /// 6. IIFE / expression callee → `IrCall { call_kind: Closure }`
76    pub(super) fn lower_call(&mut self, ce: &CallExpression) -> crate::zigir::types::IrExpr {
77        use crate::zigir::types::IrExpr;
78
79        // ── Step 0: Check for unsupported global objects ──
80        if let Some(err_msg) = self.check_unsupported_call(ce) {
81            return self.compile_error_expr(ce.span, err_msg);
82        }
83
84        // ── Step 1: Builtin detection ──
85        if let Some(builtin) = crate::native_builtins::detect_builtin_call(ce) {
86            // ── Step 1a: Array callback inlining ──
87            // NOTE: `try_inline_array_callback` parses the callback directly
88            // from AST (via `parse_callback_inline`), so the call arguments
89            // must NOT be pre-lowered at this point. Pre-lowering would invoke
90            // `lower_arrow_fn` on the arrow-function argument, which registers
91            // a closure struct in `ClosureManager`. When the call expression
92            // is then replaced by `ArrayCallbackInline`, that registered
93            // closure struct becomes dead code that fails Zig `ast-check`
94            // (anytype parameter mismatch). Defer `lower_args` until after
95            // this check so the callback is lowered only via
96            // `parse_callback_inline`, which embeds its body in the inline IR
97            // without registering a closure struct.
98            if let Some(inlined) = self.try_inline_array_callback(ce, &builtin) {
99                return inlined;
100            }
101
102            // Callback inline did not fire — safe to lower arguments now.
103            let args = self.lower_args(&ce.arguments);
104
105            // ── Step 1b: Array non-callback method inlining ──
106            if let Some(inlined) = self.try_inline_array_method(ce, &builtin, &args) {
107                return inlined;
108            }
109
110            // ── Step 1c: eval() → compile error ──
111            if matches!(builtin, crate::native_builtins::BuiltinCall::Eval) {
112                return self.compile_error_expr(ce.span, "eval() is not supported (security risk, cannot dynamically execute at compile time)");
113            }
114
115            // ── Step 1d: ES2025 Set operations → @compileError ──
116            if matches!(
117                builtin,
118                crate::native_builtins::BuiltinCall::SetUnion
119                    | crate::native_builtins::BuiltinCall::SetIntersection
120                    | crate::native_builtins::BuiltinCall::SetDifference
121                    | crate::native_builtins::BuiltinCall::SetSymmetricDifference
122                    | crate::native_builtins::BuiltinCall::SetIsSubsetOf
123                    | crate::native_builtins::BuiltinCall::SetIsSupersetOf
124                    | crate::native_builtins::BuiltinCall::SetIsDisjointFrom
125            ) {
126                let method_name = match &builtin {
127                    crate::native_builtins::BuiltinCall::SetUnion => "union",
128                    crate::native_builtins::BuiltinCall::SetIntersection => "intersection",
129                    crate::native_builtins::BuiltinCall::SetDifference => "difference",
130                    crate::native_builtins::BuiltinCall::SetSymmetricDifference => {
131                        "symmetricDifference"
132                    }
133                    crate::native_builtins::BuiltinCall::SetIsSubsetOf => "isSubsetOf",
134                    crate::native_builtins::BuiltinCall::SetIsSupersetOf => "isSupersetOf",
135                    crate::native_builtins::BuiltinCall::SetIsDisjointFrom => "isDisjointFrom",
136                    // Unreachable: the enclosing `if matches!` block only enters
137                    // for the 7 Set variants above. Use a safe fallback instead
138                    // of unreachable!() (P2-3: fragile catch-all elimination).
139                    _ => "unknown",
140                };
141                return self.compile_error_expr(
142                    ce.span,
143                    format!(
144                        "Set.prototype.{}() is not supported (ES2025 Set operation)",
145                        method_name
146                    ),
147                );
148            }
149
150            let (module, method, return_type) = builtin_call_to_ir(&builtin);
151
152            // JSON.parse can throw SyntaxError at runtime — mark function as can_throw
153            // so the emitter's `catch return error.JsThrow` is valid.
154            if matches!(builtin, crate::native_builtins::BuiltinCall::JsonParse)
155                && let Some(ctx) = self.fn_ctx.as_mut()
156            {
157                ctx.has_catchable_error = true;
158            }
159            let obj_name = Self::extract_callee_object_name_static(&ce.callee);
160
161            // ── Fix string-variable methods misidentified as array ──
162            // detect_builtin_call only checks if the callee object is a StringLiteral,
163            // not if it's a variable of type string. Fix up the module/method here.
164            let (module, method, return_type) = if let Some(name) = &obj_name {
165                if let Some(var_type) = self.type_info.var_types.get(name.as_str()) {
166                    if matches!(var_type, ZigType::Str) && module == BuiltinModule::JsArray {
167                        match method.as_str() {
168                            "at" => (BuiltinModule::JsString, "at".into(), ZigType::Str),
169                            "indexOf" => (BuiltinModule::JsString, "indexOf".into(), ZigType::I64),
170                            "includes" => {
171                                (BuiltinModule::JsString, "includes".into(), ZigType::Bool)
172                            }
173                            "lastIndexOf" => {
174                                (BuiltinModule::JsString, "lastIndexOf".into(), ZigType::I64)
175                            }
176                            "slice" => (BuiltinModule::JsString, "slice".into(), ZigType::Str),
177                            _ => (module, method, return_type),
178                        }
179                    } else if matches!(var_type, ZigType::F64 | ZigType::I64)
180                        && module == BuiltinModule::JsDate
181                        && method == "toString"
182                    {
183                        // R8-NumberToString: detect_builtin_call routes any
184                        // `.toString()` on a non-literal receiver to
185                        // DateToString because it has no type info at the
186                        // AST layer. F64/I64 variables (e.g. `const n = 42;`)
187                        // must produce `js_number.toString(...)` instead of
188                        // the semantically wrong `js_date.toString(...)`
189                        // (which would also be a Zig compile error since f64
190                        // has no such method).
191                        (BuiltinModule::JsNumber, "toString".into(), ZigType::Str)
192                    } else if matches!(var_type, ZigType::BigInt)
193                        && module == BuiltinModule::JsDate
194                        && (method == "toString" || method == "toLocaleString")
195                    {
196                        // R8-P1-4: BigInt variable `.toString(radix?)` /
197                        // `.toLocaleString()` is misrouted to DateToString /
198                        // DateToLocaleString by detect_builtin_call (no type
199                        // info at the AST layer). Rewrite to JsBigInt so
200                        // emit_bigint_builtin propagates the radix argument
201                        // (toString) or supplies the default 10 (toLocaleString).
202                        // Note: the legacy BigInt Step 1.5 interception in the
203                        // non-builtin path is dead code because
204                        // detect_builtin_call always returns Some for
205                        // `.toString()`, so this builtin-path rewrite is the
206                        // actual fix path for BigInt variables.
207                        (BuiltinModule::JsBigInt, method, ZigType::Str)
208                    } else if let ZigType::NamedStruct(n) = var_type {
209                        if Self::is_typedarray_type(n) {
210                            let ta_mod = BuiltinModule::JsTypedArray;
211                            match method.as_str() {
212                                "set" => (ta_mod, "set".into(), ZigType::Void),
213                                "get" => (ta_mod, "get".into(), ZigType::I64),
214                                "fill" => (ta_mod, "fill".into(), ZigType::Void),
215                                "slice" => {
216                                    (ta_mod, "slice".into(), ZigType::NamedStruct(n.clone()))
217                                }
218                                "copyWithin" => (ta_mod, "copyWithin".into(), ZigType::Void),
219                                _ => (module, method, return_type),
220                            }
221                        } else {
222                            (module, method, return_type)
223                        }
224                    } else {
225                        (module, method, return_type)
226                    }
227                } else {
228                    (module, method, return_type)
229                }
230            } else {
231                (module, method, return_type)
232            };
233
234            // ── Extract regex metadata for match/matchAll/search ──
235            let regex_info = Self::extract_regex_info(ce, &builtin);
236
237            // R8-P1-25: matchAll with non-/g literal RegExp → compile error
238            // JS spec §22.1.3.19: String.prototype.matchAll called with a
239            // non-global RegExp argument must throw TypeError. For literal
240            // RegExp we know at compile time whether /g is present.
241            if matches!(builtin, BuiltinCall::StringMatchAll)
242                && let Some(ref ri) = regex_info
243                && !ri.is_var_ref
244                && !ri.has_global
245            {
246                return self.compile_error_expr(
247                    ce.span,
248                    "String.prototype.matchAll called with a non-global RegExp argument (TypeError)",
249                );
250            }
251
252            // R8-P1-25: replaceAll with non-/g literal RegExp → compile error
253            // JS spec §22.1.3.18: String.prototype.replaceAll called with a
254            // non-global RegExp argument must throw TypeError.
255            if matches!(builtin, BuiltinCall::StringReplaceAll)
256                && let Some(ref ri) = regex_info
257                && !ri.is_var_ref
258                && !ri.has_global
259            {
260                return self.compile_error_expr(
261                    ce.span,
262                    "String.prototype.replaceAll called with a non-global RegExp argument (TypeError)",
263                );
264            }
265
266            // ── Derive TypedArray type suffix for JsTypedArray calls ──
267            let ta_type_suffix = if module == BuiltinModule::JsTypedArray {
268                obj_name.as_ref().and_then(|name| {
269                    self.type_info.var_types.get(name.as_str()).and_then(|zt| {
270                        if let ZigType::NamedStruct(n) = zt {
271                            Self::typedarray_type_suffix(n).map(|s| s.to_string())
272                        } else {
273                            None
274                        }
275                    })
276                })
277            } else {
278                None
279            };
280
281            // ── Fix Object.keys/getOwnPropertyNames for struct-typed arguments ──
282            // Object.keys(obj) / Object.getOwnPropertyNames(obj) where obj is a Zig struct
283            // (not HashMap) needs a different runtime function (keysStruct /
284            // getOwnPropertyNamesStruct) that uses comptime reflection.
285            let method = if module == BuiltinModule::JsObject
286                && (method == "keys" || method == "getOwnPropertyNames")
287            {
288                let ident_name = match args.first() {
289                    Some(IrExpr::Ident(ident)) => Some(ident.zig_name.as_str()),
290                    Some(IrExpr::TypedIdent { ident, .. }) => Some(ident.zig_name.as_str()),
291                    _ => None,
292                };
293                if let Some(name) = ident_name {
294                    if let Some(var_type) = self.type_info.var_types.get(name) {
295                        if matches!(var_type, ZigType::Struct(_)) {
296                            if method == "keys" {
297                                "keysStruct".into()
298                            } else {
299                                "getOwnPropertyNamesStruct".into()
300                            }
301                        } else {
302                            method
303                        }
304                    } else {
305                        method
306                    }
307                } else {
308                    method
309                }
310            } else {
311                method
312            };
313
314            // ── Handle complex receiver expressions (method chaining) ──
315            // When the receiver is a CallExpression (e.g., encodeURIComponent(str).replace(...)),
316            // extract_callee_object_name_static returns None. We lower the receiver expression
317            // and store it in obj_expr so the Emitter can inline it.
318            let mut inner_expr = if obj_name.is_none() {
319                if let Expression::StaticMemberExpression(sme) = &ce.callee {
320                    match &sme.object {
321                        // Complex receivers: lower the entire expression so the Emitter
322                        // can inline it (e.g., new Date(0).getFullYear()).
323                        Expression::CallExpression(_) | Expression::NewExpression(_) => {
324                            Some(self.lower_expr(&sme.object))
325                        }
326                        _ => None,
327                    }
328                } else {
329                    None
330                }
331            } else {
332                None
333            };
334
335            // ── Method chaining: re-attempt inline when inner expr is ArrayCallbackInline/ArrayMethodInline ──
336            // For `arr.filter(x => x > 1).map(x => x * 2)`, the inner `.filter()` was inlined
337            // as ArrayCallbackInline, but the outer `.map()` fell through because extract_callee_object_name_static
338            // returned None (receiver is a CallExpression, not an Identifier).
339            // We give it a second chance: use the inner inline's element type, generate a temp var name,
340            // and construct the outer inline directly.
341            if let Some(inner) = inner_expr.take() {
342                let chain_elem_type = match &inner {
343                    IrExpr::ArrayCallbackInline(cb) => Some(cb.elem_type.clone()),
344                    IrExpr::ArrayMethodInline(mm) => Some(mm.elem_type.clone()),
345                    _ => None,
346                };
347
348                if let Some(elem_type) = chain_elem_type {
349                    // Try to re-attempt callback inline with a synthetic obj_name
350                    if let Some(inlined) =
351                        self.try_inline_array_callback_with_chain(ce, &builtin, &elem_type, &inner)
352                    {
353                        return inlined;
354                    }
355
356                    // Try to re-attempt method inline with a synthetic obj_name
357                    if let Some(inlined) = self
358                        .try_inline_array_method_with_chain(ce, &builtin, &args, &elem_type, &inner)
359                    {
360                        return inlined;
361                    }
362
363                    // Both failed — fall through to BuiltinCall with obj_expr
364                    inner_expr = Some(inner);
365                } else {
366                    inner_expr = Some(inner);
367                }
368            }
369
370            let obj_expr = inner_expr.map(Box::new);
371
372            return IrExpr::BuiltinCall(crate::zigir::types::IrBuiltinCall {
373                module,
374                method,
375                obj_name,
376                obj_expr,
377                args,
378                return_type,
379                regex_info,
380                ta_type_suffix,
381            });
382        }
383
384        // ── Non-builtin path: lower arguments ──
385        // Reached only when `detect_builtin_call` returned None (not a builtin)
386        // — in that case no `lower_args` call happened in Step 1, so do it here.
387        let args = self.lower_args(&ce.arguments);
388
389        // ── Step 1.5: BigInt variable method interception ──
390        // `b.toString()` or `b.valueOf()` where `b` is a known BigInt variable.
391        // detect_builtin_call routes `.toString()` to DateToString by default.
392        // For BigInt-typed variables, we intercept here using type lookup.
393        if let Expression::StaticMemberExpression(sme) = &ce.callee
394            && let Expression::Identifier(id) = &sme.object
395        {
396            let var_name = id.name.as_str();
397            let var_type = self.type_info.var_types.get(var_name).cloned().or_else(|| {
398                self.fn_ctx
399                    .as_ref()
400                    .and_then(|ctx| ctx.fn_local_types.get(var_name).cloned())
401            });
402            if let Some(ZigType::BigInt) = var_type {
403                let method = sme.property.name.as_str();
404                match method {
405                    "toString" => {
406                        return IrExpr::BuiltinCall(crate::zigir::types::IrBuiltinCall {
407                            module: BuiltinModule::JsBigInt,
408                            method: "toString".into(),
409                            obj_name: Some(var_name.to_string()),
410                            obj_expr: None,
411                            args,
412                            return_type: ZigType::Str,
413                            regex_info: None,
414                            ta_type_suffix: None,
415                        });
416                    }
417                    "valueOf" => {
418                        return IrExpr::BuiltinCall(crate::zigir::types::IrBuiltinCall {
419                            module: BuiltinModule::JsBigInt,
420                            method: "valueOf".into(),
421                            obj_name: Some(var_name.to_string()),
422                            obj_expr: None,
423                            args,
424                            return_type: ZigType::BigInt,
425                            regex_info: None,
426                            ta_type_suffix: None,
427                        });
428                    }
429                    "toLocaleString" => {
430                        return IrExpr::BuiltinCall(crate::zigir::types::IrBuiltinCall {
431                            module: BuiltinModule::JsBigInt,
432                            method: "toLocaleString".into(),
433                            obj_name: Some(var_name.to_string()),
434                            obj_expr: None,
435                            args,
436                            return_type: ZigType::Str,
437                            regex_info: None,
438                            ta_type_suffix: None,
439                        });
440                    }
441                    _ => {} // other methods fall through
442                }
443            }
444        }
445
446        // ── Step 1.6: RegExp variable method interception ──
447        // `r.test(s)` or `r.exec(s)` where `r` is a known RegExp variable.
448        // detect_builtin_call only identifies RegExpTest/RegExpExec for RegExpLiteral receivers.
449        // For variable receivers, we intercept here using regexp_vars tracking.
450        if let Expression::StaticMemberExpression(sme) = &ce.callee
451            && let Expression::Identifier(id) = &sme.object
452        {
453            let var_name = id.name.as_str();
454            if let Some(ctx) = &self.fn_ctx
455                && ctx.regexp_vars.contains(var_name)
456            {
457                let method = sme.property.name.as_str();
458                match method {
459                    "test" => {
460                        return IrExpr::BuiltinCall(crate::zigir::types::IrBuiltinCall {
461                            module: BuiltinModule::JsRegExp,
462                            method: "test".into(),
463                            obj_name: Some(var_name.to_string()),
464                            obj_expr: None,
465                            args,
466                            return_type: ZigType::Bool,
467                            regex_info: Some(crate::zigir::types::IrRegexInfo {
468                                pattern: None,
469                                has_global: false,
470                                is_var_ref: true,
471                                var_name: Some(var_name.to_string()),
472                            }),
473                            ta_type_suffix: None,
474                        });
475                    }
476                    "exec" => {
477                        return IrExpr::BuiltinCall(crate::zigir::types::IrBuiltinCall {
478                            module: BuiltinModule::JsRegExp,
479                            method: "exec".into(),
480                            obj_name: Some(var_name.to_string()),
481                            obj_expr: None,
482                            args,
483                            return_type: ZigType::JsAny,
484                            regex_info: Some(crate::zigir::types::IrRegexInfo {
485                                pattern: None,
486                                has_global: false,
487                                is_var_ref: true,
488                                var_name: Some(var_name.to_string()),
489                            }),
490                            ta_type_suffix: None,
491                        });
492                    }
493                    _ => {} // other methods fall through
494                }
495            }
496        }
497
498        // ── Step 2: Identify callee pattern ──
499        match &ce.callee {
500            // Identifier callee: direct function call, host call, or closure
501            Expression::Identifier(id) => {
502                let name = id.name.as_str();
503
504                // Host function call: starts with "host_"
505                if let Some(host_name) = name.strip_prefix("host_") {
506                    let is_async = self.async_host_fns.contains(name);
507                    let return_type = self.infer_host_return_type(host_name);
508                    return IrExpr::HostCall(crate::zigir::types::IrHostCall {
509                        name: host_name.to_string(),
510                        args,
511                        return_type,
512                        is_async,
513                    });
514                }
515
516                // Closure / nested function call
517                if self
518                    .closure_mgr
519                    .current_captured
520                    .iter()
521                    .any(|(n, _, _)| n.as_str() == name)
522                    || self.is_closure_instance(name)
523                {
524                    return IrExpr::Call(crate::zigir::types::IrCallExpr {
525                        callee: Box::new(IrExpr::Ident(IrIdent::new(name))),
526                        args,
527                        call_kind: CallKind::Closure,
528                    });
529                }
530
531                // Nested function call: rewrite to name.call(args)
532                if let Some(ctx) = &self.fn_ctx
533                    && ctx.is_nested_fn(name)
534                {
535                    let callee_ident = self.make_ident(name);
536                    return IrExpr::Call(crate::zigir::types::IrCallExpr {
537                        callee: Box::new(IrExpr::Ident(callee_ident)),
538                        args,
539                        call_kind: CallKind::Closure,
540                    });
541                }
542
543                // Direct user function call
544                let args = self.pack_rest_args_if_needed(name, args);
545                IrExpr::Call(crate::zigir::types::IrCallExpr {
546                    callee: Box::new(IrExpr::Ident(IrIdent::new(name))),
547                    args,
548                    call_kind: CallKind::Direct,
549                })
550            }
551
552            // Static member expression callee: obj.method()
553            Expression::StaticMemberExpression(mem) => {
554                let method_name = mem.property.name.as_str();
555                let obj_expr = self.lower_expr(&mem.object);
556
557                // Determine method object type for CallKind::Method
558                let object_type = self.infer_method_object_kind(&mem.object);
559
560                IrExpr::Call(crate::zigir::types::IrCallExpr {
561                    callee: Box::new(IrExpr::FieldAccess {
562                        object: Box::new(obj_expr),
563                        field: method_name.to_string(),
564                        field_kind: FieldKind::StructField,
565                    }),
566                    args,
567                    call_kind: CallKind::Method { object_type },
568                })
569            }
570
571            // Function expression / arrow function callee (IIFE)
572            Expression::FunctionExpression(_) | Expression::ArrowFunctionExpression(_) => {
573                // IIFE: emit the function then call it
574                let callee = self.lower_expr(&ce.callee);
575                IrExpr::Call(crate::zigir::types::IrCallExpr {
576                    callee: Box::new(callee),
577                    args,
578                    call_kind: CallKind::Closure,
579                })
580            }
581
582            // Parenthesized expression containing function
583            Expression::ParenthesizedExpression(_) => {
584                let callee = self.lower_expr(&ce.callee);
585                IrExpr::Call(crate::zigir::types::IrCallExpr {
586                    callee: Box::new(callee),
587                    args,
588                    call_kind: CallKind::Closure,
589                })
590            }
591
592            // Any other callee type (computed member, etc.)
593            _ => {
594                let callee = self.lower_expr(&ce.callee);
595                IrExpr::Call(crate::zigir::types::IrCallExpr {
596                    callee: Box::new(callee),
597                    args,
598                    call_kind: CallKind::Direct,
599                })
600            }
601        }
602    }
603
604    /// Determine the MethodObjectKind for a method call's receiver object.
605    pub(super) fn infer_method_object_kind(
606        &self,
607        obj: &Expression,
608    ) -> crate::zigir::kinds::MethodObjectKind {
609        use crate::zigir::kinds::MethodObjectKind;
610
611        match obj {
612            Expression::Identifier(id) => {
613                if let Some(zig_type) = self.type_info.var_types.get(id.name.as_str()) {
614                    match zig_type {
615                        ZigType::ArrayList(_) => MethodObjectKind::ArrayList,
616                        ZigType::Str => MethodObjectKind::String,
617                        ZigType::NamedStruct(name) => match name.as_str() {
618                            "Map" => MethodObjectKind::Map,
619                            "Set" => MethodObjectKind::Set,
620                            "Date" => MethodObjectKind::Date,
621                            other => {
622                                if self.class_names.contains(other) {
623                                    MethodObjectKind::Class(other.to_string())
624                                } else {
625                                    MethodObjectKind::Unknown
626                                }
627                            }
628                        },
629                        ZigType::JsAny | ZigType::Anytype => MethodObjectKind::JsAny,
630                        _ => MethodObjectKind::Unknown,
631                    }
632                } else {
633                    MethodObjectKind::Unknown
634                }
635            }
636            _ => MethodObjectKind::Unknown,
637        }
638    }
639
640    /// Check if a name refers to a closure instance.
641    pub(super) fn is_closure_instance(&self, name: &str) -> bool {
642        self.closure_mgr.closure_instances.contains(name)
643    }
644
645    /// Infer the return type of a host function.
646    /// Looks up the return type from `type_info.host_return_types`, which is
647    /// populated during the type inference pass. Falls back to `ZigType::JsAny`
648    /// if the function is not registered.
649    pub(super) fn infer_host_return_type(&self, host_name: &str) -> ZigType {
650        // The HashMap key includes the "host_" prefix (e.g. "host_add")
651        let full_name = format!("host_{}", host_name);
652        self.type_info
653            .host_return_types
654            .get(&full_name)
655            .cloned()
656            .unwrap_or(ZigType::JsAny)
657    }
658
659    /// Lower an await expression.
660    pub(super) fn lower_await(&mut self, ae: &AwaitExpression) -> crate::zigir::types::IrExpr {
661        let task_var = IrIdent::new(&self.name_mangler.next_name("_t"));
662        let block_label = format!("blk_{}", self.name_mangler.peek_count("_t"));
663
664        // Check if this is an async host function call
665        if let Expression::CallExpression(call) = &ae.argument {
666            let args: Vec<_> = call
667                .arguments
668                .iter()
669                .filter_map(|a| a.as_expression().map(|e| self.lower_expr(e)))
670                .collect();
671
672            // Host async: callee is an identifier found in async_host_fns
673            if let Expression::Identifier(id) = &call.callee {
674                let name = id.name.as_str();
675                if self.async_host_fns.contains(name) {
676                    return crate::zigir::types::IrExpr::Await(crate::zigir::types::IrAwaitExpr {
677                        task_var,
678                        callee: Box::new(crate::zigir::types::IrExpr::Ident(IrIdent::new(name))),
679                        args,
680                        is_host_async: true,
681                        block_label,
682                    });
683                }
684            }
685
686            // Regular async call (non-host)
687            let callee = self.lower_expr(&call.callee);
688            return crate::zigir::types::IrExpr::Await(crate::zigir::types::IrAwaitExpr {
689                task_var,
690                callee: Box::new(callee),
691                args,
692                is_host_async: false,
693                block_label,
694            });
695        }
696
697        // Non-call await (unusual but valid JS)
698        let argument = self.lower_expr(&ae.argument);
699        crate::zigir::types::IrExpr::Await(crate::zigir::types::IrAwaitExpr {
700            task_var,
701            callee: Box::new(argument),
702            args: vec![],
703            is_host_async: false,
704            block_label,
705        })
706    }
707
708    /// Lower a new expression.
709    pub(super) fn lower_new(&mut self, ne: &NewExpression) -> crate::zigir::types::IrExpr {
710        use crate::zigir::kinds::NewConstructor;
711
712        // Determine constructor kind from callee
713        let constructor = match &ne.callee {
714            Expression::Identifier(id) => match id.name.as_str() {
715                "Map" => NewConstructor::Map,
716                "Set" => NewConstructor::Set,
717                "Date" => {
718                    // Determine DateConstructorKind from arguments
719                    let kind = if ne.arguments.is_empty() {
720                        crate::zigir::kinds::DateConstructorKind::Now
721                    } else if ne.arguments.len() >= 2 {
722                        crate::zigir::kinds::DateConstructorKind::FromComponents
723                    } else if let Some(first_arg) = ne.arguments.first()
724                        && let Some(expr) = first_arg.as_expression()
725                    {
726                        // Detect if argument is a string literal
727                        let is_string = matches!(expr, Expression::StringLiteral(_));
728                        if is_string {
729                            crate::zigir::kinds::DateConstructorKind::FromString
730                        } else {
731                            crate::zigir::kinds::DateConstructorKind::FromMillis
732                        }
733                    } else {
734                        crate::zigir::kinds::DateConstructorKind::Now
735                    };
736                    NewConstructor::Date(kind)
737                }
738                "RegExp" => NewConstructor::RegExp,
739                "Int8Array" | "Uint8Array" | "Uint8ClampedArray" | "Int16Array" | "Uint16Array"
740                | "Int32Array" | "Uint32Array" | "Float32Array" | "Float64Array"
741                | "BigInt64Array" | "BigUint64Array" => {
742                    let kind = match id.name.as_str() {
743                        "Int8Array" => crate::zigir::kinds::TypedArrayKind::Int8Array,
744                        "Uint8Array" => crate::zigir::kinds::TypedArrayKind::Uint8Array,
745                        "Uint8ClampedArray" => {
746                            crate::zigir::kinds::TypedArrayKind::Uint8ClampedArray
747                        }
748                        "Int16Array" => crate::zigir::kinds::TypedArrayKind::Int16Array,
749                        "Uint16Array" => crate::zigir::kinds::TypedArrayKind::Uint16Array,
750                        "Int32Array" => crate::zigir::kinds::TypedArrayKind::Int32Array,
751                        "Uint32Array" => crate::zigir::kinds::TypedArrayKind::Uint32Array,
752                        "Float32Array" => crate::zigir::kinds::TypedArrayKind::Float32Array,
753                        "Float64Array" => crate::zigir::kinds::TypedArrayKind::Float64Array,
754                        "BigInt64Array" => crate::zigir::kinds::TypedArrayKind::BigInt64Array,
755                        "BigUint64Array" => crate::zigir::kinds::TypedArrayKind::BigUint64Array,
756                        _ => crate::zigir::kinds::TypedArrayKind::Float64Array,
757                    };
758                    NewConstructor::TypedArray(kind)
759                }
760                "Error" => NewConstructor::Error("Error".to_string()),
761                "TypeError" => NewConstructor::Error("TypeError".to_string()),
762                "RangeError" => NewConstructor::Error("RangeError".to_string()),
763                // Wrapper constructors — emit argument value directly (no wrapper object in Zig)
764                "String" => {
765                    return if let Some(first_arg) = ne.arguments.first()
766                        && let Some(expr) = first_arg.as_expression()
767                    {
768                        self.lower_expr(expr)
769                    } else {
770                        crate::zigir::types::IrExpr::StringLiteral("".to_string())
771                    };
772                }
773                "Number" => {
774                    return if let Some(first_arg) = ne.arguments.first()
775                        && let Some(expr) = first_arg.as_expression()
776                    {
777                        self.lower_expr(expr)
778                    } else {
779                        crate::zigir::types::IrExpr::IntLiteral(0)
780                    };
781                }
782                "Boolean" => {
783                    return if let Some(first_arg) = ne.arguments.first()
784                        && let Some(expr) = first_arg.as_expression()
785                    {
786                        self.lower_expr(expr)
787                    } else {
788                        crate::zigir::types::IrExpr::BoolLiteral(false)
789                    };
790                }
791                name if self.class_names.contains(name) => NewConstructor::Class(name.to_string()),
792                // Known-unsupported constructors → structured Unsupported (Emitter generates proper @compileError)
793                "ArrayBuffer" | "SharedArrayBuffer" | "Function" | "Promise" | "WeakMap"
794                | "WeakSet" | "DataView" => {
795                    NewConstructor::Unsupported(id.name.as_str().to_string())
796                }
797                other => {
798                    let span = oxc_span::GetSpan::span(ne);
799                    return self.compile_error_expr(
800                        span,
801                        format!("Unsupported NewExpression: new {}()", other),
802                    );
803                }
804            },
805            Expression::StaticMemberExpression(mem) => {
806                if let Expression::Identifier(id) = &mem.object {
807                    let obj_name = id.name.as_str();
808                    let method_name = mem.property.name.as_str();
809                    match obj_name {
810                        "Intl" => {
811                            let span = oxc_span::GetSpan::span(ne);
812                            return self.compile_error_expr(
813                                span,
814                                format!(
815                                    "Intl.{}() is not supported (use Zig/C library for internationalization)",
816                                    method_name
817                                ),
818                            );
819                        }
820                        _ => {
821                            let span = oxc_span::GetSpan::span(ne);
822                            return self.compile_error_expr(span, "Unsupported NewExpression");
823                        }
824                    }
825                } else {
826                    let span = oxc_span::GetSpan::span(ne);
827                    return self.compile_error_expr(span, "Unsupported NewExpression");
828                }
829            }
830            _ => {
831                let span = oxc_span::GetSpan::span(ne);
832                return self.compile_error_expr(span, "Unsupported NewExpression");
833            }
834        };
835
836        let args = self.lower_args(&ne.arguments);
837
838        let result_type = match &constructor {
839            NewConstructor::Map => ZigType::NamedStruct("Map".to_string()),
840            NewConstructor::Set => ZigType::NamedStruct("Set".to_string()),
841            NewConstructor::Date(_) => ZigType::NamedStruct("Date".to_string()),
842            NewConstructor::RegExp => ZigType::NamedStruct("JsRegExp".to_string()),
843            NewConstructor::TypedArray(_) => ZigType::NamedStruct("TypedArray".to_string()),
844            NewConstructor::Class(name) => ZigType::NamedStruct(name.clone()),
845            NewConstructor::Error(_) => ZigType::JsAny,
846            _ => ZigType::JsAny,
847        };
848
849        crate::zigir::types::IrExpr::New(crate::zigir::types::IrNewExpr {
850            constructor,
851            args,
852            result_type,
853        })
854    }
855
856    /// If the callee has a synthetic rest param (from `arguments` usage),
857    /// pack extra args beyond the declared param count into a `[]const JsAny` slice.
858    ///
859    /// For `function sum() { return arguments[0]; }` called as `sum(1, 2, 3)`:
860    /// - declared_count = 0 (no explicit params)
861    /// - All args [1, 2, 3] become rest → packed into `Spread(ArrayLiteral{ JsAny.from(1), ... })`
862    /// - Emitter renders: `sum(&[_]JsAny{ JsAny.from(1), JsAny.from(2), JsAny.from(3) })`
863    ///
864    /// If the callee already has a Spread arg (e.g., `sum(...arr)`), pass it as-is.
865    fn pack_rest_args_if_needed(
866        &self,
867        callee_name: &str,
868        args: Vec<crate::zigir::types::IrExpr>,
869    ) -> Vec<crate::zigir::types::IrExpr> {
870        use crate::zigir::types::{IrArrayLiteral, IrCallExpr, IrExpr};
871
872        if !self
873            .type_info
874            .functions_needing_synthetic_rest
875            .contains(callee_name)
876        {
877            return args;
878        }
879
880        // Account for async `io` param (injected by lower_fn_params, not in fn_param_types)
881        let is_async = self
882            .type_info
883            .is_async
884            .get(callee_name)
885            .copied()
886            .unwrap_or(false);
887        let declared_count = self
888            .type_info
889            .fn_param_types
890            .get(callee_name)
891            .map(|params| params.len())
892            .unwrap_or(0)
893            + if is_async { 1 } else { 0 };
894
895        if args.len() <= declared_count {
896            // No extra args — pass empty slice for rest param
897            let mut result = args;
898            result.push(IrExpr::Spread(Box::new(IrExpr::ArrayLiteral(
899                IrArrayLiteral {
900                    elements: vec![],
901                    spread_indices: vec![],
902                },
903            ))));
904            return result;
905        }
906
907        // Split into regular and rest args
908        let mut regular_args = args;
909        let rest_args = regular_args.split_off(declared_count);
910
911        // If rest_args is a single Spread, pass as-is (e.g., sum(...arr))
912        if rest_args.len() == 1 && matches!(rest_args[0], IrExpr::Spread(_)) {
913            regular_args.extend(rest_args);
914            return regular_args;
915        }
916
917        // Pack rest args into Spread(ArrayLiteral{ JsAny.from(arg), ... })
918        let rest_elements: Vec<IrExpr> = rest_args
919            .into_iter()
920            .map(|arg| {
921                IrExpr::Call(IrCallExpr {
922                    callee: Box::new(IrExpr::FieldAccess {
923                        object: Box::new(IrExpr::Ident(IrIdent::new("JsAny"))),
924                        field: "from".to_string(),
925                        field_kind: FieldKind::StructField,
926                    }),
927                    args: vec![arg],
928                    call_kind: CallKind::Direct,
929                })
930            })
931            .collect();
932
933        regular_args.push(IrExpr::Spread(Box::new(IrExpr::ArrayLiteral(
934            IrArrayLiteral {
935                elements: rest_elements,
936                spread_indices: vec![],
937            },
938        ))));
939        regular_args
940    }
941}