1use std::collections::{HashMap, HashSet};
5
6use oxc_ast::ast::*;
7
8use crate::builtins::BuiltinRegistry;
9use crate::infer::{TypeInferrer, ZigType};
10use crate::sourcemap::{LineIndex, SourceMap, count_lines};
11
12mod builtins;
13mod closure;
14mod expr;
15mod fn_decl;
16mod stmt;
17
18#[derive(Debug, Clone)]
20struct ClosureInfo {
21 struct_name: String,
23 captured: Vec<(String, String)>,
25 params: Vec<(String, String)>,
27 return_type: String,
29 struct_def: String,
31}
32
33fn closure_name(fn_name: &str) -> String {
35 format!("_Closure_{}", fn_name)
36}
37
38struct LeafBinding<'a> {
43 name: &'a str,
44 access: String,
46}
47
48fn flatten_binding_pattern<'a>(
51 pattern: &'a BindingPattern<'a>,
52 prefix: &str,
53 result: &mut Vec<LeafBinding<'a>>,
54) {
55 match pattern {
56 BindingPattern::BindingIdentifier(id) => {
57 result.push(LeafBinding {
58 name: id.name.as_str(),
59 access: prefix.to_string(),
60 });
61 }
62 BindingPattern::ObjectPattern(obj) => {
63 for prop in &obj.properties {
64 let key_str = property_key_name(&prop.key);
65 let new_prefix = format!("{}.{}", prefix, key_str);
66 flatten_binding_pattern(&prop.value, &new_prefix, result);
67 }
68 }
70 BindingPattern::ArrayPattern(arr) => {
71 for (i, elem) in arr.elements.iter().enumerate().filter_map(|(i, opt)| opt.as_ref().map(|e| (i, e))) {
72 let new_prefix = format!("{}[{}]", prefix, i);
73 flatten_binding_pattern(elem, &new_prefix, result);
74 }
75 }
77 BindingPattern::AssignmentPattern(assign) => {
78 flatten_binding_pattern(&assign.left, prefix, result);
81 }
82 }
83}
84
85fn property_key_name(key: &PropertyKey) -> String {
88 match key {
89 PropertyKey::StaticIdentifier(id) => id.name.to_string(),
90 _ => "_computed_key".to_string(),
91 }
92}
93
94pub fn collect_binding_names(pattern: &BindingPattern, names: &mut Vec<String>) {
97 match pattern {
98 BindingPattern::BindingIdentifier(id) => {
99 names.push(id.name.to_string());
100 }
101 BindingPattern::ObjectPattern(obj) => {
102 for prop in &obj.properties {
103 collect_binding_names(&prop.value, names);
104 }
105 if let Some(rest) = &obj.rest {
106 collect_binding_names(&rest.argument, names);
107 }
108 }
109 BindingPattern::ArrayPattern(arr) => {
110 for elem in arr.elements.iter().flatten() {
111 collect_binding_names(elem, names);
112 }
113 if let Some(rest) = &arr.rest {
114 collect_binding_names(&rest.argument, names);
115 }
116 }
117 BindingPattern::AssignmentPattern(assign) => {
118 collect_binding_names(&assign.left, names);
119 }
120 }
121}
122
123pub fn collect_binding_names_with_spans(
126 pattern: &BindingPattern,
127 names: &mut Vec<(String, oxc_span::Span)>,
128) {
129 match pattern {
130 BindingPattern::BindingIdentifier(id) => {
131 names.push((id.name.to_string(), id.span));
132 }
133 BindingPattern::ObjectPattern(obj) => {
134 for prop in &obj.properties {
135 collect_binding_names_with_spans(&prop.value, names);
136 }
137 if let Some(rest) = &obj.rest {
138 collect_binding_names_with_spans(&rest.argument, names);
139 }
140 }
141 BindingPattern::ArrayPattern(arr) => {
142 for elem in arr.elements.iter().flatten() {
143 collect_binding_names_with_spans(elem, names);
144 }
145 if let Some(rest) = &arr.rest {
146 collect_binding_names_with_spans(&rest.argument, names);
147 }
148 }
149 BindingPattern::AssignmentPattern(assign) => {
150 collect_binding_names_with_spans(&assign.left, names);
151 }
152 }
153}
154
155pub fn is_simple_binding(pattern: &BindingPattern) -> bool {
157 matches!(pattern, BindingPattern::BindingIdentifier(_))
158}
159
160pub type CodegenResult = (
162 String,
163 Vec<crate::infer::Diagnostic>,
164 std::collections::HashSet<String>,
165 std::collections::HashMap<String, ZigType>,
166 Vec<CabiExport>,
167 SourceMap,
168);
169
170pub fn generate(
171 program: &Program,
172 builtins: &BuiltinRegistry,
173 exports: &HashSet<String>,
174 source_text: &str,
175 source_file: &str,
176) -> CodegenResult {
177 let mut inferrer = TypeInferrer::new();
178 inferrer.infer_program(program);
179
180 let fn_return_types = inferrer.all_fn_return_types();
182
183 let mut diagnostics = inferrer.diagnostics().to_vec();
184
185 let mut cg = ZigCodegen::new(
186 inferrer,
187 &mut diagnostics,
188 builtins,
189 exports.clone(),
190 source_text,
191 source_file,
192 );
193 cg.pre_scan_closures(program);
197
198 for def in cg.closure_struct_defs.values() {
200 cg.closure_structs.push(def.clone());
201 }
202
203 cg.in_top_level = true;
206 for stmt in &program.body {
207 cg.emit_stmt(stmt);
208 }
209
210 for def in &cg.closure_structs {
212 cg.output.push_str(def);
213 }
214
215 for def in &cg.object_type_defs {
217 cg.output.push_str(def);
218 }
219
220 for wrapper in &cg.cabi_wrappers {
222 cg.output.push_str(wrapper);
223 }
224
225 cg.emit_init_js2rust();
227 cg.emit_deinit_js2rust();
229
230 let closure_fns: HashSet<String> = cg.fn_closure_spans.keys().cloned().collect();
231
232 let cabi_exports = cg.cabi_exports;
233 let source_map = cg.source_map;
234
235 (cg.output, diagnostics, closure_fns, fn_return_types, cabi_exports, source_map)
236}
237
238#[derive(Debug, Clone)]
240pub struct CabiExport {
241 pub name: String,
243 pub params: Vec<(String, ZigType)>,
245 pub ret_type: ZigType,
247 pub has_free_func: bool,
249}
250
251struct ZigCodegen<'a> {
252 output: String,
253 indent: usize,
254 inferrer: TypeInferrer,
255 diagnostics: &'a mut Vec<crate::infer::Diagnostic>,
256 in_top_level: bool,
257 task_counter: usize,
258 builtins: &'a BuiltinRegistry,
259 closure_map: HashMap<u32, ClosureInfo>,
261 closure_struct_defs: HashMap<u32, String>,
263 fn_closure_spans: HashMap<String, u32>,
265 closure_counter: usize,
267 closure_structs: Vec<String>,
269 cabi_wrappers: Vec<String>,
271 cabi_exports: Vec<CabiExport>,
273 string_return_fns: HashSet<String>,
275 closure_vars: HashSet<String>,
277 current_fn: Option<String>,
279 exports: HashSet<String>,
281 try_label: Option<String>,
283 catch_label: Option<String>,
285 try_counter: usize,
287 temp_counter: usize,
289 destructure_prelude: Vec<String>,
292 current_class: Option<(String, Vec<String>)>,
294 object_type_defs: Vec<String>,
296 current_obj_structs: Vec<Option<String>>,
299 init_globals_code: Vec<String>,
302 source_map: SourceMap,
304 line_index: LineIndex,
306 source_file: String,
308}
309
310
311impl<'a> ZigCodegen<'a> {
312 pub(super) fn new(
313 inferrer: TypeInferrer,
314 diagnostics: &'a mut Vec<crate::infer::Diagnostic>,
315 builtins: &'a BuiltinRegistry,
316 exports: HashSet<String>,
317 source_text: &str,
318 source_file: &str,
319 ) -> Self {
320 Self {
321 output: String::new(),
322 indent: 0,
323 inferrer,
324 diagnostics,
325 in_top_level: false,
326 task_counter: 0,
327 builtins,
328 closure_map: HashMap::new(),
329 closure_struct_defs: HashMap::new(),
330 fn_closure_spans: HashMap::new(),
331 closure_counter: 0,
332 closure_structs: Vec::new(),
333 cabi_wrappers: Vec::new(),
334 cabi_exports: Vec::new(),
335 string_return_fns: HashSet::new(),
336 closure_vars: HashSet::new(),
337 current_fn: None,
338 exports,
339 try_label: None,
340 catch_label: None,
341 try_counter: 0,
342 temp_counter: 0,
343 destructure_prelude: Vec::new(),
344 current_class: None,
345 object_type_defs: Vec::new(),
346 current_obj_structs: Vec::new(),
347 init_globals_code: Vec::new(),
348 source_map: SourceMap::new(source_file),
349 line_index: LineIndex::new(source_text),
350 source_file: source_file.to_string(),
351 }
352 }
353
354 pub(super) fn emit_indent(&mut self) {
355 for _ in 0..self.indent {
356 self.output.push_str(" ");
357 }
358 }
359
360 pub(super) fn get_indent_str(&self, level: usize) -> String {
361 " ".repeat(level)
362 }
363
364 pub(super) fn push(&mut self, s: &str) {
365 self.output.push_str(s);
366 }
367
368 pub(super) fn push_line(&mut self, s: &str) {
369 self.emit_indent();
370 self.push(s);
371 self.push("\n");
372 }
373
374 pub(super) fn record_src(&mut self, span_start: u32, kind: &str) {
377 let (js_line, js_col) = self.line_index.offset_to_line_col(span_start);
378 let zig_line = count_lines(&self.output) + 1; self.source_map.add(zig_line, js_line, js_col, kind);
380 self.emit_indent();
382 self.push(&format!("// @src({}:{}) {}\n", self.source_file, js_line, kind));
383 }
384
385 pub(super) fn binding_name<'b>(&self, pattern: &BindingPattern<'b>) -> &'b str {
386 match pattern {
387 BindingPattern::BindingIdentifier(id) => id.name.as_str(),
388 _ => "_unsupported_pattern",
389 }
390 }
391
392 pub(super) fn escape_keyword(name: &str) -> String {
393 let keywords: &[&str] = &[
394 "align", "allowzero", "and", "anyframe", "anytype", "asm", "async",
395 "await", "break", "callconv", "catch", "comptime", "const", "continue",
396 "defer", "else", "enum", "errdefer", "error", "export", "extern",
397 "false", "fn", "for", "if", "inline", "linksection", "noalias",
398 "noinline", "noreturn", "nosuspend", "null", "opaque", "or", "orelse", "packed",
399 "pub", "resume", "return", "struct", "suspend", "switch", "test",
400 "threadlocal", "true", "try", "type", "undefined", "union", "unreachable",
401 "usingnamespace", "var", "volatile", "while",
402 ];
403 if keywords.contains(&name) {
404 format!("@\"{}\"", name)
405 } else {
406 name.to_string()
407 }
408 }
409
410 pub(super) fn emit_typed_init(&mut self, init: &Expression, target_type: &ZigType) {
413 match target_type {
414 ZigType::JsValue => {
415 let expr_type = self.inferrer.infer_expr(init);
416 match expr_type {
417 ZigType::I64 | ZigType::I32 | ZigType::Usize => {
418 self.push("JsValue.fromI64(");
419 self.emit_expr(init);
420 self.push(")");
421 }
422 ZigType::F64 | ZigType::F32 => {
423 self.push("JsValue.fromF64(");
424 self.emit_expr(init);
425 self.push(")");
426 }
427 ZigType::Bool => {
428 self.push("JsValue.fromBool(");
429 self.emit_expr(init);
430 self.push(")");
431 }
432 ZigType::String => {
433 self.push("JsValue.fromString(");
434 self.emit_expr(init);
435 self.push(")");
436 }
437 ZigType::Null => {
438 self.push("JsValue.fromNull()");
439 }
440 _ => {
441 self.emit_expr(init);
442 }
443 }
444 }
445 ZigType::JsAny => {
446 let expr_type = self.inferrer.infer_expr(init);
447 match expr_type {
448 ZigType::I64 | ZigType::I32 | ZigType::Usize => {
449 self.push("JsAny.fromI64(");
450 self.emit_expr(init);
451 self.push(")");
452 }
453 ZigType::F64 | ZigType::F32 => {
454 self.push("JsAny.fromF64(");
455 self.emit_expr(init);
456 self.push(")");
457 }
458 ZigType::Bool => {
459 self.push("JsAny.fromBool(");
460 self.emit_expr(init);
461 self.push(")");
462 }
463 ZigType::String => {
464 self.push("JsAny.fromString(");
465 self.emit_expr(init);
466 self.push(")");
467 }
468 ZigType::Null => {
469 self.push("JsAny.fromNull()");
470 }
471 _ => {
472 self.emit_expr(init);
473 }
474 }
475 }
476 _ => {
477 self.emit_expr(init);
478 }
479 }
480 }
481
482 pub(super) fn emit_dynamic_access_var_decl(&mut self, name: &str) {
485 self.emit_indent();
486 self.push("var ");
487 self.push(name);
488 self.push(": std.StringHashMap(JsAny) = undefined;\n");
489 }
490
491 pub(super) fn emit_dynamic_access_var_init_code(&mut self, name: &str, obj: &ObjectExpression) {
494 self.init_globals_code.push(format!(
496 " {} = std.StringHashMap(JsAny).init(allocator);\n",
497 name
498 ));
499
500 for prop in &obj.properties {
502 if let oxc_ast::ast::ObjectPropertyKind::ObjectProperty(p) = prop {
503 let field_name = match &p.key {
504 oxc_ast::ast::PropertyKey::StaticIdentifier(id) => id.name.to_string(),
505 oxc_ast::ast::PropertyKey::StringLiteral(s) => s.value.to_string(),
506 _ => continue,
507 };
508
509 let js_any_lit = self.emit_js_any_literal(&p.value);
511 self.init_globals_code.push(format!(
512 " {}.put(\"{}\", {}) catch @panic(\"OOM\");\n",
513 name, field_name, js_any_lit
514 ));
515 }
516 }
517 }
518
519 pub(super) fn emit_js_any_literal(&self, expr: &Expression) -> String {
522 match expr {
523 Expression::NumericLiteral(lit) => {
524 if lit.value.is_finite() && lit.value == lit.value.trunc() {
525 format!("JsAny.fromI64({})", lit.value as i64)
526 } else {
527 format!("JsAny.fromF64({})", lit.value)
528 }
529 }
530 Expression::StringLiteral(s) => {
531 format!("JsAny.fromString(\"{}\")", Self::escape_zig_string(&s.value))
532 }
533 Expression::BooleanLiteral(b) => {
534 format!("JsAny.fromBool({})", b.value)
535 }
536 Expression::NullLiteral(_) => {
537 "JsAny.fromNull()".to_string()
538 }
539 _ => {
540 let js_val = self.emit_js_value_literal(expr);
542 format!("JsAny.fromValue({})", js_val)
543 }
544 }
545 }
546
547 fn escape_zig_string(s: &str) -> String {
549 s.replace('\\', "\\\\")
550 .replace('"', "\\\"")
551 .replace('\n', "\\n")
552 .replace('\r', "\\r")
553 .replace('\t', "\\t")
554 }
555
556 pub(super) fn emit_js_value_literal(&self, expr: &Expression) -> String {
557 match expr {
558 Expression::NumericLiteral(lit) => {
559 let val_str = lit.value.to_string();
560 if lit.value.is_finite() && lit.value == lit.value.trunc() {
563 format!(".{{ .int = {} }}", val_str)
564 } else {
565 format!(".{{ .float = {} }}", val_str)
566 }
567 }
568 Expression::StringLiteral(lit) => {
569 format!(".{{ .string = \"{}\" }}", lit.value)
570 }
571 Expression::BooleanLiteral(lit) => {
572 format!(".{{ .bool = {} }}", if lit.value { "true" } else { "false" })
573 }
574 Expression::NullLiteral(_) => {
575 ".{ .null = {} }".to_string()
576 }
577 _ => {
578 ".{ .int = 0 }".to_string()
580 }
581 }
582 }
583
584 pub(super) fn emit_js_value_construction(&mut self, expr: &Expression) {
588 match expr {
589 Expression::NumericLiteral(lit) => {
590 let val_str = lit.value.to_string();
591 if lit.value.is_finite() && lit.value == lit.value.trunc() {
592 self.push(&format!("JsValue{{ .int = {} }}", val_str));
593 } else {
594 self.push(&format!("JsValue{{ .float = {} }}", val_str));
595 }
596 }
597 Expression::StringLiteral(lit) => {
598 self.push(&format!("JsValue{{ .string = \"{}\" }}", lit.value));
599 }
600 Expression::BooleanLiteral(lit) => {
601 let b = if lit.value { "true" } else { "false" };
602 self.push(&format!("JsValue{{ .bool = {} }}", b));
603 }
604 Expression::NullLiteral(_) => {
605 self.push("JsValue{ .null = {} }");
606 }
607 _ => {
608 self.push("JsValue{ .int = ");
610 self.emit_expr(expr);
611 self.push(" }");
612 }
613 }
614 }
615
616 pub(super) fn dynamic_field_accessor(&self, obj_expr: &Expression, prop: &str) -> String {
619 if let Expression::Identifier(id) = obj_expr {
620 let obj_type = self.inferrer.get_var_type(id.name.as_str());
621 if let ZigType::Object { fields } = obj_type
622 && let Some((_, field_type)) = fields.iter().find(|(n, _)| n == prop)
623 {
624 return match field_type {
625 ZigType::String => ".string".to_string(),
626 ZigType::F64 | ZigType::F32 => ".float".to_string(),
627 ZigType::Bool => ".bool".to_string(),
628 ZigType::Null => ".null".to_string(),
629 _ => ".asI64()".to_string(),
630 };
631 }
632 }
633 ".asI64()".to_string()
634 }
635
636 pub(super) fn emit_init_js2rust(&mut self) {
637 self.push("\n");
639 self.push("/// Initialize global allocator and all objects that use dynamic property access.\n");
640 self.push("pub fn init_js2rust(allocator: std.mem.Allocator) void {\n");
641 self.push(" js_allocator.setGlobalAllocator(allocator);\n");
642 let init_code: String = self.init_globals_code.iter().cloned().collect();
644 if !init_code.is_empty() {
645 self.push(&init_code);
646 }
647 self.push("}\n");
648 }
649
650 pub(super) fn emit_deinit_js2rust(&mut self) {
654 let mut hashmap_names: Vec<String> = Vec::new();
656 for line in &self.init_globals_code {
657 if line.contains(".init(")
658 && let Some(name) = line.trim().split(" =").next()
659 {
660 hashmap_names.push(name.to_string());
661 }
662 }
663 if hashmap_names.is_empty() {
665 return;
666 }
667 self.push("\n");
668 self.push("/// Deinitialize all global objects created by init_js2rust().\n");
669 self.push("pub fn deinit_js2rust() void {\n");
670 for name in &hashmap_names {
671 self.push(&format!(" {}.deinit();\n", name));
672 }
673 self.push("}\n");
674 }
675
676 pub(super) fn gen_obj_struct_def(struct_name: &str, fields: &[(String, ZigType)]) -> String {
677 let mut s = format!("const {} = struct {{\n", struct_name);
678 for (fname, ftype) in fields {
679 s.push_str(&format!(" {}: {},\n", fname, ftype.to_zig_str()));
680 }
681 s.push_str("};\n\n");
682 s
683 }
684
685 pub(super) fn capitalize_first(s: &str) -> String {
687 let mut chars = s.chars();
688 match chars.next() {
689 None => String::new(),
690 Some(c) => {
691 let upper = c.to_uppercase().collect::<String>();
692 upper + chars.as_str()
693 }
694 }
695 }
696
697 pub(super) fn is_string_literal_expr(expr: &Expression) -> bool {
698 matches!(expr, Expression::StringLiteral(_))
699 }
700
701 pub(super) fn emit_arg(&mut self, arg: &Argument) {
704 match arg {
705 Argument::SpreadElement(spread) => {
706 self.push("...");
707 self.emit_expr(&spread.argument);
708 }
709 _ => {
710 if let Some(expr) = arg.as_expression() {
711 self.emit_expr(expr);
712 }
713 }
714 }
715 }
716
717 pub(super) fn emit_jsany_arg(&mut self, arg: &Argument) {
719 match arg {
720 Argument::SpreadElement(_) => {
721 self.push("JsAny.fromNull()");
723 }
724 _ => {
725 if let Some(expr) = arg.as_expression() {
726 let lit = self.emit_js_any_literal(expr);
727 self.push(&lit);
728 }
729 }
730 }
731 }
732
733 pub(super) fn emit_array_element(&mut self, elem: &ArrayExpressionElement) {
734 match elem {
735 ArrayExpressionElement::SpreadElement(spread) => {
736 self.push("...");
737 self.emit_expr(&spread.argument);
738 }
739 ArrayExpressionElement::Elision(_) => {
740 self.push("undefined");
741 }
742 _ => {
743 if let Some(expr) = elem.as_expression() {
744 self.emit_expr(expr);
745 }
746 }
747 }
748 }
749
750 pub(super) fn emit_jsany_array_element(&mut self, elem: &ArrayExpressionElement) {
752 match elem {
753 ArrayExpressionElement::SpreadElement(_) => {
754 self.push("JsAny.fromNull()"); }
756 ArrayExpressionElement::Elision(_) => {
757 self.push("JsAny.fromNull()");
758 }
759 _ => {
760 if let Some(expr) = elem.as_expression() {
761 let lit = self.emit_js_any_literal(expr);
762 self.push(&lit);
763 }
764 }
765 }
766 }
767
768 pub(super) fn emit_assign_target(&mut self, target: &AssignmentTarget) {
769 match target {
770 AssignmentTarget::AssignmentTargetIdentifier(id) => {
771 self.push(&Self::escape_keyword(id.name.as_str()));
772 }
773 AssignmentTarget::ArrayAssignmentTarget(_) => {
774 self.push("_/* array destructure */");
775 }
776 AssignmentTarget::ObjectAssignmentTarget(_) => {
777 self.push("_/* object destructure */");
778 }
779 AssignmentTarget::StaticMemberExpression(mem) => {
780 self.emit_expr(&mem.object);
781 self.push(".");
782 self.push(mem.property.name.as_str());
783 }
784 AssignmentTarget::ComputedMemberExpression(mem) => {
785 let obj_type = self.inferrer.infer_expr(&mem.object);
786 if matches!(&obj_type, ZigType::Object { .. })
787 && let Expression::StringLiteral(s) = &mem.expression
788 {
789 self.emit_expr(&mem.object);
790 self.push(".");
791 self.push(s.value.as_str());
792 } else {
793 self.emit_expr(&mem.object);
794 self.push("[");
795 self.emit_expr(&mem.expression);
796 self.push("]");
797 }
798 }
799 AssignmentTarget::PrivateFieldExpression(_) => {
800 self.push("_/* private field */");
801 }
802 AssignmentTarget::TSAsExpression(ts) => {
803 self.emit_expr(&ts.expression);
804 }
805 AssignmentTarget::TSSatisfiesExpression(ts) => {
806 self.emit_expr(&ts.expression);
807 }
808 AssignmentTarget::TSNonNullExpression(ts) => {
809 self.emit_expr(&ts.expression);
810 self.push(".?");
811 }
812 AssignmentTarget::TSTypeAssertion(ts) => {
813 self.emit_expr(&ts.expression);
814 }
815 }
816 }
817
818 pub(super) fn emit_assign_target_from_simple(&mut self, target: &SimpleAssignmentTarget) {
819 match target {
820 SimpleAssignmentTarget::AssignmentTargetIdentifier(id) => {
821 self.push(&Self::escape_keyword(id.name.as_str()));
822 }
823 SimpleAssignmentTarget::StaticMemberExpression(mem) => {
824 self.emit_expr(&mem.object);
825 self.push(".");
826 self.push(mem.property.name.as_str());
827 }
828 SimpleAssignmentTarget::ComputedMemberExpression(mem) => {
829 let obj_type = self.inferrer.infer_expr(&mem.object);
830 if matches!(&obj_type, ZigType::Object { .. })
831 && let Expression::StringLiteral(s) = &mem.expression
832 {
833 self.emit_expr(&mem.object);
834 self.push(".");
835 self.push(s.value.as_str());
836 } else {
837 self.emit_expr(&mem.object);
838 self.push("[");
839 self.emit_expr(&mem.expression);
840 self.push("]");
841 }
842 }
843 SimpleAssignmentTarget::PrivateFieldExpression(_) => {
844 self.push("_/* private */");
845 }
846 _ => {
847 self.push("_/* ts assign target */");
848 }
849 }
850 }
851
852 pub(super) fn map_binary_op(&self, op: &BinaryOperator) -> &'static str {
855 match op {
856 BinaryOperator::StrictEquality => "==",
857 BinaryOperator::StrictInequality => "!=",
858 BinaryOperator::Equality => "==",
859 BinaryOperator::Inequality => "!=",
860 BinaryOperator::Addition => "+",
861 BinaryOperator::Subtraction => "-",
862 BinaryOperator::Multiplication => "*",
863 BinaryOperator::Division => "/",
864 BinaryOperator::Remainder => "%",
865 BinaryOperator::Exponential => "**",
866 BinaryOperator::LessThan => "<",
867 BinaryOperator::LessEqualThan => "<=",
868 BinaryOperator::GreaterThan => ">",
869 BinaryOperator::GreaterEqualThan => ">=",
870 BinaryOperator::ShiftLeft => "<<",
871 BinaryOperator::ShiftRight => ">>",
872 BinaryOperator::ShiftRightZeroFill => ">>",
873 BinaryOperator::BitwiseOR => "|",
874 BinaryOperator::BitwiseXOR => "^",
875 BinaryOperator::BitwiseAnd => "&",
876 BinaryOperator::In => "== /* in */",
877 BinaryOperator::Instanceof => "== /* instanceof */",
878 }
879 }
880
881 pub(super) fn map_logical_op(&self, op: &LogicalOperator) -> &'static str {
882 match op {
883 LogicalOperator::And => "and",
884 LogicalOperator::Or => "or",
885 LogicalOperator::Coalesce => "orelse",
886 }
887 }
888
889 pub(super) fn map_unary_op(&self, op: &UnaryOperator) -> &'static str {
890 match op {
891 UnaryOperator::UnaryPlus => "", UnaryOperator::UnaryNegation => "-",
893 UnaryOperator::LogicalNot => "!",
894 UnaryOperator::BitwiseNot => "~",
895 UnaryOperator::Typeof => "@TypeOf",
896 UnaryOperator::Void => "",
897 UnaryOperator::Delete => "",
898 }
899 }
900
901 pub(super) fn map_assign_op(&self, op: &AssignmentOperator) -> &'static str {
902 match op {
903 AssignmentOperator::Assign => "=",
904 AssignmentOperator::Addition => "+=",
905 AssignmentOperator::Subtraction => "-=",
906 AssignmentOperator::Multiplication => "*=",
907 AssignmentOperator::Division => "/=",
908 AssignmentOperator::Remainder => "%=",
909 AssignmentOperator::Exponential => "**=",
910 AssignmentOperator::ShiftLeft => "<<=",
911 AssignmentOperator::ShiftRight => ">>=",
912 AssignmentOperator::ShiftRightZeroFill => ">>>=",
913 AssignmentOperator::BitwiseOR => "|=",
914 AssignmentOperator::BitwiseXOR => "^=",
915 AssignmentOperator::BitwiseAnd => "&=",
916 AssignmentOperator::LogicalOr => "|=",
917 AssignmentOperator::LogicalAnd => "&=",
918 AssignmentOperator::LogicalNullish => "=?=",
919 }
920 }
921}