Skip to main content

js2zig_core/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// ── Zig reserved keyword detection ──────────────────
8
9/// Zig 0.16 reserved keywords. JS identifiers that collide with these
10/// must be renamed (prefixed with `_`) to produce valid Zig code.
11const 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
63/// Convert a JS identifier to a Zig-safe identifier.
64/// Pre-pends `_` to avoid collisions with Zig reserved keywords.
65pub(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
73// ── Helpers (methods) ──────────────────────────────
74
75impl Codegen {
76    /// Convenience method: convert a JS identifier to a Zig-safe identifier.
77    /// Also checks `shadow_renames` to rewrite shadowed variables to their
78    /// renamed counterpart (e.g. `x` → `x_1` if shadowed in a nested block).
79    pub(crate) fn zig_safe_name(&self, name: &str) -> String {
80        // Check shadow renames from innermost scope outward.
81        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    /// Push a new shadowing scope onto the rename stack.
90    /// Called when entering a nested block — any variable shadowing detected
91    /// within this scope will be recorded in the pushed HashMap.
92    pub(crate) fn push_shadow_scope(&mut self) {
93        self.shadow_renames.push(std::collections::HashMap::new());
94    }
95
96    /// Pop the innermost shadowing scope from the rename stack.
97    /// Called when leaving a nested block — shadowed variable renames are
98    /// discarded since they only apply within that block's scope.
99    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    /// Extract a property key name from a PropertyKey for destructuring.
111    /// Returns None for computed keys (not yet supported).
112    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    /// Resolve a destructuring binding pattern, returning (name, optional_default_expr).
121    /// Handles both plain bindings and `BindingPattern::AssignmentPattern` (with default).
122    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            // Zig uses `orelse` for null-coalescing, not `??`
188            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
203// ── Output helpers ──────────────────────────────────
204
205impl 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    /// Generate a unique block label (blk_0, blk_1, ...) to avoid
227    /// "redefinition of label" errors when multiple block expressions
228    /// appear in the same scope.
229    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    /// Start a block expression with a unique label.
236    /// Writes `(label: {` and returns the label string.
237    /// The caller must use `emit_break()` with the same label.
238    pub fn emit_blk_start(&mut self) -> String {
239        let label = self.next_label();
240        self.write(&format!("({}: {{", label));
241        label
242    }
243
244    /// Emit `break :label expr` inside a block expression.
245    pub fn emit_blk_break(&mut self, label: &str, expr: &str) {
246        self.write(&format!("break :{} {}", label, expr));
247    }
248
249    /// End a block expression: writes `})`.
250    pub fn emit_blk_end(&mut self) {
251        self.write("}");
252    }
253}
254
255// ── Argument extraction helpers ───────────────────
256
257impl Codegen {
258    /// Extract the first call argument as a string (via emit_expr_to_string).
259    /// Returns empty string if no argument or argument is not an expression.
260    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    /// Extract the first call argument as a string, with a custom fallback.
271    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    /// Emit the first call argument directly. Silently does nothing if none.
282    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            // Arguments are in expression position, never statement position.
287            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    /// Emit all call arguments separated by ", ".
295    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    /// Emit array expression elements separated by ", ".
305    /// Skips elements that are not expressions (spread, elision).
306    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
321// ── Template / format string helpers ───────────────
322
323impl Codegen {
324    /// If the callee is `obj.method()`, return `Some("obj")`.
325    /// Returns `None` if it's not a static member expression on an identifier.
326    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    /// Like `callee_object_name` but also handles string literals:
337    /// `"hello".trimStart()` → `Some("\"hello\"")`.
338    /// For identifiers, returns the name. For string literals, returns the escaped literal.
339    /// Returns `None` for other object types.
340    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    /// Mutable version of `callee_object_repr` that can handle complex expressions.
361    ///
362    /// Falls back to `emit_expr_to_string()` for non-Identifier/non-StringLiteral objects,
363    /// enabling method chaining like `encodeURI(str).replace(...)` or
364    /// `new Date().getTime()`.
365    pub(crate) fn callee_object_repr_mut(&mut self, callee: &Expression) -> Option<String> {
366        // Fast path: try the immutable version first (Identifier, StringLiteral)
367        if let Some(repr) = self.callee_object_repr(callee) {
368            return Some(repr);
369        }
370        // Fallback: emit the object expression to a string for complex expressions
371        if let Expression::StaticMemberExpression(mem) = callee {
372            return Some(self.emit_expr_to_string(&mem.object));
373        }
374        None
375    }
376
377    /// Try to emit a numeric literal receiver for Number instance methods
378    /// (toFixed, toExponential, toPrecision).
379    /// Handles `(77.1234).method()` where the AST object is
380    /// `ParenthesizedExpression(NumericLiteral)`.
381    /// `args_required`: if true, the method requires at least 1 argument.
382    /// Returns true if successfully emitted.
383    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    /// Emit a format string expression: either a plain string literal (no args)
426    /// or an allocPrint call (when interpolating args).
427    ///
428    /// `fmt` is a Zig format string (with `{{` / `}}` escaped).
429    /// `args` are the already-emitted argument strings.
430    pub(crate) fn emit_format_string(&mut self, fmt: &str, args: &[String]) {
431        if args.is_empty() {
432            // Pure-text → plain string literal (no allocation).
433            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// ── emit_toplevel helpers ──────────────────────────