js2zig_core/zigir/emit/
mod.rs1pub mod builtins;
9pub mod expr;
10pub mod helpers;
11pub mod stmt;
12
13use crate::zigir::types::{IrDecl, IrModule};
14
15use helpers::EmitterHelpers;
16
17pub struct Emitter {
30 output: String,
31 indent: usize,
32 inside_try_block: Option<String>,
34 try_label_counter: u32,
36 label_counter: u32,
38}
39
40impl EmitterHelpers for Emitter {
43 fn output(&self) -> &str {
44 &self.output
45 }
46 fn output_mut(&mut self) -> &mut String {
47 &mut self.output
48 }
49 fn indent(&self) -> usize {
50 self.indent
51 }
52 fn indent_mut(&mut self) -> &mut usize {
53 &mut self.indent
54 }
55}
56
57impl Default for Emitter {
58 fn default() -> Self {
59 Self::new()
60 }
61}
62
63impl Emitter {
64 pub fn new() -> Self {
65 Self {
66 output: String::new(),
67 indent: 0,
68 inside_try_block: None,
69 try_label_counter: 0,
70 label_counter: 0,
71 }
72 }
73
74 pub(crate) fn emit_expr_inline(expr: &crate::zigir::types::IrExpr) -> String {
77 let mut sub_emitter = Self::new();
78 sub_emitter.emit_expr(expr);
79 sub_emitter.output.trim().to_string()
80 }
81
82 pub fn emit_module(module: &IrModule) -> String {
84 let mut emitter = Self::new();
85 emitter.emit_module_inner(module);
86 emitter.output
87 }
88
89 fn emit_module_inner(&mut self, module: &IrModule) {
90 for closure_struct in &module.closure_structs {
93 self.emit_closure_struct(closure_struct);
94 }
95
96 for typedef in &module.typedefs {
98 self.emit_typedef(typedef);
99 }
100
101 for decl in &module.declarations {
103 self.emit_decl(decl);
104 }
105 }
106
107 fn emit_decl(&mut self, decl: &IrDecl) {
110 match decl {
111 IrDecl::Var(var_decl) => self.emit_var_decl(var_decl),
112 IrDecl::Fn(fn_decl) => self.emit_fn_decl(fn_decl),
113 IrDecl::Class(class_decl) => self.emit_class_decl(class_decl),
114 IrDecl::CompileError { span: _, msg } => {
115 if msg.starts_with("toplevel") || msg.starts_with("skipped unused") {
118 self.writeln(&format!("// error: {}", msg));
119 } else {
120 self.writeln(&format!("@compileError(\"{}\");", msg));
121 }
122 }
123 }
124 }
125
126 fn next_try_label(&mut self) -> u32 {
128 let n = self.try_label_counter;
129 self.try_label_counter += 1;
130 n
131 }
132
133 fn next_label(&mut self) -> String {
135 let n = self.label_counter;
136 self.label_counter += 1;
137 format!("blk_{}", n)
138 }
139
140 fn peek_label_id(&self) -> u32 {
142 self.label_counter
143 }
144}
145
146#[cfg(test)]
151mod tests {
152 use super::*;
153 use crate::types::ZigType;
154 use crate::zigir::ident::IrIdent;
155 use crate::zigir::types::{
156 IrBlock, IrFnDecl, IrParam, IrStmt, IrTypedef, IrTypedefField, IrVarDecl,
157 };
158
159 #[test]
160 fn test_emit_empty_module() {
161 let module = IrModule::new("test".to_string());
162 let output = Emitter::emit_module(&module);
163 assert!(output.is_empty());
164 }
165
166 #[test]
167 fn test_emit_typedef() {
168 let mut module = IrModule::new("test".to_string());
169 module.typedefs.push(IrTypedef {
170 name: "Point".to_string(),
171 fields: vec![
172 IrTypedefField {
173 name: "x".to_string(),
174 zig_type: "f64".to_string(),
175 optional: false,
176 },
177 IrTypedefField {
178 name: "y".to_string(),
179 zig_type: "f64".to_string(),
180 optional: false,
181 },
182 ],
183 is_opaque: false,
184 has_to_json: true,
185 });
186 let output = Emitter::emit_module(&module);
187 assert!(output.contains("const Point = struct {"));
188 assert!(output.contains("x: f64,"));
189 assert!(output.contains("y: f64,"));
190 assert!(output.contains("pub fn toJson"));
191 }
192
193 #[test]
194 fn test_emit_var_decl() {
195 let mut module = IrModule::new("test".to_string());
196 module.declarations.push(IrDecl::Var(IrVarDecl {
197 name: IrIdent::new("x"),
198 is_const: true,
199 zig_type: Some(ZigType::I64),
200 init: Some(crate::zigir::types::IrExpr::IntLiteral(42)),
201 is_json_parse: false,
202 needs_var_suppression: false,
203 }));
204 let output = Emitter::emit_module(&module);
205 assert!(output.contains("const x = 42"));
206 }
207
208 #[test]
209 fn test_emit_fn_decl() {
210 let mut module = IrModule::new("test".to_string());
211 module.declarations.push(IrDecl::Fn(IrFnDecl {
212 name: IrIdent::new("add"),
213 params: vec![
214 IrParam {
215 name: IrIdent::new("a"),
216 zig_type: ZigType::I64,
217 is_unused: false,
218 is_rest: false,
219 },
220 IrParam {
221 name: IrIdent::new("b"),
222 zig_type: ZigType::I64,
223 is_unused: false,
224 is_rest: false,
225 },
226 ],
227 return_type: ZigType::I64,
228 body: IrBlock::new(vec![IrStmt::Return {
229 value: Some(crate::zigir::types::IrExpr::Binary {
230 op: crate::zigir::ops::BinOp::Add,
231 left: Box::new(crate::zigir::types::IrExpr::Ident(IrIdent::new("a"))),
232 right: Box::new(crate::zigir::types::IrExpr::Ident(IrIdent::new("b"))),
233 left_type: None,
234 right_type: None,
235 }),
236 }]),
237 is_export: true,
238 is_async: false,
239 can_throw: false,
240 is_cabi: false,
241 typeof_return_body: None,
242 }));
243
244 let output = Emitter::emit_module(&module);
245 assert!(output.contains("pub fn add(a: i64, b: i64) i64"));
246 }
247
248 #[test]
249 fn test_emit_fn_decl_with_throw() {
250 let mut module = IrModule::new("test".to_string());
251 module.declarations.push(IrDecl::Fn(IrFnDecl {
252 name: IrIdent::new("mayFail"),
253 params: vec![],
254 return_type: ZigType::I64,
255 body: IrBlock::new(vec![]),
256 is_export: false,
257 is_async: false,
258 can_throw: true,
259 is_cabi: false,
260 typeof_return_body: None,
261 }));
262 let output = Emitter::emit_module(&module);
263 assert!(output.contains("fn mayFail() !i64 {"));
264 }
265}