Skip to main content

js2zig_core/native_proto/codegen/
mod.rs

1// native_proto/codegen/mod.rs
2// Core Codegen struct, constructor, and entry point.
3
4use crate::native_proto::Codegen;
5use oxc_ast::ast::*;
6
7pub mod expr;
8pub mod helpers;
9pub mod stmt;
10
11// ── Constructor ─────────────────────────────────────
12
13impl Codegen {
14    pub fn new(
15        type_info: crate::native_proto::TypeCheckResult,
16        jsdoc_data: crate::native_proto::JSDocData,
17        exported_functions: Option<std::collections::HashSet<String>>,
18    ) -> Self {
19        Self {
20            output: String::new(),
21            indent: 0,
22            errors: Vec::new(),
23            warnings: Vec::new(),
24            type_info,
25            jsdoc_data: Some(jsdoc_data),
26            current_fn_is_export: false,
27            current_fn_return_type: None,
28            exported_fns: Vec::new(),
29            cabi_exports: Vec::new(),
30            task_counter: 0,
31            exported_functions,
32            seen_return: false,
33            fn_has_throw: false,
34            in_return_expr: false,
35            in_expr_stmt: false,
36            try_label_counter: 0,
37            arrow_counter: 0,
38            pending_arrow_fns: Vec::new(),
39            inside_try_block: None,
40            current_fn: None,
41            current_captured: Vec::new(),
42            closure_vars: std::collections::HashMap::new(),
43            closure_instances: std::collections::HashSet::new(),
44            closure_defs: Vec::new(),
45            oc_counter: 0,
46            typedarray_vars: std::collections::HashMap::new(),
47        }
48    }
49}
50
51// ── Entry point ─────────────────────────────────────
52
53impl Codegen {
54    /// Emit all @typedef struct definitions at the top of the generated file.
55    fn emit_typedefs(&mut self) {
56        // Clone typedefs to avoid borrow checker issues
57        let typedefs = match &self.jsdoc_data {
58            Some(data) => data.typedefs.clone(),
59            None => return,
60        };
61        if typedefs.is_empty() {
62            return;
63        }
64        for (name, td) in &typedefs {
65            self.writeln(&format!("const {} = struct {{", name));
66            self.indent += 1;
67            for field in &td.fields {
68                let zig_ty = crate::native_proto::jsdoc::jsdoc_type_to_zig(&field.ty, &typedefs);
69                // Optional field: prepend ? to the type
70                let zig_ty = if field.optional {
71                    format!("?{}", zig_ty)
72                } else {
73                    zig_ty
74                };
75                self.writeln(&format!("{}: {},", field.name, zig_ty));
76            }
77            // Generate toJson() method for serialization using std.json.fmt()
78            // Use the global arena allocator (js_allocator.getAllocator()).
79            self.writeln("");
80            self.writeln("pub fn toJson(self: *const @This()) ![]u8 {");
81            self.indent += 1;
82            // Use std.io.Writer.Allocating + std.json.fmt() for serialization
83            self.writeln(
84                "var string = std.io.Writer.Allocating.init(js_allocator.getAllocator());",
85            );
86            self.writeln("errdefer string.deinit();");
87            self.writeln("try string.writer().print(\"{f}\", .{std.json.fmt(self.*, .{})});");
88            self.writeln("return string.toOwnedSlice();");
89            self.indent -= 1;
90            self.writeln("}");
91            self.indent -= 1;
92            self.writeln("};");
93            self.writeln("");
94        }
95    }
96
97    pub fn generate(&mut self, program: &Program) {
98        // Phase A: analyze_objects, collect_used_names, walk_stmt_for_types
99        // are all handled by TypeInferrer::infer_all() before codegen starts.
100
101        // Emit struct typedefs (from JSDoc @typedef).
102        self.emit_typedefs();
103
104        // Emit code, skipping unused toplevel constants.
105        for stmt in &program.body {
106            self.emit_toplevel(stmt);
107        }
108
109        // After generating all statements, prepend closure struct definitions
110        // so they appear at module level (before all functions).
111        if !self.closure_defs.is_empty() {
112            let mut prefix = String::new();
113            for def in self.closure_defs.iter() {
114                prefix.push_str(def);
115                prefix.push('\n');
116            }
117            self.output = prefix + &self.output;
118        }
119    }
120
121    fn emit_toplevel(&mut self, stmt: &Statement) {
122        match stmt {
123            Statement::VariableDeclaration(vd) => self.emit_var_decl(vd),
124            Statement::FunctionDeclaration(fd) => {
125                // Determine if this function is an export function.
126                // Priority:
127                // 1. If `exported_functions` is provided (from pipeline), use it.
128                // 2. Otherwise, check if the function is inside `export {...}` (not supported yet).
129                // 3. Default: non-export (pub fn, not C ABI).
130                let fn_name = fd.id.as_ref().map(|id| id.name.as_str());
131                let is_export = if let Some(ref exported) = self.exported_functions {
132                    // Use exported_functions set from pipeline
133                    fn_name.is_some_and(|name| exported.contains(name))
134                } else {
135                    // No export info: default to non-export.
136                    // NOTE: `function foo() {}` (without `export`) is non-export.
137                    false
138                };
139
140                let old_export = self.current_fn_is_export;
141                self.current_fn_is_export = is_export;
142                self.emit_fn(fd);
143                self.current_fn_is_export = old_export;
144            }
145            Statement::ExportNamedDeclaration(export_decl) => {
146                // `export function foo() {}` or `export const foo = ...`
147                // These are ALWAYS export functions.
148                match &export_decl.declaration {
149                    Some(decl) => {
150                        match decl {
151                            Declaration::FunctionDeclaration(fd) => {
152                                // is_export determined by exported_functions set,
153                                // NOT always-true — dependency files only
154                                // export names that the core file re-exports.
155                                let fn_name = fd.id.as_ref().map(|id| id.name.as_str());
156                                let is_export = self
157                                    .exported_functions
158                                    .as_ref()
159                                    .is_some_and(|ex| fn_name.is_some_and(|n| ex.contains(n)));
160                                let old_export = self.current_fn_is_export;
161                                self.current_fn_is_export = is_export;
162                                self.emit_fn(fd);
163                                self.current_fn_is_export = old_export;
164                            }
165                            Declaration::VariableDeclaration(vd) => {
166                                self.emit_var_decl(vd);
167                            }
168                            _ => { /* skip unsupported */ }
169                        }
170                    }
171                    None => { /* skip (e.g., export {{ ... }} */ }
172                }
173            }
174            _ => { /* skip */ }
175        }
176    }
177}