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 in_function: bool,
45 static_init_buffer: String,
51 static_deinit_buffer: String,
55 class_needs_deinit: HashSet<String>,
59 rest_param_names: HashSet<String>,
63}
64
65impl EmitterHelpers for Emitter {
68 fn output(&self) -> &str {
69 &self.output
70 }
71 fn output_mut(&mut self) -> &mut String {
72 &mut self.output
73 }
74 fn indent(&self) -> usize {
75 self.indent
76 }
77 fn indent_mut(&mut self) -> &mut usize {
78 &mut self.indent
79 }
80}
81
82impl Default for Emitter {
83 fn default() -> Self {
84 Self::new()
85 }
86}
87
88impl Emitter {
89 pub fn new() -> Self {
90 Self {
91 output: String::new(),
92 indent: 0,
93 inside_try_block: None,
94 try_label_counter: 0,
95 label_counter: 0,
96 in_function: false,
97 static_init_buffer: String::new(),
98 static_deinit_buffer: String::new(),
99 class_needs_deinit: HashSet::new(),
100 rest_param_names: HashSet::new(),
101 }
102 }
103
104 pub(crate) fn emit_expr_inline(expr: &crate::zigir::types::IrExpr) -> String {
107 let mut sub_emitter = Self::new();
108 sub_emitter.emit_expr(expr);
109 sub_emitter.output.trim().to_string()
110 }
111
112 pub(crate) fn emit_expr_inline_with_label_offset(
117 expr: &crate::zigir::types::IrExpr,
118 label_offset: u32,
119 ) -> (String, u32) {
120 let mut sub_emitter = Self::new();
121 sub_emitter.label_counter = label_offset;
122 sub_emitter.emit_expr(expr);
123 let new_counter = sub_emitter.label_counter;
124 (sub_emitter.output.trim().to_string(), new_counter)
125 }
126
127 pub fn emit_module(module: &IrModule) -> String {
129 let mut emitter = Self::new();
130 emitter.emit_module_inner(module);
131 emitter.output
132 }
133
134 fn emit_module_inner(&mut self, module: &IrModule) {
135 for decl in &module.declarations {
137 if let IrDecl::Fn(fn_decl) = decl {
138 for param in &fn_decl.params {
139 if param.is_rest {
140 self.rest_param_names.insert(param.name.zig_name.clone());
141 }
142 }
143 }
144 }
145
146 for closure_struct in &module.closure_structs {
149 self.emit_closure_struct(closure_struct);
150 }
151
152 for typedef in &module.typedefs {
154 self.emit_typedef(typedef);
155 }
156
157 for decl in &module.declarations {
159 self.emit_decl(decl);
160 }
161
162 if !self.static_init_buffer.is_empty() {
167 self.writeln("pub fn init_js2rust() !void {");
168 self.indent_push();
169 let buf = std::mem::take(&mut self.static_init_buffer);
170 self.write(&buf);
171 self.indent_pop();
172 self.writeln("}");
173 }
174
175 if !self.static_deinit_buffer.is_empty() {
178 self.writeln("pub fn deinit_js2rust() void {");
179 self.indent_push();
180 let buf = std::mem::take(&mut self.static_deinit_buffer);
181 self.write(&buf);
182 self.indent_pop();
183 self.writeln("}");
184 }
185 }
186
187 fn emit_decl(&mut self, decl: &IrDecl) {
190 match decl {
191 IrDecl::Var(var_decl) => self.emit_var_decl(var_decl),
192 IrDecl::Fn(fn_decl) => self.emit_fn_decl(fn_decl),
193 IrDecl::Class(class_decl) => self.emit_class_decl(class_decl),
194 IrDecl::CompileError { span: _, msg } => {
195 if msg.starts_with("toplevel") || msg.starts_with("skipped unused") {
198 self.writeln(&format!("// error: {}", msg));
199 } else {
200 self.writeln(&format!("@compileError(\"{}\");", msg));
201 }
202 }
203 }
204 }
205
206 fn next_try_label(&mut self) -> u32 {
208 let n = self.try_label_counter;
209 self.try_label_counter += 1;
210 n
211 }
212
213 fn next_label(&mut self) -> String {
215 let n = self.label_counter;
216 self.label_counter += 1;
217 format!("blk_{}", n)
218 }
219
220 fn peek_label_id(&self) -> u32 {
222 self.label_counter
223 }
224}
225
226#[cfg(test)]
231mod tests {
232 use super::*;
233 use crate::types::ZigType;
234 use crate::zigir::ident::IrIdent;
235 use crate::zigir::types::{IrBlock, IrDecl, IrFnDecl, IrTypedef, IrTypedefField, IrVarDecl};
236
237 #[test]
238 fn test_emit_empty_module() {
239 let module = IrModule::new("test".to_string());
240 let output = Emitter::emit_module(&module);
241 assert!(output.is_empty());
242 }
243
244 #[test]
245 fn test_emit_typedef() {
246 let mut module = IrModule::new("test".to_string());
247 module.typedefs.push(IrTypedef {
248 name: "Point".to_string(),
249 fields: vec![
250 IrTypedefField {
251 name: "x".to_string(),
252 zig_type: "f64".to_string(),
253 optional: false,
254 },
255 IrTypedefField {
256 name: "y".to_string(),
257 zig_type: "f64".to_string(),
258 optional: false,
259 },
260 ],
261 is_opaque: false,
262 has_to_json: true,
263 });
264 let output = Emitter::emit_module(&module);
265 assert!(output.contains("const Point = struct {"));
266 assert!(output.contains("x: f64,"));
267 assert!(output.contains("y: f64,"));
268 assert!(output.contains("pub fn toJson"));
269 }
270
271 #[test]
272 fn test_emit_var_decl() {
273 let mut module = IrModule::new("test".to_string());
274 module.declarations.push(IrDecl::Var(IrVarDecl::new_const(
275 "x",
276 Some(ZigType::I64),
277 Some(crate::zigir::types::IrExpr::IntLiteral(42)),
278 )));
279 let output = Emitter::emit_module(&module);
280 assert!(output.contains("const x = 42"));
281 }
282
283 #[test]
284 fn test_emit_fn_decl() {
285 let module = crate::zigir::passes::make_clean_add_module();
286 let output = Emitter::emit_module(&module);
287 assert!(output.contains("pub fn add(a: i64, b: i64) i64"));
288 }
289
290 #[test]
291 fn test_emit_fn_decl_with_throw() {
292 let mut module = IrModule::new("test".to_string());
293 module.declarations.push(IrDecl::Fn(IrFnDecl {
294 name: IrIdent::new("mayFail"),
295 params: vec![],
296 return_type: ZigType::I64,
297 body: IrBlock::new(vec![]),
298 is_export: false,
299 is_async: false,
300 can_throw: true,
301 is_cabi: false,
302 typeof_return_body: None,
303 }));
304 let output = Emitter::emit_module(&module);
305 assert!(output.contains("fn mayFail() !i64 {"));
306 }
307
308 #[test]
309 fn test_emit_class_with_deinit() {
310 use crate::zigir::types::{IrClassDecl, IrClassField, IrClassMethod};
311
312 let mut module = IrModule::new("test".to_string());
313 module.declarations.push(IrDecl::Class(IrClassDecl {
315 name: IrIdent::new("Cache"),
316 fields: vec![
317 IrClassField {
318 name: "data".to_string(),
319 zig_type: ZigType::NamedStruct("Map".to_string()),
320 default: None,
321 },
322 IrClassField {
323 name: "name".to_string(),
324 zig_type: ZigType::I64,
325 default: None,
326 },
327 ],
328 constructor: None,
329 methods: vec![IrClassMethod {
330 name: "get".to_string(),
331 params: vec![],
332 return_type: ZigType::Void,
333 body: IrBlock::new(vec![]),
334 is_static: false,
335 }],
336 static_inits: vec![],
337 static_blocks: vec![],
338 extends: None,
339 needs_deinit: true,
340 }));
341 let output = Emitter::emit_module(&module);
342 assert!(output.contains("pub fn deinit(self: *@This(), alloc: std.mem.Allocator) void {"));
343 assert!(output.contains("self.data.deinit(alloc);"));
344 let deinit_start = output.find("pub fn deinit").unwrap();
346 let deinit_end = output[deinit_start..].find('}').unwrap() + deinit_start;
347 let deinit_body = &output[deinit_start..deinit_end];
348 assert!(!deinit_body.contains("self.name.deinit"));
349 }
350
351 #[test]
352 fn test_emit_class_without_deinit() {
353 use crate::zigir::types::{IrClassDecl, IrClassField};
354
355 let mut module = IrModule::new("test".to_string());
356 module.declarations.push(IrDecl::Class(IrClassDecl {
358 name: IrIdent::new("Point"),
359 fields: vec![
360 IrClassField {
361 name: "x".to_string(),
362 zig_type: ZigType::I64,
363 default: None,
364 },
365 IrClassField {
366 name: "y".to_string(),
367 zig_type: ZigType::I64,
368 default: None,
369 },
370 ],
371 constructor: None,
372 methods: vec![],
373 static_inits: vec![],
374 static_blocks: vec![],
375 extends: None,
376 needs_deinit: false,
377 }));
378 let output = Emitter::emit_module(&module);
379 assert!(!output.contains("pub fn deinit"));
380 }
381
382 #[test]
383 fn test_emit_map_var_auto_cleanup() {
384 let mut module = IrModule::new("test".to_string());
385 module.declarations.push(IrDecl::Var(IrVarDecl {
386 name: IrIdent::new("m"),
387 is_const: false,
388 zig_type: Some(ZigType::NamedStruct("Map".to_string())),
389 init: None,
390 is_json_parse: false,
391 needs_var_suppression: true,
392 needs_deinit: true,
393 }));
394 let output = Emitter::emit_module(&module);
395 assert!(output.contains("defer m.deinit(js_allocator.allocator());"));
396 }
397
398 #[test]
399 fn test_emit_map_var_returned_no_deinit() {
400 let mut module = IrModule::new("test".to_string());
403 module.declarations.push(IrDecl::Var(IrVarDecl {
404 name: IrIdent::new("m"),
405 is_const: true,
406 zig_type: Some(ZigType::NamedStruct("Map".to_string())),
407 init: None,
408 is_json_parse: false,
409 needs_var_suppression: false,
410 needs_deinit: false, }));
412 let output = Emitter::emit_module(&module);
413 assert!(!output.contains("defer m.deinit"));
414 }
415
416 #[test]
417 fn test_emit_static_map_field_deinit() {
418 use crate::zigir::types::{IrClassDecl, IrClassField};
419
420 let mut module = IrModule::new("test".to_string());
421 module.declarations.push(IrDecl::Class(IrClassDecl {
423 name: IrIdent::new("Registry"),
424 fields: vec![IrClassField {
425 name: "name".to_string(),
426 zig_type: ZigType::I64,
427 default: None,
428 }],
429 constructor: None,
430 methods: vec![],
431 static_inits: vec![(
432 "entries".to_string(),
433 crate::zigir::types::IrExpr::Ident(IrIdent::new("Map")),
434 ZigType::NamedStruct("Map".to_string()),
435 )],
436 static_blocks: vec![],
437 extends: None,
438 needs_deinit: false,
439 }));
440 let output = Emitter::emit_module(&module);
441 assert!(output.contains("pub fn deinit_js2rust() void {"));
442 assert!(output.contains("__Registry_entries.deinit(js_allocator.allocator());"));
443 }
444}