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