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