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;
8
9impl Lowerer {
10    /// Lower an array expression.
11    pub(super) fn lower_array_expr(&mut self, ae: &ArrayExpression) -> crate::zigir::types::IrExpr {
12        let mut elements = Vec::new();
13        let mut spread_indices = Vec::new();
14
15        for (i, elem) in ae.elements.iter().enumerate() {
16            match elem {
17                ArrayExpressionElement::SpreadElement(se) => {
18                    spread_indices.push(i);
19                    elements.push(crate::zigir::types::IrExpr::Spread(Box::new(
20                        self.lower_expr(&se.argument),
21                    )));
22                }
23                ArrayExpressionElement::Elision(_) => {
24                    elements.push(crate::zigir::types::IrExpr::Null);
25                }
26                _ => {
27                    if let Some(expr) = elem.as_expression() {
28                        elements.push(self.lower_expr(expr));
29                    }
30                }
31            }
32        }
33
34        crate::zigir::types::IrExpr::ArrayLiteral(crate::zigir::types::IrArrayLiteral {
35            elements,
36            spread_indices,
37        })
38    }
39
40    /// Lower an object expression.
41    pub(super) fn lower_object_expr(
42        &mut self,
43        oe: &ObjectExpression,
44    ) -> crate::zigir::types::IrExpr {
45        use crate::zigir::types::IrObjectItem;
46
47        let mut items = Vec::new();
48
49        for prop in oe.properties.iter() {
50            match prop {
51                ObjectPropertyKind::ObjectProperty(op) => {
52                    let (key, is_computed) = match &op.key {
53                        PropertyKey::StaticIdentifier(id) => (id.name.to_string(), false),
54                        PropertyKey::StringLiteral(sl) => (sl.value.to_string(), false),
55                        PropertyKey::NumericLiteral(nl) => (nl.value.to_string(), false),
56                        _ => ("__computed__".to_string(), true),
57                    };
58
59                    match op.kind {
60                        PropertyKind::Init => {
61                            let value = self.lower_expr(&op.value);
62                            items.push(IrObjectItem::Field(crate::zigir::types::IrObjectField {
63                                key,
64                                value,
65                                is_computed,
66                            }));
67                        }
68                        PropertyKind::Get => {
69                            // Getter: extract return expression from function body
70                            // { get x() { return expr; } } → .x = expr
71                            if let Expression::FunctionExpression(func) = &op.value
72                                && let Some(body) = &func.body
73                                && let Some(return_expr) = Self::extract_return_expr_from_body(body)
74                            {
75                                let value = self.lower_expr(return_expr);
76                                items.push(IrObjectItem::Field(
77                                    crate::zigir::types::IrObjectField {
78                                        key,
79                                        value,
80                                        is_computed,
81                                    },
82                                ));
83                            }
84                            // If getter body is more complex, skip it (can't inline)
85                        }
86                        PropertyKind::Set => {
87                            // Setter: skip entirely, doesn't contribute a field
88                        }
89                    }
90                }
91                ObjectPropertyKind::SpreadProperty(sp) => {
92                    items.push(IrObjectItem::Spread(self.lower_expr(&sp.argument)));
93                }
94            }
95        }
96
97        crate::zigir::types::IrExpr::ObjectLiteral(crate::zigir::types::IrObjectLiteral { items })
98    }
99
100    /// Extract the return expression from a function body with a single return statement.
101    /// Used by getter property lowering: `{ get x() { return expr; } }` → `.x = expr`.
102    pub(super) fn extract_return_expr_from_body<'a>(
103        body: &'a FunctionBody<'a>,
104    ) -> Option<&'a Expression<'a>> {
105        if body.statements.len() == 1
106            && let Statement::ReturnStatement(ret) = &body.statements[0]
107        {
108            return ret.argument.as_ref();
109        }
110        None
111    }
112
113    /// Lower a template literal.
114    pub(super) fn lower_template_literal(
115        &mut self,
116        tl: &TemplateLiteral,
117    ) -> crate::zigir::types::IrExpr {
118        let parts: Vec<String> = tl.quasis.iter().map(|q| q.value.raw.to_string()).collect();
119        let exprs: Vec<crate::zigir::types::IrExpr> =
120            tl.expressions.iter().map(|e| self.lower_expr(e)).collect();
121
122        // Determine the Zig format specifier for each interpolation expression.
123        // This must match the Emitter's logic:
124        //   Str→{s}, I64/F64→{d}, Bool→{}, other→expr_is_string?{s}:{}
125        let format_specs: Vec<String> = tl
126            .expressions
127            .iter()
128            .map(|expr| {
129                if self.expr_is_string(expr) {
130                    "{s}".to_string()
131                } else {
132                    match self.infer_expr_type(expr) {
133                        Some(ty) => helpers::format_specifier_for_type(&ty).to_string(),
134                        None => "{any}".to_string(),
135                    }
136                }
137            })
138            .collect();
139
140        crate::zigir::types::IrExpr::TemplateLiteral {
141            parts,
142            exprs,
143            format_specs,
144        }
145    }
146}