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        BinOp::StrictEq => "==",
77        BinOp::StrictNe => "!=",
78        BinOp::BitAnd => "&",
79        BinOp::BitOr => "|",
80        BinOp::BitXor => "^",
81        BinOp::Shl => "<<",
82        BinOp::Shr => ">>",
83        BinOp::UrShr => ">>", // Zig logical right shift needs @as + @truncate
84        BinOp::In => "==",    // JS `in` → Zig field existence check (handled at call site)
85        BinOp::InstanceOf => "==", // Simplified
86    }
87}
88
89/// Update operator → Zig code fragment.
90pub fn update_op_to_zig(op: UpdateOp) -> &'static str {
91    match op {
92        UpdateOp::Increment => "+= 1",
93        UpdateOp::Decrement => "-= 1",
94    }
95}
96
97// AssignOp already has to_zig_str() in ops.rs — re-export for convenience.
98pub fn assign_op_to_zig(op: AssignOp) -> &'static str {
99    op.to_zig_str()
100}
101
102// ═══════════════════════════════════════════════════════
103//  ZigType → Zig type string helpers
104// ═══════════════════════════════════════════════════════
105
106/// Convert a ZigType to a Zig type annotation string for declarations.
107/// This wraps ZigType::to_zig_type() but handles Option<ZigType> (None = inferred).
108pub fn zig_type_annotation(ty: Option<&ZigType>) -> Option<String> {
109    ty.map(|t| t.to_zig_type().into_owned())
110}
111
112/// Format a function return type, considering async/throw modifiers.
113///
114/// For async functions returning a `NamedStruct`, the `host.` prefix is added
115/// because the struct type is defined in the host module (e.g., `host.FetchUserResult`).
116pub fn format_return_type(ret_type: &ZigType, is_async: bool, can_throw: bool) -> String {
117    let base = match ret_type {
118        ZigType::NamedStruct(name) if is_async => format!("host.{}", name),
119        _ => ret_type.to_zig_type().into_owned(),
120    };
121    if (is_async || can_throw) && base != "void" {
122        format!("!{}", base)
123    } else if can_throw && base == "void" {
124        "!void".to_string()
125    } else {
126        base
127    }
128}
129
130/// Format a parameter: `name: Type`.
131pub fn format_param(name: &IrIdent, ty: &ZigType) -> String {
132    format!("{}: {}", name.zig_name, ty.to_zig_type())
133}
134
135/// Format a parameter with rest awareness.
136/// If `is_rest` is true, the type is rendered as `[]const JsAny` regardless of `ty`.
137pub fn format_param_with_rest(name: &IrIdent, ty: &ZigType, is_rest: bool) -> String {
138    let type_str = if is_rest {
139        "[]const JsAny".to_string()
140    } else {
141        ty.to_zig_type().into_owned()
142    };
143    format!("{}: {}", name.zig_name, type_str)
144}
145
146/// Escape a string for use in a Zig string literal.
147pub(crate) fn escape_zig_string(s: &str) -> String {
148    let mut result = String::with_capacity(s.len() + 16);
149    for byte in s.bytes() {
150        match byte {
151            b'\\' => result.push_str("\\\\"),
152            b'"' => result.push_str("\\\""),
153            b'\n' => result.push_str("\\n"),
154            b'\r' => result.push_str("\\r"),
155            b'\t' => result.push_str("\\t"),
156            c @ 0x00..=0x1F | c @ 0x7F..=0xFF => {
157                result.push_str(&format!("\\x{:02X}", c));
158            }
159            _ => result.push(byte as char),
160        }
161    }
162    result
163}
164
165/// Escape a string for use in a Zig **format** string literal.
166/// Same as `escape_zig_string` but also doubles `{` and `}` for Zig's
167/// `std.fmt` format-string escaping (`{` → `{{`, `}` → `}}`).
168pub(crate) fn escape_zig_format_string(s: &str) -> String {
169    let escaped = escape_zig_string(s);
170    let mut result = String::with_capacity(escaped.len() + 16);
171    for ch in escaped.chars() {
172        match ch {
173            '{' => result.push_str("{{"),
174            '}' => result.push_str("}}"),
175            _ => result.push(ch),
176        }
177    }
178    result
179}
180
181/// Format a `@compileError("...")` with proper string escaping.
182pub(crate) fn compile_error(msg: &str) -> String {
183    format!("@compileError(\"{}\")", escape_zig_string(msg))
184}
185
186// ═══════════════════════════════════════════════════════
187//  Tests
188// ═══════════════════════════════════════════════════════
189
190#[cfg(test)]
191mod tests {
192    use super::*;
193
194    #[test]
195    fn test_format_return_type() {
196        assert_eq!(format_return_type(&ZigType::I64, false, false), "i64");
197        assert_eq!(format_return_type(&ZigType::I64, true, false), "!i64");
198        assert_eq!(format_return_type(&ZigType::I64, false, true), "!i64");
199        assert_eq!(format_return_type(&ZigType::Void, false, true), "!void");
200        assert_eq!(format_return_type(&ZigType::Void, false, false), "void");
201        assert_eq!(format_return_type(&ZigType::F64, true, true), "!f64");
202        // Async NamedStruct should get host. prefix
203        assert_eq!(
204            format_return_type(
205                &ZigType::NamedStruct("FetchUserResult".to_string()),
206                true,
207                false
208            ),
209            "!host.FetchUserResult"
210        );
211        // Non-async NamedStruct should NOT get host. prefix
212        assert_eq!(
213            format_return_type(&ZigType::NamedStruct("MyStruct".to_string()), false, false),
214            "MyStruct"
215        );
216    }
217
218    #[test]
219    fn test_escape_zig_string() {
220        assert_eq!(escape_zig_string("hello"), "hello");
221        assert_eq!(escape_zig_string("say \"hi\""), "say \\\"hi\\\"");
222        assert_eq!(escape_zig_string("line1\nline2"), "line1\\nline2");
223        assert_eq!(escape_zig_string("tab\there"), "tab\\there");
224        assert_eq!(escape_zig_string("back\\slash"), "back\\\\slash");
225    }
226
227    #[test]
228    fn test_escape_zig_format_string() {
229        // Basic: no braces
230        assert_eq!(escape_zig_format_string("hello"), "hello");
231        // Braces are doubled
232        assert_eq!(escape_zig_format_string("{s}"), "{{s}}");
233        // Control chars + braces
234        assert_eq!(escape_zig_format_string("a\n{b}"), "a\\n{{b}}");
235        // Quote + brace
236        assert_eq!(escape_zig_format_string("\"{x}\""), "\\\"{{x}}\\\"");
237    }
238
239    #[test]
240    fn test_bin_op_to_zig() {
241        assert_eq!(bin_op_to_zig(BinOp::Add), "+");
242        assert_eq!(bin_op_to_zig(BinOp::Le), "<=");
243        assert_eq!(bin_op_to_zig(BinOp::StrictEq), "==");
244    }
245
246    #[test]
247    fn test_update_op_to_zig() {
248        assert_eq!(update_op_to_zig(UpdateOp::Increment), "+= 1");
249        assert_eq!(update_op_to_zig(UpdateOp::Decrement), "-= 1");
250    }
251
252    #[test]
253    fn test_assign_op_to_zig() {
254        assert_eq!(assign_op_to_zig(AssignOp::Assign), "=");
255        assert_eq!(assign_op_to_zig(AssignOp::Add), "+=");
256        assert_eq!(assign_op_to_zig(AssignOp::LogicOr), "or=");
257    }
258
259    #[test]
260    fn test_format_param() {
261        let ident = IrIdent::new("foo");
262        let param = format_param(&ident, &ZigType::I64);
263        assert_eq!(param, "foo: i64");
264    }
265}