1pub mod builtins;
9pub mod expr;
10pub mod helpers;
11pub mod stmt;
12
13use crate::zigir::types::{IrDecl, IrModule};
14
15use std::collections::HashSet;
16
17use helpers::EmitterHelpers;
18
19pub struct Emitter {
32 output: String,
33 indent: usize,
34 inside_try_block: Option<String>,
36 try_label_counter: u32,
38 label_counter: u32,
40 static_init_buffer: String,
46 static_deinit_buffer: String,
50 class_needs_deinit: HashSet<String>,
54}
55
56impl EmitterHelpers for Emitter {
59 fn output(&self) -> &str {
60 &self.output
61 }
62 fn output_mut(&mut self) -> &mut String {
63 &mut self.output
64 }
65 fn indent(&self) -> usize {
66 self.indent
67 }
68 fn indent_mut(&mut self) -> &mut usize {
69 &mut self.indent
70 }
71}
72
73impl Default for Emitter {
74 fn default() -> Self {
75 Self::new()
76 }
77}
78
79impl Emitter {
80 pub fn new() -> Self {
81 Self {
82 output: String::new(),
83 indent: 0,
84 inside_try_block: None,
85 try_label_counter: 0,
86 label_counter: 0,
87 static_init_buffer: String::new(),
88 static_deinit_buffer: String::new(),
89 class_needs_deinit: HashSet::new(),
90 }
91 }
92
93 pub(crate) fn emit_expr_inline(expr: &crate::zigir::types::IrExpr) -> String {
96 let mut sub_emitter = Self::new();
97 sub_emitter.emit_expr(expr);
98 sub_emitter.output.trim().to_string()
99 }
100
101 pub(crate) fn emit_expr_inline_with_label_offset(
106 expr: &crate::zigir::types::IrExpr,
107 label_offset: u32,
108 ) -> (String, u32) {
109 let mut sub_emitter = Self::new();
110 sub_emitter.label_counter = label_offset;
111 sub_emitter.emit_expr(expr);
112 let new_counter = sub_emitter.label_counter;
113 (sub_emitter.output.trim().to_string(), new_counter)
114 }
115
116 pub fn emit_module(module: &IrModule) -> String {
118 let mut emitter = Self::new();
119 emitter.emit_module_inner(module);
120 emitter.output
121 }
122
123 fn emit_module_inner(&mut self, module: &IrModule) {
124 for closure_struct in &module.closure_structs {
127 self.emit_closure_struct(closure_struct);
128 }
129
130 for typedef in &module.typedefs {
132 self.emit_typedef(typedef);
133 }
134
135 for decl in &module.declarations {
137 self.emit_decl(decl);
138 }
139
140 if !self.static_init_buffer.is_empty() {
145 self.writeln("pub fn init_js2rust() !void {");
146 self.indent_push();
147 let buf = std::mem::take(&mut self.static_init_buffer);
148 self.write(&buf);
149 self.indent_pop();
150 self.writeln("}");
151 }
152
153 if !self.static_deinit_buffer.is_empty() {
156 self.writeln("pub fn deinit_js2rust() void {");
157 self.indent_push();
158 let buf = std::mem::take(&mut self.static_deinit_buffer);
159 self.write(&buf);
160 self.indent_pop();
161 self.writeln("}");
162 }
163 }
164
165 fn emit_decl(&mut self, decl: &IrDecl) {
168 match decl {
169 IrDecl::Var(var_decl) => self.emit_var_decl(var_decl),
170 IrDecl::Fn(fn_decl) => self.emit_fn_decl(fn_decl),
171 IrDecl::Class(class_decl) => self.emit_class_decl(class_decl),
172 IrDecl::CompileError { span: _, msg } => {
173 if msg.starts_with("toplevel") || msg.starts_with("skipped unused") {
176 self.writeln(&format!("// error: {}", msg));
177 } else {
178 self.writeln(&format!("@compileError(\"{}\");", msg));
179 }
180 }
181 }
182 }
183
184 fn next_try_label(&mut self) -> u32 {
186 let n = self.try_label_counter;
187 self.try_label_counter += 1;
188 n
189 }
190
191 fn next_label(&mut self) -> String {
193 let n = self.label_counter;
194 self.label_counter += 1;
195 format!("blk_{}", n)
196 }
197
198 fn peek_label_id(&self) -> u32 {
200 self.label_counter
201 }
202}
203
204#[cfg(test)]
209mod tests {
210 use super::*;
211 use crate::types::ZigType;
212 use crate::zigir::ident::IrIdent;
213 use crate::zigir::types::{IrBlock, IrDecl, IrFnDecl, IrTypedef, IrTypedefField, IrVarDecl};
214
215 #[test]
216 fn test_emit_empty_module() {
217 let module = IrModule::new("test".to_string());
218 let output = Emitter::emit_module(&module);
219 assert!(output.is_empty());
220 }
221
222 #[test]
223 fn test_emit_typedef() {
224 let mut module = IrModule::new("test".to_string());
225 module.typedefs.push(IrTypedef {
226 name: "Point".to_string(),
227 fields: vec![
228 IrTypedefField {
229 name: "x".to_string(),
230 zig_type: "f64".to_string(),
231 optional: false,
232 },
233 IrTypedefField {
234 name: "y".to_string(),
235 zig_type: "f64".to_string(),
236 optional: false,
237 },
238 ],
239 is_opaque: false,
240 has_to_json: true,
241 });
242 let output = Emitter::emit_module(&module);
243 assert!(output.contains("const Point = struct {"));
244 assert!(output.contains("x: f64,"));
245 assert!(output.contains("y: f64,"));
246 assert!(output.contains("pub fn toJson"));
247 }
248
249 #[test]
250 fn test_emit_var_decl() {
251 let mut module = IrModule::new("test".to_string());
252 module.declarations.push(IrDecl::Var(IrVarDecl::new_const(
253 "x",
254 Some(ZigType::I64),
255 Some(crate::zigir::types::IrExpr::IntLiteral(42)),
256 )));
257 let output = Emitter::emit_module(&module);
258 assert!(output.contains("const x = 42"));
259 }
260
261 #[test]
262 fn test_emit_fn_decl() {
263 let module = crate::zigir::passes::make_clean_add_module();
264 let output = Emitter::emit_module(&module);
265 assert!(output.contains("pub fn add(a: i64, b: i64) i64"));
266 }
267
268 #[test]
269 fn test_emit_fn_decl_with_throw() {
270 let mut module = IrModule::new("test".to_string());
271 module.declarations.push(IrDecl::Fn(IrFnDecl {
272 name: IrIdent::new("mayFail"),
273 params: vec![],
274 return_type: ZigType::I64,
275 body: IrBlock::new(vec![]),
276 is_export: false,
277 is_async: false,
278 can_throw: true,
279 is_cabi: false,
280 typeof_return_body: None,
281 }));
282 let output = Emitter::emit_module(&module);
283 assert!(output.contains("fn mayFail() !i64 {"));
284 }
285
286 #[test]
287 fn test_emit_class_with_deinit() {
288 use crate::zigir::types::{IrClassDecl, IrClassField, IrClassMethod};
289
290 let mut module = IrModule::new("test".to_string());
291 module.declarations.push(IrDecl::Class(IrClassDecl {
293 name: IrIdent::new("Cache"),
294 fields: vec![
295 IrClassField {
296 name: "data".to_string(),
297 zig_type: ZigType::NamedStruct("Map".to_string()),
298 default: None,
299 },
300 IrClassField {
301 name: "name".to_string(),
302 zig_type: ZigType::I64,
303 default: None,
304 },
305 ],
306 constructor: None,
307 methods: vec![IrClassMethod {
308 name: "get".to_string(),
309 params: vec![],
310 return_type: ZigType::Void,
311 body: IrBlock::new(vec![]),
312 is_static: false,
313 }],
314 static_inits: vec![],
315 static_blocks: vec![],
316 extends: None,
317 needs_deinit: true,
318 }));
319 let output = Emitter::emit_module(&module);
320 assert!(output.contains("pub fn deinit(self: *@This(), alloc: std.mem.Allocator) void {"));
321 assert!(output.contains("self.data.deinit(alloc);"));
322 let deinit_start = output.find("pub fn deinit").unwrap();
324 let deinit_end = output[deinit_start..].find('}').unwrap() + deinit_start;
325 let deinit_body = &output[deinit_start..deinit_end];
326 assert!(!deinit_body.contains("self.name.deinit"));
327 }
328
329 #[test]
330 fn test_emit_class_without_deinit() {
331 use crate::zigir::types::{IrClassDecl, IrClassField};
332
333 let mut module = IrModule::new("test".to_string());
334 module.declarations.push(IrDecl::Class(IrClassDecl {
336 name: IrIdent::new("Point"),
337 fields: vec![
338 IrClassField {
339 name: "x".to_string(),
340 zig_type: ZigType::I64,
341 default: None,
342 },
343 IrClassField {
344 name: "y".to_string(),
345 zig_type: ZigType::I64,
346 default: None,
347 },
348 ],
349 constructor: None,
350 methods: vec![],
351 static_inits: vec![],
352 static_blocks: vec![],
353 extends: None,
354 needs_deinit: false,
355 }));
356 let output = Emitter::emit_module(&module);
357 assert!(!output.contains("pub fn deinit"));
358 }
359
360 #[test]
361 fn test_emit_map_var_auto_cleanup() {
362 let mut module = IrModule::new("test".to_string());
363 module.declarations.push(IrDecl::Var(IrVarDecl {
364 name: IrIdent::new("m"),
365 is_const: false,
366 zig_type: Some(ZigType::NamedStruct("Map".to_string())),
367 init: None,
368 is_json_parse: false,
369 needs_var_suppression: true,
370 needs_deinit: true,
371 }));
372 let output = Emitter::emit_module(&module);
373 assert!(output.contains("defer m.deinit(js_allocator.allocator());"));
374 }
375
376 #[test]
377 fn test_emit_map_var_returned_no_deinit() {
378 let mut module = IrModule::new("test".to_string());
381 module.declarations.push(IrDecl::Var(IrVarDecl {
382 name: IrIdent::new("m"),
383 is_const: true,
384 zig_type: Some(ZigType::NamedStruct("Map".to_string())),
385 init: None,
386 is_json_parse: false,
387 needs_var_suppression: false,
388 needs_deinit: false, }));
390 let output = Emitter::emit_module(&module);
391 assert!(!output.contains("defer m.deinit"));
392 }
393
394 #[test]
395 fn test_emit_static_map_field_deinit() {
396 use crate::zigir::types::{IrClassDecl, IrClassField};
397
398 let mut module = IrModule::new("test".to_string());
399 module.declarations.push(IrDecl::Class(IrClassDecl {
401 name: IrIdent::new("Registry"),
402 fields: vec![IrClassField {
403 name: "name".to_string(),
404 zig_type: ZigType::I64,
405 default: None,
406 }],
407 constructor: None,
408 methods: vec![],
409 static_inits: vec![(
410 "entries".to_string(),
411 crate::zigir::types::IrExpr::Ident(IrIdent::new("Map")),
412 ZigType::NamedStruct("Map".to_string()),
413 )],
414 static_blocks: vec![],
415 extends: None,
416 needs_deinit: false,
417 }));
418 let output = Emitter::emit_module(&module);
419 assert!(output.contains("pub fn deinit_js2rust() void {"));
420 assert!(output.contains("__Registry_entries.deinit(js_allocator.allocator());"));
421 }
422}