Skip to main content

js2zig_core/zigir/lower/
cabi.rs

1// zigir/lower/cabi.rs
2// C ABI export metadata and utility/query methods.
3
4use oxc_ast::ast::*;
5
6use crate::types::ZigType;
7use crate::zigir::builtins::BuiltinModule;
8use crate::zigir::ident::IrIdent;
9use crate::zigir::source_span::{DiagnosticLevel, IrDiagnostic, SourceSpan};
10use crate::zigir::types::{IrCabiExport, IrDecl, IrExpr, IrParam};
11
12use super::Lowerer;
13use super::helpers::FnContext;
14
15// �T�T�T�T�T�T�T�T�T�T�T�T�T�T�T�T�T�T�T�T�T�T�T�T�T�T�T�T�T�T�T�T�T�T�T�T�T�T�T�T�T�T�T�T�T�T�T�T�T�T�T�T�T�T�T
16//  CABI export metadata
17// �T�T�T�T�T�T�T�T�T�T�T�T�T�T�T�T�T�T�T�T�T�T�T�T�T�T�T�T�T�T�T�T�T�T�T�T�T�T�T�T�T�T�T�T�T�T�T�T�T�T�T�T�T�T�T
18
19impl Lowerer {
20    /// Build C ABI export metadata from the lowered declarations.
21    ///
22    /// Corresponds to the cabi_exports construction in old
23    /// `native_proto::transpile_js_inner()`.
24    pub(super) fn build_cabi_exports(&self, declarations: &[IrDecl]) -> Vec<IrCabiExport> {
25        let mut exports = Vec::new();
26        for decl in declarations {
27            if let IrDecl::Fn(f) = decl
28                && f.is_export
29            {
30                // Keep all params including Anytype — pipeline will detect them
31                // and route to emit_const_alias instead of C ABI wrapper.
32                let params: Vec<IrParam> = f
33                    .params
34                    .iter()
35                    .map(|p| IrParam {
36                        name: p.name.clone(),
37                        zig_type: p.zig_type.clone(),
38                        is_unused: p.is_unused,
39                        is_rest: false,
40                    })
41                    .collect();
42                let ret_struct_name = if let ZigType::NamedStruct(ref s) = f.return_type {
43                    Some(s.clone())
44                } else {
45                    None
46                };
47                exports.push(IrCabiExport {
48                    name: f.name.zig_name.clone(),
49                    params,
50                    return_type: f.return_type.clone(),
51                    is_async: f.is_async,
52                    can_throw: f.can_throw,
53                    ret_struct_name,
54                });
55            }
56        }
57        exports
58    }
59}
60
61// ── Utility methods ──
62
63type CallbackInlineParts = (
64    crate::zigir::types::ArrayCallbackKind,
65    String,
66    bool,
67    String,
68    Vec<crate::zigir::types::IrStmt>,
69    Option<IrExpr>,
70);
71
72impl Lowerer {
73    /// Check whether a function name is in the exported set.
74    pub(super) fn is_export_fn(&self, fn_name: Option<&str>) -> bool {
75        if let Some(ref exported) = self.exported_functions {
76            fn_name.is_some_and(|name| exported.contains(name))
77        } else {
78            false
79        }
80    }
81
82    /// Convert a `Span` to an `IrDiagnostic` with source location.
83    pub(super) fn span_to_source_span(&self, span: Span) -> SourceSpan {
84        let offset = span.start as usize;
85        let mut line: usize = 1;
86        let mut col: usize = 1;
87        for (i, ch) in self.source.char_indices() {
88            if i >= offset {
89                break;
90            }
91            if ch == '\n' {
92                line += 1;
93                col = 1;
94            } else {
95                col += 1;
96            }
97        }
98        SourceSpan {
99            js_line: line,
100            js_col: col,
101            js_file: String::new(),
102        }
103    }
104
105    /// Add an error diagnostic.
106    pub(super) fn add_error(&mut self, span: SourceSpan, msg: impl Into<String>) {
107        self.diagnostics.push(IrDiagnostic {
108            level: DiagnosticLevel::Error,
109            span: Some(span),
110            message: msg.into(),
111        });
112    }
113
114    /// Build an IrExpr::CompileError from a Span and message.
115    /// Convenience wrapper that converts Span → SourceSpan automatically.
116    pub(super) fn compile_error_expr(&self, span: Span, msg: impl Into<String>) -> IrExpr {
117        IrExpr::CompileError {
118            span: self.span_to_source_span(span),
119            msg: msg.into(),
120        }
121    }
122
123    /// Create an IrIdent for the given JS name, applying shadow renaming.
124    pub(super) fn make_ident(&self, js_name: &str) -> IrIdent {
125        self.name_mangler.make_ident(js_name)
126    }
127
128    /// Build IrCapture list from raw capture tuples (name, zig_type, is_mut).
129    /// Shared by closure.rs, decl.rs, and function.rs.
130    /// When name is "__self", sets init_expr to "self" so the emitter
131    /// generates `.__self = &self` instead of `.__self = &__self`.
132    pub(super) fn make_ir_captures(
133        &self,
134        captures: Vec<(String, ZigType, bool)>,
135    ) -> Vec<crate::zigir::types::IrCapture> {
136        captures
137            .into_iter()
138            .map(|(name, zig_type, is_mut)| crate::zigir::types::IrCapture {
139                name: self.make_ident(&name),
140                zig_type,
141                is_mut,
142                init_expr: if name == "__self" {
143                    Some("self".to_string())
144                } else {
145                    None
146                },
147            })
148            .collect()
149    }
150
151    /// Detect nested closure capture: returns the names of captured variables
152    /// that are fields on the enclosing closure (i.e. in `current_captured`).
153    pub(super) fn detect_nested_captures(
154        &self,
155        captures: &[(String, ZigType, bool)],
156    ) -> Vec<String> {
157        captures
158            .iter()
159            .filter(|(name, _, _)| {
160                self.closure_mgr
161                    .current_captured
162                    .iter()
163                    .any(|(n, _, _)| n == name)
164            })
165            .map(|(name, _, _)| name.clone())
166            .collect()
167    }
168
169    pub(super) fn lower_args<'a>(
170        &mut self,
171        args: &oxc_allocator::Vec<'a, Argument<'a>>,
172    ) -> Vec<IrExpr> {
173        args.iter()
174            .map(|arg| match arg {
175                Argument::SpreadElement(se) => {
176                    IrExpr::Spread(Box::new(self.lower_expr(&se.argument)))
177                }
178                _ => {
179                    let expr = arg
180                        .as_expression()
181                        .expect("non-SpreadElement Argument is always an Expression");
182                    self.lower_expr(expr)
183                }
184            })
185            .collect()
186    }
187
188    /// Try to inline an array non-callback method (includes, indexOf, lastIndexOf,
189    /// join, slice, splice, at, concat, copyWithin, fill) when we have the
190    /// object variable name. Returns `IrExpr::ArrayMethodInline` if inlinable.
191    pub(super) fn try_inline_array_method(
192        &self,
193        ce: &CallExpression,
194        builtin: &crate::native_builtins::BuiltinCall,
195        args: &[IrExpr],
196    ) -> Option<IrExpr> {
197        use crate::zigir::types::{IrArrayMethodInline, IrExpr};
198
199        // Never inline array methods for string variables — these should go through
200        // BuiltinCall (JsString) instead. Check variable type from TypeInfo.
201        let obj_name_raw = Self::extract_callee_object_name_static(&ce.callee);
202        if let Some(name) = &obj_name_raw
203            && let Some(var_type) = self.type_info.var_types.get(name.as_str())
204        {
205            if matches!(var_type, ZigType::Str) {
206                return None;
207            }
208            if let ZigType::NamedStruct(n) = var_type
209                && Self::is_typedarray_type(n)
210            {
211                return None;
212            }
213        }
214        let obj_name = obj_name_raw?;
215
216        let kind = Self::resolve_method_kind(builtin)?;
217
218        let elem_type = self
219            .type_info
220            .array_element_types
221            .get(obj_name.as_str())
222            .cloned()
223            .unwrap_or(ZigType::JsAny);
224
225        Some(IrExpr::ArrayMethodInline(Box::new(IrArrayMethodInline {
226            kind,
227            obj_name,
228            obj_expr: None,
229            elem_type,
230            args: args.to_vec(),
231        })))
232    }
233
234    /// Shared logic: resolve callback kind from BuiltinCall.
235    fn resolve_callback_kind(
236        builtin: &crate::native_builtins::BuiltinCall,
237    ) -> Option<crate::zigir::types::ArrayCallbackKind> {
238        use crate::native_builtins::BuiltinCall as BC;
239        use crate::zigir::types::ArrayCallbackKind;
240        match builtin {
241            BC::ArrayForEach => Some(ArrayCallbackKind::ForEach),
242            BC::ArraySome => Some(ArrayCallbackKind::Some),
243            BC::ArrayEvery => Some(ArrayCallbackKind::Every),
244            BC::ArrayFilter => Some(ArrayCallbackKind::Filter),
245            BC::ArrayFind => Some(ArrayCallbackKind::Find),
246            BC::ArrayFindIndex => Some(ArrayCallbackKind::FindIndex),
247            BC::ArrayFindLast => Some(ArrayCallbackKind::FindLast),
248            BC::ArrayFindLastIndex => Some(ArrayCallbackKind::FindLastIndex),
249            BC::ArrayMap => Some(ArrayCallbackKind::Map),
250            BC::ArrayReduce => Some(ArrayCallbackKind::Reduce),
251            BC::ArrayReduceRight => Some(ArrayCallbackKind::ReduceRight),
252            BC::ArraySort => Some(ArrayCallbackKind::Sort),
253            BC::ArrayToSorted => Some(ArrayCallbackKind::ToSorted),
254            BC::ArrayFlatMap => Some(ArrayCallbackKind::FlatMap),
255            _ => None,
256        }
257    }
258
259    /// Shared logic: resolve method kind from BuiltinCall.
260    fn resolve_method_kind(
261        builtin: &crate::native_builtins::BuiltinCall,
262    ) -> Option<crate::zigir::types::ArrayMethodKind> {
263        use crate::native_builtins::BuiltinCall as BC;
264        use crate::zigir::types::ArrayMethodKind;
265        match builtin {
266            BC::ArrayIncludes => Some(ArrayMethodKind::Includes),
267            BC::ArrayIndexOf => Some(ArrayMethodKind::IndexOf),
268            BC::ArrayLastIndexOf => Some(ArrayMethodKind::LastIndexOf),
269            BC::ArrayJoin => Some(ArrayMethodKind::Join),
270            BC::ArraySlice => Some(ArrayMethodKind::Slice),
271            BC::ArraySplice => Some(ArrayMethodKind::Splice),
272            BC::ArrayAt => Some(ArrayMethodKind::At),
273            BC::ArrayConcat => Some(ArrayMethodKind::Concat),
274            BC::ArrayCopyWithin => Some(ArrayMethodKind::CopyWithin),
275            BC::ArrayFill => Some(ArrayMethodKind::Fill),
276            BC::ArrayWith => Some(ArrayMethodKind::With),
277            BC::ArrayToReversed => Some(ArrayMethodKind::ToReversed),
278            BC::ArrayToSorted => Some(ArrayMethodKind::ToSorted),
279            BC::ArrayToSpliced => Some(ArrayMethodKind::ToSpliced),
280            _ => None,
281        }
282    }
283
284    /// Shared logic: parse callback parameters and lower the body from a CallExpression.
285    /// Returns (kind, elem_param, has_idx_param, idx_param, ir_body, reduce_init) or None.
286    ///
287    /// `elem_type` and `collection_kind` are used to set `var_types` for the callback
288    /// parameters BEFORE lowering the body, so binary expressions in the body have
289    /// correct type info (e.g., Map/Set forEach params are JsAny).
290    fn parse_callback_inline(
291        &mut self,
292        ce: &CallExpression,
293        kind: crate::zigir::types::ArrayCallbackKind,
294        elem_type: &ZigType,
295        collection_kind: crate::zigir::types::CollectionKind,
296    ) -> Option<CallbackInlineParts> {
297        use crate::zigir::types::ArrayCallbackKind;
298
299        let first_arg = ce.arguments.first()?.as_expression()?;
300
301        let (params, body) = match first_arg {
302            Expression::ArrowFunctionExpression(arrow) => (&arrow.params, &arrow.body),
303            Expression::FunctionExpression(f) => match &f.body {
304                Some(b) => (&f.params, b),
305                None => return None,
306            },
307            _ => return None,
308        };
309
310        let elem_param_raw = params
311            .items
312            .first()
313            .and_then(|p| crate::infer::binding_name(&p.pattern))
314            .unwrap_or("_")
315            .to_string();
316        let idx_param_raw = params
317            .items
318            .get(1)
319            .and_then(|p| crate::infer::binding_name(&p.pattern));
320        let has_idx_param = idx_param_raw.is_some();
321
322        // Set var_types for callback params BEFORE lowering the body.
323        // This ensures binary expressions in the body have correct type info.
324        // - elem param: uses the inferred element type (JsAny for Map/Set)
325        // - idx param: JsAny for Map (key), I64 for Array (numeric index)
326        if elem_param_raw != "_" {
327            self.type_info
328                .var_types
329                .insert(elem_param_raw.clone(), elem_type.clone());
330        }
331        if let Some(idx_name) = idx_param_raw
332            && idx_name != "_"
333        {
334            let idx_type = match collection_kind {
335                crate::zigir::types::CollectionKind::Map => ZigType::JsAny,
336                _ => ZigType::I64,
337            };
338            self.type_info
339                .var_types
340                .insert(idx_name.to_string(), idx_type);
341        }
342
343        // Check if parameters are actually used in the callback body.
344        let elem_used = body
345            .statements
346            .iter()
347            .any(|s| Self::ast_stmt_uses_ident(&elem_param_raw, s));
348        let elem_param = if elem_used {
349            elem_param_raw
350        } else {
351            "_".to_string()
352        };
353
354        let idx_param = if let Some(idx_name) = idx_param_raw {
355            if idx_name != "_"
356                && body
357                    .statements
358                    .iter()
359                    .any(|s| Self::ast_stmt_uses_ident(idx_name, s))
360            {
361                idx_name.to_string()
362            } else {
363                "_".to_string()
364            }
365        } else {
366            String::new()
367        };
368
369        // Lower the callback body
370        let ir_body: Vec<crate::zigir::types::IrStmt> =
371            body.statements.iter().map(|s| self.lower_stmt(s)).collect();
372
373        // Reduce init value
374        let reduce_init = if matches!(
375            kind,
376            ArrayCallbackKind::Reduce | ArrayCallbackKind::ReduceRight
377        ) && ce.arguments.len() >= 2
378        {
379            ce.arguments
380                .get(1)
381                .and_then(|a| a.as_expression())
382                .map(|e| self.lower_expr(e))
383        } else {
384            None
385        };
386
387        Some((
388            kind,
389            elem_param,
390            has_idx_param,
391            idx_param,
392            ir_body,
393            reduce_init,
394        ))
395    }
396
397    /// Try to inline an array callback method (forEach, some, every, filter, find,
398    /// findIndex, findLast, findLastIndex, map, reduce) when the first argument
399    /// is an ArrowFunctionExpression or FunctionExpression.
400    ///
401    /// Returns `IrExpr::ArrayCallbackInline` if inlinable, `None` otherwise.
402    pub(super) fn try_inline_array_callback(
403        &mut self,
404        ce: &CallExpression,
405        builtin: &crate::native_builtins::BuiltinCall,
406    ) -> Option<IrExpr> {
407        use crate::zigir::types::{IrArrayCallbackInline, IrExpr};
408
409        let kind = Self::resolve_callback_kind(builtin)?;
410
411        // Determine obj_name, elem_type, and collection_kind BEFORE parsing the
412        // callback body, so var_types can be set for the callback params.
413        let obj_name = self.extract_callee_object_name(ce)?;
414        let elem_type = self
415            .type_info
416            .array_element_types
417            .get(obj_name.as_str())
418            .cloned()
419            .unwrap_or(ZigType::JsAny);
420
421        // Determine collection kind based on variable type
422        let collection_kind = self
423            .type_info
424            .var_types
425            .get(obj_name.as_str())
426            .map(|t| {
427                if matches!(t, ZigType::NamedStruct(s) if s == "Map") {
428                    crate::zigir::types::CollectionKind::Map
429                } else if matches!(t, ZigType::NamedStruct(s) if s == "Set") {
430                    crate::zigir::types::CollectionKind::Set
431                } else {
432                    crate::zigir::types::CollectionKind::Array
433                }
434            })
435            .unwrap_or(crate::zigir::types::CollectionKind::Array);
436
437        let (kind, elem_param, has_idx_param, idx_param, ir_body, reduce_init) =
438            self.parse_callback_inline(ce, kind, &elem_type, collection_kind.clone())?;
439
440        Some(IrExpr::ArrayCallbackInline(Box::new(
441            IrArrayCallbackInline {
442                kind,
443                collection_kind,
444                obj_name,
445                obj_expr: None,
446                elem_type,
447                elem_param,
448                has_idx_param,
449                idx_param,
450                body: ir_body,
451                reduce_init,
452            },
453        )))
454    }
455
456    /// Try to inline an array callback method when the receiver is a chained expression
457    /// (e.g., `arr.filter(x => x > 1).map(x => x * 2)`). The inner expression has already
458    /// been lowered (typically to `ArrayCallbackInline` or `ArrayMethodInline`), and we know
459    /// its element type. We construct the outer callback inline with a synthetic `obj_name`
460    /// (a temp var placeholder) and store the inner expression in `obj_expr` so the emitter
461    /// can render it inline.
462    pub(super) fn try_inline_array_callback_with_chain(
463        &mut self,
464        ce: &CallExpression,
465        builtin: &crate::native_builtins::BuiltinCall,
466        elem_type: &ZigType,
467        inner_expr: &IrExpr,
468    ) -> Option<IrExpr> {
469        use crate::zigir::types::{IrArrayCallbackInline, IrExpr};
470
471        let kind = Self::resolve_callback_kind(builtin)?;
472        let (kind, elem_param, has_idx_param, idx_param, ir_body, reduce_init) = self
473            .parse_callback_inline(
474                ce,
475                kind,
476                elem_type,
477                crate::zigir::types::CollectionKind::Array,
478            )?;
479
480        let chain_obj_name = self.name_mangler.next_name("__chain");
481
482        Some(IrExpr::ArrayCallbackInline(Box::new(
483            IrArrayCallbackInline {
484                kind,
485                collection_kind: crate::zigir::types::CollectionKind::Array,
486                obj_name: chain_obj_name,
487                obj_expr: Some(Box::new(inner_expr.clone())),
488                elem_type: elem_type.clone(),
489                elem_param,
490                has_idx_param,
491                idx_param,
492                body: ir_body,
493                reduce_init,
494            },
495        )))
496    }
497
498    /// Try to inline an array non-callback method when the receiver is a chained expression.
499    /// Similar to `try_inline_array_callback_with_chain` but for methods like join, slice, etc.
500    pub(super) fn try_inline_array_method_with_chain(
501        &mut self,
502        _ce: &CallExpression,
503        builtin: &crate::native_builtins::BuiltinCall,
504        args: &[IrExpr],
505        elem_type: &ZigType,
506        inner_expr: &IrExpr,
507    ) -> Option<IrExpr> {
508        use crate::zigir::types::{IrArrayMethodInline, IrExpr};
509
510        let kind = Self::resolve_method_kind(builtin)?;
511
512        let chain_obj_name = self.name_mangler.next_name("__chain");
513
514        Some(IrExpr::ArrayMethodInline(Box::new(IrArrayMethodInline {
515            kind,
516            obj_name: chain_obj_name,
517            obj_expr: Some(Box::new(inner_expr.clone())),
518            elem_type: elem_type.clone(),
519            args: args.to_vec(),
520        })))
521    }
522
523    /// Extract the object variable name from a CallExpression's callee.
524    pub(super) fn extract_callee_object_name(&self, ce: &CallExpression) -> Option<String> {
525        Self::extract_callee_object_name_static(&ce.callee)
526    }
527
528    /// Extract the object variable name from a callee Expression.
529    pub(super) fn extract_callee_object_name_static(callee: &Expression) -> Option<String> {
530        match callee {
531            Expression::StaticMemberExpression(mem) => match &mem.object {
532                Expression::Identifier(id) => Some(id.name.as_str().to_string()),
533                Expression::StringLiteral(sl) => {
534                    // "hello".method() — format as Zig string literal
535                    let escaped = crate::zigir::emit::helpers::escape_zig_string(sl.value.as_str());
536                    Some(format!("\"{}\"", escaped))
537                }
538                Expression::TemplateLiteral(tl)
539                    if tl.quasis.len() == 1 && tl.expressions.is_empty() =>
540                {
541                    // `hello`.method() — same as StringLiteral
542                    let escaped =
543                        crate::zigir::emit::helpers::escape_zig_string(&tl.quasis[0].value.raw);
544                    Some(format!("\"{}\"", escaped))
545                }
546                // R8-NumberToString: numeric-literal receivers like
547                // `(42).toString(16)` inline the numeric value directly.
548                // Hex/binary literals are already resolved to a `f64`
549                // value by the parser; `format!("{}", value)` emits the
550                // decimal form which Zig coerces to the runtime `f64`
551                // parameter automatically. This also fixes pre-existing
552                // `(42).toFixed(2)` mis-emission that produced an empty
553                // receiver slot.
554                Expression::NumericLiteral(nl) => Some(format!("{}", nl.value)),
555                // R8-P1-4: BigInt-literal receivers like `255n.toString(16)`
556                // inline as a JsBigInt init expression. The literal cannot
557                // be a plain Zig value because large BigInts overflow f64,
558                // so unlike NumericLiteral we emit a full constructor call.
559                Expression::BigIntLiteral(bl) => Some(format!(
560                    "(js_bigint.JsBigInt.init(js_allocator.allocator(), \"{}\") catch @panic(\"OOM: BigInt init\"))",
561                    crate::zigir::emit::helpers::escape_zig_string(bl.value.as_str())
562                )),
563                // Parenthesized-literal receivers: `((42)).method()` is
564                // syntactically equivalent to `(42).method()`. Only the
565                // common numeric/bigint cases are inlined here — anything
566                // else (e.g. parenthesized binary expressions) falls back
567                // to the lowerer's complex-receiver path.
568                Expression::ParenthesizedExpression(pe) => match &pe.expression {
569                    Expression::NumericLiteral(nl) => Some(format!("{}", nl.value)),
570                    Expression::BigIntLiteral(bl) => Some(format!(
571                        "(js_bigint.JsBigInt.init(js_allocator.allocator(), \"{}\") catch @panic(\"OOM: BigInt init\"))",
572                        crate::zigir::emit::helpers::escape_zig_string(bl.value.as_str())
573                    )),
574                    _ => None,
575                },
576                _ => None,
577            },
578            _ => None,
579        }
580    }
581
582    pub(super) fn is_typedarray_type(name: &str) -> bool {
583        matches!(
584            name,
585            "Int8Array"
586                | "Uint8Array"
587                | "Uint8ClampedArray"
588                | "Int16Array"
589                | "Uint16Array"
590                | "Int32Array"
591                | "Uint32Array"
592                | "Float32Array"
593                | "Float64Array"
594                | "BigInt64Array"
595                | "BigUint64Array"
596        )
597    }
598
599    /// Check if an expression is a RegExp: either a literal `/pattern/` or `new RegExp(...)`.
600    pub(super) fn is_regexp_expr(expr: &Expression) -> bool {
601        match expr {
602            Expression::RegExpLiteral(_) => true,
603            Expression::NewExpression(ne) => {
604                if let Expression::Identifier(id) = &ne.callee {
605                    id.name.as_str() == "RegExp"
606                } else {
607                    false
608                }
609            }
610            _ => false,
611        }
612    }
613
614    pub(super) fn typedarray_type_suffix(name: &str) -> Option<&'static str> {
615        match name {
616            "Int8Array" => Some("I8"),
617            "Uint8Array" | "Uint8ClampedArray" => Some("U8"),
618            "Int16Array" => Some("I16"),
619            "Uint16Array" => Some("U16"),
620            "Int32Array" => Some("I32"),
621            "Uint32Array" => Some("U32"),
622            "Float32Array" => Some("F32"),
623            "Float64Array" => Some("F64"),
624            "BigInt64Array" => Some("I64"),
625            "BigUint64Array" => Some("U64"),
626            _ => None,
627        }
628    }
629
630    /// Extract regex metadata from the first argument of a String.match/matchAll/search call,
631    /// or from the receiver of a RegExpTest/RegExpExec call.
632    /// Returns `None` for all other builtin calls.
633    pub(super) fn extract_regex_info(
634        ce: &CallExpression,
635        builtin: &crate::native_builtins::BuiltinCall,
636    ) -> Option<crate::zigir::types::IrRegexInfo> {
637        use crate::native_builtins::BuiltinCall;
638        use oxc_ast::ast::Expression;
639
640        match builtin {
641            BuiltinCall::StringMatch
642            | BuiltinCall::StringMatchAll
643            | BuiltinCall::StringSearch
644            | BuiltinCall::StringReplace
645            | BuiltinCall::StringReplaceAll => {}
646            // RegExpTest/RegExpExec: extract pattern from the *receiver* (callee object)
647            BuiltinCall::RegExpTest | BuiltinCall::RegExpExec => {
648                return if let Expression::StaticMemberExpression(sme) = &ce.callee {
649                    match &sme.object {
650                        Expression::RegExpLiteral(re) => {
651                            let pattern = re.regex.pattern.text.as_str();
652                            let escaped = pattern.replace('\\', "\\\\").replace('"', "\\\"");
653                            Some(crate::zigir::types::IrRegexInfo {
654                                pattern: Some(escaped),
655                                has_global: Self::regexp_has_global(re),
656                                is_var_ref: false,
657                                var_name: None,
658                            })
659                        }
660                        Expression::Identifier(id) => Some(crate::zigir::types::IrRegexInfo {
661                            pattern: None,
662                            has_global: false,
663                            is_var_ref: true,
664                            var_name: Some(id.name.to_string()),
665                        }),
666                        _ => None,
667                    }
668                } else {
669                    None
670                };
671            }
672            _ => return None,
673        }
674
675        if let Some(first_arg) = ce.arguments.first()
676            && let Some(expr) = first_arg.as_expression()
677        {
678            match expr {
679                Expression::RegExpLiteral(re) => {
680                    let pattern = re.regex.pattern.text.as_str();
681                    let escaped = pattern.replace('\\', "\\\\").replace('"', "\\\"");
682                    let has_global = Self::regexp_has_global(re);
683                    Some(crate::zigir::types::IrRegexInfo {
684                        pattern: Some(escaped),
685                        has_global,
686                        is_var_ref: false,
687                        var_name: None,
688                    })
689                }
690                Expression::Identifier(id) => Some(crate::zigir::types::IrRegexInfo {
691                    pattern: None,
692                    has_global: false,
693                    is_var_ref: true,
694                    var_name: Some(id.name.as_str().to_string()),
695                }),
696                _ => None,
697            }
698        } else {
699            None
700        }
701    }
702
703    /// Check whether a RegExp literal has the `g` (global) flag set.
704    /// Uses `re.regex.flags` (the parsed AST flags) rather than string-parsing
705    /// `re.raw`, which is more robust and consistent with how flags are
706    /// extracted in `lower_expr` (`mod.rs:44`).
707    fn regexp_has_global(re: &oxc_ast::ast::RegExpLiteral) -> bool {
708        re.regex.flags.to_string().contains('g')
709    }
710
711    // AST ident-usage helpers — used to check whether a callback parameter is actually referenced.
712
713    pub(super) fn ast_stmt_uses_ident(ident: &str, stmt: &Statement) -> bool {
714        match stmt {
715            Statement::ReturnStatement(r) => r
716                .argument
717                .as_ref()
718                .is_some_and(|e| Self::ast_expr_uses_ident(ident, e)),
719            Statement::ExpressionStatement(e) => Self::ast_expr_uses_ident(ident, &e.expression),
720            Statement::BlockStatement(b) => {
721                b.body.iter().any(|s| Self::ast_stmt_uses_ident(ident, s))
722            }
723            _ => false,
724        }
725    }
726
727    pub(super) fn ast_expr_uses_ident(ident: &str, expr: &Expression) -> bool {
728        match expr {
729            Expression::Identifier(id) => id.name.as_str() == ident,
730            Expression::BinaryExpression(b) => {
731                Self::ast_expr_uses_ident(ident, &b.left)
732                    || Self::ast_expr_uses_ident(ident, &b.right)
733            }
734            Expression::UnaryExpression(u) => Self::ast_expr_uses_ident(ident, &u.argument),
735            Expression::StaticMemberExpression(m) => Self::ast_expr_uses_ident(ident, &m.object),
736            Expression::ComputedMemberExpression(m) => {
737                Self::ast_expr_uses_ident(ident, &m.object)
738                    || Self::ast_expr_uses_ident(ident, &m.expression)
739            }
740            Expression::CallExpression(c) => {
741                Self::ast_expr_uses_ident(ident, &c.callee)
742                    || c.arguments.iter().any(|a| match a.as_expression() {
743                        Some(e) => Self::ast_expr_uses_ident(ident, e),
744                        None => false,
745                    })
746            }
747            Expression::ParenthesizedExpression(p) => {
748                Self::ast_expr_uses_ident(ident, &p.expression)
749            }
750            Expression::AssignmentExpression(a) => {
751                // Check both sides: `x = expr` uses ident if either side references it.
752                let left_matches = match &a.left {
753                    oxc_ast::ast::AssignmentTarget::AssignmentTargetIdentifier(id) => {
754                        id.name.as_str() == ident
755                    }
756                    _ => false,
757                };
758                left_matches || Self::ast_expr_uses_ident(ident, &a.right)
759            }
760            Expression::UpdateExpression(u) => {
761                // ++x / x-- : argument is SimpleAssignmentTarget (Identifier or MemberExpr)
762                match &u.argument {
763                    oxc_ast::ast::SimpleAssignmentTarget::AssignmentTargetIdentifier(id) => {
764                        id.name.as_str() == ident
765                    }
766                    _ => false,
767                }
768            }
769            Expression::LogicalExpression(l) => {
770                Self::ast_expr_uses_ident(ident, &l.left)
771                    || Self::ast_expr_uses_ident(ident, &l.right)
772            }
773            Expression::ConditionalExpression(c) => {
774                Self::ast_expr_uses_ident(ident, &c.test)
775                    || Self::ast_expr_uses_ident(ident, &c.consequent)
776                    || Self::ast_expr_uses_ident(ident, &c.alternate)
777            }
778            Expression::NumericLiteral(_)
779            | Expression::StringLiteral(_)
780            | Expression::BooleanLiteral(_)
781            | Expression::NullLiteral(_)
782            | Expression::BigIntLiteral(_)
783            | Expression::RegExpLiteral(_) => false,
784            // Conservative: assume identifier MAY appear in unhandled variants
785            _ => true,
786        }
787    }
788}
789
790// �T�T�T�T�T�T�T�T�T�T�T�T�T�T�T�T�T�T�T�T�T�T�T�T�T�T�T�T�T�T�T�T�T�T�T�T�T�T�T�T�T�T�T�T�T�T�T�T�T�T�T�T�T�T�T
791//  FnContext management
792// �T�T�T�T�T�T�T�T�T�T�T�T�T�T�T�T�T�T�T�T�T�T�T�T�T�T�T�T�T�T�T�T�T�T�T�T�T�T�T�T�T�T�T�T�T�T�T�T�T�T�T�T�T�T�T
793
794impl Lowerer {
795    /// Enter a function context. Saves any existing context (nesting support).
796    pub(super) fn enter_fn(
797        &mut self,
798        name: &str,
799        is_export: bool,
800        return_type: Option<ZigType>,
801    ) -> Option<FnContext> {
802        let old = self.fn_ctx.take();
803        // R8-C7: Reset the this-rewrite flag inside the new function context.
804        // `this.field = value` in a nested function must NOT be rewritten because
805        // its `this` is not the constructor's. The saved value is stashed on the
806        // new FnContext and restored by `exit_fn`.
807        let saved_rewrite = self.this_rewrite_fields.take();
808        self.this_rewrite_fields = None;
809        let mut new_ctx = FnContext::new(name, is_export, return_type);
810        new_ctx.saved_this_rewrite_fields = saved_rewrite;
811        self.fn_ctx = Some(new_ctx);
812        old
813    }
814
815    /// Exit the current function context. Restores the previous one if any.
816    pub(super) fn exit_fn(&mut self, saved: Option<FnContext>) -> FnContext {
817        let mut ctx = self.fn_ctx.take().expect("exit_fn called without enter_fn");
818        // R8-C7: Restore the this-rewrite flag that was active before this fn.
819        // `.take()` leaves None in the ctx so it can still be returned whole.
820        self.this_rewrite_fields = ctx.saved_this_rewrite_fields.take();
821        self.fn_ctx = saved;
822        ctx
823    }
824}
825
826/// Map a BuiltinCall to (BuiltinModule, method_name, return_type).
827pub fn builtin_call_to_ir(
828    bc: &crate::native_builtins::BuiltinCall,
829) -> (BuiltinModule, String, ZigType) {
830    use crate::native_builtins::BuiltinCall;
831
832    match bc {
833        // Math
834        BuiltinCall::MathAbs => (BuiltinModule::JsMath, "abs".into(), ZigType::F64),
835        BuiltinCall::MathFloor => (BuiltinModule::JsMath, "floor".into(), ZigType::F64),
836        BuiltinCall::MathCeil => (BuiltinModule::JsMath, "ceil".into(), ZigType::F64),
837        BuiltinCall::MathRound => (BuiltinModule::JsMath, "round".into(), ZigType::F64),
838        BuiltinCall::MathSqrt => (BuiltinModule::JsMath, "sqrt".into(), ZigType::F64),
839        BuiltinCall::MathRandom => (BuiltinModule::JsMath, "random".into(), ZigType::F64),
840        BuiltinCall::MathPow => (BuiltinModule::JsMath, "pow".into(), ZigType::F64),
841        BuiltinCall::MathMax => (BuiltinModule::JsMath, "max".into(), ZigType::F64),
842        BuiltinCall::MathMin => (BuiltinModule::JsMath, "min".into(), ZigType::F64),
843        BuiltinCall::MathHypot => (BuiltinModule::JsMath, "hypot".into(), ZigType::F64),
844        BuiltinCall::MathSin => (BuiltinModule::JsMath, "sin".into(), ZigType::F64),
845        BuiltinCall::MathCos => (BuiltinModule::JsMath, "cos".into(), ZigType::F64),
846        BuiltinCall::MathTan => (BuiltinModule::JsMath, "tan".into(), ZigType::F64),
847        BuiltinCall::MathAsin => (BuiltinModule::JsMath, "asin".into(), ZigType::F64),
848        BuiltinCall::MathAcos => (BuiltinModule::JsMath, "acos".into(), ZigType::F64),
849        BuiltinCall::MathAtan => (BuiltinModule::JsMath, "atan".into(), ZigType::F64),
850        BuiltinCall::MathAtan2 => (BuiltinModule::JsMath, "atan2".into(), ZigType::F64),
851        BuiltinCall::MathLog => (BuiltinModule::JsMath, "log".into(), ZigType::F64),
852        BuiltinCall::MathLog10 => (BuiltinModule::JsMath, "log10".into(), ZigType::F64),
853        BuiltinCall::MathLog2 => (BuiltinModule::JsMath, "log2".into(), ZigType::F64),
854        BuiltinCall::MathExp => (BuiltinModule::JsMath, "exp".into(), ZigType::F64),
855        BuiltinCall::MathSign => (BuiltinModule::JsMath, "sign".into(), ZigType::F64),
856        BuiltinCall::MathTrunc => (BuiltinModule::JsMath, "trunc".into(), ZigType::F64),
857        BuiltinCall::MathCbrt => (BuiltinModule::JsMath, "cbrt".into(), ZigType::F64),
858        BuiltinCall::MathExpm1 => (BuiltinModule::JsMath, "expm1".into(), ZigType::F64),
859        BuiltinCall::MathSinh => (BuiltinModule::JsMath, "sinh".into(), ZigType::F64),
860        BuiltinCall::MathCosh => (BuiltinModule::JsMath, "cosh".into(), ZigType::F64),
861        BuiltinCall::MathTanh => (BuiltinModule::JsMath, "tanh".into(), ZigType::F64),
862        BuiltinCall::MathAsinh => (BuiltinModule::JsMath, "asinh".into(), ZigType::F64),
863        BuiltinCall::MathAcosh => (BuiltinModule::JsMath, "acosh".into(), ZigType::F64),
864        BuiltinCall::MathAtanh => (BuiltinModule::JsMath, "atanh".into(), ZigType::F64),
865        BuiltinCall::MathClz32 => (BuiltinModule::JsMath, "clz32".into(), ZigType::I64),
866        BuiltinCall::MathFround => (BuiltinModule::JsMath, "fround".into(), ZigType::F64),
867        BuiltinCall::MathImul => (BuiltinModule::JsMath, "imul".into(), ZigType::I64),
868        BuiltinCall::MathLog1p => (BuiltinModule::JsMath, "log1p".into(), ZigType::F64),
869
870        // Console
871        BuiltinCall::ConsoleLog => (BuiltinModule::JsConsole, "log".into(), ZigType::Void),
872        BuiltinCall::ConsoleError => (BuiltinModule::JsConsole, "error".into(), ZigType::Void),
873        BuiltinCall::ConsoleWarn => (BuiltinModule::JsConsole, "warn".into(), ZigType::Void),
874
875        // JSON
876        BuiltinCall::JsonStringify => (BuiltinModule::JsJson, "stringify".into(), ZigType::Str),
877        BuiltinCall::JsonParse => (BuiltinModule::JsJson, "parse".into(), ZigType::JsAny),
878
879        // Global functions
880        BuiltinCall::ParseInt => (BuiltinModule::JsUri, "parseInt".into(), ZigType::F64),
881        BuiltinCall::ParseFloat => (BuiltinModule::JsUri, "parseFloat".into(), ZigType::F64),
882        BuiltinCall::IsNaN => (BuiltinModule::JsUri, "isNaN".into(), ZigType::Bool),
883        BuiltinCall::IsFinite => (BuiltinModule::JsUri, "isFinite".into(), ZigType::Bool),
884        BuiltinCall::EncodeURIComponent => (
885            BuiltinModule::JsUri,
886            "encodeURIComponent".into(),
887            ZigType::Str,
888        ),
889        BuiltinCall::DecodeURIComponent => (
890            BuiltinModule::JsUri,
891            "decodeURIComponent".into(),
892            ZigType::Str,
893        ),
894        BuiltinCall::EncodeURI => (BuiltinModule::JsUri, "encodeURI".into(), ZigType::Str),
895        BuiltinCall::DecodeURI => (BuiltinModule::JsUri, "decodeURI".into(), ZigType::Str),
896        BuiltinCall::Eval => (BuiltinModule::JsUri, "eval".into(), ZigType::Void),
897
898        // Constructors
899        BuiltinCall::NumberConstructor => {
900            (BuiltinModule::JsNumber, "constructor".into(), ZigType::F64)
901        }
902        BuiltinCall::StringConstructor => {
903            (BuiltinModule::JsString, "constructor".into(), ZigType::Str)
904        }
905        BuiltinCall::BooleanConstructor => (
906            BuiltinModule::JsNumber,
907            "booleanConstructor".into(),
908            ZigType::Bool,
909        ),
910        BuiltinCall::BigIntConstructor => (
911            BuiltinModule::JsBigInt,
912            "bigIntConstructor".into(),
913            ZigType::BigInt,
914        ),
915        BuiltinCall::BigIntToString => (BuiltinModule::JsBigInt, "toString".into(), ZigType::Str),
916        BuiltinCall::BigIntValueOf => (BuiltinModule::JsBigInt, "valueOf".into(), ZigType::BigInt),
917        BuiltinCall::BigIntToLocaleString => (
918            BuiltinModule::JsBigInt,
919            "toLocaleString".into(),
920            ZigType::Str,
921        ),
922        BuiltinCall::BigIntAsIntN => (BuiltinModule::JsBigInt, "asIntN".into(), ZigType::BigInt),
923        BuiltinCall::BigIntAsUintN => (BuiltinModule::JsBigInt, "asUintN".into(), ZigType::BigInt),
924        BuiltinCall::ObjectConstructor => (
925            BuiltinModule::JsObject,
926            "constructor".into(),
927            ZigType::JsAny,
928        ),
929        BuiltinCall::SymbolConstructor => (
930            BuiltinModule::JsSymbol,
931            "constructor".into(),
932            ZigType::JsSymbol,
933        ),
934
935        // Number static methods
936        BuiltinCall::NumberIsNaN => (BuiltinModule::JsNumber, "isNaN".into(), ZigType::Bool),
937        BuiltinCall::NumberIsFinite => (BuiltinModule::JsNumber, "isFinite".into(), ZigType::Bool),
938        BuiltinCall::NumberIsInteger => {
939            (BuiltinModule::JsNumber, "isInteger".into(), ZigType::Bool)
940        }
941        BuiltinCall::NumberIsSafeInteger => (
942            BuiltinModule::JsNumber,
943            "isSafeInteger".into(),
944            ZigType::Bool,
945        ),
946        BuiltinCall::NumberParseInt => (BuiltinModule::JsNumber, "parseInt".into(), ZigType::F64),
947        BuiltinCall::NumberParseFloat => {
948            (BuiltinModule::JsNumber, "parseFloat".into(), ZigType::F64)
949        }
950
951        // Number instance methods
952        BuiltinCall::NumberToFixed => (BuiltinModule::JsNumber, "toFixed".into(), ZigType::Str),
953        BuiltinCall::NumberToExponential => (
954            BuiltinModule::JsNumber,
955            "toExponential".into(),
956            ZigType::Str,
957        ),
958        BuiltinCall::NumberToPrecision => {
959            (BuiltinModule::JsNumber, "toPrecision".into(), ZigType::Str)
960        }
961        BuiltinCall::NumberToString => (BuiltinModule::JsNumber, "toString".into(), ZigType::Str),
962
963        // String instance methods
964        BuiltinCall::StringIndexOf => (BuiltinModule::JsString, "indexOf".into(), ZigType::I64),
965        BuiltinCall::StringIncludes => (BuiltinModule::JsString, "includes".into(), ZigType::Bool),
966        BuiltinCall::StringStartsWith => {
967            (BuiltinModule::JsString, "startsWith".into(), ZigType::Bool)
968        }
969        BuiltinCall::StringEndsWith => (BuiltinModule::JsString, "endsWith".into(), ZigType::Bool),
970        BuiltinCall::StringLastIndexOf => {
971            (BuiltinModule::JsString, "lastIndexOf".into(), ZigType::I64)
972        }
973        BuiltinCall::StringTrim => (BuiltinModule::JsString, "trim".into(), ZigType::Str),
974        BuiltinCall::StringSplit => (
975            BuiltinModule::JsString,
976            "split".into(),
977            ZigType::ArrayList(Box::new(ZigType::Str)),
978        ),
979        BuiltinCall::StringPadStart => (BuiltinModule::JsString, "padStart".into(), ZigType::Str),
980        BuiltinCall::StringPadEnd => (BuiltinModule::JsString, "padEnd".into(), ZigType::Str),
981        BuiltinCall::StringTrimStart => (BuiltinModule::JsString, "trimStart".into(), ZigType::Str),
982        BuiltinCall::StringTrimEnd => (BuiltinModule::JsString, "trimEnd".into(), ZigType::Str),
983        BuiltinCall::StringToUpperCase => {
984            (BuiltinModule::JsString, "toUpperCase".into(), ZigType::Str)
985        }
986        BuiltinCall::StringToLowerCase => {
987            (BuiltinModule::JsString, "toLowerCase".into(), ZigType::Str)
988        }
989        BuiltinCall::StringCharAt => (BuiltinModule::JsString, "charAt".into(), ZigType::Str),
990        BuiltinCall::StringCharCodeAt => {
991            (BuiltinModule::JsString, "charCodeAt".into(), ZigType::F64)
992        }
993        BuiltinCall::StringCodePointAt => (
994            BuiltinModule::JsString,
995            "codePointAt".into(),
996            ZigType::JsAny,
997        ),
998        BuiltinCall::StringConcat => (BuiltinModule::JsString, "concat".into(), ZigType::Str),
999        BuiltinCall::StringSlice => (BuiltinModule::JsString, "slice".into(), ZigType::Str),
1000        BuiltinCall::StringReplace => (BuiltinModule::JsString, "replace".into(), ZigType::Str),
1001        BuiltinCall::StringReplaceAll => {
1002            (BuiltinModule::JsString, "replaceAll".into(), ZigType::Str)
1003        }
1004        BuiltinCall::StringRepeat => (BuiltinModule::JsString, "repeat".into(), ZigType::Str),
1005        BuiltinCall::StringSubstring => (BuiltinModule::JsString, "substring".into(), ZigType::Str),
1006        BuiltinCall::StringAt => (BuiltinModule::JsString, "at".into(), ZigType::Str),
1007        BuiltinCall::StringMatch => (BuiltinModule::JsString, "match".into(), ZigType::JsAny),
1008        BuiltinCall::StringSearch => (BuiltinModule::JsString, "search".into(), ZigType::I64),
1009        BuiltinCall::StringFromCharCode => {
1010            (BuiltinModule::JsString, "fromCharCode".into(), ZigType::Str)
1011        }
1012        BuiltinCall::StringFromCodePoint => (
1013            BuiltinModule::JsString,
1014            "fromCodePoint".into(),
1015            ZigType::Str,
1016        ),
1017        BuiltinCall::StringMatchAll => (BuiltinModule::JsString, "matchAll".into(), ZigType::JsAny),
1018        BuiltinCall::StringLocaleCompare => (
1019            BuiltinModule::JsString,
1020            "localeCompare".into(),
1021            ZigType::I64,
1022        ),
1023        BuiltinCall::StringNormalize => (BuiltinModule::JsString, "normalize".into(), ZigType::Str),
1024        BuiltinCall::StringToLocaleUpperCase => (
1025            BuiltinModule::JsString,
1026            "toLocaleUpperCase".into(),
1027            ZigType::Str,
1028        ),
1029        BuiltinCall::StringToLocaleLowerCase => (
1030            BuiltinModule::JsString,
1031            "toLocaleLowerCase".into(),
1032            ZigType::Str,
1033        ),
1034
1035        // Array methods
1036        BuiltinCall::ArrayPush => (BuiltinModule::JsArray, "push".into(), ZigType::I64),
1037        BuiltinCall::ArrayPop => (BuiltinModule::JsArray, "pop".into(), ZigType::JsAny),
1038        BuiltinCall::ArrayShift => (BuiltinModule::JsArray, "shift".into(), ZigType::JsAny),
1039        BuiltinCall::ArrayUnshift => (BuiltinModule::JsArray, "unshift".into(), ZigType::I64),
1040        BuiltinCall::ArrayReverse => (BuiltinModule::JsArray, "reverse".into(), ZigType::JsAny),
1041        BuiltinCall::ArraySort => (BuiltinModule::JsArray, "sort".into(), ZigType::JsAny),
1042        BuiltinCall::ArrayIndexOf => (BuiltinModule::JsArray, "indexOf".into(), ZigType::I64),
1043        BuiltinCall::ArrayIncludes => (BuiltinModule::JsArray, "includes".into(), ZigType::Bool),
1044        BuiltinCall::ArrayJoin => (BuiltinModule::JsArray, "join".into(), ZigType::Str),
1045        BuiltinCall::ArraySlice => (
1046            BuiltinModule::JsArray,
1047            "slice".into(),
1048            ZigType::ArrayList(Box::new(ZigType::JsAny)),
1049        ),
1050        BuiltinCall::ArraySplice => (
1051            BuiltinModule::JsArray,
1052            "splice".into(),
1053            ZigType::ArrayList(Box::new(ZigType::JsAny)),
1054        ),
1055        BuiltinCall::ArrayConcat => (
1056            BuiltinModule::JsArray,
1057            "concat".into(),
1058            ZigType::ArrayList(Box::new(ZigType::JsAny)),
1059        ),
1060        BuiltinCall::ArrayAt => (BuiltinModule::JsArray, "at".into(), ZigType::JsAny),
1061        BuiltinCall::ArrayLastIndexOf => {
1062            (BuiltinModule::JsArray, "lastIndexOf".into(), ZigType::I64)
1063        }
1064        BuiltinCall::ArrayCopyWithin => {
1065            (BuiltinModule::JsArray, "copyWithin".into(), ZigType::JsAny)
1066        }
1067        BuiltinCall::ArrayForEach => (BuiltinModule::JsArray, "forEach".into(), ZigType::Void),
1068        BuiltinCall::ArrayMap => (
1069            BuiltinModule::JsArray,
1070            "map".into(),
1071            ZigType::ArrayList(Box::new(ZigType::JsAny)),
1072        ),
1073        BuiltinCall::ArrayFilter => (
1074            BuiltinModule::JsArray,
1075            "filter".into(),
1076            ZigType::ArrayList(Box::new(ZigType::JsAny)),
1077        ),
1078        BuiltinCall::ArrayReduce => (BuiltinModule::JsArray, "reduce".into(), ZigType::JsAny),
1079        BuiltinCall::ArraySome => (BuiltinModule::JsArray, "some".into(), ZigType::Bool),
1080        BuiltinCall::ArrayEvery => (BuiltinModule::JsArray, "every".into(), ZigType::Bool),
1081        BuiltinCall::ArrayFlat => (
1082            BuiltinModule::JsArray,
1083            "flat".into(),
1084            ZigType::ArrayList(Box::new(ZigType::JsAny)),
1085        ),
1086        BuiltinCall::ArrayFlatMap => (
1087            BuiltinModule::JsArray,
1088            "flatMap".into(),
1089            ZigType::ArrayList(Box::new(ZigType::JsAny)),
1090        ),
1091        BuiltinCall::ArrayFind => (BuiltinModule::JsArray, "find".into(), ZigType::JsAny),
1092        BuiltinCall::ArrayFindIndex => (BuiltinModule::JsArray, "findIndex".into(), ZigType::I64),
1093        BuiltinCall::ArrayFindLast => (BuiltinModule::JsArray, "findLast".into(), ZigType::JsAny),
1094        BuiltinCall::ArrayFindLastIndex => {
1095            (BuiltinModule::JsArray, "findLastIndex".into(), ZigType::I64)
1096        }
1097        BuiltinCall::ArrayReduceRight => {
1098            (BuiltinModule::JsArray, "reduceRight".into(), ZigType::JsAny)
1099        }
1100        BuiltinCall::ArrayFill => (BuiltinModule::JsArray, "fill".into(), ZigType::JsAny),
1101        BuiltinCall::ArrayWith => (
1102            BuiltinModule::JsArray,
1103            "with".into(),
1104            ZigType::ArrayList(Box::new(ZigType::JsAny)),
1105        ),
1106        BuiltinCall::ArrayToReversed => (
1107            BuiltinModule::JsArray,
1108            "toReversed".into(),
1109            ZigType::ArrayList(Box::new(ZigType::JsAny)),
1110        ),
1111        BuiltinCall::ArrayToSorted => (
1112            BuiltinModule::JsArray,
1113            "toSorted".into(),
1114            ZigType::ArrayList(Box::new(ZigType::JsAny)),
1115        ),
1116        BuiltinCall::ArrayToSpliced => (
1117            BuiltinModule::JsArray,
1118            "toSpliced".into(),
1119            ZigType::ArrayList(Box::new(ZigType::JsAny)),
1120        ),
1121        BuiltinCall::ArrayKeys => (
1122            BuiltinModule::JsArray,
1123            "keys".into(),
1124            ZigType::ArrayList(Box::new(ZigType::I64)),
1125        ),
1126        BuiltinCall::ArrayValues => (
1127            BuiltinModule::JsArray,
1128            "values".into(),
1129            ZigType::ArrayList(Box::new(ZigType::JsAny)),
1130        ),
1131        BuiltinCall::ArrayEntries => (
1132            BuiltinModule::JsArray,
1133            "entries".into(),
1134            ZigType::ArrayList(Box::new(ZigType::JsAny)),
1135        ),
1136        BuiltinCall::ArrayFrom => (
1137            BuiltinModule::JsArray,
1138            "from".into(),
1139            ZigType::ArrayList(Box::new(ZigType::JsAny)),
1140        ),
1141        BuiltinCall::ArrayOf => (
1142            BuiltinModule::JsArray,
1143            "of".into(),
1144            ZigType::ArrayList(Box::new(ZigType::JsAny)),
1145        ),
1146        BuiltinCall::ArrayIsArray => (BuiltinModule::JsArray, "isArray".into(), ZigType::Bool),
1147        BuiltinCall::TypedArraySubarray => (
1148            BuiltinModule::JsTypedArray,
1149            "subarray".into(),
1150            ZigType::JsAny,
1151        ),
1152
1153        // Map/Set
1154        BuiltinCall::MapSet => (
1155            BuiltinModule::JsCollections,
1156            "set".into(),
1157            ZigType::NamedStruct("Map".into()),
1158        ),
1159        BuiltinCall::MapGet => (BuiltinModule::JsCollections, "get".into(), ZigType::JsAny),
1160        BuiltinCall::MapHas => (BuiltinModule::JsCollections, "has".into(), ZigType::Bool),
1161        BuiltinCall::MapDelete => (BuiltinModule::JsCollections, "delete".into(), ZigType::Bool),
1162        BuiltinCall::MapKeys => (
1163            BuiltinModule::JsCollections,
1164            "keys".into(),
1165            ZigType::ArrayList(Box::new(ZigType::Str)),
1166        ),
1167        BuiltinCall::MapValues => (
1168            BuiltinModule::JsCollections,
1169            "values".into(),
1170            ZigType::ArrayList(Box::new(ZigType::JsAny)),
1171        ),
1172        BuiltinCall::MapEntries => (
1173            BuiltinModule::JsCollections,
1174            "entries".into(),
1175            ZigType::ArrayList(Box::new(ZigType::JsAny)),
1176        ),
1177        BuiltinCall::MapClear => (BuiltinModule::JsCollections, "clear".into(), ZigType::Void),
1178        BuiltinCall::SetAdd => (
1179            BuiltinModule::JsCollections,
1180            "add".into(),
1181            ZigType::NamedStruct("Set".into()),
1182        ),
1183
1184        // Date static
1185        BuiltinCall::DateNow => (BuiltinModule::JsDate, "now".into(), ZigType::I64),
1186        BuiltinCall::DateParse => (BuiltinModule::JsDate, "parse".into(), ZigType::I64),
1187        BuiltinCall::DateUTC => (BuiltinModule::JsDate, "utc".into(), ZigType::I64),
1188
1189        // Date instance
1190        BuiltinCall::DateGetTime => (BuiltinModule::JsDate, "getTime".into(), ZigType::I64),
1191        BuiltinCall::DateGetFullYear => (BuiltinModule::JsDate, "getFullYear".into(), ZigType::I64),
1192        BuiltinCall::DateGetMonth => (BuiltinModule::JsDate, "getMonth".into(), ZigType::I64),
1193        BuiltinCall::DateGetDate => (BuiltinModule::JsDate, "getDate".into(), ZigType::I64),
1194        BuiltinCall::DateGetDay => (BuiltinModule::JsDate, "getDay".into(), ZigType::I64),
1195        BuiltinCall::DateGetHours => (BuiltinModule::JsDate, "getHours".into(), ZigType::I64),
1196        BuiltinCall::DateGetMinutes => (BuiltinModule::JsDate, "getMinutes".into(), ZigType::I64),
1197        BuiltinCall::DateGetSeconds => (BuiltinModule::JsDate, "getSeconds".into(), ZigType::I64),
1198        BuiltinCall::DateGetMilliseconds => (
1199            BuiltinModule::JsDate,
1200            "getMilliseconds".into(),
1201            ZigType::I64,
1202        ),
1203        BuiltinCall::DateGetTimezoneOffset => (
1204            BuiltinModule::JsDate,
1205            "getTimezoneOffset".into(),
1206            ZigType::I64,
1207        ),
1208        BuiltinCall::DateToISOString => (BuiltinModule::JsDate, "toISOString".into(), ZigType::Str),
1209        BuiltinCall::DateToString => (BuiltinModule::JsDate, "toString".into(), ZigType::Str),
1210        BuiltinCall::DateToDateString => {
1211            (BuiltinModule::JsDate, "toDateString".into(), ZigType::Str)
1212        }
1213        BuiltinCall::DateToTimeString => {
1214            (BuiltinModule::JsDate, "toTimeString".into(), ZigType::Str)
1215        }
1216        BuiltinCall::DateToLocaleString => {
1217            (BuiltinModule::JsDate, "toLocaleString".into(), ZigType::Str)
1218        }
1219        BuiltinCall::DateToLocaleDateString => (
1220            BuiltinModule::JsDate,
1221            "toLocaleDateString".into(),
1222            ZigType::Str,
1223        ),
1224        BuiltinCall::DateToLocaleTimeString => (
1225            BuiltinModule::JsDate,
1226            "toLocaleTimeString".into(),
1227            ZigType::Str,
1228        ),
1229        BuiltinCall::DateGetUTCFullYear => {
1230            (BuiltinModule::JsDate, "getUTCFullYear".into(), ZigType::I64)
1231        }
1232        BuiltinCall::DateGetUTCMonth => (BuiltinModule::JsDate, "getUTCMonth".into(), ZigType::I64),
1233        BuiltinCall::DateGetUTCDate => (BuiltinModule::JsDate, "getUTCDate".into(), ZigType::I64),
1234        BuiltinCall::DateGetUTCDay => (BuiltinModule::JsDate, "getUTCDay".into(), ZigType::I64),
1235        BuiltinCall::DateGetUTCHours => (BuiltinModule::JsDate, "getUTCHours".into(), ZigType::I64),
1236        BuiltinCall::DateGetUTCMinutes => {
1237            (BuiltinModule::JsDate, "getUTCMinutes".into(), ZigType::I64)
1238        }
1239        BuiltinCall::DateGetUTCSeconds => {
1240            (BuiltinModule::JsDate, "getUTCSeconds".into(), ZigType::I64)
1241        }
1242        BuiltinCall::DateGetUTCMilliseconds => (
1243            BuiltinModule::JsDate,
1244            "getUTCMilliseconds".into(),
1245            ZigType::I64,
1246        ),
1247        BuiltinCall::DateToJSON => (BuiltinModule::JsDate, "toJSON".into(), ZigType::Str),
1248        BuiltinCall::DateValueOf => (BuiltinModule::JsDate, "valueOf".into(), ZigType::I64),
1249        BuiltinCall::DateSetFullYear => (BuiltinModule::JsDate, "setFullYear".into(), ZigType::I64),
1250        BuiltinCall::DateSetMonth => (BuiltinModule::JsDate, "setMonth".into(), ZigType::I64),
1251        BuiltinCall::DateSetDate => (BuiltinModule::JsDate, "setDate".into(), ZigType::I64),
1252        BuiltinCall::DateSetHours => (BuiltinModule::JsDate, "setHours".into(), ZigType::I64),
1253        BuiltinCall::DateSetMinutes => (BuiltinModule::JsDate, "setMinutes".into(), ZigType::I64),
1254        BuiltinCall::DateSetSeconds => (BuiltinModule::JsDate, "setSeconds".into(), ZigType::I64),
1255        BuiltinCall::DateSetMilliseconds => (
1256            BuiltinModule::JsDate,
1257            "setMilliseconds".into(),
1258            ZigType::I64,
1259        ),
1260        BuiltinCall::DateSetUTCFullYear => {
1261            (BuiltinModule::JsDate, "setUTCFullYear".into(), ZigType::I64)
1262        }
1263        BuiltinCall::DateSetUTCMonth => (BuiltinModule::JsDate, "setUTCMonth".into(), ZigType::I64),
1264        BuiltinCall::DateSetUTCDate => (BuiltinModule::JsDate, "setUTCDate".into(), ZigType::I64),
1265        BuiltinCall::DateSetUTCHours => (BuiltinModule::JsDate, "setUTCHours".into(), ZigType::I64),
1266        BuiltinCall::DateSetUTCMinutes => {
1267            (BuiltinModule::JsDate, "setUTCMinutes".into(), ZigType::I64)
1268        }
1269        BuiltinCall::DateSetUTCSeconds => {
1270            (BuiltinModule::JsDate, "setUTCSeconds".into(), ZigType::I64)
1271        }
1272        BuiltinCall::DateSetUTCMilliseconds => (
1273            BuiltinModule::JsDate,
1274            "setUTCMilliseconds".into(),
1275            ZigType::I64,
1276        ),
1277        BuiltinCall::DateSetTime => (BuiltinModule::JsDate, "setTime".into(), ZigType::I64),
1278        BuiltinCall::DateToUTCString => (BuiltinModule::JsDate, "toUTCString".into(), ZigType::Str),
1279
1280        // Object static
1281        BuiltinCall::ObjectKeys => (
1282            BuiltinModule::JsObject,
1283            "keys".into(),
1284            ZigType::ArrayList(Box::new(ZigType::Str)),
1285        ),
1286        BuiltinCall::ObjectValues => (
1287            BuiltinModule::JsObject,
1288            "values".into(),
1289            ZigType::ArrayList(Box::new(ZigType::JsAny)),
1290        ),
1291        BuiltinCall::ObjectEntries => (
1292            BuiltinModule::JsObject,
1293            "entries".into(),
1294            ZigType::ArrayList(Box::new(ZigType::JsAny)),
1295        ),
1296        BuiltinCall::ObjectFromEntries => (
1297            BuiltinModule::JsObject,
1298            "fromEntries".into(),
1299            ZigType::JsAny,
1300        ),
1301        BuiltinCall::ObjectAssign => (BuiltinModule::JsObject, "assign".into(), ZigType::JsAny),
1302        BuiltinCall::ObjectFreeze => (BuiltinModule::JsObject, "freeze".into(), ZigType::JsAny),
1303        BuiltinCall::ObjectSeal => (BuiltinModule::JsObject, "seal".into(), ZigType::JsAny),
1304        BuiltinCall::ObjectPreventExtensions => (
1305            BuiltinModule::JsObject,
1306            "preventExtensions".into(),
1307            ZigType::JsAny,
1308        ),
1309        BuiltinCall::ObjectHasOwn => (BuiltinModule::JsObject, "hasOwn".into(), ZigType::Bool),
1310        BuiltinCall::ObjectIs => (BuiltinModule::JsObject, "is".into(), ZigType::Bool),
1311        BuiltinCall::ObjectGetOwnPropertyNames => (
1312            BuiltinModule::JsObject,
1313            "getOwnPropertyNames".into(),
1314            ZigType::ArrayList(Box::new(ZigType::Str)),
1315        ),
1316        BuiltinCall::ObjectCreate => (BuiltinModule::JsObject, "create".into(), ZigType::JsAny),
1317        BuiltinCall::ObjectDefineProperty => (
1318            BuiltinModule::JsObject,
1319            "defineProperty".into(),
1320            ZigType::JsAny,
1321        ),
1322        BuiltinCall::ObjectGetPrototypeOf => (
1323            BuiltinModule::JsObject,
1324            "getPrototypeOf".into(),
1325            ZigType::JsAny,
1326        ),
1327        BuiltinCall::ObjectDefineProperties => (
1328            BuiltinModule::JsObject,
1329            "defineProperties".into(),
1330            ZigType::JsAny,
1331        ),
1332        BuiltinCall::ObjectGetOwnPropertyDescriptor => (
1333            BuiltinModule::JsObject,
1334            "getOwnPropertyDescriptor".into(),
1335            ZigType::JsAny,
1336        ),
1337        BuiltinCall::ObjectSetPrototypeOf => (
1338            BuiltinModule::JsObject,
1339            "setPrototypeOf".into(),
1340            ZigType::JsAny,
1341        ),
1342        BuiltinCall::ObjectIsSealed => (BuiltinModule::JsObject, "isSealed".into(), ZigType::Bool),
1343        BuiltinCall::ObjectIsFrozen => (BuiltinModule::JsObject, "isFrozen".into(), ZigType::Bool),
1344        BuiltinCall::ObjectIsExtensible => (
1345            BuiltinModule::JsObject,
1346            "isExtensible".into(),
1347            ZigType::Bool,
1348        ),
1349        BuiltinCall::ObjectGroupBy => (BuiltinModule::JsObject, "groupBy".into(), ZigType::JsAny),
1350
1351        // Symbol
1352        BuiltinCall::SymbolFor => (BuiltinModule::JsSymbol, "for".into(), ZigType::JsSymbol), // Emitter renames "for" �� "symbolFor" to avoid Zig keyword
1353        BuiltinCall::SymbolKeyFor => (BuiltinModule::JsSymbol, "keyFor".into(), ZigType::Str),
1354
1355        // RegExp
1356        BuiltinCall::RegExpTest => (BuiltinModule::JsRegExp, "test".into(), ZigType::Bool),
1357        BuiltinCall::RegExpExec => (BuiltinModule::JsRegExp, "exec".into(), ZigType::JsAny),
1358
1359        // ES2025 Set operations — intercepted in lower_call() before reaching here,
1360        // but must be covered for exhaustive match
1361        BuiltinCall::SetUnion
1362        | BuiltinCall::SetIntersection
1363        | BuiltinCall::SetDifference
1364        | BuiltinCall::SetSymmetricDifference
1365        | BuiltinCall::SetIsSubsetOf
1366        | BuiltinCall::SetIsSupersetOf
1367        | BuiltinCall::SetIsDisjointFrom => (
1368            BuiltinModule::JsCollections,
1369            "unsupported_es2025".into(),
1370            ZigType::JsAny,
1371        ),
1372    }
1373}
1374
1375// �T�T�T�T�T�T�T�T�T�T�T�T�T�T�T�T�T�T�T�T�T�T�T�T�T�T�T�T�T�T�T�T�T�T�T�T�T�T�T�T�T�T�T�T�T�T�T�T�T�T�T�T�T�T�T
1376//  Free helper functions for destructuring
1377// �T�T�T�T�T�T�T�T�T�T�T�T�T�T�T�T�T�T�T�T�T�T�T�T�T�T�T�T�T�T�T�T�T�T�T�T�T�T�T�T�T�T�T�T�T�T�T�T�T�T�T�T�T�T�T
1378
1379/// Check if an init expression may have side effects (needs temp variable in destructure).
1380pub fn init_may_have_side_effects(init: &Expression) -> bool {
1381    matches!(
1382        init,
1383        Expression::CallExpression(_)
1384            | Expression::NewExpression(_)
1385            | Expression::AssignmentExpression(_)
1386            | Expression::UpdateExpression(_)
1387    )
1388}
1389
1390/// Extract the string name of a property key (static identifier, string literal, private id).
1391pub fn property_key_name(key: &PropertyKey) -> Option<String> {
1392    match key {
1393        PropertyKey::StaticIdentifier(id) => Some(id.name.to_string()),
1394        PropertyKey::StringLiteral(sl) => Some(sl.value.to_string()),
1395        PropertyKey::PrivateIdentifier(id) => Some(id.name.to_string()),
1396        _ => None,
1397    }
1398}