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 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
67impl Codegen {
70 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 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 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 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 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 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
121impl Codegen {
124 fn emit_typedefs(&mut self) {
126 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 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 self.writeln("");
150 self.writeln("pub fn toJson(self: *const @This()) ![]u8 {");
151 self.indent += 1;
152 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 self.emit_typedefs();
173
174 for stmt in &program.body {
176 self.emit_toplevel(stmt);
177 }
178
179 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 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 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 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 fn_name.is_some_and(|name| exported.contains(name))
219 } else {
220 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 match &export_decl.declaration {
234 Some(decl) => {
235 match decl {
236 Declaration::FunctionDeclaration(fd) => {
237 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 _ => { }
254 }
255 }
256 None => { }
257 }
258 }
259 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 _ => { }
267 }
268
269 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}