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