Skip to main content

js2zig_core/zigir/emit/
helpers.rs

1// zigir/emit/helpers.rs
2// Emitter output helpers: write, writeln, write_indent, etc.
3// Also trait definition for shared helper methods.
4
5use crate::types::ZigType;
6use crate::zigir::ident::IrIdent;
7use crate::zigir::ops::AssignOp;
8use crate::zigir::ops::BinOp;
9use crate::zigir::ops::LogicalOp;
10use crate::zigir::ops::UnaOp;
11use crate::zigir::ops::UpdateOp;
12
13// ═══════════════════════════════════════════════════════
14//  Emitter output helpers
15// ═══════════════════════════════════════════════════════
16
17pub trait EmitterHelpers {
18    fn output(&self) -> &str;
19    fn output_mut(&mut self) -> &mut String;
20    fn indent(&self) -> usize;
21    fn indent_mut(&mut self) -> &mut usize;
22
23    /// Append raw string to output buffer.
24    fn write(&mut self, s: &str) {
25        self.output_mut().push_str(s);
26    }
27
28    /// Append single char to output buffer.
29    fn push(&mut self, ch: char) {
30        self.output_mut().push(ch);
31    }
32
33    /// Write an indented line: indent + content + newline.
34    fn writeln(&mut self, s: &str) {
35        self.write_indent();
36        self.output_mut().push_str(s);
37        self.output_mut().push('\n');
38    }
39
40    /// Emit current indent level (4 spaces per level).
41    fn write_indent(&mut self) {
42        for _ in 0..self.indent() {
43            self.output_mut().push_str("    ");
44        }
45    }
46
47    /// Increase indent level.
48    fn indent_push(&mut self) {
49        *self.indent_mut() += 1;
50    }
51
52    /// Decrease indent level.
53    fn indent_pop(&mut self) {
54        assert!(self.indent() > 0, "indent underflow");
55        *self.indent_mut() -= 1;
56    }
57}
58
59// ═══════════════════════════════════════════════════════
60//  Operator → Zig string conversion
61// ═══════════════════════════════════════════════════════
62
63/// Binary operator → Zig operator string.
64pub fn bin_op_to_zig(op: BinOp) -> &'static str {
65    match op {
66        BinOp::Add => "+",
67        BinOp::Sub => "-",
68        BinOp::Mul => "*",
69        BinOp::Div => "/",
70        BinOp::Mod => "%",
71        BinOp::Pow => "@pow", // Zig uses std.math.pow / @pow
72        BinOp::Lt => "<",
73        BinOp::Gt => ">",
74        BinOp::Le => "<=",
75        BinOp::Ge => ">=",
76        BinOp::Eq => "==",
77        BinOp::Ne => "!=",
78        BinOp::StrictEq => "==",
79        BinOp::StrictNe => "!=",
80        BinOp::BitAnd => "&",
81        BinOp::BitOr => "|",
82        BinOp::BitXor => "^",
83        BinOp::Shl => "<<",
84        BinOp::Shr => ">>",
85        BinOp::UrShr => ">>", // Zig logical right shift needs @as + @truncate
86        BinOp::In => "==",    // JS `in` → Zig field existence check (handled at call site)
87        BinOp::InstanceOf => "==", // Simplified
88    }
89}
90
91/// Unary operator → Zig operator string.
92pub fn una_op_to_zig(op: UnaOp) -> &'static str {
93    match op {
94        UnaOp::Neg => "-",
95        UnaOp::Not => "!",
96        UnaOp::BitNot => "~",
97        UnaOp::TypeOf => "typeof", // handled specially at emit time
98        UnaOp::Void => "void",     // handled specially at emit time
99        UnaOp::Delete => "delete", // handled specially at emit time
100    }
101}
102
103/// Logical operator → Zig operator string.
104pub fn logical_op_to_zig(op: LogicalOp) -> &'static str {
105    match op {
106        LogicalOp::And => "and",
107        LogicalOp::Or => "or",
108        LogicalOp::Nullish => "orelse",
109    }
110}
111
112/// Update operator → Zig code fragment.
113pub fn update_op_to_zig(op: UpdateOp) -> &'static str {
114    match op {
115        UpdateOp::Increment => "+= 1",
116        UpdateOp::Decrement => "-= 1",
117    }
118}
119
120// AssignOp already has to_zig_str() in ops.rs — re-export for convenience.
121pub fn assign_op_to_zig(op: AssignOp) -> &'static str {
122    op.to_zig_str()
123}
124
125// ═══════════════════════════════════════════════════════
126//  ZigType → Zig type string helpers
127// ═══════════════════════════════════════════════════════
128
129/// Convert a ZigType to a Zig type annotation string for declarations.
130/// This wraps ZigType::to_zig_type() but handles Option<ZigType> (None = inferred).
131pub fn zig_type_annotation(ty: Option<&ZigType>) -> Option<String> {
132    ty.map(|t| t.to_zig_type())
133}
134
135/// Format a function return type, considering async/throw modifiers.
136///
137/// For async functions returning a `NamedStruct`, the `host.` prefix is added
138/// because the struct type is defined in the host module (e.g., `host.FetchUserResult`).
139pub fn format_return_type(ret_type: &ZigType, is_async: bool, can_throw: bool) -> String {
140    let base = match ret_type {
141        ZigType::NamedStruct(name) if is_async => format!("host.{}", name),
142        _ => ret_type.to_zig_type(),
143    };
144    if (is_async || can_throw) && base != "void" {
145        format!("!{}", base)
146    } else if can_throw && base == "void" {
147        "!void".to_string()
148    } else {
149        base
150    }
151}
152
153/// Format a parameter: `name: Type`.
154pub fn format_param(name: &IrIdent, ty: &ZigType) -> String {
155    format!("{}: {}", name.zig_name, ty.to_zig_type())
156}
157
158/// Format a parameter with rest awareness.
159/// If `is_rest` is true, the type is rendered as `[]const JsAny` regardless of `ty`.
160pub fn format_param_with_rest(name: &IrIdent, ty: &ZigType, is_rest: bool) -> String {
161    let type_str = if is_rest {
162        "[]const JsAny".to_string()
163    } else {
164        ty.to_zig_type()
165    };
166    format!("{}: {}", name.zig_name, type_str)
167}
168
169/// Escape a string for use in a Zig string literal.
170pub fn escape_zig_string(s: &str) -> String {
171    let mut result = String::with_capacity(s.len() + 16);
172    for byte in s.bytes() {
173        match byte {
174            b'\\' => result.push_str("\\\\"),
175            b'"' => result.push_str("\\\""),
176            b'\n' => result.push_str("\\n"),
177            b'\r' => result.push_str("\\r"),
178            b'\t' => result.push_str("\\t"),
179            c @ 0x00..=0x1F | c @ 0x7F..=0xFF => {
180                result.push_str(&format!("\\x{:02X}", c));
181            }
182            _ => result.push(byte as char),
183        }
184    }
185    result
186}
187
188// ═══════════════════════════════════════════════════════
189//  Tests
190// ═══════════════════════════════════════════════════════
191
192#[cfg(test)]
193mod tests {
194    use super::*;
195
196    #[test]
197    fn test_format_return_type() {
198        assert_eq!(format_return_type(&ZigType::I64, false, false), "i64");
199        assert_eq!(format_return_type(&ZigType::I64, true, false), "!i64");
200        assert_eq!(format_return_type(&ZigType::I64, false, true), "!i64");
201        assert_eq!(format_return_type(&ZigType::Void, false, true), "!void");
202        assert_eq!(format_return_type(&ZigType::Void, false, false), "void");
203        assert_eq!(format_return_type(&ZigType::F64, true, true), "!f64");
204        // Async NamedStruct should get host. prefix
205        assert_eq!(
206            format_return_type(
207                &ZigType::NamedStruct("FetchUserResult".to_string()),
208                true,
209                false
210            ),
211            "!host.FetchUserResult"
212        );
213        // Non-async NamedStruct should NOT get host. prefix
214        assert_eq!(
215            format_return_type(&ZigType::NamedStruct("MyStruct".to_string()), false, false),
216            "MyStruct"
217        );
218    }
219
220    #[test]
221    fn test_escape_zig_string() {
222        assert_eq!(escape_zig_string("hello"), "hello");
223        assert_eq!(escape_zig_string("say \"hi\""), "say \\\"hi\\\"");
224        assert_eq!(escape_zig_string("line1\nline2"), "line1\\nline2");
225        assert_eq!(escape_zig_string("tab\there"), "tab\\there");
226        assert_eq!(escape_zig_string("back\\slash"), "back\\\\slash");
227    }
228
229    #[test]
230    fn test_bin_op_to_zig() {
231        assert_eq!(bin_op_to_zig(BinOp::Add), "+");
232        assert_eq!(bin_op_to_zig(BinOp::Le), "<=");
233        assert_eq!(bin_op_to_zig(BinOp::StrictEq), "==");
234    }
235
236    #[test]
237    fn test_logical_op_to_zig() {
238        assert_eq!(logical_op_to_zig(LogicalOp::And), "and");
239        assert_eq!(logical_op_to_zig(LogicalOp::Or), "or");
240        assert_eq!(logical_op_to_zig(LogicalOp::Nullish), "orelse");
241    }
242
243    #[test]
244    fn test_update_op_to_zig() {
245        assert_eq!(update_op_to_zig(UpdateOp::Increment), "+= 1");
246        assert_eq!(update_op_to_zig(UpdateOp::Decrement), "-= 1");
247    }
248
249    #[test]
250    fn test_assign_op_to_zig() {
251        assert_eq!(assign_op_to_zig(AssignOp::Assign), "=");
252        assert_eq!(assign_op_to_zig(AssignOp::Add), "+=");
253        assert_eq!(assign_op_to_zig(AssignOp::LogicOr), "or=");
254    }
255
256    #[test]
257    fn test_format_param() {
258        let ident = IrIdent::new("foo");
259        let param = format_param(&ident, &ZigType::I64);
260        assert_eq!(param, "foo: i64");
261    }
262}