1use crate::types::ZigType;
6use crate::zigir::ident::IrIdent;
7use crate::zigir::ops::AssignOp;
8use crate::zigir::ops::BinOp;
9use crate::zigir::ops::UpdateOp;
10
11pub 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 fn write(&mut self, s: &str) {
23 self.output_mut().push_str(s);
24 }
25
26 fn push(&mut self, ch: char) {
28 self.output_mut().push(ch);
29 }
30
31 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 fn write_indent(&mut self) {
40 for _ in 0..self.indent() {
41 self.output_mut().push_str(" ");
42 }
43 }
44
45 fn indent_push(&mut self) {
47 *self.indent_mut() += 1;
48 }
49
50 fn indent_pop(&mut self) {
52 assert!(self.indent() > 0, "indent underflow");
53 *self.indent_mut() -= 1;
54 }
55}
56
57pub 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", 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 => ">>", BinOp::In => "==", BinOp::InstanceOf => "==", }
87}
88
89pub fn update_op_to_zig(op: UpdateOp) -> &'static str {
91 match op {
92 UpdateOp::Increment => "+= 1",
93 UpdateOp::Decrement => "-= 1",
94 }
95}
96
97pub fn assign_op_to_zig(op: AssignOp) -> &'static str {
99 op.to_zig_str()
100}
101
102pub fn zig_type_annotation(ty: Option<&ZigType>) -> Option<String> {
109 ty.map(|t| t.to_zig_type().into_owned())
110}
111
112pub 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
130pub fn format_param(name: &IrIdent, ty: &ZigType) -> String {
132 format!("{}: {}", name.zig_name, ty.to_zig_type())
133}
134
135pub 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
146pub(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
165pub(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
181pub(crate) fn compile_error(msg: &str) -> String {
183 format!("@compileError(\"{}\")", escape_zig_string(msg))
184}
185
186#[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 assert_eq!(
204 format_return_type(
205 &ZigType::NamedStruct("FetchUserResult".to_string()),
206 true,
207 false
208 ),
209 "!host.FetchUserResult"
210 );
211 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 assert_eq!(escape_zig_format_string("hello"), "hello");
231 assert_eq!(escape_zig_format_string("{s}"), "{{s}}");
233 assert_eq!(escape_zig_format_string("a\n{b}"), "a\\n{{b}}");
235 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}