Skip to main content

js2zig_core/zigir/emit/
mod.rs

1// zigir/emit/mod.rs
2// ZigIR → Zig source code emission:纯格式化,无语义决策。
3//
4// Emitter 接受 &IrModule,逐节点遍历 IR 树,生成格式化的 Zig 源代码字符串。
5// 所有语义决策(类型推断、名称篡改、闭包分析)已在 Lowerer 阶段完成。
6// Emitter 只负责将 IR 节点映射为 Zig 代码文本。
7
8pub 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
19// ═══════════════════════════════════════════════════════
20//  Emitter struct
21// ═══════════════════════════════════════════════════════
22
23/// ZigIR → Zig source code emitter.
24///
25/// Generates Zig source code from structured IR instead of AST + inline type lookups. The Emitter is stateless with
26/// respect to semantics — all meaning is encoded in the IR nodes.
27///
28/// Internal state:
29/// - `output`: accumulated Zig source buffer
30/// - `indent`: current indentation level (4 spaces per level)
31pub struct Emitter {
32    output: String,
33    indent: usize,
34    /// When inside a try block, this holds the label that `throw` should break to.
35    inside_try_block: Option<String>,
36    /// Counter for generating unique try-block labels (_js_try_blk_N).
37    try_label_counter: u32,
38    /// Counter for generating unique block labels (for array literal labeled blocks).
39    label_counter: u32,
40    /// Buffer for static block init code. When non-empty, `emit_module_inner`
41    /// generates a `pub fn init_js2rust() !void { ... }` at the end of the
42    /// module so the orchestrator's `init_js2rust()` will call it, ensuring
43    /// static blocks execute at runtime (Zig's lazy analysis would otherwise
44    /// skip unreferenced top-level `const` declarations).
45    static_init_buffer: String,
46    /// Buffer for static deinit code. When non-empty, `emit_module_inner`
47    /// generates a `pub fn deinit_js2rust() void { ... }` that calls
48    /// `.deinit(alloc)` on all static Map/Set/ArrayList fields.
49    static_deinit_buffer: String,
50    /// Set of class names that have `needs_deinit = true` (contain Map/Set/ArrayList fields).
51    /// Used by `emit_var_decl` to determine whether a local variable of a NamedStruct
52    /// type should get `defer varname.deinit(alloc)`.
53    class_needs_deinit: HashSet<String>,
54}
55
56// ── EmitterHelpers trait implementation ───────────────
57
58impl 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    /// Emit an IrExpr to a separate string (for inline embedding in templates).
94    /// Temporarily swaps the output buffer so the expression is captured alone.
95    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    /// Like `emit_expr_inline`, but initializes the sub-emitter's `label_counter`
102    /// to `label_offset` instead of 0, ensuring that any labeled blocks generated
103    /// inside the sub-expression use label numbers ≥ `label_offset`.
104    /// Returns `(rendered_string, updated_label_counter)`.
105    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    /// Emit a complete IrModule to a Zig source string.
117    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        // 1. Emit closure struct definitions (prepended before declarations).
125        //    Closure struct definitions are emitted before declarations.
126        for closure_struct in &module.closure_structs {
127            self.emit_closure_struct(closure_struct);
128        }
129
130        // 2. Emit JSDoc @typedef struct definitions.
131        for typedef in &module.typedefs {
132            self.emit_typedef(typedef);
133        }
134
135        // 3. Emit top-level declarations (functions, variables, classes).
136        for decl in &module.declarations {
137            self.emit_decl(decl);
138        }
139
140        // 4. If any class had static {} blocks, generate init_js2rust()
141        //    so the orchestrator calls it from root init_js2rust().
142        //    This ensures static blocks execute at runtime rather than being
143        //    skipped by Zig's lazy analysis of unreferenced top-level `const`.
144        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        // 5. If any static Map/Set/ArrayList fields need deinit, generate
154        //    deinit_js2rust() so the orchestrator calls it from root deinit_js2rust().
155        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    // ── Declaration dispatch ─────────────────────────
166
167    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                // Toplevel "errors" are emitted as comments (soft diagnostics),
174                // not @compileError — soft diagnostics.
175                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    /// Return the next try-label id and advance the counter.
185    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    /// Return the next block label (e.g., `blk_0`, `blk_1`) and advance the counter.
192    fn next_label(&mut self) -> String {
193        let n = self.label_counter;
194        self.label_counter += 1;
195        format!("blk_{}", n)
196    }
197
198    /// Peek at the current label counter without advancing (for generating unique temp var names).
199    fn peek_label_id(&self) -> u32 {
200        self.label_counter
201    }
202}
203
204// ═══════════════════════════════════════════════════════
205//  Tests
206// ═══════════════════════════════════════════════════════
207
208#[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        // Class with a Map field → needs_deinit = true → generates deinit() method
292        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        // I64 field should NOT appear in deinit body
323        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        // Class with only I64 fields → needs_deinit = false → no deinit() method
335        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        // When needs_deinit is false (ownership transferred via return),
379        // no defer deinit should be emitted.
380        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, // cleared by ownership transfer pass
389        }));
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        // Class with static Map field → deinit_js2rust() generated
400        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}