1pub mod builtins;
9pub mod expr;
10pub mod helpers;
11pub mod stmt;
12
13use crate::types::ZigType;
14use crate::zigir::types::{IrDecl, IrModule};
15
16use std::collections::HashSet;
17
18use helpers::EmitterHelpers;
19
20pub struct Emitter {
33 output: String,
34 indent: usize,
35 inside_try_block: Option<String>,
37 try_label_counter: u32,
39 label_counter: u32,
41 do_while_counter: u32,
49 in_function: bool,
54 static_init_buffer: String,
60 static_deinit_buffer: String,
64 class_needs_deinit: HashSet<String>,
68 rest_param_names: HashSet<String>,
72}
73
74impl EmitterHelpers for Emitter {
77 fn output(&self) -> &str {
78 &self.output
79 }
80 fn output_mut(&mut self) -> &mut String {
81 &mut self.output
82 }
83 fn indent(&self) -> usize {
84 self.indent
85 }
86 fn indent_mut(&mut self) -> &mut usize {
87 &mut self.indent
88 }
89}
90
91impl Default for Emitter {
92 fn default() -> Self {
93 Self::new()
94 }
95}
96
97impl Emitter {
98 pub fn new() -> Self {
99 Self {
100 output: String::new(),
101 indent: 0,
102 inside_try_block: None,
103 try_label_counter: 0,
104 label_counter: 0,
105 do_while_counter: 0,
106 in_function: false,
107 static_init_buffer: String::new(),
108 static_deinit_buffer: String::new(),
109 class_needs_deinit: HashSet::new(),
110 rest_param_names: HashSet::new(),
111 }
112 }
113
114 #[allow(dead_code)]
119 pub(crate) fn emit_expr_inline(expr: &crate::zigir::types::IrExpr) -> String {
120 let mut sub_emitter = Self::new();
121 sub_emitter.emit_expr(expr);
122 sub_emitter.output.trim().to_string()
123 }
124
125 pub(crate) fn emit_expr_inline_with_label_offset(
130 expr: &crate::zigir::types::IrExpr,
131 label_offset: u32,
132 ) -> (String, u32) {
133 let mut sub_emitter = Self::new();
134 sub_emitter.label_counter = label_offset;
135 sub_emitter.emit_expr(expr);
136 let new_counter = sub_emitter.label_counter;
137 (sub_emitter.output.trim().to_string(), new_counter)
138 }
139
140 pub fn emit_module(module: &IrModule) -> String {
142 let mut emitter = Self::new();
143 emitter.emit_module_inner(module);
144 emitter.output
145 }
146
147 fn emit_module_inner(&mut self, module: &IrModule) {
148 for decl in &module.declarations {
150 if let IrDecl::Fn(fn_decl) = decl {
151 for param in &fn_decl.params {
152 if param.is_rest {
153 self.rest_param_names.insert(param.name.zig_name.clone());
154 }
155 }
156 }
157 }
158
159 for decl in &module.declarations {
166 let IrDecl::Class(cls) = decl else {
167 continue;
168 };
169 if cls.needs_deinit {
170 self.class_needs_deinit.insert(cls.name.zig_name.clone());
171 }
172 }
173 loop {
174 let mut changed = false;
175 for decl in &module.declarations {
176 let IrDecl::Class(cls) = decl else {
177 continue;
178 };
179 let name = &cls.name.zig_name;
180 if self.class_needs_deinit.contains(name) {
181 continue;
182 }
183 let has_deinit_field = cls.fields.iter().any(|f| {
184 matches!(
185 &f.zig_type,
186 ZigType::NamedStruct(n) if self.class_needs_deinit.contains(n.as_str())
187 )
188 });
189 if has_deinit_field {
190 self.class_needs_deinit.insert(name.clone());
191 changed = true;
192 }
193 }
194 if !changed {
195 break;
196 }
197 }
198
199 for closure_struct in &module.closure_structs {
202 self.emit_closure_struct(closure_struct);
203 }
204
205 for typedef in &module.typedefs {
207 self.emit_typedef(typedef);
208 }
209
210 for decl in &module.declarations {
212 self.emit_decl(decl);
213 }
214
215 if !self.static_init_buffer.is_empty() {
220 self.writeln("pub fn init_js2rust() !void {");
221 self.indent_push();
222 let buf = std::mem::take(&mut self.static_init_buffer);
223 self.write(&buf);
224 self.indent_pop();
225 self.writeln("}");
226 }
227
228 if !self.static_deinit_buffer.is_empty() {
231 self.writeln("pub fn deinit_js2rust() void {");
232 self.indent_push();
233 let buf = std::mem::take(&mut self.static_deinit_buffer);
234 self.write(&buf);
235 self.indent_pop();
236 self.writeln("}");
237 }
238 }
239
240 fn emit_decl(&mut self, decl: &IrDecl) {
243 match decl {
244 IrDecl::Var(var_decl) => self.emit_var_decl(var_decl),
245 IrDecl::Fn(fn_decl) => self.emit_fn_decl(fn_decl),
246 IrDecl::Class(class_decl) => self.emit_class_decl(class_decl),
247 IrDecl::CompileError { span: _, msg } => {
248 if msg.starts_with("toplevel") || msg.starts_with("skipped unused") {
251 self.writeln(&format!("// error: {}", msg));
252 } else {
253 self.writeln(&format!("@compileError(\"{}\");", msg));
254 }
255 }
256 }
257 }
258
259 fn next_try_label(&mut self) -> u32 {
261 let n = self.try_label_counter;
262 self.try_label_counter += 1;
263 n
264 }
265
266 fn next_label(&mut self) -> String {
268 let n = self.label_counter;
269 self.label_counter += 1;
270 format!("blk_{}", n)
271 }
272
273 fn next_do_while_flag(&mut self) -> String {
278 let n = self.do_while_counter;
279 self.do_while_counter += 1;
280 format!("__dw_first_{}", n)
281 }
282
283 fn peek_label_id(&self) -> u32 {
285 self.label_counter
286 }
287}
288
289#[cfg(test)]
294mod tests {
295 use super::*;
296 use crate::types::ZigType;
297 use crate::zigir::ident::IrIdent;
298 use crate::zigir::types::{IrBlock, IrDecl, IrFnDecl, IrTypedef, IrTypedefField, IrVarDecl};
299
300 #[test]
301 fn test_emit_empty_module() {
302 let module = IrModule::new("test".to_string());
303 let output = Emitter::emit_module(&module);
304 assert!(output.is_empty());
305 }
306
307 #[test]
308 fn test_emit_typedef() {
309 let mut module = IrModule::new("test".to_string());
310 module.typedefs.push(IrTypedef {
311 name: "Point".to_string(),
312 fields: vec![
313 IrTypedefField {
314 name: "x".to_string(),
315 zig_type: "f64".to_string(),
316 optional: false,
317 },
318 IrTypedefField {
319 name: "y".to_string(),
320 zig_type: "f64".to_string(),
321 optional: false,
322 },
323 ],
324 is_opaque: false,
325 has_to_json: true,
326 });
327 let output = Emitter::emit_module(&module);
328 assert!(output.contains("const Point = struct {"));
329 assert!(output.contains("x: f64,"));
330 assert!(output.contains("y: f64,"));
331 assert!(output.contains("pub fn toJson"));
332 }
333
334 #[test]
335 fn test_emit_var_decl() {
336 let mut module = IrModule::new("test".to_string());
337 module.declarations.push(IrDecl::Var(IrVarDecl::new_const(
338 "x",
339 Some(ZigType::I64),
340 Some(crate::zigir::types::IrExpr::IntLiteral(42)),
341 )));
342 let output = Emitter::emit_module(&module);
343 assert!(output.contains("const x = 42"));
344 }
345
346 #[test]
347 fn test_emit_fn_decl() {
348 let module = crate::zigir::passes::make_clean_add_module();
349 let output = Emitter::emit_module(&module);
350 assert!(output.contains("pub fn add(a: i64, b: i64) i64"));
351 }
352
353 #[test]
354 fn test_emit_fn_decl_with_throw() {
355 let mut module = IrModule::new("test".to_string());
356 module.declarations.push(IrDecl::Fn(IrFnDecl {
357 name: IrIdent::new("mayFail"),
358 params: vec![],
359 return_type: ZigType::I64,
360 body: IrBlock::new(vec![]),
361 is_export: false,
362 is_async: false,
363 can_throw: true,
364 is_cabi: false,
365 typeof_return_body: None,
366 }));
367 let output = Emitter::emit_module(&module);
368 assert!(output.contains("fn mayFail() !i64 {"));
369 }
370
371 #[test]
372 fn test_emit_class_with_deinit() {
373 use crate::zigir::types::{IrClassDecl, IrClassField, IrClassMethod};
374
375 let mut module = IrModule::new("test".to_string());
376 module.declarations.push(IrDecl::Class(IrClassDecl {
378 name: IrIdent::new("Cache"),
379 fields: vec![
380 IrClassField {
381 name: "data".to_string(),
382 zig_type: ZigType::NamedStruct("Map".to_string()),
383 default: None,
384 },
385 IrClassField {
386 name: "name".to_string(),
387 zig_type: ZigType::I64,
388 default: None,
389 },
390 ],
391 constructor: None,
392 methods: vec![IrClassMethod {
393 name: "get".to_string(),
394 params: vec![],
395 return_type: ZigType::Void,
396 body: IrBlock::new(vec![]),
397 is_static: false,
398 }],
399 static_inits: vec![],
400 static_blocks: vec![],
401 extends: None,
402 needs_deinit: true,
403 }));
404 let output = Emitter::emit_module(&module);
405 assert!(output.contains("pub fn deinit(self: *@This(), alloc: std.mem.Allocator) void {"));
406 assert!(output.contains("self.data.deinit(alloc);"));
407 let deinit_start = output.find("pub fn deinit").unwrap();
409 let deinit_end = output[deinit_start..].find('}').unwrap() + deinit_start;
410 let deinit_body = &output[deinit_start..deinit_end];
411 assert!(!deinit_body.contains("self.name.deinit"));
412 }
413
414 #[test]
415 fn test_emit_class_without_deinit() {
416 use crate::zigir::types::{IrClassDecl, IrClassField};
417
418 let mut module = IrModule::new("test".to_string());
419 module.declarations.push(IrDecl::Class(IrClassDecl {
421 name: IrIdent::new("Point"),
422 fields: vec![
423 IrClassField {
424 name: "x".to_string(),
425 zig_type: ZigType::I64,
426 default: None,
427 },
428 IrClassField {
429 name: "y".to_string(),
430 zig_type: ZigType::I64,
431 default: None,
432 },
433 ],
434 constructor: None,
435 methods: vec![],
436 static_inits: vec![],
437 static_blocks: vec![],
438 extends: None,
439 needs_deinit: false,
440 }));
441 let output = Emitter::emit_module(&module);
442 assert!(!output.contains("pub fn deinit"));
443 }
444
445 #[test]
446 fn test_emit_map_var_auto_cleanup() {
447 let mut module = IrModule::new("test".to_string());
448 module.declarations.push(IrDecl::Var(IrVarDecl {
449 name: IrIdent::new("m"),
450 is_const: false,
451 zig_type: Some(ZigType::NamedStruct("Map".to_string())),
452 init: None,
453 is_json_parse: false,
454 needs_var_suppression: true,
455 needs_deinit: true,
456 }));
457 let output = Emitter::emit_module(&module);
458 assert!(output.contains("defer m.deinit(js_allocator.allocator());"));
459 }
460
461 #[test]
462 fn test_emit_map_var_returned_no_deinit() {
463 let mut module = IrModule::new("test".to_string());
466 module.declarations.push(IrDecl::Var(IrVarDecl {
467 name: IrIdent::new("m"),
468 is_const: true,
469 zig_type: Some(ZigType::NamedStruct("Map".to_string())),
470 init: None,
471 is_json_parse: false,
472 needs_var_suppression: false,
473 needs_deinit: false, }));
475 let output = Emitter::emit_module(&module);
476 assert!(!output.contains("defer m.deinit"));
477 }
478
479 #[test]
480 fn test_emit_static_map_field_deinit() {
481 use crate::zigir::types::{IrClassDecl, IrClassField};
482
483 let mut module = IrModule::new("test".to_string());
484 module.declarations.push(IrDecl::Class(IrClassDecl {
486 name: IrIdent::new("Registry"),
487 fields: vec![IrClassField {
488 name: "name".to_string(),
489 zig_type: ZigType::I64,
490 default: None,
491 }],
492 constructor: None,
493 methods: vec![],
494 static_inits: vec![(
495 "entries".to_string(),
496 crate::zigir::types::IrExpr::Ident(IrIdent::new("Map")),
497 ZigType::NamedStruct("Map".to_string()),
498 )],
499 static_blocks: vec![],
500 extends: None,
501 needs_deinit: false,
502 }));
503 let output = Emitter::emit_module(&module);
504 assert!(output.contains("pub fn deinit_js2rust() void {"));
505 assert!(output.contains("__Registry_entries.deinit(js_allocator.allocator());"));
506 }
507
508 #[test]
509 fn test_p0_6_default_init_uses_field_zero_value() {
510 use crate::zigir::types::{IrClassDecl, IrClassField};
511
512 let mut module = IrModule::new("test".to_string());
513 module.declarations.push(IrDecl::Class(IrClassDecl {
517 name: IrIdent::new("Config"),
518 fields: vec![
519 IrClassField {
520 name: "count".to_string(),
521 zig_type: ZigType::I64,
522 default: None,
523 },
524 IrClassField {
525 name: "ratio".to_string(),
526 zig_type: ZigType::F64,
527 default: None,
528 },
529 IrClassField {
530 name: "enabled".to_string(),
531 zig_type: ZigType::Bool,
532 default: None,
533 },
534 IrClassField {
535 name: "label".to_string(),
536 zig_type: ZigType::Str,
537 default: None,
538 },
539 ],
540 constructor: None,
541 methods: vec![],
542 static_inits: vec![],
543 static_blocks: vec![],
544 extends: None,
545 needs_deinit: false,
546 }));
547 let output = Emitter::emit_module(&module);
548
549 assert!(
551 output.contains(".ratio = 0.0"),
552 "F64 field should use '0.0', got:\n{}",
553 output
554 );
555 assert!(
556 output.contains(".enabled = false"),
557 "Bool field should use 'false', got:\n{}",
558 output
559 );
560 assert!(
561 output.contains(".label = \"\""),
562 "Str field should use empty string, got:\n{}",
563 output
564 );
565 assert!(
567 !output.contains(".enabled = 0"),
568 "Bool field should NOT use '0' (old bug)"
569 );
570 }
571}