Skip to main content

js2zig_core/zigir/lower/expr/
mod.rs

1// zigir/lower/expr/mod.rs
2// Expression lowering: main dispatch + identifier handling.
3
4use oxc_ast::ast::*;
5
6use crate::zigir::ident::IrIdent;
7use crate::zigir::kinds::FieldKind;
8use crate::zigir::ops::LogicalOp;
9use crate::zigir::source_span::SourceSpan;
10
11use super::Lowerer;
12
13pub mod call;
14pub mod container;
15pub mod function;
16pub mod idents;
17pub mod member;
18pub mod operators;
19pub mod optional;
20
21impl Lowerer {
22    pub(crate) fn lower_expr(&mut self, expr: &Expression) -> crate::zigir::types::IrExpr {
23        use crate::zigir::types::IrExpr;
24
25        match expr {
26            // ── Literals ──────────────────────────────────────────────────────
27            Expression::NumericLiteral(n) => {
28                // Zig considers `-0` ambiguous; emit `-0.0` explicitly for negative zero
29                if n.value == -0.0 && n.value.is_sign_negative() {
30                    IrExpr::FloatLiteral(-0.0)
31                } else if n.value.fract() == 0.0 && n.value.abs() < i64::MAX as f64 {
32                    IrExpr::IntLiteral(n.value as i64)
33                } else {
34                    IrExpr::FloatLiteral(n.value)
35                }
36            }
37            Expression::StringLiteral(s) => IrExpr::StringLiteral(s.value.to_string()),
38            Expression::BooleanLiteral(b) => IrExpr::BoolLiteral(b.value),
39            Expression::NullLiteral(_) => IrExpr::Null,
40            Expression::RegExpLiteral(rl) => {
41                // JS regexp literal `/pattern/flags` → new RegExp(pattern, flags)
42                let pattern = rl.regex.pattern.text.as_str();
43                let escaped = pattern.replace('\\', "\\\\").replace('"', "\\\"");
44                let flags = rl.regex.flags.to_string();
45                IrExpr::New(crate::zigir::types::IrNewExpr {
46                    constructor: crate::zigir::kinds::NewConstructor::RegExp,
47                    args: vec![IrExpr::StringLiteral(escaped), IrExpr::StringLiteral(flags)],
48                    result_type: crate::types::ZigType::JsAny,
49                })
50            }
51            Expression::BigIntLiteral(bi) => {
52                // BigInt literal: store the decimal value string (without trailing 'n')
53                let s = bi.value.as_str().to_string();
54                IrExpr::BigIntLiteral(s)
55            }
56
57            // ── Identifier ────────────────────────────────────────────────────
58            Expression::Identifier(id) => self.lower_ident_expr(id),
59
60            // ── This ──────────────────────────────────────────────────────────
61            Expression::ThisExpression(te) => {
62                if self.in_static_block {
63                    // In a static block, `this` refers to the class constructor itself.
64                    // Replace with the class name identifier so that `this.field`
65                    // is correctly routed to `__ClassName_field` via the existing
66                    // static field detection logic.
67                    if let Some(ref class_name) = self.current_class {
68                        IrExpr::Ident(IrIdent::new(class_name))
69                    } else {
70                        let span = self.span_to_source_span(te.span);
71                        self.add_error(span, "`this` used in static block without class context");
72                        IrExpr::CompileError {
73                            span: SourceSpan::default(),
74                            msg: "`this` used in static block without class context".to_string(),
75                        }
76                    }
77                } else if self.current_class.is_some() {
78                    IrExpr::This
79                } else {
80                    let span = self.span_to_source_span(te.span);
81                    self.add_error(span, "`this` used outside of a class method");
82                    IrExpr::CompileError {
83                        span: SourceSpan::default(),
84                        msg: "`this` used outside of a class method".to_string(),
85                    }
86                }
87            }
88
89            // ── Binary expression ─────────────────────────────────────────────
90            Expression::BinaryExpression(be) => self.lower_binary(be),
91
92            // ── Logical expression ────────────────────────────────────────────
93            Expression::LogicalExpression(le) => {
94                let op = match le.operator {
95                    LogicalOperator::And => LogicalOp::And,
96                    LogicalOperator::Or => LogicalOp::Or,
97                    LogicalOperator::Coalesce => LogicalOp::Nullish,
98                };
99                let left_type = self
100                    .infer_expr_type(&le.left)
101                    .unwrap_or(crate::types::ZigType::JsAny);
102                let right_type = self
103                    .infer_expr_type(&le.right)
104                    .unwrap_or(crate::types::ZigType::JsAny);
105                IrExpr::Logical {
106                    op,
107                    left: Box::new(self.lower_expr(&le.left)),
108                    right: Box::new(self.lower_expr(&le.right)),
109                    left_type: Some(left_type),
110                    right_type: Some(right_type),
111                }
112            }
113
114            // ── Unary expression ──────────────────────────────────────────────
115            Expression::UnaryExpression(ue) => self.lower_unary(ue),
116
117            // ── Update expression ─────────────────────────────────────────────
118            Expression::UpdateExpression(ue) => self.lower_update(ue),
119
120            // ── Assignment expression ─────────────────────────────────────────
121            Expression::AssignmentExpression(ae) => self.lower_assignment(ae),
122
123            // ── Parenthesized ─────────────────────────────────────────────────
124            Expression::ParenthesizedExpression(pe) => {
125                IrExpr::Paren(Box::new(self.lower_expr(&pe.expression)))
126            }
127
128            // ── Conditional ──────────────────────────────────────────────────
129            Expression::ConditionalExpression(ce) => IrExpr::Conditional {
130                cond: Box::new(self.lower_expr(&ce.test)),
131                then: Box::new(self.lower_expr(&ce.consequent)),
132                else_: Box::new(self.lower_expr(&ce.alternate)),
133            },
134
135            // ── Sequence expression ───────────────────────────────────────────
136            Expression::SequenceExpression(se) => {
137                let exprs: Vec<IrExpr> =
138                    se.expressions.iter().map(|e| self.lower_expr(e)).collect();
139                IrExpr::Sequence(exprs)
140            }
141
142            // ── Calls ─────────────────────────────────────────────────────────
143            Expression::CallExpression(ce) => self.lower_call(ce),
144            Expression::NewExpression(ne) => self.lower_new(ne),
145
146            // ── Member access ─────────────────────────────────────────────────
147            Expression::StaticMemberExpression(mem) => {
148                // Handle optional member access (?.) via the optional chain path
149                if mem.optional {
150                    return self.lower_optional_sme_chain(mem);
151                }
152                self.lower_static_member(mem)
153            }
154            Expression::ComputedMemberExpression(mem) => {
155                if mem.optional {
156                    return self.lower_optional_cme_chain(mem);
157                }
158                self.lower_computed_member(mem)
159            }
160
161            // ── Array / Object literals ──────────────────────────────────────
162            Expression::ArrayExpression(ae) => self.lower_array_expr(ae),
163            Expression::ObjectExpression(oe) => self.lower_object_expr(oe),
164
165            // ── Function expressions ─────────────────────────────────────────
166            Expression::ArrowFunctionExpression(af) => self.lower_arrow_fn(af),
167            Expression::FunctionExpression(fe) => self.lower_fn_expr(fe),
168
169            // ── Template literal ──────────────────────────────────────────────
170            Expression::TemplateLiteral(tl) => self.lower_template_literal(tl),
171
172            // ── Tagged template ──────────────────────────────────────────────
173            Expression::TaggedTemplateExpression(tte) => {
174                let span = self.span_to_source_span(tte.span);
175                self.add_error(span, "Tagged template literals are not supported");
176                IrExpr::CompileError {
177                    span: SourceSpan::default(),
178                    msg: "Tagged template literals not supported".to_string(),
179                }
180            }
181
182            // ── Await ─────────────────────────────────────────────────────────
183            Expression::AwaitExpression(ae) => self.lower_await(ae),
184
185            // ── typeof / void / delete ────────────────────────────────────────
186            // (handled via UnaryExpression, but also here as fallback)
187
188            // ── Yield ─────────────────────────────────────────────────────────
189            Expression::YieldExpression(ye) => {
190                let span = self.span_to_source_span(ye.span);
191                self.add_error(span, "Yield expressions are not supported");
192                IrExpr::CompileError {
193                    span: SourceSpan::default(),
194                    msg: "yield not supported".to_string(),
195                }
196            }
197
198            // ── MetaProperty (import.meta, new.target) ──────
199            Expression::MetaProperty(mp) => {
200                let meta_name = mp.meta.name.as_str();
201                let prop_name = mp.property.name.as_str();
202                let span = self.span_to_source_span(mp.span);
203                self.add_error(
204                    span,
205                    format!("MetaProperty {}.{} is not supported", meta_name, prop_name),
206                );
207                IrExpr::CompileError {
208                    span: SourceSpan::default(),
209                    msg: format!("MetaProperty {}.{} not supported", meta_name, prop_name),
210                }
211            }
212
213            // ── Super ────────────────────────────────────────────────────────
214            Expression::Super(sup) => {
215                let span = self.span_to_source_span(sup.span);
216                self.add_error(span, "super is not supported");
217                IrExpr::CompileError {
218                    span: SourceSpan::default(),
219                    msg: "super not supported".to_string(),
220                }
221            }
222
223            // ── Import ────────────────────────────────────────────────────────
224            Expression::ImportExpression(ie) => {
225                let span = self.span_to_source_span(ie.span);
226                self.add_error(span, "dynamic import() is not supported");
227                IrExpr::CompileError {
228                    span: SourceSpan::default(),
229                    msg: "dynamic import() not supported".to_string(),
230                }
231            }
232
233            // ── PrivateFieldAccess ────────────────────────────────────────────
234            Expression::PrivateFieldExpression(pfe) => {
235                // Private fields are lowered like normal member access
236                // with a field_kind marker
237                let object = Box::new(self.lower_expr(&pfe.object));
238                let field = pfe.field.name.to_string();
239                IrExpr::FieldAccess {
240                    object,
241                    field,
242                    field_kind: FieldKind::Private,
243                }
244            }
245
246            // ── Optional chaining (?.) ───────────────────────────────────────
247            Expression::ChainExpression(ce) => self.lower_optional_chain(ce),
248
249            // ── Class expression (anonymous or named class as value) ──
250            // e.g. `const X = class {}` or `const X = class Y {}`
251            // Lower same as ClassDeclaration, register as pending decl,
252            // return an Ident referencing the class struct name.
253            Expression::ClassExpression(ce) => {
254                if ce.super_class.is_some() {
255                    let span = self.span_to_source_span(ce.span);
256                    self.add_error(
257                        span.clone(),
258                        "class extends is not supported: use composition instead",
259                    );
260                    IrExpr::CompileError {
261                        span,
262                        msg: "class extends is not supported: use composition instead".to_string(),
263                    }
264                } else if let Some(ir_class) = self.lower_class_decl(ce) {
265                    let class_name = ir_class.name.js_name.clone();
266                    self.class_names.insert(class_name.clone());
267                    // Register extends relationship for instanceof chain traversal
268                    if let Some(ref parent) = ir_class.extends {
269                        self.class_extends_map
270                            .insert(class_name.clone(), parent.clone());
271                    }
272                    self.pending_expr_fns
273                        .push(crate::zigir::types::IrDecl::Class(ir_class));
274                    IrExpr::Ident(self.make_ident(&class_name))
275                } else {
276                    IrExpr::CompileError {
277                        span: SourceSpan::default(),
278                        msg: "class expression could not be lowered".to_string(),
279                    }
280                }
281            }
282
283            // ── Fallback ──────────────────────────────────────────────────────
284            _ => IrExpr::CompileError {
285                span: SourceSpan::default(),
286                msg: format!("unsupported expression type: {expr:?}"),
287            },
288        }
289    }
290
291    /// Lower an identifier expression with special handling for
292    /// built-in globals (NaN, Infinity, undefined, arguments)
293    /// and captured closure variables.
294    pub(super) fn lower_ident_expr(
295        &mut self,
296        id: &IdentifierReference,
297    ) -> crate::zigir::types::IrExpr {
298        use crate::zigir::types::IrExpr;
299
300        let var_name = id.name.as_str();
301
302        // arguments object: rewrite to rest param name
303        // - Non-export with synthetic rest: `__arguments` (the rest param)
304        // - Function with explicit rest: the rest param name (e.g., `args`)
305        // - Export function (no rest): falls back to `__arguments` VarDecl
306        if var_name == "arguments" {
307            if let Some(ctx) = self.fn_ctx.as_ref()
308                && let Some(rest_name) = &ctx.rest_param_name
309            {
310                return IrExpr::Ident(IrIdent::new(rest_name));
311            }
312            return IrExpr::Ident(IrIdent::new("__arguments"));
313        }
314
315        // JS global constants
316        if var_name == "NaN" {
317            return IrExpr::BuiltinCall(crate::zigir::types::IrBuiltinCall::simple(
318                crate::zigir::builtins::BuiltinModule::JsMath,
319                "nan_f64",
320                None,
321                None,
322                vec![],
323                crate::types::ZigType::F64,
324            ));
325        }
326        if var_name == "Infinity" {
327            return IrExpr::BuiltinCall(crate::zigir::types::IrBuiltinCall::simple(
328                crate::zigir::builtins::BuiltinModule::JsMath,
329                "inf_f64",
330                None,
331                None,
332                vec![],
333                crate::types::ZigType::F64,
334            ));
335        }
336        // undefined → JsAny.fromUndefined()
337        // (Stored as Ident with special name; Emitter will handle)
338        if var_name == "undefined" {
339            return IrExpr::Undefined;
340        }
341
342        // Check if this identifier is a captured closure variable.
343        // If so, rewrite to self.var_name (value capture) or self.var_name.* (ref capture).
344        if let Some((_, _, is_mut)) = self
345            .closure_mgr
346            .current_captured
347            .iter()
348            .find(|(n, _, _)| n == var_name)
349        {
350            let field_name = self.make_ident(var_name);
351            let self_access = IrExpr::FieldAccess {
352                object: Box::new(IrExpr::Ident(IrIdent::new("self"))),
353                field: field_name.zig_name.clone(),
354                field_kind: FieldKind::StructField,
355            };
356            return if *is_mut {
357                // Reference capture: dereference the pointer
358                IrExpr::FieldAccess {
359                    object: Box::new(self_access),
360                    field: "*".to_string(),
361                    field_kind: FieldKind::PointerDeref,
362                }
363            } else {
364                self_access
365            };
366        }
367
368        IrExpr::Ident(self.make_ident(var_name))
369    }
370}