Skip to main content

js2zig_core/zigir/emit/expr/
call_member.rs

1// zigir/emit/expr/call_member.rs
2// Call expression, field access, index access, and computed field emission.
3
4use crate::zigir::emit::Emitter;
5use crate::zigir::emit::helpers::EmitterHelpers;
6use crate::zigir::kinds::{CallKind, ComputedKeyKind, FieldKind, IndexKind};
7
8impl Emitter {
9    pub(super) fn emit_call_expr(&mut self, call: &crate::zigir::types::IrCallExpr) {
10        match &call.call_kind {
11            CallKind::Direct | CallKind::Method { .. } => {
12                self.emit_expr(&call.callee);
13                self.emit_args(&call.args);
14            }
15            CallKind::Closure => {
16                // Struct literal + method call needs parentheses in Zig:
17                // (StructName{ .field = val }).call(args)
18                if matches!(*call.callee, crate::zigir::types::IrExpr::Closure(_)) {
19                    self.write("(");
20                    self.emit_expr(&call.callee);
21                    self.write(")");
22                } else {
23                    self.emit_expr(&call.callee);
24                }
25                self.write(".call(");
26                self.emit_inline_args(&call.args);
27                self.write(")");
28            }
29        }
30    }
31
32    pub(super) fn emit_field_access(
33        &mut self,
34        object: &crate::zigir::types::IrExpr,
35        field: &str,
36        kind: &FieldKind,
37    ) {
38        match kind {
39            // Direct field access: obj.field (same for StructField, Namespace, Private)
40            FieldKind::StructField | FieldKind::Namespace | FieldKind::Private => {
41                self.emit_dot_access(object, field);
42            }
43            FieldKind::ArrayListLen => {
44                self.emit_expr(object);
45                self.write(".items.len");
46            }
47            FieldKind::StringLen => {
48                // JS string.length returns UTF-16 code unit count, not byte count
49                self.write("js_string.utf16Len(");
50                self.emit_expr(object);
51                self.write(")");
52            }
53            FieldKind::SliceLen => {
54                // Slice/TypedArray length: element count.
55                self.emit_expr(object);
56                self.write(".len");
57            }
58            FieldKind::ArgumentsLen => {
59                // arguments.length: JS .length is i64, but []const JsAny .len is usize.
60                // Cast to i64 for correct JS semantics.
61                self.write("@as(i64, @intCast(");
62                self.emit_expr(object);
63                self.write(".len))");
64            }
65            FieldKind::MapSetSize => {
66                self.emit_expr(object);
67                self.write(".size()");
68            }
69            FieldKind::MathConstant(val) => {
70                // Zig 0.16.0: std.math constants are comptime_float with higher
71                // precision than f64. Wrap in @as(f64, ...) so string formatting
72                // and template literals produce JS-compatible output (e.g. PI =>
73                // "3.141592653589793", not the full-precision comptime value).
74                match val.as_str() {
75                    "PI" => self.write("@as(f64, std.math.pi)"),
76                    "E" => self.write("@as(f64, std.math.e)"),
77                    "LN2" => self.write("@as(f64, std.math.ln2)"),
78                    "LN10" => self.write("@as(f64, std.math.ln10)"),
79                    "LOG2E" => self.write("@as(f64, std.math.log2e)"),
80                    "LOG10E" => self.write("@as(f64, std.math.log10e)"),
81                    "SQRT1_2" => self.write("@as(f64, std.math.sqrt1_2)"),
82                    "SQRT2" => self.write("@as(f64, std.math.sqrt2)"),
83                    _ => self.write(&format!("@as(f64, std.math.{})", val.to_lowercase())),
84                }
85            }
86            FieldKind::NumberConstant(val) => {
87                // Map JS Number constants to Zig std.math equivalents
88                match val.as_str() {
89                    "MAX_VALUE" => self.write("std.math.floatMax(f64)"),
90                    "MIN_VALUE" => self.write("std.math.floatMin(f64)"),
91                    "NaN" => self.write("std.math.nan(f64)"),
92                    "NEGATIVE_INFINITY" => self.write("-std.math.inf(f64)"),
93                    "POSITIVE_INFINITY" => self.write("std.math.inf(f64)"),
94                    "EPSILON" => self.write("std.math.floatEps(f64)"),
95                    "MAX_SAFE_INTEGER" => self.write("9007199254740991"),
96                    "MIN_SAFE_INTEGER" => self.write("-9007199254740991"),
97                    _ => self.write(&format!("std.math.{}", val)),
98                }
99            }
100            FieldKind::SymbolWellKnown(val) => {
101                // Symbol well-known properties: Symbol.iterator → js_symbol.symbolIterator()
102                // All well-known symbol accessors are prefixed with "symbol" in the runtime
103                let zig_name = match val.as_str() {
104                    "iterator" => "symbolIterator".to_string(),
105                    "asyncIterator" => "symbolAsyncIterator".to_string(),
106                    "hasInstance" => "symbolHasInstance".to_string(),
107                    "isConcatSpreadable" => "symbolIsConcatSpreadable".to_string(),
108                    "species" => "symbolSpecies".to_string(),
109                    "toPrimitive" => "symbolToPrimitive".to_string(),
110                    "toStringTag" => "symbolToStringTag".to_string(),
111                    "unscopables" => "symbolUnscopables".to_string(),
112                    "match" => "symbolMatch".to_string(),
113                    "matchAll" => "symbolMatchAll".to_string(),
114                    "replace" => "symbolReplace".to_string(),
115                    "search" => "symbolSearch".to_string(),
116                    "split" => "symbolSplit".to_string(),
117                    "dispose" => "symbolDispose".to_string(),
118                    other => {
119                        // Fallback: capitalize first letter and prepend "symbol"
120                        let mut chars = other.chars();
121                        match chars.next() {
122                            None => "symbol".to_string(),
123                            Some(c) => format!("symbol{}{}", c.to_uppercase(), chars.as_str()),
124                        }
125                    }
126                };
127                self.write(&format!("js_symbol.{}()", zig_name));
128            }
129            FieldKind::TypedArrayProp { prop, type_suffix } => {
130                if let Some(suffix) = type_suffix {
131                    self.write(&format!("js_runtime.js_typedarray.{}{}(", prop, suffix));
132                    self.emit_expr(object);
133                    self.write(")");
134                } else {
135                    self.emit_dot_access(object, prop);
136                }
137            }
138            FieldKind::PointerDeref => {
139                self.emit_expr(object);
140                self.write(".*");
141            }
142            FieldKind::RegExpProp { prop } => {
143                // regex.source → regex.pattern; others map directly (regex.flags → .flags, etc.)
144                if prop == "source" {
145                    self.emit_dot_access(object, "pattern");
146                } else {
147                    self.emit_dot_access(object, prop);
148                }
149            }
150            FieldKind::StaticField { class_name } => {
151                // ClassName.field → __ClassName_field module-scope var
152                self.emit_static_field(class_name, field);
153            }
154        }
155    }
156
157    pub(super) fn emit_index_access(
158        &mut self,
159        object: &crate::zigir::types::IrExpr,
160        index: &crate::zigir::types::IrExpr,
161        kind: &IndexKind,
162    ) {
163        match kind {
164            IndexKind::ArrayListItem => {
165                self.emit_arraylist_item(object, index);
166            }
167            IndexKind::SliceIndex => {
168                self.emit_slice_index(object, index);
169            }
170        }
171    }
172
173    pub(super) fn emit_computed_field(
174        &mut self,
175        object: &crate::zigir::types::IrExpr,
176        key: &crate::zigir::types::IrExpr,
177        kind: &ComputedKeyKind,
178    ) {
179        use crate::zigir::emit::helpers;
180        match kind {
181            ComputedKeyKind::StructField => {
182                self.write("@field(");
183                self.emit_expr(object);
184                self.write(", ");
185                self.emit_expr(key);
186                self.write(")");
187            }
188            ComputedKeyKind::MapGet => {
189                self.emit_expr(object);
190                self.write(".get(");
191                self.emit_expr(key);
192                self.write(")");
193            }
194            ComputedKeyKind::JsAnyGetByKey => {
195                self.emit_expr(object);
196                self.write(".getByKey(");
197                self.emit_expr(key);
198                self.write(", js_allocator.allocator())");
199            }
200            ComputedKeyKind::ArrayListItem => {
201                self.emit_arraylist_item(object, key);
202            }
203            ComputedKeyKind::StringCharAt => {
204                // str[idx] in JS returns a single-character substring (charAt
205                // semantics). Use js_string.charAt which returns `[]const u8`.
206                // Match the fallible string-method pattern used elsewhere:
207                // `catch @panic("OOM: string method")` (avoids forcing an
208                // error-union return type on the enclosing function).
209                self.write("js_string.charAt(js_allocator.allocator(), ");
210                self.emit_expr(object);
211                self.write(", ");
212                self.emit_expr(key);
213                self.write(") catch @panic(\"OOM: string method\")");
214            }
215            ComputedKeyKind::CompileError(msg) => {
216                self.write(&helpers::compile_error(msg));
217            }
218        }
219    }
220
221    // ── Shared index/field helpers ────────────────────────
222    // Used by emit_index_access, emit_computed_field, and emit_assign_target_inner.
223
224    /// Emit `object.field` — dot-access on an expression.
225    pub(super) fn emit_dot_access(&mut self, object: &crate::zigir::types::IrExpr, field: &str) {
226        self.emit_expr(object);
227        self.write(&format!(".{}", field));
228    }
229
230    /// Emit `object.items[@as(usize, @intCast(index))]` — ArrayList element access.
231    pub(super) fn emit_arraylist_item(
232        &mut self,
233        object: &crate::zigir::types::IrExpr,
234        index: &crate::zigir::types::IrExpr,
235    ) {
236        self.emit_expr(object);
237        self.write(".items[@as(usize, @intCast(");
238        self.emit_expr(index);
239        self.write("))]");
240    }
241
242    /// Emit `object[@as(usize, @intCast(index))]` — Slice/array index access.
243    /// The @intCast is needed because JS indices are i64 but Zig indexing requires usize.
244    pub(super) fn emit_slice_index(
245        &mut self,
246        object: &crate::zigir::types::IrExpr,
247        index: &crate::zigir::types::IrExpr,
248    ) {
249        self.emit_expr(object);
250        self.write("[@as(usize, @intCast(");
251        self.emit_expr(index);
252        self.write("))]");
253    }
254
255    /// Emit `__ClassName_field` — static field access on a class.
256    pub(super) fn emit_static_field(&mut self, class_name: &str, field: &str) {
257        self.write(&format!("__{}_{}", class_name, field));
258    }
259}