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    /// Whether we are currently emitting inside a function body.
41    /// Top-level declarations (const, var) cannot use `return` or `try`,
42    /// so error-propagation patterns like `catch return error.JsThrow` must
43    /// be replaced with `catch @panic(...)` at the top level.
44    in_function: bool,
45    /// Buffer for static block init code. When non-empty, `emit_module_inner`
46    /// generates a `pub fn init_js2rust() !void { ... }` at the end of the
47    /// module so the orchestrator's `init_js2rust()` will call it, ensuring
48    /// static blocks execute at runtime (Zig's lazy analysis would otherwise
49    /// skip unreferenced top-level `const` declarations).
50    static_init_buffer: String,
51    /// Buffer for static deinit code. When non-empty, `emit_module_inner`
52    /// generates a `pub fn deinit_js2rust() void { ... }` that calls
53    /// `.deinit(alloc)` on all static Map/Set/ArrayList fields.
54    static_deinit_buffer: String,
55    /// Set of class names that have `needs_deinit = true` (contain Map/Set/ArrayList fields).
56    /// Used by `emit_var_decl` to determine whether a local variable of a NamedStruct
57    /// type should get `defer varname.deinit(alloc)`.
58    class_needs_deinit: HashSet<String>,
59    /// Names of all rest parameters across all functions in the module.
60    /// Used by `emit_args` to distinguish rest param spreads (already `[]const JsAny`)
61    /// from ArrayList spreads (need `.items`).
62    rest_param_names: HashSet<String>,
63}
64
65// ── EmitterHelpers trait implementation ───────────────
66
67impl 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    /// Emit an IrExpr to a separate string (for inline embedding in templates).
105    /// Temporarily swaps the output buffer so the expression is captured alone.
106    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    /// Like `emit_expr_inline`, but initializes the sub-emitter's `label_counter`
113    /// to `label_offset` instead of 0, ensuring that any labeled blocks generated
114    /// inside the sub-expression use label numbers ≥ `label_offset`.
115    /// Returns `(rendered_string, updated_label_counter)`.
116    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    /// Emit a complete IrModule to a Zig source string.
128    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        // 0. Pre-scan: collect all rest param names for emit_args spread handling.
136        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        // 1. Emit closure struct definitions (prepended before declarations).
147        //    Closure struct definitions are emitted before declarations.
148        for closure_struct in &module.closure_structs {
149            self.emit_closure_struct(closure_struct);
150        }
151
152        // 2. Emit JSDoc @typedef struct definitions.
153        for typedef in &module.typedefs {
154            self.emit_typedef(typedef);
155        }
156
157        // 3. Emit top-level declarations (functions, variables, classes).
158        for decl in &module.declarations {
159            self.emit_decl(decl);
160        }
161
162        // 4. If any class had static {} blocks, generate init_js2rust()
163        //    so the orchestrator calls it from root init_js2rust().
164        //    This ensures static blocks execute at runtime rather than being
165        //    skipped by Zig's lazy analysis of unreferenced top-level `const`.
166        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        // 5. If any static Map/Set/ArrayList fields need deinit, generate
176        //    deinit_js2rust() so the orchestrator calls it from root deinit_js2rust().
177        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    // ── Declaration dispatch ─────────────────────────
188
189    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                // Toplevel "errors" are emitted as comments (soft diagnostics),
196                // not @compileError — soft diagnostics.
197                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    /// Return the next try-label id and advance the counter.
207    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    /// Return the next block label (e.g., `blk_0`, `blk_1`) and advance the counter.
214    fn next_label(&mut self) -> String {
215        let n = self.label_counter;
216        self.label_counter += 1;
217        format!("blk_{}", n)
218    }
219
220    /// Peek at the current label counter without advancing (for generating unique temp var names).
221    fn peek_label_id(&self) -> u32 {
222        self.label_counter
223    }
224}
225
226// ═══════════════════════════════════════════════════════
227//  Tests
228// ═══════════════════════════════════════════════════════
229
230#[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        // Class with a Map field → needs_deinit = true → generates deinit() method
314        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        // I64 field should NOT appear in deinit body
345        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        // Class with only I64 fields → needs_deinit = false → no deinit() method
357        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        // When needs_deinit is false (ownership transferred via return),
401        // no defer deinit should be emitted.
402        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, // cleared by ownership transfer pass
411        }));
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        // Class with static Map field → deinit_js2rust() generated
422        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}