1use super::Codegen;
5use oxc_ast::ast::*;
6
7const ZIG_RESERVED_KEYWORDS: &[&str] = &[
12 "addrspace",
13 "align",
14 "allowzero",
15 "and",
16 "anyframe",
17 "anytype",
18 "asm",
19 "async",
20 "await",
21 "break",
22 "callconv",
23 "catch",
24 "comptime",
25 "const",
26 "continue",
27 "defer",
28 "else",
29 "enum",
30 "errdefer",
31 "error",
32 "export",
33 "extern",
34 "fn",
35 "for",
36 "if",
37 "inline",
38 "linksection",
39 "noalias",
40 "noinline",
41 "nosuspend",
42 "opaque",
43 "or",
44 "orelse",
45 "packed",
46 "pub",
47 "resume",
48 "return",
49 "struct",
50 "suspend",
51 "switch",
52 "test",
53 "threadlocal",
54 "try",
55 "union",
56 "unreachable",
57 "usingnamespace",
58 "var",
59 "volatile",
60 "while",
61];
62
63pub(crate) fn zig_safe_name(name: &str) -> String {
66 if ZIG_RESERVED_KEYWORDS.contains(&name) {
67 format!("_{}", name)
68 } else {
69 name.to_string()
70 }
71}
72
73impl Codegen {
76 pub(crate) fn zig_safe_name(&self, name: &str) -> String {
80 for scope in self.shadow_renames.iter().rev() {
82 if let Some(renamed) = scope.get(name) {
83 return renamed.clone();
84 }
85 }
86 zig_safe_name(name)
87 }
88
89 pub(crate) fn push_shadow_scope(&mut self) {
93 self.shadow_renames.push(std::collections::HashMap::new());
94 }
95
96 pub(crate) fn pop_shadow_scope(&mut self) {
100 self.shadow_renames.pop();
101 }
102
103 pub(crate) fn binding_name<'a>(&self, pattern: &BindingPattern<'a>) -> Option<&'a str> {
104 match pattern {
105 BindingPattern::BindingIdentifier(id) => Some(id.name.as_str()),
106 _ => None,
107 }
108 }
109
110 pub(crate) fn property_key_name(&self, key: &PropertyKey) -> Option<String> {
113 match key {
114 PropertyKey::StaticIdentifier(id) => Some(id.name.to_string()),
115 PropertyKey::PrivateIdentifier(id) => Some(id.name.to_string()),
116 _ => None,
117 }
118 }
119
120 pub(crate) fn destructure_binding<'a>(
123 &mut self,
124 pattern: &BindingPattern<'a>,
125 ) -> Option<(&'a str, Option<String>)> {
126 match pattern {
127 BindingPattern::BindingIdentifier(id) => Some((id.name.as_str(), None)),
128 BindingPattern::AssignmentPattern(ap) => {
129 let name = self.binding_name(&ap.left)?;
130 let default_str = self.emit_expr_to_string(&ap.right);
131 Some((name, Some(default_str)))
132 }
133 _ => None,
134 }
135 }
136
137 pub(crate) fn binary_op(op: BinaryOperator) -> &'static str {
138 match op {
139 BinaryOperator::Addition => "+",
140 BinaryOperator::Subtraction => "-",
141 BinaryOperator::Multiplication => "*",
142 BinaryOperator::Division => "/",
143 BinaryOperator::Remainder => "%",
144 BinaryOperator::LessThan => "<",
145 BinaryOperator::GreaterThan => ">",
146 BinaryOperator::LessEqualThan => "<=",
147 BinaryOperator::GreaterEqualThan => ">=",
148 BinaryOperator::Equality => "==",
149 BinaryOperator::Inequality => "!=",
150 BinaryOperator::StrictEquality => "==",
151 BinaryOperator::StrictInequality => "!=",
152 BinaryOperator::ShiftLeft => "<<",
153 BinaryOperator::ShiftRight => ">>",
154 BinaryOperator::ShiftRightZeroFill => ">>",
155 BinaryOperator::BitwiseAnd => "&",
156 BinaryOperator::BitwiseOR => "|",
157 BinaryOperator::BitwiseXOR => "^",
158 _ => "/* op */",
159 }
160 }
161
162 pub(crate) fn assignment_op(op: AssignmentOperator) -> &'static str {
163 match op {
164 AssignmentOperator::Assign => "=",
165 AssignmentOperator::Addition => "+=",
166 AssignmentOperator::Subtraction => "-=",
167 AssignmentOperator::Multiplication => "*=",
168 AssignmentOperator::Division => "/=",
169 AssignmentOperator::Remainder => "%=",
170 AssignmentOperator::Exponential => "**=",
171 AssignmentOperator::ShiftLeft => "<<=",
172 AssignmentOperator::ShiftRight => ">>=",
173 AssignmentOperator::ShiftRightZeroFill => ">>=",
174 AssignmentOperator::BitwiseAnd => "&=",
175 AssignmentOperator::BitwiseOR => "|=",
176 AssignmentOperator::BitwiseXOR => "^=",
177 AssignmentOperator::LogicalAnd => "&&=",
178 AssignmentOperator::LogicalOr => "||=",
179 AssignmentOperator::LogicalNullish => "??=",
180 }
181 }
182
183 pub(crate) fn logical_op(op: LogicalOperator) -> &'static str {
184 match op {
185 LogicalOperator::And => "and",
186 LogicalOperator::Or => "or",
187 LogicalOperator::Coalesce => "orelse",
189 }
190 }
191
192 pub(crate) fn unary_prefix(op: UnaryOperator) -> &'static str {
193 match op {
194 UnaryOperator::UnaryNegation => "-",
195 UnaryOperator::UnaryPlus => "+",
196 UnaryOperator::LogicalNot => "!",
197 UnaryOperator::BitwiseNot => "~",
198 _ => "",
199 }
200 }
201}
202
203impl Codegen {
206 pub fn write(&mut self, s: &str) {
207 self.output.push_str(s);
208 }
209
210 pub fn push(&mut self, ch: char) {
211 self.output.push(ch);
212 }
213
214 pub fn writeln(&mut self, s: &str) {
215 self.write_indent();
216 self.output.push_str(s);
217 self.output.push('\n');
218 }
219
220 pub fn write_indent(&mut self) {
221 for _ in 0..self.indent {
222 self.output.push_str(" ");
223 }
224 }
225
226 pub fn next_label(&mut self) -> String {
230 let id = self.label_counter;
231 self.label_counter += 1;
232 format!("blk_{}", id)
233 }
234
235 pub fn emit_blk_start(&mut self) -> String {
239 let label = self.next_label();
240 self.write(&format!("({}: {{", label));
241 label
242 }
243
244 pub fn emit_blk_break(&mut self, label: &str, expr: &str) {
246 self.write(&format!("break :{} {}", label, expr));
247 }
248
249 pub fn emit_blk_end(&mut self) {
251 self.write("}");
252 }
253}
254
255impl Codegen {
258 pub(crate) fn first_arg_string(&mut self, args: &[Argument]) -> String {
261 if let Some(arg) = args.first()
262 && let Some(expr) = arg.as_expression()
263 {
264 self.emit_expr_to_string(expr)
265 } else {
266 String::new()
267 }
268 }
269
270 pub(crate) fn first_arg_string_or(&mut self, args: &[Argument], default: &str) -> String {
272 if let Some(arg) = args.first()
273 && let Some(expr) = arg.as_expression()
274 {
275 self.emit_expr_to_string(expr)
276 } else {
277 default.to_string()
278 }
279 }
280
281 pub(crate) fn emit_first_arg(&mut self, args: &[Argument]) {
283 if let Some(arg) = args.first()
284 && let Some(expr) = arg.as_expression()
285 {
286 let saved = self.in_expr_stmt;
288 self.in_expr_stmt = false;
289 self.emit_expr(expr);
290 self.in_expr_stmt = saved;
291 }
292 }
293
294 pub(crate) fn emit_comma_separated_args(&mut self, args: &[Argument]) {
296 for (i, arg) in args.iter().enumerate() {
297 if i > 0 {
298 self.write(", ");
299 }
300 self.emit_expr_arg(arg);
301 }
302 }
303
304 pub(crate) fn emit_comma_separated_array_elements(
307 &mut self,
308 elements: &[ArrayExpressionElement],
309 ) {
310 for (i, elem) in elements.iter().enumerate() {
311 if i > 0 {
312 self.write(", ");
313 }
314 if let Some(e) = elem.as_expression() {
315 self.emit_expr(e);
316 }
317 }
318 }
319}
320
321impl Codegen {
324 pub(crate) fn callee_object_name<'a>(&self, callee: &'a Expression) -> Option<&'a str> {
327 if let Expression::StaticMemberExpression(mem) = callee
328 && let Expression::Identifier(obj) = &mem.object
329 {
330 Some(obj.name.as_str())
331 } else {
332 None
333 }
334 }
335
336 pub(crate) fn callee_object_repr(&self, callee: &Expression) -> Option<String> {
341 if let Expression::StaticMemberExpression(mem) = callee {
342 if let Expression::Identifier(obj) = &mem.object {
343 return Some(obj.name.to_string());
344 }
345 if let Expression::StringLiteral(lit) = &mem.object {
346 let escaped = lit
347 .value
348 .as_str()
349 .replace('\\', "\\\\")
350 .replace('\"', "\\\"")
351 .replace('\n', "\\n")
352 .replace('\r', "\\r")
353 .replace('\t', "\\t");
354 return Some(format!("\"{}\"", escaped));
355 }
356 }
357 None
358 }
359
360 pub(crate) fn callee_object_repr_mut(&mut self, callee: &Expression) -> Option<String> {
366 if let Some(repr) = self.callee_object_repr(callee) {
368 return Some(repr);
369 }
370 if let Expression::StaticMemberExpression(mem) = callee {
372 return Some(self.emit_expr_to_string(&mem.object));
373 }
374 None
375 }
376
377 pub(crate) fn emit_numeric_receiver(
384 &mut self,
385 callee: &Expression,
386 method_name: &str,
387 arguments: &[Argument],
388 args_required: bool,
389 ) -> bool {
390 let num_expr = if let Expression::StaticMemberExpression(mem) = callee {
391 match &mem.object {
392 Expression::NumericLiteral(_) => Some(&mem.object),
393 Expression::ParenthesizedExpression(pe)
394 if matches!(&pe.expression, Expression::NumericLiteral(_)) =>
395 {
396 Some(&pe.expression)
397 }
398 _ => None,
399 }
400 } else {
401 None
402 };
403 if let Some(expr) = num_expr {
404 if args_required && arguments.is_empty() {
405 self.errors
406 .push(format!("{method_name}() requires at least 1 argument"));
407 return false;
408 }
409 self.write(&format!(
410 "js_number.{method_name}(js_allocator.allocator(), ",
411 ));
412 self.emit_expr(expr);
413 if arguments.is_empty() {
414 self.write(", null");
415 } else {
416 self.write(", ");
417 self.emit_first_arg(arguments);
418 }
419 self.write(")");
420 return true;
421 }
422 false
423 }
424
425 pub(crate) fn emit_format_string(&mut self, fmt: &str, args: &[String]) {
431 if args.is_empty() {
432 self.write(&format!(
434 "\"{}\"",
435 fmt.replace("{{", "{").replace("}}", "}")
436 ));
437 } else {
438 let args_str = format!(".{{{}}}", args.join(", "));
439 self.write(&format!(
440 "std.fmt.allocPrint(js_allocator.allocator(), \"{}\", {}) catch @panic(\"OOM: template literal allocPrint\")",
441 fmt, args_str
442 ));
443 }
444 }
445}
446
447