Skip to main content

js2zig_core/native_proto/codegen/
helpers.rs

1// native_proto/codegen/helpers.rs
2// Type inference helpers, operator mappings, and output helpers.
3
4use super::Codegen;
5use oxc_ast::ast::*;
6
7// ── Helpers (methods) ──────────────────────────────
8
9impl Codegen {
10    pub(crate) fn binding_name<'a>(&self, pattern: &BindingPattern<'a>) -> Option<&'a str> {
11        match pattern {
12            BindingPattern::BindingIdentifier(id) => Some(id.name.as_str()),
13            _ => None,
14        }
15    }
16
17    pub(crate) fn binary_op(op: BinaryOperator) -> &'static str {
18        match op {
19            BinaryOperator::Addition => "+",
20            BinaryOperator::Subtraction => "-",
21            BinaryOperator::Multiplication => "*",
22            BinaryOperator::Division => "/",
23            BinaryOperator::Remainder => "%",
24            BinaryOperator::LessThan => "<",
25            BinaryOperator::GreaterThan => ">",
26            BinaryOperator::LessEqualThan => "<=",
27            BinaryOperator::GreaterEqualThan => ">=",
28            BinaryOperator::Equality => "==",
29            BinaryOperator::Inequality => "!=",
30            BinaryOperator::StrictEquality => "==",
31            BinaryOperator::StrictInequality => "!=",
32            BinaryOperator::ShiftLeft => "<<",
33            BinaryOperator::ShiftRight => ">>",
34            BinaryOperator::BitwiseAnd => "&",
35            BinaryOperator::BitwiseOR => "|",
36            BinaryOperator::BitwiseXOR => "^",
37            _ => "/* op */",
38        }
39    }
40
41    pub(crate) fn assignment_op(op: AssignmentOperator) -> &'static str {
42        match op {
43            AssignmentOperator::Assign => "=",
44            AssignmentOperator::Addition => "+=",
45            AssignmentOperator::Subtraction => "-=",
46            AssignmentOperator::Multiplication => "*=",
47            AssignmentOperator::Division => "/=",
48            AssignmentOperator::Remainder => "%=",
49            AssignmentOperator::ShiftLeft => "<<=",
50            AssignmentOperator::ShiftRight => ">>=",
51            AssignmentOperator::BitwiseAnd => "&=",
52            AssignmentOperator::BitwiseOR => "|=",
53            AssignmentOperator::BitwiseXOR => "^=",
54            _ => "=",
55        }
56    }
57
58    pub(crate) fn logical_op(op: LogicalOperator) -> &'static str {
59        match op {
60            LogicalOperator::And => "and",
61            LogicalOperator::Or => "or",
62            LogicalOperator::Coalesce => "??",
63        }
64    }
65
66    pub(crate) fn unary_prefix(op: UnaryOperator) -> &'static str {
67        match op {
68            UnaryOperator::UnaryNegation => "-",
69            UnaryOperator::UnaryPlus => "+",
70            UnaryOperator::LogicalNot => "!",
71            _ => "",
72        }
73    }
74}
75
76// ── Output helpers ──────────────────────────────────
77
78impl Codegen {
79    pub fn write(&mut self, s: &str) {
80        self.output.push_str(s);
81    }
82
83    pub fn push(&mut self, ch: char) {
84        self.output.push(ch);
85    }
86
87    pub fn writeln(&mut self, s: &str) {
88        self.write_indent();
89        self.output.push_str(s);
90        self.output.push('\n');
91    }
92
93    pub fn write_indent(&mut self) {
94        for _ in 0..self.indent {
95            self.output.push_str("    ");
96        }
97    }
98}
99
100// ── Argument extraction helpers ───────────────────
101
102impl Codegen {
103    /// Extract the first call argument as a string (via emit_expr_to_string).
104    /// Returns empty string if no argument or argument is not an expression.
105    pub(crate) fn first_arg_string(&mut self, args: &[Argument]) -> String {
106        if let Some(arg) = args.first()
107            && let Some(expr) = arg.as_expression()
108        {
109            self.emit_expr_to_string(expr)
110        } else {
111            String::new()
112        }
113    }
114
115    /// Extract the first call argument as a string, with a custom fallback.
116    pub(crate) fn first_arg_string_or(&mut self, args: &[Argument], default: &str) -> String {
117        if let Some(arg) = args.first()
118            && let Some(expr) = arg.as_expression()
119        {
120            self.emit_expr_to_string(expr)
121        } else {
122            default.to_string()
123        }
124    }
125
126    /// Emit the first call argument directly. Silently does nothing if none.
127    pub(crate) fn emit_first_arg(&mut self, args: &[Argument]) {
128        if let Some(arg) = args.first()
129            && let Some(expr) = arg.as_expression()
130        {
131            self.emit_expr(expr);
132        }
133    }
134
135    /// Emit all call arguments separated by ", ".
136    pub(crate) fn emit_comma_separated_args(&mut self, args: &[Argument]) {
137        for (i, arg) in args.iter().enumerate() {
138            if i > 0 {
139                self.write(", ");
140            }
141            self.emit_expr_arg(arg);
142        }
143    }
144
145    /// Emit array expression elements separated by ", ".
146    /// Skips elements that are not expressions (spread, elision).
147    pub(crate) fn emit_comma_separated_array_elements(
148        &mut self,
149        elements: &[ArrayExpressionElement],
150    ) {
151        for (i, elem) in elements.iter().enumerate() {
152            if i > 0 {
153                self.write(", ");
154            }
155            if let Some(e) = elem.as_expression() {
156                self.emit_expr(e);
157            }
158        }
159    }
160}
161
162// ── Template / format string helpers ───────────────
163
164impl Codegen {
165    /// If the callee is `obj.method()`, return `Some("obj")`.
166    /// Returns `None` if it's not a static member expression on an identifier.
167    pub(crate) fn callee_object_name<'a>(&self, callee: &'a Expression) -> Option<&'a str> {
168        if let Expression::StaticMemberExpression(mem) = callee
169            && let Expression::Identifier(obj) = &mem.object
170        {
171            Some(obj.name.as_str())
172        } else {
173            None
174        }
175    }
176
177    /// Emit a format string expression: either a plain string literal (no args)
178    /// or an allocPrint call (when interpolating args).
179    ///
180    /// `fmt` is a Zig format string (with `{{` / `}}` escaped).
181    /// `args` are the already-emitted argument strings.
182    pub(crate) fn emit_format_string(&mut self, fmt: &str, args: &[String]) {
183        if args.is_empty() {
184            // Pure-text → plain string literal (no allocation).
185            self.write(&format!(
186                "\"{}\"",
187                fmt.replace("{{", "{").replace("}}", "}")
188            ));
189        } else {
190            let args_str = format!(".{{{}}}", args.join(", "));
191            self.write(&format!(
192                "std.fmt.allocPrint(js_allocator.getAllocator(), \"{}\", {}) catch @panic(\"OOM: template literal allocPrint\")",
193                fmt, args_str
194            ));
195        }
196    }
197}
198
199// ── emit_toplevel helpers ──────────────────────────