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 => "==",
80 BinOp::StrictNe => "!=",
81 BinOp::BitAnd => "&",
82 BinOp::BitOr => "|",
83 BinOp::BitXor => "^",
84 BinOp::Shl => "<<",
85 BinOp::Shr => ">>",
86 BinOp::UrShr => ">>", BinOp::In => "==", BinOp::InstanceOf => "==", }
90}
91
92pub fn update_op_to_zig(op: UpdateOp) -> &'static str {
94 match op {
95 UpdateOp::Increment => "+= 1",
96 UpdateOp::Decrement => "-= 1",
97 }
98}
99
100pub fn assign_op_to_zig(op: AssignOp) -> &'static str {
102 op.to_zig_str()
103}
104
105pub fn zig_type_annotation(ty: Option<&ZigType>) -> Option<String> {
112 ty.map(|t| t.to_zig_type().into_owned())
113}
114
115pub 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
133pub fn format_param(name: &IrIdent, ty: &ZigType) -> String {
135 format!("{}: {}", name.zig_name, ty.to_zig_type())
136}
137
138pub 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
149pub(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
168pub(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
184pub(crate) fn compile_error(msg: &str) -> String {
186 format!("@compileError(\"{}\")", escape_zig_string(msg))
187}
188
189#[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 assert_eq!(
207 format_return_type(
208 &ZigType::NamedStruct("FetchUserResult".to_string()),
209 true,
210 false
211 ),
212 "!host.FetchUserResult"
213 );
214 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 assert_eq!(escape_zig_format_string("hello"), "hello");
234 assert_eq!(escape_zig_format_string("{s}"), "{{s}}");
236 assert_eq!(escape_zig_format_string("a\n{b}"), "a\\n{{b}}");
238 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}