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("var string = std.io.Writer.Allocating.init(js_allocator.allocator());");
155 self.writeln("errdefer string.deinit();");
156 self.writeln("try string.writer().print(\"{f}\", .{std.json.fmt(self.*, .{})});");
157 self.writeln("return string.toOwnedSlice();");
158 self.indent -= 1;
159 self.writeln("}");
160 self.indent -= 1;
161 self.writeln("};");
162 self.writeln("");
163 }
164 }
165
166 pub fn generate(&mut self, program: &Program) {
167 self.emit_typedefs();
172
173 for stmt in &program.body {
175 self.emit_toplevel(stmt);
176 }
177
178 if !self.closure_defs.is_empty() {
181 let mut prefix = String::new();
182 for def in self.closure_defs.iter() {
183 prefix.push_str(def);
184 prefix.push('\n');
185 }
186 self.output = prefix + &self.output;
187 }
188 }
189
190 fn emit_toplevel(&mut self, stmt: &Statement) {
191 if !self.pending_expr_fns.is_empty() {
193 let pending = std::mem::take(&mut self.pending_expr_fns);
194 for def in pending {
195 self.write(&def);
196 }
197 }
198
199 let snapshot = self.output.len();
202
203 match stmt {
204 Statement::VariableDeclaration(vd) => self.emit_var_decl(vd),
205 Statement::ClassDeclaration(cd) => {
206 self.emit_class(cd);
207 }
208 Statement::FunctionDeclaration(fd) => {
209 let fn_name = fd.id.as_ref().map(|id| id.name.as_str());
215 let is_export = if let Some(ref exported) = self.exported_functions {
216 fn_name.is_some_and(|name| exported.contains(name))
218 } else {
219 false
222 };
223
224 let old_export = self.current_fn_is_export;
225 self.current_fn_is_export = is_export;
226 self.emit_fn(fd);
227 self.current_fn_is_export = old_export;
228 }
229 Statement::ExportNamedDeclaration(export_decl) => {
230 match &export_decl.declaration {
233 Some(decl) => {
234 match decl {
235 Declaration::FunctionDeclaration(fd) => {
236 let fn_name = fd.id.as_ref().map(|id| id.name.as_str());
240 let is_export = self
241 .exported_functions
242 .as_ref()
243 .is_some_and(|ex| fn_name.is_some_and(|n| ex.contains(n)));
244 let old_export = self.current_fn_is_export;
245 self.current_fn_is_export = is_export;
246 self.emit_fn(fd);
247 self.current_fn_is_export = old_export;
248 }
249 Declaration::VariableDeclaration(vd) => {
250 self.emit_var_decl(vd);
251 }
252 _ => { }
253 }
254 }
255 None => { }
256 }
257 }
258 Statement::WithStatement(ws) => {
260 self.compile_error_stmt(
261 ws.span,
262 "with statement is not supported and deprecated in strict mode. Use explicit property access instead.",
263 );
264 }
265 _ => { }
266 }
267
268 if !self.pending_expr_fns.is_empty() {
271 let pending = std::mem::take(&mut self.pending_expr_fns);
272 let statement_output = self.output[snapshot..].to_string();
273 self.output.truncate(snapshot);
274 for def in pending {
275 self.write(&def);
276 }
277 self.write(&statement_output);
278 }
279 }
280}