Skip to main content

js2zig_core/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::*;
6use oxc_span::Span;
7
8pub mod expr;
9pub mod helpers;
10pub mod stmt;
11
12// ── Constructor ─────────────────────────────────────
13
14impl Codegen {
15    pub fn new(
16        type_info: crate::native_proto::TypeCheckResult,
17        jsdoc_data: crate::native_proto::JSDocData,
18        exported_functions: Option<std::collections::HashSet<String>>,
19        async_host_fns: std::collections::HashSet<String>,
20        source: String,
21    ) -> Self {
22        Self {
23            output: String::new(),
24            indent: 0,
25            errors: Vec::new(),
26            warnings: Vec::new(),
27            type_info,
28            jsdoc_data: Some(jsdoc_data),
29            current_fn_is_export: false,
30            current_fn_return_type: None,
31            exported_fns: Vec::new(),
32            task_counter: 0,
33            exported_functions,
34            seen_return: false,
35            fn_has_throw: false,
36            in_return_expr: false,
37            in_expr_stmt: false,
38            call_generated_catch: false,
39            try_label_counter: 0,
40            arrow_counter: 0,
41            inside_try_block: None,
42            current_fn: None,
43            current_captured: Vec::new(),
44            closure_vars: std::collections::HashMap::new(),
45            closure_instances: std::collections::HashSet::new(),
46            closure_defs: Vec::new(),
47            oc_counter: 0,
48            destructure_counter: 0,
49            for_of_counter: 0,
50            fn_expr_counter: 0,
51            pending_expr_fns: Vec::new(),
52            typedarray_vars: std::collections::HashMap::new(),
53            regexp_vars: std::collections::HashSet::new(),
54            async_host_fns,
55            nested_fn_names: std::collections::HashSet::new(),
56            current_nested_fn_name: None,
57            current_class: None,
58            class_names: std::collections::HashSet::new(),
59            source,
60            label_counter: 0,
61            fn_scope_vars: std::collections::HashSet::new(),
62            shadow_renames: Vec::new(),
63            shadow_counter: 0,
64        }
65    }
66}
67
68// ── Diagnostics helpers ──────────────────────────────
69
70impl Codegen {
71    /// Convert a byte offset into the source text to (1-based line, 1-based column).
72    fn offset_to_line_col(&self, offset: u32) -> (usize, usize) {
73        let offset = offset as usize;
74        let mut line: usize = 1;
75        let mut col: usize = 1;
76        for (i, ch) in self.source.char_indices() {
77            if i >= offset {
78                break;
79            }
80            if ch == '\n' {
81                line += 1;
82                col = 1;
83            } else {
84                col += 1;
85            }
86        }
87        (line, col)
88    }
89
90    /// Format a Span as "line:col".
91    fn span_to_string(&self, span: Span) -> String {
92        let (line, col) = self.offset_to_line_col(span.start);
93        format!("{}:{}", line, col)
94    }
95
96    /// Write a `@compileError("msg (at L:C)")` with source location (no trailing `;\n`).
97    /// For statement-level use, call `compile_error_stmt` instead (adds `;\n`).
98    pub(crate) fn compile_error(&mut self, span: Span, msg: &str) {
99        let loc = self.span_to_string(span);
100        self.write(&format!("@compileError(\"{msg} (at {loc})\")"));
101    }
102
103    /// Write a `@compileError(...)` with source location, taking an already-formatted message.
104    pub(crate) fn compile_error_fmt(&mut self, span: Span, msg: String) {
105        let loc = self.span_to_string(span);
106        self.write(&format!("@compileError(\"{msg} (at {loc})\")"));
107    }
108
109    /// Like `compile_error` but for statement-level: writes `;\n` after the call.
110    pub(crate) fn compile_error_stmt(&mut self, span: Span, msg: &str) {
111        let loc = self.span_to_string(span);
112        self.write(&format!("@compileError(\"{msg} (at {loc})\");\n"));
113    }
114
115    /// Like `compile_error_fmt` but for statement-level: writes `;\n` after the call.
116    pub(crate) fn compile_error_stmt_fmt(&mut self, span: Span, msg: String) {
117        let loc = self.span_to_string(span);
118        self.write(&format!("@compileError(\"{msg} (at {loc})\");\n"));
119    }
120}
121
122// ── Entry point ─────────────────────────────────────
123
124impl Codegen {
125    /// Emit all @typedef struct definitions at the top of the generated file.
126    fn emit_typedefs(&mut self) {
127        // Clone typedefs to avoid borrow checker issues
128        let typedefs = match &self.jsdoc_data {
129            Some(data) => data.typedefs.clone(),
130            None => return,
131        };
132        if typedefs.is_empty() {
133            return;
134        }
135        for (name, td) in &typedefs {
136            self.writeln(&format!("const {} = struct {{", name));
137            self.indent += 1;
138            for field in &td.fields {
139                let zig_ty = crate::native_proto::jsdoc::jsdoc_type_to_zig(&field.ty, &typedefs);
140                // Optional field: prepend ? to the type
141                let zig_ty = if field.optional {
142                    format!("?{}", zig_ty)
143                } else {
144                    zig_ty
145                };
146                self.writeln(&format!("{}: {},", field.name, zig_ty));
147            }
148            // Generate toJson() method for serialization using std.json.fmt()
149            // Use the global arena allocator (js_allocator.getAllocator()).
150            self.writeln("");
151            self.writeln("pub fn toJson(self: *const @This()) ![]u8 {");
152            self.indent += 1;
153            // Use std.io.Writer.Allocating + std.json.fmt() for serialization
154            self.writeln(
155                "var string = std.io.Writer.Allocating.init(js_allocator.getAllocator());",
156            );
157            self.writeln("errdefer string.deinit();");
158            self.writeln("try string.writer().print(\"{f}\", .{std.json.fmt(self.*, .{})});");
159            self.writeln("return string.toOwnedSlice();");
160            self.indent -= 1;
161            self.writeln("}");
162            self.indent -= 1;
163            self.writeln("};");
164            self.writeln("");
165        }
166    }
167
168    pub fn generate(&mut self, program: &Program) {
169        // Phase A: analyze_objects, collect_used_names, walk_stmt_for_types
170        // are all handled by TypeInferrer::infer_all() before codegen starts.
171
172        // Emit struct typedefs (from JSDoc @typedef).
173        self.emit_typedefs();
174
175        // Emit code, skipping unused toplevel constants.
176        for stmt in &program.body {
177            self.emit_toplevel(stmt);
178        }
179
180        // After generating all statements, prepend closure struct definitions
181        // so they appear at module level (before all functions).
182        if !self.closure_defs.is_empty() {
183            let mut prefix = String::new();
184            for def in self.closure_defs.iter() {
185                prefix.push_str(def);
186                prefix.push('\n');
187            }
188            self.output = prefix + &self.output;
189        }
190    }
191
192    fn emit_toplevel(&mut self, stmt: &Statement) {
193        // Flush any function definitions that were deferred from a previous statement.
194        if !self.pending_expr_fns.is_empty() {
195            let pending = std::mem::take(&mut self.pending_expr_fns);
196            for def in pending {
197                self.write(&def);
198            }
199        }
200
201        // Snapshot: if this statement generates deferred function definitions,
202        // they must be inserted BEFORE the statement output.
203        let snapshot = self.output.len();
204
205        match stmt {
206            Statement::VariableDeclaration(vd) => self.emit_var_decl(vd),
207            Statement::ClassDeclaration(cd) => {
208                self.emit_class(cd);
209            }
210            Statement::FunctionDeclaration(fd) => {
211                // Determine if this function is an export function.
212                // Priority:
213                // 1. If `exported_functions` is provided (from pipeline), use it.
214                // 2. Otherwise, check if the function is inside `export {...}` (not supported yet).
215                // 3. Default: non-export (pub fn, not C ABI).
216                let fn_name = fd.id.as_ref().map(|id| id.name.as_str());
217                let is_export = if let Some(ref exported) = self.exported_functions {
218                    // Use exported_functions set from pipeline
219                    fn_name.is_some_and(|name| exported.contains(name))
220                } else {
221                    // No export info: default to non-export.
222                    // NOTE: `function foo() {}` (without `export`) is non-export.
223                    false
224                };
225
226                let old_export = self.current_fn_is_export;
227                self.current_fn_is_export = is_export;
228                self.emit_fn(fd);
229                self.current_fn_is_export = old_export;
230            }
231            Statement::ExportNamedDeclaration(export_decl) => {
232                // `export function foo() {}` or `export const foo = ...`
233                // These are ALWAYS export functions.
234                match &export_decl.declaration {
235                    Some(decl) => {
236                        match decl {
237                            Declaration::FunctionDeclaration(fd) => {
238                                // is_export determined by exported_functions set,
239                                // NOT always-true — dependency files only
240                                // export names that the core file re-exports.
241                                let fn_name = fd.id.as_ref().map(|id| id.name.as_str());
242                                let is_export = self
243                                    .exported_functions
244                                    .as_ref()
245                                    .is_some_and(|ex| fn_name.is_some_and(|n| ex.contains(n)));
246                                let old_export = self.current_fn_is_export;
247                                self.current_fn_is_export = is_export;
248                                self.emit_fn(fd);
249                                self.current_fn_is_export = old_export;
250                            }
251                            Declaration::VariableDeclaration(vd) => {
252                                self.emit_var_decl(vd);
253                            }
254                            _ => { /* skip unsupported */ }
255                        }
256                    }
257                    None => { /* skip (e.g., export {{ ... }} */ }
258                }
259            }
260            // 🔘 with statement: not supported (deprecated in strict mode)
261            Statement::WithStatement(ws) => {
262                self.compile_error_stmt(
263                    ws.span,
264                    "with statement is not supported and deprecated in strict mode. Use explicit property access instead.",
265                );
266            }
267            _ => { /* skip */ }
268        }
269
270        // If this toplevel statement generated deferred function definitions,
271        // insert them BEFORE the statement output (def-before-use).
272        if !self.pending_expr_fns.is_empty() {
273            let pending = std::mem::take(&mut self.pending_expr_fns);
274            let statement_output = self.output[snapshot..].to_string();
275            self.output.truncate(snapshot);
276            for def in pending {
277                self.write(&def);
278            }
279            self.write(&statement_output);
280        }
281    }
282}