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 crate::types::ZigType;
7
8use super::Lowerer;
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                            if let Expression::FunctionExpression(func) = &op.value
73                                && let Some(body) = &func.body
74                                && let Some(return_expr) = Self::extract_return_expr_from_body(body)
75                            {
76                                let value = self.lower_expr(return_expr);
77                                items.push(IrObjectItem::Field(
78                                    crate::zigir::types::IrObjectField {
79                                        key,
80                                        value,
81                                        is_computed,
82                                    },
83                                ));
84                            }
85                            // If getter body is more complex, skip it (can't inline)
86                        }
87                        PropertyKind::Set => {
88                            // Setter: skip entirely, doesn't contribute a field
89                        }
90                    }
91                }
92                ObjectPropertyKind::SpreadProperty(sp) => {
93                    items.push(IrObjectItem::Spread(self.lower_expr(&sp.argument)));
94                }
95            }
96        }
97
98        crate::zigir::types::IrExpr::ObjectLiteral(crate::zigir::types::IrObjectLiteral { items })
99    }
100
101    /// Extract the return expression from a function body with a single return statement.
102    /// Used by getter property lowering: `{ get x() { return expr; } }` → `.x = expr`.
103    pub(super) fn extract_return_expr_from_body<'a>(
104        body: &'a FunctionBody<'a>,
105    ) -> Option<&'a Expression<'a>> {
106        if body.statements.len() == 1
107            && let Statement::ReturnStatement(ret) = &body.statements[0]
108        {
109            return ret.argument.as_ref();
110        }
111        None
112    }
113
114    /// Lower a template literal.
115    pub(super) fn lower_template_literal(
116        &mut self,
117        tl: &TemplateLiteral,
118    ) -> crate::zigir::types::IrExpr {
119        let parts: Vec<String> = tl.quasis.iter().map(|q| q.value.raw.to_string()).collect();
120        let exprs: Vec<crate::zigir::types::IrExpr> =
121            tl.expressions.iter().map(|e| self.lower_expr(e)).collect();
122
123        // Determine the Zig format specifier for each interpolation expression.
124        // This must match the Emitter's logic:
125        //   Str→{s}, I64/F64→{d}, Bool→{}, other→expr_is_string?{s}:{}
126        let format_specs: Vec<String> = tl
127            .expressions
128            .iter()
129            .map(|expr| match self.infer_expr_type(expr) {
130                Some(ZigType::Str) => "{s}".to_string(),
131                Some(ZigType::I64) => "{d}".to_string(),
132                Some(ZigType::F64) => "{d:.15}".to_string(),
133                Some(ZigType::Bool) => "{}".to_string(),
134                _ => {
135                    if self.expr_is_string(expr) {
136                        "{s}".to_string()
137                    } else {
138                        "{}".to_string()
139                    }
140                }
141            })
142            .collect();
143
144        crate::zigir::types::IrExpr::TemplateLiteral {
145            parts,
146            exprs,
147            format_specs,
148        }
149    }
150}