Skip to main content

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        let parts: Vec<String> = tl.quasis.iter().map(|q| q.value.raw.to_string()).collect();
147        let exprs: Vec<crate::zigir::types::IrExpr> =
148            tl.expressions.iter().map(|e| self.lower_expr(e)).collect();
149
150        // Determine the Zig format specifier for each interpolation expression.
151        // This must match the Emitter's logic:
152        //   Str→{s}, I64/F64→{d}, Bool→{}, other→expr_is_string?{s}:{}
153        let format_specs: Vec<String> = tl
154            .expressions
155            .iter()
156            .map(|expr| {
157                if self.expr_is_string(expr) {
158                    "{s}".to_string()
159                } else {
160                    match self.infer_expr_type(expr) {
161                        Some(ty) => helpers::format_specifier_for_type(&ty).to_string(),
162                        None => "{any}".to_string(),
163                    }
164                }
165            })
166            .collect();
167
168        crate::zigir::types::IrExpr::TemplateLiteral {
169            parts,
170            exprs,
171            format_specs,
172        }
173    }
174}