Skip to main content

js2zig_core/zigir/emit/expr/
container.rs

1// zigir/emit/expr/container.rs
2// Array and object literal emission.
3
4use crate::zigir::emit::Emitter;
5use crate::zigir::emit::helpers::EmitterHelpers;
6
7impl Emitter {
8    pub(super) fn emit_array_literal(&mut self, arr: &crate::zigir::types::IrArrayLiteral) {
9        if arr.elements.is_empty() {
10            self.write("std.ArrayList(JsAny).empty");
11            return;
12        }
13
14        // Determine element type: if any spread is present, force JsAny (mixed types guaranteed).
15        // Otherwise, scan ALL elements — if any differ from the first, use JsAny.
16        let elem_type = if !arr.spread_indices.is_empty() {
17            "JsAny"
18        } else {
19            let first_type = arr
20                .elements
21                .first()
22                .map(|e| match e {
23                    crate::zigir::types::IrExpr::IntLiteral(_) => "i64",
24                    crate::zigir::types::IrExpr::FloatLiteral(_) => "f64",
25                    crate::zigir::types::IrExpr::StringLiteral(_) => "[]const u8",
26                    crate::zigir::types::IrExpr::BoolLiteral(_) => "bool",
27                    // Non-literal elements (Ident, Call, FieldAccess, etc.)
28                    // have no statically-known type at the emit layer. Fall
29                    // back to JsAny rather than i64: this guarantees the
30                    // generated ArrayList is type-compatible with whatever
31                    // the expression evaluates to (JsAny.from polymorphism
32                    // handles all element types). Forcing i64 here would
33                    // produce Zig compile errors like "expected i64, found
34                    // f64" for cases like `const arr = [someF64Var]`.
35                    _ => "JsAny",
36                })
37                .unwrap_or("JsAny");
38
39            let all_same = arr.elements.iter().all(|e| match e {
40                crate::zigir::types::IrExpr::IntLiteral(_) => first_type == "i64",
41                crate::zigir::types::IrExpr::FloatLiteral(_) => first_type == "f64",
42                crate::zigir::types::IrExpr::StringLiteral(_) => first_type == "[]const u8",
43                crate::zigir::types::IrExpr::BoolLiteral(_) => first_type == "bool",
44                // Non-literal matches only when first_type has already
45                // degraded to JsAny — preserving the conservative fallback.
46                _ => first_type == "JsAny",
47            });
48
49            if all_same { first_type } else { "JsAny" }
50        };
51        let needs_jsany_wrap = elem_type == "JsAny";
52
53        // Emit as labeled block with ArrayList builder:
54        // (blk: { var __arr: std.ArrayList(Type) = .empty; append...; break :blk __arr; })
55        let blk = self.next_label();
56        self.write(&format!(
57            "({}: {{ var __arr: std.ArrayList({}) = .empty; ",
58            blk, elem_type
59        ));
60        for (i, elem) in arr.elements.iter().enumerate() {
61            if arr.spread_indices.contains(&i) {
62                // Spread: iterate the source's `.items` slice and append each
63                // element wrapped via `JsAny.from(...)`. This handles ANY
64                // ArrayList element type uniformly (i64, f64, []const u8, JsAny,
65                // bool, comptime_int, etc.).
66                //
67                // Why not appendSlice: the receiver __arr is always
68                // `std.ArrayList(JsAny)` when a spread is present (see the
69                // `elem_type` decision above), so `appendSlice` would require
70                // the source's `.items` to be `[]const JsAny`. That fails to
71                // compile for the common `ArrayList(i64)` / `ArrayList(bool)` /
72                // `ArrayList([]const u8)` cases. The for-loop + JsAny.from
73                // approach is type-polymorphic via anytype.
74                //
75                // The loop variable name (`__spread_item`) is scoped to each
76                // for-loop body, so reusing it across multiple spreads in the
77                // same literal is safe.
78                if let crate::zigir::types::IrExpr::Spread(inner) = elem {
79                    self.write("for (");
80                    self.emit_expr(inner);
81                    self.write(
82                        ".items) |__spread_item| __arr.append(js_allocator.allocator(), \
83                         JsAny.from(__spread_item)) catch @panic(\"OOM: Array.spread\"); ",
84                    );
85                }
86            } else {
87                self.write("__arr.append(js_allocator.allocator(), ");
88                if needs_jsany_wrap {
89                    self.write("JsAny.from(");
90                }
91                self.emit_expr(elem);
92                if needs_jsany_wrap {
93                    self.write(")");
94                }
95                self.write(") catch @panic(\"OOM: Array.push append\"); ");
96            }
97        }
98        self.write(&format!("break :{} __arr; }})", blk));
99    }
100
101    /// Emit object field pairs (`.key = value` or `@"key" = value`), preceded by
102    /// separator handling. Shared between the inline-property path and the
103    /// spreadMerge inline-text path.
104    fn emit_object_fields<'a, I>(&mut self, fields: I)
105    where
106        I: Iterator<Item = &'a crate::zigir::types::IrObjectField>,
107    {
108        let mut first = true;
109        for field in fields {
110            if !first {
111                self.write(", ");
112            }
113            first = false;
114            if field.is_computed {
115                self.write(&format!("@\"{}\" = ", field.key));
116            } else {
117                self.write(&format!(".{} = ", field.key));
118            }
119            self.emit_expr(&field.value);
120        }
121    }
122
123    pub(super) fn emit_object_literal(&mut self, obj: &crate::zigir::types::IrObjectLiteral) {
124        use crate::zigir::types::IrObjectItem;
125
126        // Empty object → JsObjectMap.init(allocator)
127        // JsObjectMap is StringArrayHashMap(JsAny) — insertion-order-preserving.
128        if obj.items.is_empty() {
129            self.write("JsObjectMap.init(js_allocator.allocator())");
130            return;
131        }
132
133        // Check if any spread items exist
134        let has_spread = obj
135            .items
136            .iter()
137            .any(|item| matches!(item, IrObjectItem::Spread(_)));
138
139        // Extract inline fields once — reused in both branches below
140        let inline_fields: Vec<_> = obj
141            .items
142            .iter()
143            .filter_map(|item| match item {
144                IrObjectItem::Field(f) => Some(f),
145                _ => None,
146            })
147            .collect();
148
149        if !has_spread {
150            // Pure inline properties — emit directly as .{ ... }
151            self.write(".{ ");
152            self.emit_object_fields(inline_fields.iter().copied());
153            self.write(" }");
154            return;
155        }
156
157        // Has spread: build a left-fold spreadMerge(...) chain.
158        // Strategy:
159        //   { ...a }                       → a
160        //   { ...a, ...b }                 → js_runtime.spreadMerge(a, b)
161        //   { ...a, b: 1 }                 → js_runtime.spreadMerge(a, .{ .b = 1 })
162        //   { ...a, ...b, c: 1 }           → js_runtime.spreadMerge(spreadMerge(a, b), .{ .c = 1 })
163
164        // Collect spread expression texts.
165        // Use emit_expr_inline_with_label_offset to avoid label conflicts
166        // when spread expressions contain labeled blocks (e.g., callback inlining).
167        let mut parts: Vec<String> = obj
168            .items
169            .iter()
170            .filter_map(|item| match item {
171                IrObjectItem::Spread(expr) => {
172                    let (text, new_counter) =
173                        Self::emit_expr_inline_with_label_offset(expr, self.label_counter);
174                    self.label_counter = new_counter;
175                    Some(text)
176                }
177                _ => None,
178            })
179            .collect();
180
181        // Append inline fields as a single .{ .key = val } text, if any
182        if !inline_fields.is_empty() {
183            let saved_output = std::mem::take(&mut self.output);
184            self.write(".{ ");
185            self.emit_object_fields(inline_fields.iter().copied());
186            self.write(" }");
187            let text = std::mem::take(&mut self.output);
188            self.output = saved_output;
189            parts.push(text);
190        }
191
192        match parts.len() {
193            0 => unreachable!("emit_array_with_spread: parts is empty but has_spread=true"),
194            1 => {
195                self.write(&parts[0]);
196            }
197            _ => {
198                let result = parts[1..].iter().fold(parts[0].clone(), |acc, next| {
199                    format!("js_runtime.spreadMerge({}, {})", acc, next)
200                });
201                self.write(&result);
202            }
203        }
204    }
205}