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::types::ZigType;
14use crate::zigir::types::{IrDecl, IrModule};
15
16use std::collections::HashSet;
17
18use helpers::EmitterHelpers;
19
20// ═══════════════════════════════════════════════════════
21//  Emitter struct
22// ═══════════════════════════════════════════════════════
23
24/// ZigIR → Zig source code emitter.
25///
26/// Generates Zig source code from structured IR instead of AST + inline type lookups. The Emitter is stateless with
27/// respect to semantics — all meaning is encoded in the IR nodes.
28///
29/// Internal state:
30/// - `output`: accumulated Zig source buffer
31/// - `indent`: current indentation level (4 spaces per level)
32pub struct Emitter {
33    output: String,
34    indent: usize,
35    /// When inside a try block, this holds the label that `throw` should break to.
36    inside_try_block: Option<String>,
37    /// Counter for generating unique try-block labels (_js_try_blk_N).
38    try_label_counter: u32,
39    /// Counter for generating unique block labels (for array literal labeled blocks).
40    label_counter: u32,
41    /// Counter for generating unique do-while "first iteration" flag names
42    /// (`__dw_first_0`, `__dw_first_1`, ...). Zig 0.16 forbids local-variable
43    /// shadowing across nesting scopes, so each nested do-while must use a
44    /// distinct flag name (e.g., an outer loop and an inner do-while inside
45    /// its body would otherwise both declare `__dw_first` and fail Zig
46    /// `ast-check` with `local variable '__dw_first' shadows local variable
47    /// from outer scope`).
48    do_while_counter: u32,
49    /// Whether we are currently emitting inside a function body.
50    /// Top-level declarations (const, var) cannot use `return` or `try`,
51    /// so error-propagation patterns like `catch return error.JsThrow` must
52    /// be replaced with `catch @panic(...)` at the top level.
53    in_function: bool,
54    /// Buffer for static block init code. When non-empty, `emit_module_inner`
55    /// generates a `pub fn init_js2rust() !void { ... }` at the end of the
56    /// module so the orchestrator's `init_js2rust()` will call it, ensuring
57    /// static blocks execute at runtime (Zig's lazy analysis would otherwise
58    /// skip unreferenced top-level `const` declarations).
59    static_init_buffer: String,
60    /// Buffer for static deinit code. When non-empty, `emit_module_inner`
61    /// generates a `pub fn deinit_js2rust() void { ... }` that calls
62    /// `.deinit(alloc)` on all static Map/Set/ArrayList fields.
63    static_deinit_buffer: String,
64    /// Set of class names that have `needs_deinit = true` (contain Map/Set/ArrayList fields).
65    /// Used by `emit_var_decl` to determine whether a local variable of a NamedStruct
66    /// type should get `defer varname.deinit(alloc)`.
67    class_needs_deinit: HashSet<String>,
68    /// Names of all rest parameters across all functions in the module.
69    /// Used by `emit_args` to distinguish rest param spreads (already `[]const JsAny`)
70    /// from ArrayList spreads (need `.items`).
71    rest_param_names: HashSet<String>,
72}
73
74// ── EmitterHelpers trait implementation ───────────────
75
76impl 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    /// Emit an IrExpr to a separate string (for inline embedding in templates).
115    /// Temporarily swaps the output buffer so the expression is captured alone.
116    /// Kept for future use; current callers use `emit_expr_inline_with_label_offset`
117    /// to avoid label conflicts.
118    #[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    /// Like `emit_expr_inline`, but initializes the sub-emitter's `label_counter`
126    /// to `label_offset` instead of 0, ensuring that any labeled blocks generated
127    /// inside the sub-expression use label numbers ≥ `label_offset`.
128    /// Returns `(rendered_string, updated_label_counter)`.
129    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    /// Emit a complete IrModule to a Zig source string.
141    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        // 0. Pre-scan: collect all rest param names for emit_args spread handling.
149        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        // 0.5. Pre-scan: build class_needs_deinit set with propagation.
160        //     Initial values come from each class's needs_deinit flag (direct
161        //     Map/Set/ArrayList/BigInt fields). Then propagate transitively:
162        //     if a class has a field whose type is another class that needs
163        //     deinit, this class also needs deinit. Fixpoint iteration handles
164        //     Arbitrary nesting depth (A -> B -> C with Map field).
165        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        // 1. Emit closure struct definitions (prepended before declarations).
200        //    Closure struct definitions are emitted before declarations.
201        for closure_struct in &module.closure_structs {
202            self.emit_closure_struct(closure_struct);
203        }
204
205        // 2. Emit JSDoc @typedef struct definitions.
206        for typedef in &module.typedefs {
207            self.emit_typedef(typedef);
208        }
209
210        // 3. Emit top-level declarations (functions, variables, classes).
211        for decl in &module.declarations {
212            self.emit_decl(decl);
213        }
214
215        // 4. If any class had static {} blocks, generate init_js2rust()
216        //    so the orchestrator calls it from root init_js2rust().
217        //    This ensures static blocks execute at runtime rather than being
218        //    skipped by Zig's lazy analysis of unreferenced top-level `const`.
219        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        // 5. If any static Map/Set/ArrayList fields need deinit, generate
229        //    deinit_js2rust() so the orchestrator calls it from root deinit_js2rust().
230        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    // ── Declaration dispatch ─────────────────────────
241
242    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                // Toplevel "errors" are emitted as comments (soft diagnostics),
249                // not @compileError — soft diagnostics.
250                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    /// Return the next try-label id and advance the counter.
260    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    /// Return the next block label (e.g., `blk_0`, `blk_1`) and advance the counter.
267    fn next_label(&mut self) -> String {
268        let n = self.label_counter;
269        self.label_counter += 1;
270        format!("blk_{}", n)
271    }
272
273    /// Return the next do-while "first iteration" flag name
274    /// (`__dw_first_0`, `__dw_first_1`, ...) and advance the counter.
275    /// Pairs of nested do-whiles must use distinct flag names to avoid Zig's
276    /// "local variable shadows local variable from outer scope" error.
277    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    /// Peek at the current label counter without advancing (for generating unique temp var names).
284    fn peek_label_id(&self) -> u32 {
285        self.label_counter
286    }
287}
288
289// ═══════════════════════════════════════════════════════
290//  Tests
291// ═══════════════════════════════════════════════════════
292
293#[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        // Class with a Map field → needs_deinit = true → generates deinit() method
377        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        // I64 field should NOT appear in deinit body
408        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        // Class with only I64 fields → needs_deinit = false → no deinit() method
420        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        // When needs_deinit is false (ownership transferred via return),
464        // no defer deinit should be emitted.
465        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, // cleared by ownership transfer pass
474        }));
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        // Class with static Map field → deinit_js2rust() generated
485        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        // Class with no constructor → emit_default_init generates init().
514        // Fields of various types with no default → must use field_zero_value
515        // (e.g. false for Bool, "" for Str, 0.0 for F64), not "0" for all.
516        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        // init() should use type-correct zero values, not "0" for all
550        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        // Negative: the old bug emitted "0" for every type
566        assert!(
567            !output.contains(".enabled = 0"),
568            "Bool field should NOT use '0' (old bug)"
569        );
570    }
571}