js2zig_core/zigir/lower/expr/container.rs
1// zigir/lower/expr/container.rs
2// Array, object, template literal lowering.
3
4use oxc_ast::ast::*;
5
6use super::Lowerer;
7use crate::zigir::lower::helpers;
8use crate::zigir::source_span::SourceSpan;
9
10impl Lowerer {
11 /// Lower an array expression.
12 pub(super) fn lower_array_expr(&mut self, ae: &ArrayExpression) -> crate::zigir::types::IrExpr {
13 let mut elements = Vec::new();
14 let mut spread_indices = Vec::new();
15
16 for (i, elem) in ae.elements.iter().enumerate() {
17 match elem {
18 ArrayExpressionElement::SpreadElement(se) => {
19 spread_indices.push(i);
20 elements.push(crate::zigir::types::IrExpr::Spread(Box::new(
21 self.lower_expr(&se.argument),
22 )));
23 }
24 ArrayExpressionElement::Elision(_) => {
25 elements.push(crate::zigir::types::IrExpr::Null);
26 }
27 _ => {
28 if let Some(expr) = elem.as_expression() {
29 elements.push(self.lower_expr(expr));
30 }
31 }
32 }
33 }
34
35 crate::zigir::types::IrExpr::ArrayLiteral(crate::zigir::types::IrArrayLiteral {
36 elements,
37 spread_indices,
38 })
39 }
40
41 /// Lower an object expression.
42 pub(super) fn lower_object_expr(
43 &mut self,
44 oe: &ObjectExpression,
45 ) -> crate::zigir::types::IrExpr {
46 use crate::zigir::types::IrObjectItem;
47
48 let mut items = Vec::new();
49
50 for prop in oe.properties.iter() {
51 match prop {
52 ObjectPropertyKind::ObjectProperty(op) => {
53 let (key, is_computed) = match &op.key {
54 PropertyKey::StaticIdentifier(id) => (id.name.to_string(), false),
55 PropertyKey::StringLiteral(sl) => (sl.value.to_string(), false),
56 PropertyKey::NumericLiteral(nl) => (nl.value.to_string(), false),
57 _ => ("__computed__".to_string(), true),
58 };
59
60 match op.kind {
61 PropertyKind::Init => {
62 let value = self.lower_expr(&op.value);
63 items.push(IrObjectItem::Field(crate::zigir::types::IrObjectField {
64 key,
65 value,
66 is_computed,
67 }));
68 }
69 PropertyKind::Get => {
70 // Getter: extract return expression from function body
71 // { get x() { return expr; } } → .x = expr
72 // Only single-return getters are inlined; complex ones get @compileError
73 if let Expression::FunctionExpression(func) = &op.value
74 && let Some(body) = &func.body
75 && let Some(return_expr) = Self::extract_return_expr_from_body(body)
76 {
77 let value = self.lower_expr(return_expr);
78 items.push(IrObjectItem::Field(
79 crate::zigir::types::IrObjectField {
80 key,
81 value,
82 is_computed,
83 },
84 ));
85 } else {
86 // Complex getter (multiple statements) — @compileError
87 let span = self.span_to_source_span(op.span);
88 self.add_error(span, "getter with complex body is not supported (only single-return getters are inlined)");
89 items.push(IrObjectItem::Field(
90 crate::zigir::types::IrObjectField {
91 key,
92 value: crate::zigir::types::IrExpr::CompileError {
93 span: SourceSpan::default(),
94 msg: "complex getter not supported".to_string(),
95 },
96 is_computed,
97 },
98 ));
99 }
100 }
101 PropertyKind::Set => {
102 // Setter: @compileError — Zig structs don't support setters
103 let span = self.span_to_source_span(op.span);
104 self.add_error(
105 span,
106 "setter property is not supported (Zig structs have no setters)",
107 );
108 items.push(IrObjectItem::Field(crate::zigir::types::IrObjectField {
109 key,
110 value: crate::zigir::types::IrExpr::CompileError {
111 span: SourceSpan::default(),
112 msg: "setter not supported".to_string(),
113 },
114 is_computed,
115 }));
116 }
117 }
118 }
119 ObjectPropertyKind::SpreadProperty(sp) => {
120 items.push(IrObjectItem::Spread(self.lower_expr(&sp.argument)));
121 }
122 }
123 }
124
125 crate::zigir::types::IrExpr::ObjectLiteral(crate::zigir::types::IrObjectLiteral { items })
126 }
127
128 /// Extract the return expression from a function body with a single return statement.
129 /// Used by getter property lowering: `{ get x() { return expr; } }` → `.x = expr`.
130 pub(super) fn extract_return_expr_from_body<'a>(
131 body: &'a FunctionBody<'a>,
132 ) -> Option<&'a Expression<'a>> {
133 if body.statements.len() == 1
134 && let Statement::ReturnStatement(ret) = &body.statements[0]
135 {
136 return ret.argument.as_ref();
137 }
138 None
139 }
140
141 /// Lower a template literal.
142 pub(super) fn lower_template_literal(
143 &mut self,
144 tl: &TemplateLiteral,
145 ) -> crate::zigir::types::IrExpr {
146 // Use the COOKED value (post-escape-interpretation), not `raw`.
147 // `raw` is the literal source text (e.g. `\\n` as two bytes 0x5C 0x6E);
148 // `cooked` is the interpreted string (a real 0x0A newline byte). When
149 // the emitter wraps a quasi in a Zig string literal via
150 // `escape_zig_format_string`, the cooked value's real control bytes
151 // get re-escaped to Zig escapes (e.g. `\n`) which Zig then correctly
152 // interprets at runtime. Using `raw` instead produced double-escaped
153 // output ("hello\\nworld" → runtime "hello\nworld" with literal
154 // backslash-n). Note: `cooked` is `None` for invalid escape sequences
155 // (e.g. `\u` not followed by valid hex); fall back to `raw` only then
156 // (R6-3).
157 let parts: Vec<String> = tl
158 .quasis
159 .iter()
160 .map(|q| {
161 q.value
162 .cooked
163 .as_ref()
164 .map(|c| c.to_string())
165 .unwrap_or_else(|| q.value.raw.to_string())
166 })
167 .collect();
168 let exprs: Vec<crate::zigir::types::IrExpr> =
169 tl.expressions.iter().map(|e| self.lower_expr(e)).collect();
170
171 // Determine the Zig format specifier for each interpolation expression.
172 // This must match the Emitter's logic:
173 // Str→{s}, I64/F64→{d}, Bool→{}, other→expr_is_string?{s}:{}
174 let format_specs: Vec<String> = tl
175 .expressions
176 .iter()
177 .map(|expr| {
178 if self.expr_is_string(expr) {
179 "{s}".to_string()
180 } else {
181 match self.infer_expr_type(expr) {
182 Some(ty) => helpers::format_specifier_for_type(&ty).to_string(),
183 None => "{any}".to_string(),
184 }
185 }
186 })
187 .collect();
188
189 crate::zigir::types::IrExpr::TemplateLiteral {
190 parts,
191 exprs,
192 format_specs,
193 }
194 }
195}