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 helpers::EmitterHelpers;
16
17// ═══════════════════════════════════════════════════════
18//  Emitter struct
19// ═══════════════════════════════════════════════════════
20
21/// ZigIR → Zig source code emitter.
22///
23/// Generates Zig source code from structured IR instead of AST + inline type lookups. The Emitter is stateless with
24/// respect to semantics — all meaning is encoded in the IR nodes.
25///
26/// Internal state:
27/// - `output`: accumulated Zig source buffer
28/// - `indent`: current indentation level (4 spaces per level)
29pub struct Emitter {
30    output: String,
31    indent: usize,
32    /// When inside a try block, this holds the label that `throw` should break to.
33    inside_try_block: Option<String>,
34    /// Counter for generating unique try-block labels (_js_try_blk_N).
35    try_label_counter: u32,
36    /// Counter for generating unique block labels (for array literal labeled blocks).
37    label_counter: u32,
38}
39
40// ── EmitterHelpers trait implementation ───────────────
41
42impl 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    /// Emit an IrExpr to a separate string (for inline embedding in templates).
75    /// Temporarily swaps the output buffer so the expression is captured alone.
76    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    /// Emit a complete IrModule to a Zig source string.
83    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        // 1. Emit closure struct definitions (prepended before declarations).
91        //    Closure struct definitions are emitted before declarations.
92        for closure_struct in &module.closure_structs {
93            self.emit_closure_struct(closure_struct);
94        }
95
96        // 2. Emit JSDoc @typedef struct definitions.
97        for typedef in &module.typedefs {
98            self.emit_typedef(typedef);
99        }
100
101        // 3. Emit top-level declarations (functions, variables, classes).
102        for decl in &module.declarations {
103            self.emit_decl(decl);
104        }
105    }
106
107    // ── Declaration dispatch ─────────────────────────
108
109    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                // Toplevel "errors" are emitted as comments (soft diagnostics),
116                // not @compileError — soft diagnostics.
117                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    /// Return the next try-label id and advance the counter.
127    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    /// Return the next block label (e.g., `blk_0`, `blk_1`) and advance the counter.
134    fn next_label(&mut self) -> String {
135        let n = self.label_counter;
136        self.label_counter += 1;
137        format!("blk_{}", n)
138    }
139
140    /// Peek at the current label counter without advancing (for generating unique temp var names).
141    fn peek_label_id(&self) -> u32 {
142        self.label_counter
143    }
144}
145
146// ═══════════════════════════════════════════════════════
147//  Tests
148// ═══════════════════════════════════════════════════════
149
150#[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}