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                            _ => None,
38                        },
39                        "Map" if method_name == "groupBy" => Some(
40                            "Map.groupBy() is not supported (requires iterable grouping)".to_string(),
41                        ),
42                        _ => None,
43                    }
44                } else {
45                    None
46                }
47            }
48            Expression::Identifier(id) => match id.name.as_str() {
49                name @ "Atomics" | name @ "Reflect" => {
50                    Some(format!("{} is not supported in js2zig", name))
51                }
52                _ => None,
53            },
54            _ => None,
55        }
56    }
57
58    /// Lower a call expression.
59    ///
60    /// Routing priority:
61    /// 1. Builtin detection → `IrBuiltinCall`
62    /// 2. Closure / nested function call → `IrCall { call_kind: Closure }`
63    /// 3. Host function call → `IrHostCall`
64    /// 4. Direct user function → `IrCall { call_kind: Direct }`
65    /// 5. Method call → `IrCall { call_kind: Method { .. } }`
66    /// 6. IIFE / expression callee → `IrCall { call_kind: Closure }`
67    pub(super) fn lower_call(&mut self, ce: &CallExpression) -> crate::zigir::types::IrExpr {
68        use crate::zigir::types::IrExpr;
69
70        // ── Step 0: Check for unsupported global objects ──
71        if let Some(err_msg) = self.check_unsupported_call(ce) {
72            return self.compile_error_expr(ce.span, err_msg);
73        }
74
75        let args = self.lower_args(&ce.arguments);
76
77        // ── Step 1: Builtin detection ──
78        if let Some(builtin) = crate::native_builtins::detect_builtin_call(ce) {
79            // ── Step 1a: Array callback inlining ──
80            if let Some(inlined) = self.try_inline_array_callback(ce, &builtin) {
81                return inlined;
82            }
83
84            // ── Step 1b: Array non-callback method inlining ──
85            if let Some(inlined) = self.try_inline_array_method(ce, &builtin, &args) {
86                return inlined;
87            }
88
89            // ── Step 1c: eval() → compile error ──
90            if matches!(builtin, crate::native_builtins::BuiltinCall::Eval) {
91                return self.compile_error_expr(ce.span, "eval() is not supported (security risk, cannot dynamically execute at compile time)");
92            }
93
94            let (module, method, return_type) = builtin_call_to_ir(&builtin);
95
96            // JSON.parse can throw SyntaxError at runtime — mark function as can_throw
97            // so the emitter's `catch return error.JsThrow` is valid.
98            if matches!(builtin, crate::native_builtins::BuiltinCall::JsonParse) {
99                if let Some(ctx) = self.fn_ctx.as_mut() {
100                    ctx.has_catchable_error = true;
101                }
102            }
103            let obj_name = Self::extract_callee_object_name_static(&ce.callee);
104
105            // ── Fix string-variable methods misidentified as array ──
106            // detect_builtin_call only checks if the callee object is a StringLiteral,
107            // not if it's a variable of type string. Fix up the module/method here.
108            let (module, method, return_type) = if let Some(name) = &obj_name {
109                if let Some(var_type) = self.type_info.var_types.get(name.as_str()) {
110                    if matches!(var_type, ZigType::Str) && module == BuiltinModule::JsArray {
111                        match method.as_str() {
112                            "at" => (BuiltinModule::JsString, "at".into(), ZigType::Str),
113                            "indexOf" => (BuiltinModule::JsString, "indexOf".into(), ZigType::I64),
114                            "includes" => {
115                                (BuiltinModule::JsString, "includes".into(), ZigType::Bool)
116                            }
117                            "lastIndexOf" => {
118                                (BuiltinModule::JsString, "lastIndexOf".into(), ZigType::I64)
119                            }
120                            "slice" => (BuiltinModule::JsString, "slice".into(), ZigType::Str),
121                            _ => (module, method, return_type),
122                        }
123                    } else if let ZigType::NamedStruct(n) = var_type {
124                        if Self::is_typedarray_type(n) {
125                            let ta_mod = BuiltinModule::JsTypedArray;
126                            match method.as_str() {
127                                "set" => (ta_mod, "set".into(), ZigType::Void),
128                                "get" => (ta_mod, "get".into(), ZigType::I64),
129                                "fill" => (ta_mod, "fill".into(), ZigType::Void),
130                                "slice" => {
131                                    (ta_mod, "slice".into(), ZigType::NamedStruct(n.clone()))
132                                }
133                                "copyWithin" => (ta_mod, "copyWithin".into(), ZigType::Void),
134                                _ => (module, method, return_type),
135                            }
136                        } else {
137                            (module, method, return_type)
138                        }
139                    } else {
140                        (module, method, return_type)
141                    }
142                } else {
143                    (module, method, return_type)
144                }
145            } else {
146                (module, method, return_type)
147            };
148
149            // ── Extract regex metadata for match/matchAll/search ──
150            let regex_info = Self::extract_regex_info(ce, &builtin);
151
152            // ── Derive TypedArray type suffix for JsTypedArray calls ──
153            let ta_type_suffix = if module == BuiltinModule::JsTypedArray {
154                obj_name.as_ref().and_then(|name| {
155                    self.type_info.var_types.get(name.as_str()).and_then(|zt| {
156                        if let ZigType::NamedStruct(n) = zt {
157                            Self::typedarray_type_suffix(n).map(|s| s.to_string())
158                        } else {
159                            None
160                        }
161                    })
162                })
163            } else {
164                None
165            };
166
167            // ── Fix Object.keys/getOwnPropertyNames for struct-typed arguments ──
168            // Object.keys(obj) / Object.getOwnPropertyNames(obj) where obj is a Zig struct
169            // (not HashMap) needs a different runtime function (keysStruct /
170            // getOwnPropertyNamesStruct) that uses comptime reflection.
171            let method = if module == BuiltinModule::JsObject
172                && (method == "keys" || method == "getOwnPropertyNames")
173            {
174                if let Some(IrExpr::Ident(ident)) = args.first() {
175                    if let Some(var_type) = self.type_info.var_types.get(ident.zig_name.as_str()) {
176                        if matches!(var_type, ZigType::Struct(_)) {
177                            if method == "keys" {
178                                "keysStruct".into()
179                            } else {
180                                "getOwnPropertyNamesStruct".into()
181                            }
182                        } else {
183                            method
184                        }
185                    } else {
186                        method
187                    }
188                } else {
189                    method
190                }
191            } else {
192                method
193            };
194
195            // ── Handle complex receiver expressions (method chaining) ──
196            // When the receiver is a CallExpression (e.g., encodeURIComponent(str).replace(...)),
197            // extract_callee_object_name_static returns None. We lower the receiver expression
198            // and store it in obj_expr so the Emitter can inline it.
199            let mut inner_expr = if obj_name.is_none() {
200                if let Expression::StaticMemberExpression(sme) = &ce.callee {
201                    match &sme.object {
202                        // Complex receivers: lower the entire expression so the Emitter
203                        // can inline it (e.g., new Date(0).getFullYear()).
204                        Expression::CallExpression(_) | Expression::NewExpression(_) => {
205                            Some(self.lower_expr(&sme.object))
206                        }
207                        _ => None,
208                    }
209                } else {
210                    None
211                }
212            } else {
213                None
214            };
215
216            // ── Method chaining: re-attempt inline when inner expr is ArrayCallbackInline/ArrayMethodInline ──
217            // For `arr.filter(x => x > 1).map(x => x * 2)`, the inner `.filter()` was inlined
218            // as ArrayCallbackInline, but the outer `.map()` fell through because extract_callee_object_name_static
219            // returned None (receiver is a CallExpression, not an Identifier).
220            // We give it a second chance: use the inner inline's element type, generate a temp var name,
221            // and construct the outer inline directly.
222            if let Some(inner) = inner_expr.take() {
223                let chain_elem_type = match &inner {
224                    IrExpr::ArrayCallbackInline(cb) => Some(cb.elem_type.clone()),
225                    IrExpr::ArrayMethodInline(mm) => Some(mm.elem_type.clone()),
226                    _ => None,
227                };
228
229                if let Some(elem_type) = chain_elem_type {
230                    // Try to re-attempt callback inline with a synthetic obj_name
231                    if let Some(inlined) =
232                        self.try_inline_array_callback_with_chain(ce, &builtin, &elem_type, &inner)
233                    {
234                        return inlined;
235                    }
236
237                    // Try to re-attempt method inline with a synthetic obj_name
238                    if let Some(inlined) = self
239                        .try_inline_array_method_with_chain(ce, &builtin, &args, &elem_type, &inner)
240                    {
241                        return inlined;
242                    }
243
244                    // Both failed — fall through to BuiltinCall with obj_expr
245                    inner_expr = Some(inner);
246                } else {
247                    inner_expr = Some(inner);
248                }
249            }
250
251            let obj_expr = inner_expr.map(Box::new);
252
253            return IrExpr::BuiltinCall(crate::zigir::types::IrBuiltinCall {
254                module,
255                method,
256                obj_name,
257                obj_expr,
258                args,
259                return_type,
260                regex_info,
261                ta_type_suffix,
262            });
263        }
264
265        // ── Step 1.5: BigInt variable method interception ──
266        // `b.toString()` or `b.valueOf()` where `b` is a known BigInt variable.
267        // detect_builtin_call routes `.toString()` to DateToString by default.
268        // For BigInt-typed variables, we intercept here using type lookup.
269        if let Expression::StaticMemberExpression(sme) = &ce.callee
270            && let Expression::Identifier(id) = &sme.object
271        {
272            let var_name = id.name.as_str();
273            let var_type = self.type_info.var_types.get(var_name).cloned().or_else(|| {
274                self.fn_ctx
275                    .as_ref()
276                    .and_then(|ctx| ctx.fn_local_types.get(var_name).cloned())
277            });
278            if let Some(ZigType::BigInt) = var_type {
279                let method = sme.property.name.as_str();
280                match method {
281                    "toString" => {
282                        return IrExpr::BuiltinCall(crate::zigir::types::IrBuiltinCall {
283                            module: BuiltinModule::JsBigInt,
284                            method: "toString".into(),
285                            obj_name: Some(var_name.to_string()),
286                            obj_expr: None,
287                            args,
288                            return_type: ZigType::Str,
289                            regex_info: None,
290                            ta_type_suffix: None,
291                        });
292                    }
293                    "valueOf" => {
294                        return IrExpr::BuiltinCall(crate::zigir::types::IrBuiltinCall {
295                            module: BuiltinModule::JsBigInt,
296                            method: "valueOf".into(),
297                            obj_name: Some(var_name.to_string()),
298                            obj_expr: None,
299                            args,
300                            return_type: ZigType::BigInt,
301                            regex_info: None,
302                            ta_type_suffix: None,
303                        });
304                    }
305                    "toLocaleString" => {
306                        return IrExpr::BuiltinCall(crate::zigir::types::IrBuiltinCall {
307                            module: BuiltinModule::JsBigInt,
308                            method: "toLocaleString".into(),
309                            obj_name: Some(var_name.to_string()),
310                            obj_expr: None,
311                            args,
312                            return_type: ZigType::Str,
313                            regex_info: None,
314                            ta_type_suffix: None,
315                        });
316                    }
317                    _ => {} // other methods fall through
318                }
319            }
320        }
321
322        // ── Step 1.6: RegExp variable method interception ──
323        // `r.test(s)` or `r.exec(s)` where `r` is a known RegExp variable.
324        // detect_builtin_call only identifies RegExpTest/RegExpExec for RegExpLiteral receivers.
325        // For variable receivers, we intercept here using regexp_vars tracking.
326        if let Expression::StaticMemberExpression(sme) = &ce.callee
327            && let Expression::Identifier(id) = &sme.object
328        {
329            let var_name = id.name.as_str();
330            if let Some(ctx) = &self.fn_ctx
331                && ctx.regexp_vars.contains(var_name)
332            {
333                let method = sme.property.name.as_str();
334                match method {
335                    "test" => {
336                        return IrExpr::BuiltinCall(crate::zigir::types::IrBuiltinCall {
337                            module: BuiltinModule::JsRegExp,
338                            method: "test".into(),
339                            obj_name: Some(var_name.to_string()),
340                            obj_expr: None,
341                            args,
342                            return_type: ZigType::Bool,
343                            regex_info: Some(crate::zigir::types::IrRegexInfo {
344                                pattern: None,
345                                has_global: false,
346                                is_var_ref: true,
347                                var_name: Some(var_name.to_string()),
348                            }),
349                            ta_type_suffix: None,
350                        });
351                    }
352                    "exec" => {
353                        return IrExpr::BuiltinCall(crate::zigir::types::IrBuiltinCall {
354                            module: BuiltinModule::JsRegExp,
355                            method: "exec".into(),
356                            obj_name: Some(var_name.to_string()),
357                            obj_expr: None,
358                            args,
359                            return_type: ZigType::JsAny,
360                            regex_info: Some(crate::zigir::types::IrRegexInfo {
361                                pattern: None,
362                                has_global: false,
363                                is_var_ref: true,
364                                var_name: Some(var_name.to_string()),
365                            }),
366                            ta_type_suffix: None,
367                        });
368                    }
369                    _ => {} // other methods fall through
370                }
371            }
372        }
373
374        // ── Step 2: Identify callee pattern ──
375        match &ce.callee {
376            // Identifier callee: direct function call, host call, or closure
377            Expression::Identifier(id) => {
378                let name = id.name.as_str();
379
380                // Host function call: starts with "host_"
381                if let Some(host_name) = name.strip_prefix("host_") {
382                    let is_async = self.async_host_fns.contains(name);
383                    let return_type = self.infer_host_return_type(host_name);
384                    return IrExpr::HostCall(crate::zigir::types::IrHostCall {
385                        name: host_name.to_string(),
386                        args,
387                        return_type,
388                        is_async,
389                    });
390                }
391
392                // Closure / nested function call
393                if self
394                    .closure_mgr
395                    .current_captured
396                    .iter()
397                    .any(|(n, _, _)| n.as_str() == name)
398                    || self.is_closure_instance(name)
399                {
400                    return IrExpr::Call(crate::zigir::types::IrCallExpr {
401                        callee: Box::new(IrExpr::Ident(IrIdent::new(name))),
402                        args,
403                        call_kind: CallKind::Closure,
404                    });
405                }
406
407                // Nested function call: rewrite to name.call(args)
408                if let Some(ctx) = &self.fn_ctx
409                    && ctx.is_nested_fn(name)
410                {
411                    let callee_ident = self.make_ident(name);
412                    return IrExpr::Call(crate::zigir::types::IrCallExpr {
413                        callee: Box::new(IrExpr::Ident(callee_ident)),
414                        args,
415                        call_kind: CallKind::Closure,
416                    });
417                }
418
419                // Direct user function call
420                IrExpr::Call(crate::zigir::types::IrCallExpr {
421                    callee: Box::new(IrExpr::Ident(IrIdent::new(name))),
422                    args,
423                    call_kind: CallKind::Direct,
424                })
425            }
426
427            // Static member expression callee: obj.method()
428            Expression::StaticMemberExpression(mem) => {
429                let method_name = mem.property.name.as_str();
430                let obj_expr = self.lower_expr(&mem.object);
431
432                // Determine method object type for CallKind::Method
433                let object_type = self.infer_method_object_kind(&mem.object);
434
435                IrExpr::Call(crate::zigir::types::IrCallExpr {
436                    callee: Box::new(IrExpr::FieldAccess {
437                        object: Box::new(obj_expr),
438                        field: method_name.to_string(),
439                        field_kind: FieldKind::StructField,
440                    }),
441                    args,
442                    call_kind: CallKind::Method { object_type },
443                })
444            }
445
446            // Function expression / arrow function callee (IIFE)
447            Expression::FunctionExpression(_) | Expression::ArrowFunctionExpression(_) => {
448                // IIFE: emit the function then call it
449                let callee = self.lower_expr(&ce.callee);
450                IrExpr::Call(crate::zigir::types::IrCallExpr {
451                    callee: Box::new(callee),
452                    args,
453                    call_kind: CallKind::Closure,
454                })
455            }
456
457            // Parenthesized expression containing function
458            Expression::ParenthesizedExpression(_) => {
459                let callee = self.lower_expr(&ce.callee);
460                IrExpr::Call(crate::zigir::types::IrCallExpr {
461                    callee: Box::new(callee),
462                    args,
463                    call_kind: CallKind::Closure,
464                })
465            }
466
467            // Any other callee type (computed member, etc.)
468            _ => {
469                let callee = self.lower_expr(&ce.callee);
470                IrExpr::Call(crate::zigir::types::IrCallExpr {
471                    callee: Box::new(callee),
472                    args,
473                    call_kind: CallKind::Direct,
474                })
475            }
476        }
477    }
478
479    /// Determine the MethodObjectKind for a method call's receiver object.
480    pub(super) fn infer_method_object_kind(
481        &self,
482        obj: &Expression,
483    ) -> crate::zigir::kinds::MethodObjectKind {
484        use crate::zigir::kinds::MethodObjectKind;
485
486        match obj {
487            Expression::Identifier(id) => {
488                if let Some(zig_type) = self.type_info.var_types.get(id.name.as_str()) {
489                    match zig_type {
490                        ZigType::ArrayList(_) => MethodObjectKind::ArrayList,
491                        ZigType::Str => MethodObjectKind::String,
492                        ZigType::NamedStruct(name) => match name.as_str() {
493                            "Map" => MethodObjectKind::Map,
494                            "Set" => MethodObjectKind::Set,
495                            "Date" | "JsDate" => MethodObjectKind::Date,
496                            other => {
497                                if self.class_names.contains(other) {
498                                    MethodObjectKind::Class(other.to_string())
499                                } else {
500                                    MethodObjectKind::Unknown
501                                }
502                            }
503                        },
504                        ZigType::JsAny | ZigType::Anytype => MethodObjectKind::JsAny,
505                        _ => MethodObjectKind::Unknown,
506                    }
507                } else {
508                    MethodObjectKind::Unknown
509                }
510            }
511            _ => MethodObjectKind::Unknown,
512        }
513    }
514
515    /// Check if a name refers to a closure instance.
516    pub(super) fn is_closure_instance(&self, name: &str) -> bool {
517        self.closure_mgr.closure_instances.contains(name)
518    }
519
520    /// Infer the return type of a host function.
521    /// Looks up the return type from `type_info.host_return_types`, which is
522    /// populated during the type inference pass. Falls back to `ZigType::JsAny`
523    /// if the function is not registered.
524    pub(super) fn infer_host_return_type(&self, host_name: &str) -> ZigType {
525        // The HashMap key includes the "host_" prefix (e.g. "host_add")
526        let full_name = format!("host_{}", host_name);
527        self.type_info
528            .host_return_types
529            .get(&full_name)
530            .cloned()
531            .unwrap_or(ZigType::JsAny)
532    }
533
534    /// Lower an await expression.
535    pub(super) fn lower_await(&mut self, ae: &AwaitExpression) -> crate::zigir::types::IrExpr {
536        let task_var = IrIdent::new(&self.name_mangler.next_name("_t"));
537        let block_label = format!("blk_{}", self.name_mangler.peek_count("_t"));
538
539        // Check if this is an async host function call
540        if let Expression::CallExpression(call) = &ae.argument {
541            let args: Vec<_> = call
542                .arguments
543                .iter()
544                .filter_map(|a| a.as_expression().map(|e| self.lower_expr(e)))
545                .collect();
546
547            // Host async: callee is an identifier found in async_host_fns
548            if let Expression::Identifier(id) = &call.callee {
549                let name = id.name.as_str();
550                if self.async_host_fns.contains(name) {
551                    return crate::zigir::types::IrExpr::Await(crate::zigir::types::IrAwaitExpr {
552                        task_var,
553                        callee: Box::new(crate::zigir::types::IrExpr::Ident(IrIdent::new(name))),
554                        args,
555                        is_host_async: true,
556                        block_label,
557                    });
558                }
559            }
560
561            // Regular async call (non-host)
562            let callee = self.lower_expr(&call.callee);
563            return crate::zigir::types::IrExpr::Await(crate::zigir::types::IrAwaitExpr {
564                task_var,
565                callee: Box::new(callee),
566                args,
567                is_host_async: false,
568                block_label,
569            });
570        }
571
572        // Non-call await (unusual but valid JS)
573        let argument = self.lower_expr(&ae.argument);
574        crate::zigir::types::IrExpr::Await(crate::zigir::types::IrAwaitExpr {
575            task_var,
576            callee: Box::new(argument),
577            args: vec![],
578            is_host_async: false,
579            block_label,
580        })
581    }
582
583    /// Lower a new expression.
584    pub(super) fn lower_new(&mut self, ne: &NewExpression) -> crate::zigir::types::IrExpr {
585        use crate::zigir::kinds::NewConstructor;
586
587        // Determine constructor kind from callee
588        let constructor = match &ne.callee {
589            Expression::Identifier(id) => match id.name.as_str() {
590                "Map" => NewConstructor::Map,
591                "Set" => NewConstructor::Set,
592                "Date" => {
593                    // Determine DateConstructorKind from arguments
594                    let kind = if ne.arguments.is_empty() {
595                        crate::zigir::kinds::DateConstructorKind::Now
596                    } else if ne.arguments.len() >= 2 {
597                        crate::zigir::kinds::DateConstructorKind::FromComponents
598                    } else if let Some(first_arg) = ne.arguments.first()
599                        && let Some(expr) = first_arg.as_expression()
600                    {
601                        // Detect if argument is a string literal
602                        let is_string = matches!(expr, Expression::StringLiteral(_));
603                        if is_string {
604                            crate::zigir::kinds::DateConstructorKind::FromString
605                        } else {
606                            crate::zigir::kinds::DateConstructorKind::FromMillis
607                        }
608                    } else {
609                        crate::zigir::kinds::DateConstructorKind::Now
610                    };
611                    NewConstructor::Date(kind)
612                }
613                "RegExp" => NewConstructor::RegExp,
614                "Int8Array" | "Uint8Array" | "Uint8ClampedArray" | "Int16Array" | "Uint16Array"
615                | "Int32Array" | "Uint32Array" | "Float32Array" | "Float64Array"
616                | "BigInt64Array" | "BigUint64Array" => {
617                    let kind = match id.name.as_str() {
618                        "Int8Array" => crate::zigir::kinds::TypedArrayKind::Int8Array,
619                        "Uint8Array" => crate::zigir::kinds::TypedArrayKind::Uint8Array,
620                        "Uint8ClampedArray" => {
621                            crate::zigir::kinds::TypedArrayKind::Uint8ClampedArray
622                        }
623                        "Int16Array" => crate::zigir::kinds::TypedArrayKind::Int16Array,
624                        "Uint16Array" => crate::zigir::kinds::TypedArrayKind::Uint16Array,
625                        "Int32Array" => crate::zigir::kinds::TypedArrayKind::Int32Array,
626                        "Uint32Array" => crate::zigir::kinds::TypedArrayKind::Uint32Array,
627                        "Float32Array" => crate::zigir::kinds::TypedArrayKind::Float32Array,
628                        "Float64Array" => crate::zigir::kinds::TypedArrayKind::Float64Array,
629                        "BigInt64Array" => crate::zigir::kinds::TypedArrayKind::BigInt64Array,
630                        "BigUint64Array" => crate::zigir::kinds::TypedArrayKind::BigUint64Array,
631                        _ => crate::zigir::kinds::TypedArrayKind::Float64Array,
632                    };
633                    NewConstructor::TypedArray(kind)
634                }
635                "Error" => NewConstructor::Error("Error".to_string()),
636                "TypeError" => NewConstructor::Error("TypeError".to_string()),
637                "RangeError" => NewConstructor::Error("RangeError".to_string()),
638                // Wrapper constructors — emit argument value directly (no wrapper object in Zig)
639                "String" => {
640                    return if let Some(first_arg) = ne.arguments.first()
641                        && let Some(expr) = first_arg.as_expression()
642                    {
643                        self.lower_expr(expr)
644                    } else {
645                        crate::zigir::types::IrExpr::StringLiteral("".to_string())
646                    };
647                }
648                "Number" => {
649                    return if let Some(first_arg) = ne.arguments.first()
650                        && let Some(expr) = first_arg.as_expression()
651                    {
652                        self.lower_expr(expr)
653                    } else {
654                        crate::zigir::types::IrExpr::IntLiteral(0)
655                    };
656                }
657                "Boolean" => {
658                    return if let Some(first_arg) = ne.arguments.first()
659                        && let Some(expr) = first_arg.as_expression()
660                    {
661                        self.lower_expr(expr)
662                    } else {
663                        crate::zigir::types::IrExpr::BoolLiteral(false)
664                    };
665                }
666                name if self.class_names.contains(name) => NewConstructor::Class(name.to_string()),
667                // Known-unsupported constructors → structured Unsupported (Emitter generates proper @compileError)
668                "ArrayBuffer" | "SharedArrayBuffer" | "Function" | "Promise" | "WeakMap"
669                | "WeakSet" | "DataView" => {
670                    NewConstructor::Unsupported(id.name.as_str().to_string())
671                }
672                other => {
673                    let span = oxc_span::GetSpan::span(ne);
674                    return self.compile_error_expr(
675                        span,
676                        format!("Unsupported NewExpression: new {}()", other),
677                    );
678                }
679            },
680            _ => {
681                let span = oxc_span::GetSpan::span(ne);
682                return self.compile_error_expr(span, "Unsupported NewExpression");
683            }
684        };
685
686        let args = self.lower_args(&ne.arguments);
687
688        let result_type = match &constructor {
689            NewConstructor::Map => ZigType::NamedStruct("Map".to_string()),
690            NewConstructor::Set => ZigType::NamedStruct("Set".to_string()),
691            NewConstructor::Date(_) => ZigType::NamedStruct("JsDate".to_string()),
692            NewConstructor::RegExp => ZigType::JsAny,
693            NewConstructor::TypedArray(_) => ZigType::NamedStruct("TypedArray".to_string()),
694            NewConstructor::Class(name) => ZigType::NamedStruct(name.clone()),
695            NewConstructor::Error(_) => ZigType::JsAny,
696            _ => ZigType::JsAny,
697        };
698
699        crate::zigir::types::IrExpr::New(crate::zigir::types::IrNewExpr {
700            constructor,
701            args,
702            result_type,
703        })
704    }
705}