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