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