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 struct HostTypeInfo<'a> {
174 pub return_types: &'a HashMap<String, ZigType>,
175 pub param_types: &'a HashMap<String, Vec<ZigType>>,
176 pub struct_fields: &'a HashMap<String, Vec<(String, ZigType)>>,
177 pub async_fns: &'a HashSet<String>,
179}
180
181pub fn generate(
182 program: &Program,
183 builtins: &BuiltinRegistry,
184 exports: &HashSet<String>,
185 source_text: &str,
186 source_file: &str,
187 host_info: &HostTypeInfo,
188) -> CodegenResult {
189 let mut inferrer = TypeInferrer::new();
190
191 for (name, ret_type) in host_info.return_types {
193 inferrer.add_host_return_type(name.clone(), ret_type.clone());
194 }
195
196 inferrer.register_host_param_types(host_info.param_types);
198
199 inferrer.register_host_struct_fields(host_info.struct_fields);
201
202 inferrer.infer_program(program);
203
204 let fn_return_types = inferrer.all_fn_return_types();
206
207 let mut diagnostics = inferrer.diagnostics().to_vec();
208
209 let mut cg = ZigCodegen::new(
210 inferrer,
211 &mut diagnostics,
212 builtins,
213 exports.clone(),
214 source_text,
215 source_file,
216 host_info.async_fns.clone(),
217 );
218 cg.pre_scan_closures(program);
222
223 for def in cg.closure_struct_defs.values() {
225 cg.closure_structs.push(def.clone());
226 }
227
228 cg.in_top_level = true;
231 for stmt in &program.body {
232 cg.emit_stmt(stmt);
233 }
234
235 for def in &cg.closure_structs {
237 cg.output.push_str(def);
238 }
239
240 for def in &cg.object_type_defs {
242 cg.output.push_str(def);
243 }
244
245 for wrapper in &cg.cabi_wrappers {
247 cg.output.push_str(wrapper);
248 }
249
250 cg.emit_init_js2rust();
252 cg.emit_deinit_js2rust();
254
255 let closure_fns: HashSet<String> = cg.fn_closure_spans.keys().cloned().collect();
256
257 let cabi_exports = cg.cabi_exports;
258 let source_map = cg.source_map;
259
260 (cg.output, diagnostics, closure_fns, fn_return_types, cabi_exports, source_map)
261}
262
263#[derive(Debug, Clone)]
265pub struct CabiExport {
266 pub name: String,
268 pub params: Vec<(String, ZigType)>,
270 pub ret_type: ZigType,
272 pub has_free_func: bool,
274 pub is_async: bool,
276}
277
278struct ZigCodegen<'a> {
279 output: String,
280 indent: usize,
281 inferrer: TypeInferrer,
282 diagnostics: &'a mut Vec<crate::infer::Diagnostic>,
283 in_top_level: bool,
284 task_counter: usize,
285 builtins: &'a BuiltinRegistry,
286 closure_map: HashMap<u32, ClosureInfo>,
288 closure_struct_defs: HashMap<u32, String>,
290 fn_closure_spans: HashMap<String, u32>,
292 closure_counter: usize,
294 closure_structs: Vec<String>,
296 cabi_wrappers: Vec<String>,
298 cabi_exports: Vec<CabiExport>,
300 string_return_fns: HashSet<String>,
302 closure_vars: HashSet<String>,
304 current_fn: Option<String>,
306 exports: HashSet<String>,
308 try_label: Option<String>,
310 catch_label: Option<String>,
312 try_counter: usize,
314 temp_counter: usize,
316 destructure_prelude: Vec<String>,
319 current_class: Option<(String, Vec<String>)>,
321 object_type_defs: Vec<String>,
323 current_obj_structs: Vec<Option<String>>,
326 init_globals_code: Vec<String>,
329 source_map: SourceMap,
331 line_index: LineIndex,
333 source_file: String,
335 #[allow(dead_code)]
337 async_host_fns: HashSet<String>,
338}
339
340
341impl<'a> ZigCodegen<'a> {
342 pub(super) fn new(
343 inferrer: TypeInferrer,
344 diagnostics: &'a mut Vec<crate::infer::Diagnostic>,
345 builtins: &'a BuiltinRegistry,
346 exports: HashSet<String>,
347 source_text: &str,
348 source_file: &str,
349 async_host_fns: HashSet<String>,
350 ) -> Self {
351 Self {
352 output: String::new(),
353 indent: 0,
354 inferrer,
355 diagnostics,
356 in_top_level: false,
357 task_counter: 0,
358 builtins,
359 closure_map: HashMap::new(),
360 closure_struct_defs: HashMap::new(),
361 fn_closure_spans: HashMap::new(),
362 closure_counter: 0,
363 closure_structs: Vec::new(),
364 cabi_wrappers: Vec::new(),
365 cabi_exports: Vec::new(),
366 string_return_fns: HashSet::new(),
367 closure_vars: HashSet::new(),
368 current_fn: None,
369 exports,
370 try_label: None,
371 catch_label: None,
372 try_counter: 0,
373 temp_counter: 0,
374 destructure_prelude: Vec::new(),
375 current_class: None,
376 object_type_defs: Vec::new(),
377 current_obj_structs: Vec::new(),
378 init_globals_code: Vec::new(),
379 source_map: SourceMap::new(source_file),
380 line_index: LineIndex::new(source_text),
381 source_file: source_file.to_string(),
382 async_host_fns,
383 }
384 }
385
386 pub(super) fn emit_indent(&mut self) {
387 for _ in 0..self.indent {
388 self.output.push_str(" ");
389 }
390 }
391
392 pub(super) fn get_indent_str(&self, level: usize) -> String {
393 " ".repeat(level)
394 }
395
396 pub(super) fn push(&mut self, s: &str) {
397 self.output.push_str(s);
398 }
399
400 pub(super) fn push_line(&mut self, s: &str) {
401 self.emit_indent();
402 self.push(s);
403 self.push("\n");
404 }
405
406 pub(super) fn record_src(&mut self, span_start: u32, kind: &str) {
409 let (js_line, js_col) = self.line_index.offset_to_line_col(span_start);
410 let zig_line = count_lines(&self.output) + 1; self.source_map.add(zig_line, js_line, js_col, kind);
412 self.emit_indent();
414 self.push(&format!("// @src({}:{}) {}\n", self.source_file, js_line, kind));
415 }
416
417 pub(super) fn binding_name<'b>(&self, pattern: &BindingPattern<'b>) -> &'b str {
418 match pattern {
419 BindingPattern::BindingIdentifier(id) => id.name.as_str(),
420 _ => "_unsupported_pattern",
421 }
422 }
423
424 pub(super) fn escape_keyword(name: &str) -> String {
425 let keywords: &[&str] = &[
426 "align", "allowzero", "and", "anyframe", "anytype", "asm", "async",
427 "await", "break", "callconv", "catch", "comptime", "const", "continue",
428 "defer", "else", "enum", "errdefer", "error", "export", "extern",
429 "false", "fn", "for", "if", "inline", "linksection", "noalias",
430 "noinline", "noreturn", "nosuspend", "null", "opaque", "or", "orelse", "packed",
431 "pub", "resume", "return", "struct", "suspend", "switch", "test",
432 "threadlocal", "true", "try", "type", "undefined", "union", "unreachable",
433 "usingnamespace", "var", "volatile", "while",
434 ];
435 if keywords.contains(&name) {
436 format!("@\"{}\"", name)
437 } else {
438 name.to_string()
439 }
440 }
441
442 pub(super) fn emit_typed_init(&mut self, init: &Expression, target_type: &ZigType) {
445 match target_type {
446 ZigType::JsValue => {
447 let expr_type = self.inferrer.infer_expr(init);
448 match expr_type {
449 ZigType::I64 | ZigType::I32 | ZigType::Usize => {
450 self.push("JsValue.fromI64(");
451 self.emit_expr(init);
452 self.push(")");
453 }
454 ZigType::F64 | ZigType::F32 => {
455 self.push("JsValue.fromF64(");
456 self.emit_expr(init);
457 self.push(")");
458 }
459 ZigType::Bool => {
460 self.push("JsValue.fromBool(");
461 self.emit_expr(init);
462 self.push(")");
463 }
464 ZigType::String => {
465 self.push("JsValue.fromString(");
466 self.emit_expr(init);
467 self.push(")");
468 }
469 ZigType::Null => {
470 self.push("JsValue.fromNull()");
471 }
472 _ => {
473 self.emit_expr(init);
474 }
475 }
476 }
477 ZigType::JsAny => {
478 let expr_type = self.inferrer.infer_expr(init);
479 match expr_type {
480 ZigType::I64 | ZigType::I32 | ZigType::Usize => {
481 self.push("JsAny.fromI64(");
482 self.emit_expr(init);
483 self.push(")");
484 }
485 ZigType::F64 | ZigType::F32 => {
486 self.push("JsAny.fromF64(");
487 self.emit_expr(init);
488 self.push(")");
489 }
490 ZigType::Bool => {
491 self.push("JsAny.fromBool(");
492 self.emit_expr(init);
493 self.push(")");
494 }
495 ZigType::String => {
496 self.push("JsAny.fromString(");
497 self.emit_expr(init);
498 self.push(")");
499 }
500 ZigType::Null => {
501 self.push("JsAny.fromNull()");
502 }
503 _ => {
504 self.emit_expr(init);
505 }
506 }
507 }
508 _ => {
509 self.emit_expr(init);
510 }
511 }
512 }
513
514 pub(super) fn emit_dynamic_access_var_decl(&mut self, name: &str) {
517 self.emit_indent();
518 self.push("var ");
519 self.push(name);
520 self.push(": std.StringHashMap(JsAny) = undefined;\n");
521 }
522
523 pub(super) fn emit_dynamic_access_var_init_code(&mut self, name: &str, obj: &ObjectExpression) {
526 self.init_globals_code.push(format!(
528 " {} = std.StringHashMap(JsAny).init(allocator);\n",
529 name
530 ));
531
532 for prop in &obj.properties {
534 if let oxc_ast::ast::ObjectPropertyKind::ObjectProperty(p) = prop {
535 let field_name = match &p.key {
536 oxc_ast::ast::PropertyKey::StaticIdentifier(id) => id.name.to_string(),
537 oxc_ast::ast::PropertyKey::StringLiteral(s) => s.value.to_string(),
538 _ => continue,
539 };
540
541 let js_any_lit = self.emit_js_any_literal(&p.value);
543 self.init_globals_code.push(format!(
544 " {}.put(\"{}\", {}) catch @panic(\"OOM\");\n",
545 name, field_name, js_any_lit
546 ));
547 }
548 }
549 }
550
551 pub(super) fn emit_js_any_literal(&self, expr: &Expression) -> String {
554 match expr {
555 Expression::NumericLiteral(lit) => {
556 if lit.value.is_finite() && lit.value == lit.value.trunc() {
557 format!("JsAny.fromI64({})", lit.value as i64)
558 } else {
559 format!("JsAny.fromF64({})", lit.value)
560 }
561 }
562 Expression::StringLiteral(s) => {
563 format!("JsAny.fromString(\"{}\")", Self::escape_zig_string(&s.value))
564 }
565 Expression::BooleanLiteral(b) => {
566 format!("JsAny.fromBool({})", b.value)
567 }
568 Expression::NullLiteral(_) => {
569 "JsAny.fromNull()".to_string()
570 }
571 _ => {
572 let js_val = self.emit_js_value_literal(expr);
574 format!("JsAny.fromValue({})", js_val)
575 }
576 }
577 }
578
579 fn escape_zig_string(s: &str) -> String {
581 s.replace('\\', "\\\\")
582 .replace('"', "\\\"")
583 .replace('\n', "\\n")
584 .replace('\r', "\\r")
585 .replace('\t', "\\t")
586 }
587
588 pub(super) fn emit_js_value_literal(&self, expr: &Expression) -> String {
589 match expr {
590 Expression::NumericLiteral(lit) => {
591 let val_str = lit.value.to_string();
592 if lit.value.is_finite() && lit.value == lit.value.trunc() {
595 format!(".{{ .int = {} }}", val_str)
596 } else {
597 format!(".{{ .float = {} }}", val_str)
598 }
599 }
600 Expression::StringLiteral(lit) => {
601 format!(".{{ .string = \"{}\" }}", lit.value)
602 }
603 Expression::BooleanLiteral(lit) => {
604 format!(".{{ .bool = {} }}", if lit.value { "true" } else { "false" })
605 }
606 Expression::NullLiteral(_) => {
607 ".{ .null = {} }".to_string()
608 }
609 _ => {
610 ".{ .int = 0 }".to_string()
612 }
613 }
614 }
615
616 pub(super) fn emit_js_value_construction(&mut self, expr: &Expression) {
620 match expr {
621 Expression::NumericLiteral(lit) => {
622 let val_str = lit.value.to_string();
623 if lit.value.is_finite() && lit.value == lit.value.trunc() {
624 self.push(&format!("JsValue{{ .int = {} }}", val_str));
625 } else {
626 self.push(&format!("JsValue{{ .float = {} }}", val_str));
627 }
628 }
629 Expression::StringLiteral(lit) => {
630 self.push(&format!("JsValue{{ .string = \"{}\" }}", lit.value));
631 }
632 Expression::BooleanLiteral(lit) => {
633 let b = if lit.value { "true" } else { "false" };
634 self.push(&format!("JsValue{{ .bool = {} }}", b));
635 }
636 Expression::NullLiteral(_) => {
637 self.push("JsValue{ .null = {} }");
638 }
639 _ => {
640 self.push("JsValue{ .int = ");
642 self.emit_expr(expr);
643 self.push(" }");
644 }
645 }
646 }
647
648 pub(super) fn dynamic_field_accessor(&self, obj_expr: &Expression, prop: &str) -> String {
651 if let Expression::Identifier(id) = obj_expr {
652 let obj_type = self.inferrer.get_var_type(id.name.as_str());
653 if let ZigType::Object { fields } = obj_type
654 && let Some((_, field_type)) = fields.iter().find(|(n, _)| n == prop)
655 {
656 return match field_type {
657 ZigType::String => ".string".to_string(),
658 ZigType::F64 | ZigType::F32 => ".float".to_string(),
659 ZigType::Bool => ".bool".to_string(),
660 ZigType::Null => ".null".to_string(),
661 _ => ".asI64()".to_string(),
662 };
663 }
664 }
665 ".asI64()".to_string()
666 }
667
668 pub(super) fn emit_init_js2rust(&mut self) {
669 self.push("\n");
671 self.push("/// Initialize global allocator and all objects that use dynamic property access.\n");
672 self.push("pub fn init_js2rust(allocator: std.mem.Allocator) void {\n");
673 self.push(" js_allocator.setGlobalAllocator(allocator);\n");
674 let init_code: String = self.init_globals_code.iter().cloned().collect();
676 if !init_code.is_empty() {
677 self.push(&init_code);
678 }
679 self.push("}\n");
680 }
681
682 pub(super) fn emit_deinit_js2rust(&mut self) {
686 let mut hashmap_names: Vec<String> = Vec::new();
688 for line in &self.init_globals_code {
689 if line.contains(".init(")
690 && let Some(name) = line.trim().split(" =").next()
691 {
692 hashmap_names.push(name.to_string());
693 }
694 }
695 if hashmap_names.is_empty() {
697 return;
698 }
699 self.push("\n");
700 self.push("/// Deinitialize all global objects created by init_js2rust().\n");
701 self.push("pub fn deinit_js2rust() void {\n");
702 for name in &hashmap_names {
703 self.push(&format!(" {}.deinit();\n", name));
704 }
705 self.push("}\n");
706 }
707
708 pub(super) fn gen_obj_struct_def(struct_name: &str, fields: &[(String, ZigType)]) -> String {
709 let mut s = format!("const {} = struct {{\n", struct_name);
710 for (fname, ftype) in fields {
711 s.push_str(&format!(" {}: {},\n", fname, ftype.to_zig_str()));
712 }
713 s.push_str("};\n\n");
714 s
715 }
716
717 pub(super) fn capitalize_first(s: &str) -> String {
719 let mut chars = s.chars();
720 match chars.next() {
721 None => String::new(),
722 Some(c) => {
723 let upper = c.to_uppercase().collect::<String>();
724 upper + chars.as_str()
725 }
726 }
727 }
728
729 pub(super) fn is_string_literal_expr(expr: &Expression) -> bool {
730 matches!(expr, Expression::StringLiteral(_))
731 }
732
733 pub(super) fn emit_arg(&mut self, arg: &Argument) {
736 match arg {
737 Argument::SpreadElement(spread) => {
738 self.push("...");
739 self.emit_expr(&spread.argument);
740 }
741 _ => {
742 if let Some(expr) = arg.as_expression() {
743 self.emit_expr(expr);
744 }
745 }
746 }
747 }
748
749 pub(super) fn emit_jsany_arg(&mut self, arg: &Argument) {
751 match arg {
752 Argument::SpreadElement(_) => {
753 self.push("JsAny.fromNull()");
755 }
756 _ => {
757 if let Some(expr) = arg.as_expression() {
758 let lit = self.emit_js_any_literal(expr);
759 self.push(&lit);
760 }
761 }
762 }
763 }
764
765 pub(super) fn emit_array_element(&mut self, elem: &ArrayExpressionElement) {
766 match elem {
767 ArrayExpressionElement::SpreadElement(spread) => {
768 self.push("...");
769 self.emit_expr(&spread.argument);
770 }
771 ArrayExpressionElement::Elision(_) => {
772 self.push("undefined");
773 }
774 _ => {
775 if let Some(expr) = elem.as_expression() {
776 self.emit_expr(expr);
777 }
778 }
779 }
780 }
781
782 pub(super) fn emit_jsany_array_element(&mut self, elem: &ArrayExpressionElement) {
784 match elem {
785 ArrayExpressionElement::SpreadElement(_) => {
786 self.push("JsAny.fromNull()"); }
788 ArrayExpressionElement::Elision(_) => {
789 self.push("JsAny.fromNull()");
790 }
791 _ => {
792 if let Some(expr) = elem.as_expression() {
793 let lit = self.emit_js_any_literal(expr);
794 self.push(&lit);
795 }
796 }
797 }
798 }
799
800 pub(super) fn emit_assign_target(&mut self, target: &AssignmentTarget) {
801 match target {
802 AssignmentTarget::AssignmentTargetIdentifier(id) => {
803 self.push(&Self::escape_keyword(id.name.as_str()));
804 }
805 AssignmentTarget::ArrayAssignmentTarget(_) => {
806 self.push("_/* array destructure */");
807 }
808 AssignmentTarget::ObjectAssignmentTarget(_) => {
809 self.push("_/* object destructure */");
810 }
811 AssignmentTarget::StaticMemberExpression(mem) => {
812 self.emit_expr(&mem.object);
813 self.push(".");
814 self.push(mem.property.name.as_str());
815 }
816 AssignmentTarget::ComputedMemberExpression(mem) => {
817 let obj_type = self.inferrer.infer_expr(&mem.object);
818 if matches!(&obj_type, ZigType::Object { .. })
819 && let Expression::StringLiteral(s) = &mem.expression
820 {
821 self.emit_expr(&mem.object);
822 self.push(".");
823 self.push(s.value.as_str());
824 } else {
825 self.emit_expr(&mem.object);
826 self.push("[");
827 self.emit_expr(&mem.expression);
828 self.push("]");
829 }
830 }
831 AssignmentTarget::PrivateFieldExpression(_) => {
832 self.push("_/* private field */");
833 }
834 AssignmentTarget::TSAsExpression(ts) => {
835 self.emit_expr(&ts.expression);
836 }
837 AssignmentTarget::TSSatisfiesExpression(ts) => {
838 self.emit_expr(&ts.expression);
839 }
840 AssignmentTarget::TSNonNullExpression(ts) => {
841 self.emit_expr(&ts.expression);
842 self.push(".?");
843 }
844 AssignmentTarget::TSTypeAssertion(ts) => {
845 self.emit_expr(&ts.expression);
846 }
847 }
848 }
849
850 pub(super) fn emit_assign_target_from_simple(&mut self, target: &SimpleAssignmentTarget) {
851 match target {
852 SimpleAssignmentTarget::AssignmentTargetIdentifier(id) => {
853 self.push(&Self::escape_keyword(id.name.as_str()));
854 }
855 SimpleAssignmentTarget::StaticMemberExpression(mem) => {
856 self.emit_expr(&mem.object);
857 self.push(".");
858 self.push(mem.property.name.as_str());
859 }
860 SimpleAssignmentTarget::ComputedMemberExpression(mem) => {
861 let obj_type = self.inferrer.infer_expr(&mem.object);
862 if matches!(&obj_type, ZigType::Object { .. })
863 && let Expression::StringLiteral(s) = &mem.expression
864 {
865 self.emit_expr(&mem.object);
866 self.push(".");
867 self.push(s.value.as_str());
868 } else {
869 self.emit_expr(&mem.object);
870 self.push("[");
871 self.emit_expr(&mem.expression);
872 self.push("]");
873 }
874 }
875 SimpleAssignmentTarget::PrivateFieldExpression(_) => {
876 self.push("_/* private */");
877 }
878 _ => {
879 self.push("_/* ts assign target */");
880 }
881 }
882 }
883
884 pub(super) fn map_binary_op(&self, op: &BinaryOperator) -> &'static str {
887 match op {
888 BinaryOperator::StrictEquality => "==",
889 BinaryOperator::StrictInequality => "!=",
890 BinaryOperator::Equality => "==",
891 BinaryOperator::Inequality => "!=",
892 BinaryOperator::Addition => "+",
893 BinaryOperator::Subtraction => "-",
894 BinaryOperator::Multiplication => "*",
895 BinaryOperator::Division => "/",
896 BinaryOperator::Remainder => "%",
897 BinaryOperator::Exponential => "**",
898 BinaryOperator::LessThan => "<",
899 BinaryOperator::LessEqualThan => "<=",
900 BinaryOperator::GreaterThan => ">",
901 BinaryOperator::GreaterEqualThan => ">=",
902 BinaryOperator::ShiftLeft => "<<",
903 BinaryOperator::ShiftRight => ">>",
904 BinaryOperator::ShiftRightZeroFill => ">>",
905 BinaryOperator::BitwiseOR => "|",
906 BinaryOperator::BitwiseXOR => "^",
907 BinaryOperator::BitwiseAnd => "&",
908 BinaryOperator::In => "== /* in */",
909 BinaryOperator::Instanceof => "== /* instanceof */",
910 }
911 }
912
913 pub(super) fn map_logical_op(&self, op: &LogicalOperator) -> &'static str {
914 match op {
915 LogicalOperator::And => "and",
916 LogicalOperator::Or => "or",
917 LogicalOperator::Coalesce => "orelse",
918 }
919 }
920
921 pub(super) fn map_unary_op(&self, op: &UnaryOperator) -> &'static str {
922 match op {
923 UnaryOperator::UnaryPlus => "", UnaryOperator::UnaryNegation => "-",
925 UnaryOperator::LogicalNot => "!",
926 UnaryOperator::BitwiseNot => "~",
927 UnaryOperator::Typeof => "@TypeOf",
928 UnaryOperator::Void => "",
929 UnaryOperator::Delete => "",
930 }
931 }
932
933 pub(super) fn map_assign_op(&self, op: &AssignmentOperator) -> &'static str {
934 match op {
935 AssignmentOperator::Assign => "=",
936 AssignmentOperator::Addition => "+=",
937 AssignmentOperator::Subtraction => "-=",
938 AssignmentOperator::Multiplication => "*=",
939 AssignmentOperator::Division => "/=",
940 AssignmentOperator::Remainder => "%=",
941 AssignmentOperator::Exponential => "**=",
942 AssignmentOperator::ShiftLeft => "<<=",
943 AssignmentOperator::ShiftRight => ">>=",
944 AssignmentOperator::ShiftRightZeroFill => ">>>=",
945 AssignmentOperator::BitwiseOR => "|=",
946 AssignmentOperator::BitwiseXOR => "^=",
947 AssignmentOperator::BitwiseAnd => "&=",
948 AssignmentOperator::LogicalOr => "|=",
949 AssignmentOperator::LogicalAnd => "&=",
950 AssignmentOperator::LogicalNullish => "=?=",
951 }
952 }
953}