js2zig_core/codegen/
mod.rs1use crate::native_proto::Codegen;
5use oxc_ast::ast::*;
6use oxc_span::Span;
7
8pub mod expr;
9pub mod helpers;
10pub mod stmt;
11
12impl 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
68impl Codegen {
71 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 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 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 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 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 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
122impl Codegen {
125 fn emit_typedefs(&mut self) {
127 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 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 self.writeln("");
151 self.writeln("pub fn toJson(self: *const @This()) ![]u8 {");
152 self.indent += 1;
153 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 self.emit_typedefs();
174
175 for stmt in &program.body {
177 self.emit_toplevel(stmt);
178 }
179
180 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 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 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 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 fn_name.is_some_and(|name| exported.contains(name))
220 } else {
221 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 match &export_decl.declaration {
235 Some(decl) => {
236 match decl {
237 Declaration::FunctionDeclaration(fd) => {
238 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 _ => { }
255 }
256 }
257 None => { }
258 }
259 }
260 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 _ => { }
268 }
269
270 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}