Skip to main content

js2zig_core/codegen/
mod.rs

1//! Code generation from JS AST to Zig source code.
2//! Main module: struct definitions, helpers, public API.
3
4use std::collections::{HashMap, HashSet};
5
6use oxc_ast::ast::*;
7
8use crate::builtins::BuiltinRegistry;
9use crate::infer::{TypeInferrer, ZigType};
10use crate::sourcemap::{LineIndex, SourceMap, count_lines};
11
12mod builtins;
13mod closure;
14mod expr;
15mod fn_decl;
16mod stmt;
17
18/// Information about a closure generated from an inline arrow function
19#[derive(Debug, Clone)]
20struct ClosureInfo {
21    /// Struct name, e.g. "_Closure_makeAdder"
22    struct_name: String,
23    /// Captured (free) variable names and their Zig types
24    captured: Vec<(String, String)>,
25    /// Arrow function parameter names and types
26    params: Vec<(String, String)>,
27    /// Return type as Zig string
28    return_type: String,
29    /// Pre-generated struct definition string (filled during record_closure)
30    struct_def: String,
31}
32
33/// Generate a unique closure struct name from a function name
34fn closure_name(fn_name: &str) -> String {
35    format!("_Closure_{}", fn_name)
36}
37
38/// A single leaf binding extracted from a destructuring pattern.
39/// For `const { a: { b, c } } = obj`, we get two leaf bindings:
40///   LeafBinding { name: "b", access: "_tmp.a.b", default: None }
41///   LeafBinding { name: "c", access: "_tmp.a.c", default: None }
42struct LeafBinding<'a> {
43    name: &'a str,
44    /// Full access path from the temp variable (e.g. "_tmp.a.b" or "_tmp[0].x")
45    access: String,
46}
47
48/// Recursively flatten a BindingPattern into a list of leaf bindings.
49/// `prefix` is the access path from the temp variable (e.g. "_tmp").
50fn flatten_binding_pattern<'a>(
51    pattern: &'a BindingPattern<'a>,
52    prefix: &str,
53    result: &mut Vec<LeafBinding<'a>>,
54) {
55    match pattern {
56        BindingPattern::BindingIdentifier(id) => {
57            result.push(LeafBinding {
58                name: id.name.as_str(),
59                access: prefix.to_string(),
60            });
61        }
62        BindingPattern::ObjectPattern(obj) => {
63            for prop in &obj.properties {
64                let key_str = property_key_name(&prop.key);
65                let new_prefix = format!("{}.{}", prefix, key_str);
66                flatten_binding_pattern(&prop.value, &new_prefix, result);
67            }
68            // rest: ...rest — skip for now (requires runtime support)
69        }
70        BindingPattern::ArrayPattern(arr) => {
71            for (i, elem) in arr.elements.iter().enumerate().filter_map(|(i, opt)| opt.as_ref().map(|e| (i, e))) {
72                let new_prefix = format!("{}[{}]", prefix, i);
73                flatten_binding_pattern(elem, &new_prefix, result);
74            }
75            // rest: ...rest — skip for now
76        }
77        BindingPattern::AssignmentPattern(assign) => {
78            // Default value: for simplicity, skip the default in the first pass
79            // The leaf binding gets the access path; default is not emitted.
80            flatten_binding_pattern(&assign.left, prefix, result);
81        }
82    }
83}
84
85/// Extract a string representation of a PropertyKey for use in access paths.
86/// E.g., `{ a: x }` → "a"
87fn property_key_name(key: &PropertyKey) -> String {
88    match key {
89        PropertyKey::StaticIdentifier(id) => id.name.to_string(),
90        _ => "_computed_key".to_string(),
91    }
92}
93
94/// Collect all leaf identifier names from a BindingPattern.
95/// Used by preprocess and infer to register variable names without access paths.
96pub fn collect_binding_names(pattern: &BindingPattern, names: &mut Vec<String>) {
97    match pattern {
98        BindingPattern::BindingIdentifier(id) => {
99            names.push(id.name.to_string());
100        }
101        BindingPattern::ObjectPattern(obj) => {
102            for prop in &obj.properties {
103                collect_binding_names(&prop.value, names);
104            }
105            if let Some(rest) = &obj.rest {
106                collect_binding_names(&rest.argument, names);
107            }
108        }
109        BindingPattern::ArrayPattern(arr) => {
110            for elem in arr.elements.iter().flatten() {
111                collect_binding_names(elem, names);
112            }
113            if let Some(rest) = &arr.rest {
114                collect_binding_names(&rest.argument, names);
115            }
116        }
117        BindingPattern::AssignmentPattern(assign) => {
118            collect_binding_names(&assign.left, names);
119        }
120    }
121}
122
123/// Collect all leaf identifier names and their spans from a BindingPattern.
124/// Used by preprocess for rename edits.
125pub fn collect_binding_names_with_spans(
126    pattern: &BindingPattern,
127    names: &mut Vec<(String, oxc_span::Span)>,
128) {
129    match pattern {
130        BindingPattern::BindingIdentifier(id) => {
131            names.push((id.name.to_string(), id.span));
132        }
133        BindingPattern::ObjectPattern(obj) => {
134            for prop in &obj.properties {
135                collect_binding_names_with_spans(&prop.value, names);
136            }
137            if let Some(rest) = &obj.rest {
138                collect_binding_names_with_spans(&rest.argument, names);
139            }
140        }
141        BindingPattern::ArrayPattern(arr) => {
142            for elem in arr.elements.iter().flatten() {
143                collect_binding_names_with_spans(elem, names);
144            }
145            if let Some(rest) = &arr.rest {
146                collect_binding_names_with_spans(&rest.argument, names);
147            }
148        }
149        BindingPattern::AssignmentPattern(assign) => {
150            collect_binding_names_with_spans(&assign.left, names);
151        }
152    }
153}
154
155/// Check whether a BindingPattern is just a simple identifier (no destructuring).
156pub fn is_simple_binding(pattern: &BindingPattern) -> bool {
157    matches!(pattern, BindingPattern::BindingIdentifier(_))
158}
159
160/// Return type for codegen::generate: (zig_code, diagnostics, closure_fns, fn_return_types, cabi_exports, source_map)
161pub type CodegenResult = (
162    String,
163    Vec<crate::infer::Diagnostic>,
164    std::collections::HashSet<String>,
165    std::collections::HashMap<String, ZigType>,
166    Vec<CabiExport>,
167    SourceMap,
168);
169
170/// Host function type information passed from pipeline to codegen.
171/// Contains return types, parameter types, and struct field types
172/// for both sync and async host functions.
173pub struct HostTypeInfo<'a> {
174    pub return_types: &'a HashMap<String, ZigType>,
175    pub param_types: &'a HashMap<String, Vec<ZigType>>,
176    pub struct_fields: &'a HashMap<String, Vec<(String, ZigType)>>,
177    /// Names of async host functions (used to append `_async` suffix in io.async calls)
178    pub async_fns: &'a HashSet<String>,
179}
180
181pub fn generate(
182    program: &Program,
183    builtins: &BuiltinRegistry,
184    exports: &HashSet<String>,
185    source_text: &str,
186    source_file: &str,
187    host_info: &HostTypeInfo,
188) -> CodegenResult {
189    let mut inferrer = TypeInferrer::new();
190
191    // Register host function return types before inference
192    for (name, ret_type) in host_info.return_types {
193        inferrer.add_host_return_type(name.clone(), ret_type.clone());
194    }
195
196    // Register host function parameter types for type inference
197    inferrer.register_host_param_types(host_info.param_types);
198
199    // Register host struct field types for member access inference
200    inferrer.register_host_struct_fields(host_info.struct_fields);
201
202    inferrer.infer_program(program);
203
204    // Extract fn_return_types before inferrer is consumed by ZigCodegen
205    let fn_return_types = inferrer.all_fn_return_types();
206
207    let mut diagnostics = inferrer.diagnostics().to_vec();
208
209    let mut cg = ZigCodegen::new(
210        inferrer,
211        &mut diagnostics,
212        builtins,
213        exports.clone(),
214        source_text,
215        source_file,
216        host_info.async_fns.clone(),
217    );
218    // Header is added by project.rs/generate_lib_zig() — do NOT emit here.
219
220    // Pre-scan: find functions that return inline arrow functions
221    cg.pre_scan_closures(program);
222
223    // Push all pre-generated closure struct defs to the output buffer
224    for def in cg.closure_struct_defs.values() {
225        cg.closure_structs.push(def.clone());
226    }
227
228    // Top-level: only VariableDeclaration and FunctionDeclaration
229    // Rejected statements produce Error diagnostics inside emit_stmt()
230    cg.in_top_level = true;
231    for stmt in &program.body {
232        cg.emit_stmt(stmt);
233    }
234
235    // Emit buffered closure struct definitions
236    for def in &cg.closure_structs {
237        cg.output.push_str(def);
238    }
239
240    // Emit buffered object type struct definitions
241    for def in &cg.object_type_defs {
242        cg.output.push_str(def);
243    }
244
245    // Emit C ABI export wrappers (after all functions, before tests)
246    for wrapper in &cg.cabi_wrappers {
247        cg.output.push_str(wrapper);
248    }
249
250    // Emit init_js2rust() function if there are dynamic access variables
251    cg.emit_init_js2rust();
252    // Emit deinit_js2rust() function for cleanup
253    cg.emit_deinit_js2rust();
254
255    let closure_fns: HashSet<String> = cg.fn_closure_spans.keys().cloned().collect();
256
257    let cabi_exports = cg.cabi_exports;
258    let source_map = cg.source_map;
259
260    (cg.output, diagnostics, closure_fns, fn_return_types, cabi_exports, source_map)
261}
262
263/// Metadata for a C ABI exported function, used by sys crate to generate Rust FFI bindings.
264#[derive(Debug, Clone)]
265pub struct CabiExport {
266    /// C ABI exported function name (e.g. "chineseAdd")
267    pub name: String,
268    /// (param_name, ZigType) pairs
269    pub params: Vec<(String, ZigType)>,
270    /// Return type (ZigType)
271    pub ret_type: ZigType,
272    /// Whether a corresponding free_xxx function exists
273    pub has_free_func: bool,
274    /// Whether this is an async export (impl takes `io: Io` as first param)
275    pub is_async: bool,
276}
277
278struct ZigCodegen<'a> {
279    output: String,
280    indent: usize,
281    inferrer: TypeInferrer,
282    diagnostics: &'a mut Vec<crate::infer::Diagnostic>,
283    in_top_level: bool,
284    task_counter: usize,
285    builtins: &'a BuiltinRegistry,
286    /// arrow.span.start → ClosureInfo for ALL detected inline arrow functions
287    closure_map: HashMap<u32, ClosureInfo>,
288    /// arrow.span.start → pre-generated struct definition string
289    closure_struct_defs: HashMap<u32, String>,
290    /// fn_name → arrow.span.start (for functions that return a closure)
291    fn_closure_spans: HashMap<String, u32>,
292    /// Counter for generating unique synthetic closure names
293    closure_counter: usize,
294    /// Buffered closure struct definitions to emit after all functions
295    closure_structs: Vec<String>,
296    /// Buffered C ABI export wrappers to emit after all functions
297    cabi_wrappers: Vec<String>,
298    /// C ABI export metadata for sys crate FFI bindings
299    cabi_exports: Vec<CabiExport>,
300    /// Set of function names that need free_xxx functions (return strings)
301    string_return_fns: HashSet<String>,
302    /// Set of variable names that hold closure struct instances
303    closure_vars: HashSet<String>,
304    /// Current function name for closure lookup
305    current_fn: Option<String>,
306    /// Set of exported function/var names (from preprocess)
307    exports: HashSet<String>,
308    /// Current try-block label (for translating `throw` to `break :label error.X`)
309    try_label: Option<String>,
310    /// Current catch-block label (for translating `return` in catch to `break :label expr`)
311    catch_label: Option<String>,
312    /// Counter for generating unique try-block labels
313    try_counter: usize,
314    /// Counter for generating unique temp variable names (destructuring)
315    temp_counter: usize,
316    /// Pending body prelude statements for destructured function parameters
317    /// Cleared after each function body is emitted.
318    destructure_prelude: Vec<String>,
319    /// Current class context: (struct_name, field_names) for `self` tracking
320    current_class: Option<(String, Vec<String>)>,
321    /// Buffered struct type definitions for top-level object literals
322    object_type_defs: Vec<String>,
323    /// Per-function: struct name for each Object-typed parameter (indexed by param position).
324    /// Populated at the start of emit_fn_decl, consumed by emit_params, cleared after the function.
325    current_obj_structs: Vec<Option<String>>,
326    /// Buffered initialization code for init_globals() function.
327    /// Each string is a line of code to be inserted into init_globals().
328    init_globals_code: Vec<String>,
329    /// Source map: tracks JS→Zig line mappings
330    source_map: SourceMap,
331    /// Line index for the JS source (byte offset → line/col)
332    line_index: LineIndex,
333    /// JS source file name
334    source_file: String,
335    /// Names of async host functions (to append `_async` in io.async calls)
336    #[allow(dead_code)]
337    async_host_fns: HashSet<String>,
338}
339
340
341impl<'a> ZigCodegen<'a> {
342    pub(super) fn new(
343        inferrer: TypeInferrer,
344        diagnostics: &'a mut Vec<crate::infer::Diagnostic>,
345        builtins: &'a BuiltinRegistry,
346        exports: HashSet<String>,
347        source_text: &str,
348        source_file: &str,
349        async_host_fns: HashSet<String>,
350    ) -> Self {
351        Self {
352            output: String::new(),
353            indent: 0,
354            inferrer,
355            diagnostics,
356            in_top_level: false,
357            task_counter: 0,
358            builtins,
359            closure_map: HashMap::new(),
360            closure_struct_defs: HashMap::new(),
361            fn_closure_spans: HashMap::new(),
362            closure_counter: 0,
363            closure_structs: Vec::new(),
364            cabi_wrappers: Vec::new(),
365            cabi_exports: Vec::new(),
366            string_return_fns: HashSet::new(),
367            closure_vars: HashSet::new(),
368            current_fn: None,
369            exports,
370            try_label: None,
371            catch_label: None,
372            try_counter: 0,
373            temp_counter: 0,
374            destructure_prelude: Vec::new(),
375            current_class: None,
376            object_type_defs: Vec::new(),
377            current_obj_structs: Vec::new(),
378            init_globals_code: Vec::new(),
379            source_map: SourceMap::new(source_file),
380            line_index: LineIndex::new(source_text),
381            source_file: source_file.to_string(),
382            async_host_fns,
383        }
384    }
385
386    pub(super) fn emit_indent(&mut self) {
387        for _ in 0..self.indent {
388            self.output.push_str("    ");
389        }
390    }
391
392    pub(super) fn get_indent_str(&self, level: usize) -> String {
393        "    ".repeat(level)
394    }
395
396    pub(super) fn push(&mut self, s: &str) {
397        self.output.push_str(s);
398    }
399
400    pub(super) fn push_line(&mut self, s: &str) {
401        self.emit_indent();
402        self.push(s);
403        self.push("\n");
404    }
405
406    /// Record a source mapping and emit an inline `// @src(file:line) kind` comment.
407    /// `span_start` is the byte offset in the JS source.
408    pub(super) fn record_src(&mut self, span_start: u32, kind: &str) {
409        let (js_line, js_col) = self.line_index.offset_to_line_col(span_start);
410        let zig_line = count_lines(&self.output) + 1; // next line to be written
411        self.source_map.add(zig_line, js_line, js_col, kind);
412        // Emit inline comment
413        self.emit_indent();
414        self.push(&format!("// @src({}:{}) {}\n", self.source_file, js_line, kind));
415    }
416
417    pub(super) fn binding_name<'b>(&self, pattern: &BindingPattern<'b>) -> &'b str {
418        match pattern {
419            BindingPattern::BindingIdentifier(id) => id.name.as_str(),
420            _ => "_unsupported_pattern",
421        }
422    }
423
424    pub(super) fn escape_keyword(name: &str) -> String {
425        let keywords: &[&str] = &[
426            "align", "allowzero", "and", "anyframe", "anytype", "asm", "async",
427            "await", "break", "callconv", "catch", "comptime", "const", "continue",
428            "defer", "else", "enum", "errdefer", "error", "export", "extern",
429            "false", "fn", "for", "if", "inline", "linksection", "noalias",
430            "noinline", "noreturn", "nosuspend", "null", "opaque", "or", "orelse", "packed",
431            "pub", "resume", "return", "struct", "suspend", "switch", "test",
432            "threadlocal", "true", "try", "type", "undefined", "union", "unreachable",
433            "usingnamespace", "var", "volatile", "while",
434        ];
435        if keywords.contains(&name) {
436            format!("@\"{}\"", name)
437        } else {
438            name.to_string()
439        }
440    }
441
442    /// Wrap an init expression with the appropriate constructor for JsValue/JsAny types.
443    /// For precise Zig types (I64, F64, Bool, String), the expression is emitted as-is.
444    pub(super) fn emit_typed_init(&mut self, init: &Expression, target_type: &ZigType) {
445        match target_type {
446            ZigType::JsValue => {
447                let expr_type = self.inferrer.infer_expr(init);
448                match expr_type {
449                    ZigType::I64 | ZigType::I32 | ZigType::Usize => {
450                        self.push("JsValue.fromI64(");
451                        self.emit_expr(init);
452                        self.push(")");
453                    }
454                    ZigType::F64 | ZigType::F32 => {
455                        self.push("JsValue.fromF64(");
456                        self.emit_expr(init);
457                        self.push(")");
458                    }
459                    ZigType::Bool => {
460                        self.push("JsValue.fromBool(");
461                        self.emit_expr(init);
462                        self.push(")");
463                    }
464                    ZigType::String => {
465                        self.push("JsValue.fromString(");
466                        self.emit_expr(init);
467                        self.push(")");
468                    }
469                    ZigType::Null => {
470                        self.push("JsValue.fromNull()");
471                    }
472                    _ => {
473                        self.emit_expr(init);
474                    }
475                }
476            }
477            ZigType::JsAny => {
478                let expr_type = self.inferrer.infer_expr(init);
479                match expr_type {
480                    ZigType::I64 | ZigType::I32 | ZigType::Usize => {
481                        self.push("JsAny.fromI64(");
482                        self.emit_expr(init);
483                        self.push(")");
484                    }
485                    ZigType::F64 | ZigType::F32 => {
486                        self.push("JsAny.fromF64(");
487                        self.emit_expr(init);
488                        self.push(")");
489                    }
490                    ZigType::Bool => {
491                        self.push("JsAny.fromBool(");
492                        self.emit_expr(init);
493                        self.push(")");
494                    }
495                    ZigType::String => {
496                        self.push("JsAny.fromString(");
497                        self.emit_expr(init);
498                        self.push(")");
499                    }
500                    ZigType::Null => {
501                        self.push("JsAny.fromNull()");
502                    }
503                    _ => {
504                        self.emit_expr(init);
505                    }
506                }
507            }
508            _ => {
509                self.emit_expr(init);
510            }
511        }
512    }
513
514    // ========== Statements ==========
515
516    pub(super) fn emit_dynamic_access_var_decl(&mut self, name: &str) {
517        self.emit_indent();
518        self.push("var ");
519        self.push(name);
520        self.push(": std.StringHashMap(JsAny) = undefined;\n");
521    }
522
523    /// Generate initialization code for a dynamic access variable.
524    /// The code is buffered in init_globals_code and emitted in init_js2rust().
525    pub(super) fn emit_dynamic_access_var_init_code(&mut self, name: &str, obj: &ObjectExpression) {
526        // Add initialization code: name = std.StringHashMap(JsAny).init(allocator);
527        self.init_globals_code.push(format!(
528            "    {} = std.StringHashMap(JsAny).init(allocator);\n",
529            name
530        ));
531
532        // Add put() calls for each property
533        for prop in &obj.properties {
534            if let oxc_ast::ast::ObjectPropertyKind::ObjectProperty(p) = prop {
535                let field_name = match &p.key {
536                    oxc_ast::ast::PropertyKey::StaticIdentifier(id) => id.name.to_string(),
537                    oxc_ast::ast::PropertyKey::StringLiteral(s) => s.value.to_string(),
538                    _ => continue,
539                };
540
541                // Generate JsAny literal based on expression type
542                let js_any_lit = self.emit_js_any_literal(&p.value);
543                self.init_globals_code.push(format!(
544                    "    {}.put(\"{}\", {}) catch @panic(\"OOM\");\n",
545                    name, field_name, js_any_lit
546                ));
547            }
548        }
549    }
550
551    /// Generate a JsAny literal from a constant expression.
552    /// For non-constant expressions, wraps in JsAny.fromValue(JsValue{...}).
553    pub(super) fn emit_js_any_literal(&self, expr: &Expression) -> String {
554        match expr {
555            Expression::NumericLiteral(lit) => {
556                if lit.value.is_finite() && lit.value == lit.value.trunc() {
557                    format!("JsAny.fromI64({})", lit.value as i64)
558                } else {
559                    format!("JsAny.fromF64({})", lit.value)
560                }
561            }
562            Expression::StringLiteral(s) => {
563                format!("JsAny.fromString(\"{}\")", Self::escape_zig_string(&s.value))
564            }
565            Expression::BooleanLiteral(b) => {
566                format!("JsAny.fromBool({})", b.value)
567            }
568            Expression::NullLiteral(_) => {
569                "JsAny.fromNull()".to_string()
570            }
571            _ => {
572                // For non-literal expressions, fall back to JsValue wrapping
573                let js_val = self.emit_js_value_literal(expr);
574                format!("JsAny.fromValue({})", js_val)
575            }
576        }
577    }
578
579    /// Escape a string for Zig string literal context.
580    fn escape_zig_string(s: &str) -> String {
581        s.replace('\\', "\\\\")
582            .replace('"', "\\\"")
583            .replace('\n', "\\n")
584            .replace('\r', "\\r")
585            .replace('\t', "\\t")
586    }
587
588    pub(super) fn emit_js_value_literal(&self, expr: &Expression) -> String {
589        match expr {
590            Expression::NumericLiteral(lit) => {
591                let val_str = lit.value.to_string();
592                // Use is_finite() + trunc() to reliably detect integer literals.
593                // f64::fract() can be unreliable due to floating-point precision.
594                if lit.value.is_finite() && lit.value == lit.value.trunc() {
595                    format!(".{{ .int = {} }}", val_str)
596                } else {
597                    format!(".{{ .float = {} }}", val_str)
598                }
599            }
600            Expression::StringLiteral(lit) => {
601                format!(".{{ .string = \"{}\" }}", lit.value)
602            }
603            Expression::BooleanLiteral(lit) => {
604                format!(".{{ .bool = {} }}", if lit.value { "true" } else { "false" })
605            }
606            Expression::NullLiteral(_) => {
607                ".{ .null = {} }".to_string()
608            }
609            _ => {
610                // Unsupported - store as int 0
611                ".{ .int = 0 }".to_string()
612            }
613        }
614    }
615
616    /// Emit JsValue construction code for an expression (used in HashMap.put() calls).
617    /// For literals, emit inline JsValue literal.
618    /// For complex expressions, emit a simple wrap (assumes i64).
619    pub(super) fn emit_js_value_construction(&mut self, expr: &Expression) {
620        match expr {
621            Expression::NumericLiteral(lit) => {
622                let val_str = lit.value.to_string();
623                if lit.value.is_finite() && lit.value == lit.value.trunc() {
624                    self.push(&format!("JsValue{{ .int = {} }}", val_str));
625                } else {
626                    self.push(&format!("JsValue{{ .float = {} }}", val_str));
627                }
628            }
629            Expression::StringLiteral(lit) => {
630                self.push(&format!("JsValue{{ .string = \"{}\" }}", lit.value));
631            }
632            Expression::BooleanLiteral(lit) => {
633                let b = if lit.value { "true" } else { "false" };
634                self.push(&format!("JsValue{{ .bool = {} }}", b));
635            }
636            Expression::NullLiteral(_) => {
637                self.push("JsValue{ .null = {} }");
638            }
639            _ => {
640                // TODO: use runtime helper for proper type conversion
641                self.push("JsValue{ .int = ");
642                self.emit_expr(expr);
643                self.push(" }");
644            }
645        }
646    }
647
648    /// Return the correct JsValue variant field accessor for a HashMap field lookup.
649    /// Look up the field type from the original object type stored in the type inferrer.
650    pub(super) fn dynamic_field_accessor(&self, obj_expr: &Expression, prop: &str) -> String {
651        if let Expression::Identifier(id) = obj_expr {
652            let obj_type = self.inferrer.get_var_type(id.name.as_str());
653            if let ZigType::Object { fields } = obj_type
654                && let Some((_, field_type)) = fields.iter().find(|(n, _)| n == prop)
655            {
656                return match field_type {
657                    ZigType::String => ".string".to_string(),
658                    ZigType::F64 | ZigType::F32 => ".float".to_string(),
659                    ZigType::Bool => ".bool".to_string(),
660                    ZigType::Null => ".null".to_string(),
661                    _ => ".asI64()".to_string(),
662                };
663            }
664        }
665        ".asI64()".to_string()
666    }
667
668    pub(super) fn emit_init_js2rust(&mut self) {
669        // Always generate init_js2rust() — empty if no dynamic access vars
670        self.push("\n");
671        self.push("/// Initialize global allocator and all objects that use dynamic property access.\n");
672        self.push("pub fn init_js2rust(allocator: std.mem.Allocator) void {\n");
673        self.push("    js_allocator.setGlobalAllocator(allocator);\n");
674        // Collect init code to avoid borrowing self twice
675        let init_code: String = self.init_globals_code.iter().cloned().collect();
676        if !init_code.is_empty() {
677            self.push(&init_code);
678        }
679        self.push("}\n");
680    }
681
682    /// Emit deinit_js2rust() that frees all global HashMaps.
683    /// Only generated when there are actual resources to free (HashMap .deinit() calls).
684    /// When empty, the function is omitted — lib.zig provides the top-level shell for tests.
685    pub(super) fn emit_deinit_js2rust(&mut self) {
686        // Extract HashMap variable names from init code (format: "    varname = std.StringHashMap...")
687        let mut hashmap_names: Vec<String> = Vec::new();
688        for line in &self.init_globals_code {
689            if line.contains(".init(")
690                && let Some(name) = line.trim().split(" =").next()
691            {
692                hashmap_names.push(name.to_string());
693            }
694        }
695        // Skip generation when no resources need cleanup — lib.zig still provides the shell
696        if hashmap_names.is_empty() {
697            return;
698        }
699        self.push("\n");
700        self.push("/// Deinitialize all global objects created by init_js2rust().\n");
701        self.push("pub fn deinit_js2rust() void {\n");
702        for name in &hashmap_names {
703            self.push(&format!("    {}.deinit();\n", name));
704        }
705        self.push("}\n");
706    }
707
708    pub(super) fn gen_obj_struct_def(struct_name: &str, fields: &[(String, ZigType)]) -> String {
709        let mut s = format!("const {} = struct {{\n", struct_name);
710        for (fname, ftype) in fields {
711            s.push_str(&format!("    {}: {},\n", fname, ftype.to_zig_str()));
712        }
713        s.push_str("};\n\n");
714        s
715    }
716
717    /// Capitalize the first letter for struct naming (e.g., "person" → "Person")
718    pub(super) fn capitalize_first(s: &str) -> String {
719        let mut chars = s.chars();
720        match chars.next() {
721            None => String::new(),
722            Some(c) => {
723                let upper = c.to_uppercase().collect::<String>();
724                upper + chars.as_str()
725            }
726        }
727    }
728
729    pub(super) fn is_string_literal_expr(expr: &Expression) -> bool {
730        matches!(expr, Expression::StringLiteral(_))
731    }
732
733    // ========== Expression Helpers ==========
734
735    pub(super) fn emit_arg(&mut self, arg: &Argument) {
736        match arg {
737            Argument::SpreadElement(spread) => {
738                self.push("...");
739                self.emit_expr(&spread.argument);
740            }
741            _ => {
742                if let Some(expr) = arg.as_expression() {
743                    self.emit_expr(expr);
744                }
745            }
746        }
747    }
748
749    /// Emit an argument wrapped in JsAny constructor for dynamic array methods.
750    pub(super) fn emit_jsany_arg(&mut self, arg: &Argument) {
751        match arg {
752            Argument::SpreadElement(_) => {
753                // Spread not supported in dynamic array method args
754                self.push("JsAny.fromNull()");
755            }
756            _ => {
757                if let Some(expr) = arg.as_expression() {
758                    let lit = self.emit_js_any_literal(expr);
759                    self.push(&lit);
760                }
761            }
762        }
763    }
764
765    pub(super) fn emit_array_element(&mut self, elem: &ArrayExpressionElement) {
766        match elem {
767            ArrayExpressionElement::SpreadElement(spread) => {
768                self.push("...");
769                self.emit_expr(&spread.argument);
770            }
771            ArrayExpressionElement::Elision(_) => {
772                self.push("undefined");
773            }
774            _ => {
775                if let Some(expr) = elem.as_expression() {
776                    self.emit_expr(expr);
777                }
778            }
779        }
780    }
781
782    /// Emit an array element wrapped in JsAny constructor for dynamic arrays.
783    pub(super) fn emit_jsany_array_element(&mut self, elem: &ArrayExpressionElement) {
784        match elem {
785            ArrayExpressionElement::SpreadElement(_) => {
786                self.push("JsAny.fromNull()"); // spread not supported in array literal
787            }
788            ArrayExpressionElement::Elision(_) => {
789                self.push("JsAny.fromNull()");
790            }
791            _ => {
792                if let Some(expr) = elem.as_expression() {
793                    let lit = self.emit_js_any_literal(expr);
794                    self.push(&lit);
795                }
796            }
797        }
798    }
799
800    pub(super) fn emit_assign_target(&mut self, target: &AssignmentTarget) {
801        match target {
802            AssignmentTarget::AssignmentTargetIdentifier(id) => {
803                self.push(&Self::escape_keyword(id.name.as_str()));
804            }
805            AssignmentTarget::ArrayAssignmentTarget(_) => {
806                self.push("_/* array destructure */");
807            }
808            AssignmentTarget::ObjectAssignmentTarget(_) => {
809                self.push("_/* object destructure */");
810            }
811            AssignmentTarget::StaticMemberExpression(mem) => {
812                self.emit_expr(&mem.object);
813                self.push(".");
814                self.push(mem.property.name.as_str());
815            }
816            AssignmentTarget::ComputedMemberExpression(mem) => {
817                let obj_type = self.inferrer.infer_expr(&mem.object);
818                if matches!(&obj_type, ZigType::Object { .. })
819                    && let Expression::StringLiteral(s) = &mem.expression
820                {
821                    self.emit_expr(&mem.object);
822                    self.push(".");
823                    self.push(s.value.as_str());
824                } else {
825                    self.emit_expr(&mem.object);
826                    self.push("[");
827                    self.emit_expr(&mem.expression);
828                    self.push("]");
829                }
830            }
831            AssignmentTarget::PrivateFieldExpression(_) => {
832                self.push("_/* private field */");
833            }
834            AssignmentTarget::TSAsExpression(ts) => {
835                self.emit_expr(&ts.expression);
836            }
837            AssignmentTarget::TSSatisfiesExpression(ts) => {
838                self.emit_expr(&ts.expression);
839            }
840            AssignmentTarget::TSNonNullExpression(ts) => {
841                self.emit_expr(&ts.expression);
842                self.push(".?");
843            }
844            AssignmentTarget::TSTypeAssertion(ts) => {
845                self.emit_expr(&ts.expression);
846            }
847        }
848    }
849
850    pub(super) fn emit_assign_target_from_simple(&mut self, target: &SimpleAssignmentTarget) {
851        match target {
852            SimpleAssignmentTarget::AssignmentTargetIdentifier(id) => {
853                self.push(&Self::escape_keyword(id.name.as_str()));
854            }
855            SimpleAssignmentTarget::StaticMemberExpression(mem) => {
856                self.emit_expr(&mem.object);
857                self.push(".");
858                self.push(mem.property.name.as_str());
859            }
860            SimpleAssignmentTarget::ComputedMemberExpression(mem) => {
861                let obj_type = self.inferrer.infer_expr(&mem.object);
862                if matches!(&obj_type, ZigType::Object { .. })
863                    && let Expression::StringLiteral(s) = &mem.expression
864                {
865                    self.emit_expr(&mem.object);
866                    self.push(".");
867                    self.push(s.value.as_str());
868                } else {
869                    self.emit_expr(&mem.object);
870                    self.push("[");
871                    self.emit_expr(&mem.expression);
872                    self.push("]");
873                }
874            }
875            SimpleAssignmentTarget::PrivateFieldExpression(_) => {
876                self.push("_/* private */");
877            }
878            _ => {
879                self.push("_/* ts assign target */");
880            }
881        }
882    }
883
884    // ========== Operator Mappings ==========
885
886    pub(super) fn map_binary_op(&self, op: &BinaryOperator) -> &'static str {
887        match op {
888            BinaryOperator::StrictEquality => "==",
889            BinaryOperator::StrictInequality => "!=",
890            BinaryOperator::Equality => "==",
891            BinaryOperator::Inequality => "!=",
892            BinaryOperator::Addition => "+",
893            BinaryOperator::Subtraction => "-",
894            BinaryOperator::Multiplication => "*",
895            BinaryOperator::Division => "/",
896            BinaryOperator::Remainder => "%",
897            BinaryOperator::Exponential => "**",
898            BinaryOperator::LessThan => "<",
899            BinaryOperator::LessEqualThan => "<=",
900            BinaryOperator::GreaterThan => ">",
901            BinaryOperator::GreaterEqualThan => ">=",
902            BinaryOperator::ShiftLeft => "<<",
903            BinaryOperator::ShiftRight => ">>",
904            BinaryOperator::ShiftRightZeroFill => ">>",
905            BinaryOperator::BitwiseOR => "|",
906            BinaryOperator::BitwiseXOR => "^",
907            BinaryOperator::BitwiseAnd => "&",
908            BinaryOperator::In => "== /* in */",
909            BinaryOperator::Instanceof => "== /* instanceof */",
910        }
911    }
912
913    pub(super) fn map_logical_op(&self, op: &LogicalOperator) -> &'static str {
914        match op {
915            LogicalOperator::And => "and",
916            LogicalOperator::Or => "or",
917            LogicalOperator::Coalesce => "orelse",
918        }
919    }
920
921    pub(super) fn map_unary_op(&self, op: &UnaryOperator) -> &'static str {
922        match op {
923            UnaryOperator::UnaryPlus => "",  // Zig doesn't support unary plus
924            UnaryOperator::UnaryNegation => "-",
925            UnaryOperator::LogicalNot => "!",
926            UnaryOperator::BitwiseNot => "~",
927            UnaryOperator::Typeof => "@TypeOf",
928            UnaryOperator::Void => "",
929            UnaryOperator::Delete => "",
930        }
931    }
932
933    pub(super) fn map_assign_op(&self, op: &AssignmentOperator) -> &'static str {
934        match op {
935            AssignmentOperator::Assign => "=",
936            AssignmentOperator::Addition => "+=",
937            AssignmentOperator::Subtraction => "-=",
938            AssignmentOperator::Multiplication => "*=",
939            AssignmentOperator::Division => "/=",
940            AssignmentOperator::Remainder => "%=",
941            AssignmentOperator::Exponential => "**=",
942            AssignmentOperator::ShiftLeft => "<<=",
943            AssignmentOperator::ShiftRight => ">>=",
944            AssignmentOperator::ShiftRightZeroFill => ">>>=",
945            AssignmentOperator::BitwiseOR => "|=",
946            AssignmentOperator::BitwiseXOR => "^=",
947            AssignmentOperator::BitwiseAnd => "&=",
948            AssignmentOperator::LogicalOr => "|=",
949            AssignmentOperator::LogicalAnd => "&=",
950            AssignmentOperator::LogicalNullish => "=?=",
951        }
952    }
953}