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
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
// zigir/lower/closure.rs
// Closure struct lowering and capture analysis.
use oxc_ast::ast::*;
use std::cell::{Cell, RefCell};
use std::collections::HashSet;
use crate::types::ZigType;
use crate::zigir::types::{IrBlock, IrParam};
use super::Lowerer;
// ¨T¨T¨T¨T¨T¨T¨T¨T¨T¨T¨T¨T¨T¨T¨T¨T¨T¨T¨T¨T¨T¨T¨T¨T¨T¨T¨T¨T¨T¨T¨T¨T¨T¨T¨T¨T¨T¨T¨T¨T¨T¨T¨T¨T¨T¨T¨T¨T¨T¨T¨T¨T¨T¨T¨T
// Closure struct lowering
// ¨T¨T¨T¨T¨T¨T¨T¨T¨T¨T¨T¨T¨T¨T¨T¨T¨T¨T¨T¨T¨T¨T¨T¨T¨T¨T¨T¨T¨T¨T¨T¨T¨T¨T¨T¨T¨T¨T¨T¨T¨T¨T¨T¨T¨T¨T¨T¨T¨T¨T¨T¨T¨T¨T¨T
impl Lowerer {
/// Convert collected closure definitions from ClosureManager
/// into IrClosureStruct nodes.
///
/// In ZigIR these are structured IrClosureStruct nodes.
///
/// After lowering, `closure_mgr.closure_vars` contains the mapping from
/// struct name ¡ú captured vars that was built during `lower_arrow_fn` /
/// `lower_fn_expr`. We produce one `IrClosureStruct` per entry.
pub(super) fn lower_closure_structs(&self) -> Vec<crate::zigir::types::IrClosureStruct> {
self.closure_mgr
.closure_vars
.iter()
.map(|(struct_name, captured)| {
let ir_captures = self.make_ir_captures(
captured
.iter()
.map(|(name, zig_type, is_mut)| (name.clone(), zig_type.clone(), *is_mut))
.collect(),
);
crate::zigir::types::IrClosureStruct {
name: self.make_ident(struct_name),
captured: ir_captures,
fn_params: vec![], // Will be filled by the Emitter from the IrClosure
return_type: ZigType::Void,
typeof_return_body: None,
body: IrBlock::new(vec![]),
}
})
.collect()
}
}
// ¨T¨T¨T¨T¨T¨T¨T¨T¨T¨T¨T¨T¨T¨T¨T¨T¨T¨T¨T¨T¨T¨T¨T¨T¨T¨T¨T¨T¨T¨T¨T¨T¨T¨T¨T¨T¨T¨T¨T¨T¨T¨T¨T¨T¨T¨T¨T¨T¨T¨T¨T¨T¨T¨T¨T
// Closure capture analysis
// ¨T¨T¨T¨T¨T¨T¨T¨T¨T¨T¨T¨T¨T¨T¨T¨T¨T¨T¨T¨T¨T¨T¨T¨T¨T¨T¨T¨T¨T¨T¨T¨T¨T¨T¨T¨T¨T¨T¨T¨T¨T¨T¨T¨T¨T¨T¨T¨T¨T¨T¨T¨T¨T¨T¨T
impl Lowerer {
/// Collect captured variables from an arrow function body.
///
/// A variable is "captured" if it's referenced in the body but is not a
/// parameter and not a locally declared variable.
pub(super) fn collect_arrow_captures(
&self,
arrow: &ArrowFunctionExpression,
) -> Vec<(String, ZigType, bool)> {
let param_names = Self::collect_param_names(&arrow.params.items);
self.collect_captures_from_body(¶m_names, &arrow.body.statements, true)
}
/// Detect variables captured by a nested function (declaration or expression).
///
/// Returns list of (variable_name, ZigType, is_mutable) for variables from
/// the enclosing scope that are referenced in the function body.
pub(super) fn detect_fn_body_captures(&self, fd: &Function) -> Vec<(String, ZigType, bool)> {
let param_names = Self::collect_param_names(&fd.params.items);
fd.body
.as_ref()
.map(|body| self.collect_captures_from_body(¶m_names, &body.statements, true))
.unwrap_or_default()
}
/// Extract parameter names from a parameter list.
fn collect_param_names(params: &oxc_allocator::Vec<'_, FormalParameter>) -> HashSet<String> {
params
.iter()
.filter_map(|p| crate::infer::binding_name(&p.pattern))
.map(|s| s.to_string())
.collect()
}
/// Core capture-collection logic shared by arrow and regular functions.
fn collect_captures_from_body(
&self,
param_names: &HashSet<String>,
stmts: &oxc_allocator::Vec<'_, Statement>,
include_local_decls: bool,
) -> Vec<(String, ZigType, bool)> {
let captured = RefCell::new(Vec::new());
let seen = RefCell::new(HashSet::new());
let mut local_names = param_names.clone();
if include_local_decls {
local_names.extend(Self::collect_local_declarations(stmts));
}
for stmt in stmts {
Self::collect_idents_from_stmt(stmt, &captured, &seen, &local_names, &self.type_info);
}
let mut captured = captured.into_inner();
let mutated = Self::detect_mutated_vars_in_stmts(stmts);
for (name, _ztype, is_mut) in &mut captured {
*is_mut = mutated.contains(name);
}
captured
}
/// Collect locally declared variable names from a list of statements.
/// These variables (const/let/var in the function body) are NOT captures.
/// Recurses into nested control flow (if/for/while/block/try/switch, etc.)
/// but does NOT recurse into FunctionDeclaration bodies (separate scope).
pub(super) fn collect_local_declarations(
stmts: &oxc_allocator::Vec<'_, Statement>,
) -> HashSet<String> {
let names = RefCell::new(HashSet::new());
for stmt in stmts {
Self::collect_local_decls_from_stmt(stmt, &names);
}
names.into_inner()
}
fn collect_local_decls_from_stmt(stmt: &Statement, names: &RefCell<HashSet<String>>) {
crate::infer::ast_walk::for_each_stmt_child(
stmt,
&mut |s| Self::collect_local_decls_from_stmt(s, names),
&mut |_| {}, // on_expr: not needed for local declarations
&mut |vd| {
for decl in &vd.declarations {
if let Some(name) = crate::infer::binding_name(&decl.id) {
names.borrow_mut().insert(name.to_string());
}
}
},
);
}
/// Detect which variables are mutated (assigned to or updated) in a list of statements.
pub(super) fn detect_mutated_vars_in_stmts(stmts: &[Statement]) -> HashSet<String> {
let mutated = RefCell::new(HashSet::new());
for stmt in stmts {
Self::detect_mutated_in_stmt(stmt, &mutated);
}
mutated.into_inner()
}
pub(super) fn detect_mutated_in_stmt(stmt: &Statement, mutated: &RefCell<HashSet<String>>) {
crate::infer::ast_walk::for_each_stmt_child(
stmt,
&mut |s| Self::detect_mutated_in_stmt(s, mutated),
&mut |e| Self::detect_mutated_in_expr(e, mutated),
&mut |_vd| {
// VariableDeclaration inits are not mutation targets; skip.
},
);
}
pub(super) fn detect_mutated_in_expr(expr: &Expression, mutated: &RefCell<HashSet<String>>) {
crate::infer::ast_walk::for_each_expr_child(
expr,
&mut |e| Self::detect_mutated_in_expr(e, mutated),
&mut |_| {}, // on_ident: identifiers are not mutations
&mut |target| {
// AssignmentExpression left-hand side
if let AssignmentTarget::AssignmentTargetIdentifier(id) = target {
mutated.borrow_mut().insert(id.name.to_string());
}
},
&mut |simple_target| {
// UpdateExpression target (i++, ++i, etc.)
if let SimpleAssignmentTarget::AssignmentTargetIdentifier(id) = simple_target {
mutated.borrow_mut().insert(id.name.to_string());
}
},
&mut |_params, _stmts| {
// Function/arrow scope boundary — stop recursing.
// Mutations inside nested functions don't affect the
// enclosing scope's variable set.
},
);
}
/// Helper: collect identifiers from a function body (params + statements).
/// Shared by FunctionExpression and ArrowFunctionExpression to avoid duplication.
/// Also collects local declarations from the nested function body to avoid
/// misclassifying them as captures.
fn collect_idents_from_fn_body(
params: &[FormalParameter],
stmts: &oxc_allocator::Vec<'_, Statement>,
captured: &RefCell<Vec<(String, ZigType, bool)>>,
seen: &RefCell<HashSet<String>>,
local_names: &HashSet<String>,
type_info: &crate::infer::TypeCheckResult,
) {
let mut inner_locals = local_names.clone();
for param in params {
if let Some(pname) = crate::infer::binding_name(¶m.pattern) {
inner_locals.insert(pname.to_string());
}
}
// Also collect the nested function's own local declarations so they
// are not falsely treated as captures from the enclosing scope.
inner_locals.extend(Self::collect_local_declarations(stmts));
for stmt in stmts {
Self::collect_idents_from_stmt(stmt, captured, seen, &inner_locals, type_info);
}
}
/// Helper: collect identifiers from a statement that reference variables
/// in an enclosing scope (possible captures).
///
/// Recurses into ALL statement types (if/while/for/try/block/switch/etc.)
/// using `for_each_stmt_child` to ensure identifiers inside control flow
/// are properly detected as captures.
pub(super) fn collect_idents_from_stmt(
stmt: &Statement,
captured: &RefCell<Vec<(String, ZigType, bool)>>,
seen: &RefCell<HashSet<String>>,
local_names: &HashSet<String>,
type_info: &crate::infer::TypeCheckResult,
) {
crate::infer::ast_walk::for_each_stmt_child(
stmt,
&mut |s| Self::collect_idents_from_stmt(s, captured, seen, local_names, type_info),
&mut |e| Self::collect_idents_from_expr(e, captured, seen, local_names, type_info),
&mut |vd| {
crate::infer::ast_walk::for_each_var_decl_init(vd, &mut |init| {
Self::collect_idents_from_expr(init, captured, seen, local_names, type_info);
});
},
);
}
/// Helper: collect identifiers from an expression that reference variables
/// in an enclosing scope.
///
/// Recurses into ALL expression types using `for_each_expr_child` to ensure
/// identifiers inside member accesses, assignments, conditionals, arrays,
/// objects, optional chains, etc. are properly detected as captures.
pub(super) fn collect_idents_from_expr(
expr: &Expression,
captured: &RefCell<Vec<(String, ZigType, bool)>>,
seen: &RefCell<HashSet<String>>,
local_names: &HashSet<String>,
type_info: &crate::infer::TypeCheckResult,
) {
crate::infer::ast_walk::for_each_expr_child(
expr,
&mut |e| Self::collect_idents_from_expr(e, captured, seen, local_names, type_info),
&mut |name| {
Self::check_and_add_capture(name, captured, seen, local_names, type_info);
},
&mut |target| {
match target {
AssignmentTarget::AssignmentTargetIdentifier(id) => {
Self::check_and_add_capture(
id.name.as_str(),
captured,
seen,
local_names,
type_info,
);
}
AssignmentTarget::StaticMemberExpression(mem) => {
Self::collect_idents_from_expr(
&mem.object,
captured,
seen,
local_names,
type_info,
);
}
AssignmentTarget::ComputedMemberExpression(mem) => {
Self::collect_idents_from_expr(
&mem.object,
captured,
seen,
local_names,
type_info,
);
Self::collect_idents_from_expr(
&mem.expression,
captured,
seen,
local_names,
type_info,
);
}
AssignmentTarget::PrivateFieldExpression(pfe) => {
Self::collect_idents_from_expr(
&pfe.object,
captured,
seen,
local_names,
type_info,
);
}
_ => {} // Destructuring targets — best effort skip
}
},
&mut |simple_target| match simple_target {
SimpleAssignmentTarget::AssignmentTargetIdentifier(id) => {
Self::check_and_add_capture(
id.name.as_str(),
captured,
seen,
local_names,
type_info,
);
}
SimpleAssignmentTarget::StaticMemberExpression(mem) => {
Self::collect_idents_from_expr(
&mem.object,
captured,
seen,
local_names,
type_info,
);
}
SimpleAssignmentTarget::ComputedMemberExpression(mem) => {
Self::collect_idents_from_expr(
&mem.object,
captured,
seen,
local_names,
type_info,
);
Self::collect_idents_from_expr(
&mem.expression,
captured,
seen,
local_names,
type_info,
);
}
SimpleAssignmentTarget::PrivateFieldExpression(pfe) => {
Self::collect_idents_from_expr(
&pfe.object,
captured,
seen,
local_names,
type_info,
);
}
_ => {}
},
&mut |params, stmts| {
Self::collect_idents_from_fn_body(
params,
stmts,
captured,
seen,
local_names,
type_info,
);
},
);
}
/// Check if a name should be added to the capture list.
/// A name is captured if it is NOT a local variable, NOT already seen,
/// and NOT a JavaScript built-in identifier.
fn check_and_add_capture(
name: &str,
captured: &RefCell<Vec<(String, ZigType, bool)>>,
seen: &RefCell<HashSet<String>>,
local_names: &HashSet<String>,
type_info: &crate::infer::TypeCheckResult,
) {
if !local_names.contains(name)
&& !seen.borrow().contains(name)
&& !crate::native_builtins::is_js_builtin_identifier(name)
{
seen.borrow_mut().insert(name.to_string());
let ztype = type_info
.var_types
.get(name)
.cloned()
.unwrap_or(ZigType::JsAny);
captured.borrow_mut().push((name.to_string(), ztype, false));
}
}
/// Lower arrow function parameters into IrParam list.
pub(super) fn lower_arrow_params(&mut self, arrow: &ArrowFunctionExpression) -> Vec<IrParam> {
let mut params = Vec::new();
for param in &arrow.params.items {
if let Some(pname) = crate::infer::binding_name(¶m.pattern) {
let ptype = self
.type_info
.var_types
.get(pname)
.cloned()
.unwrap_or(ZigType::Anytype);
params.push(IrParam {
name: self.make_ident(pname),
zig_type: ptype,
is_unused: false,
is_rest: false,
});
}
}
params
}
/// Find the first `IrExpr` returned from a block of IR statements.
/// Used for `@TypeOf(return_expr)` when the return type is `AnytypeReturn`.
pub(super) fn find_first_return_expr_in_block(
block: &IrBlock,
) -> Option<&crate::zigir::types::IrExpr> {
for stmt in &block.stmts {
if let Some(expr) = Self::find_first_return_expr_in_stmt(stmt) {
return Some(expr);
}
}
None
}
pub(super) fn find_first_return_expr_in_stmt(
stmt: &crate::zigir::types::IrStmt,
) -> Option<&crate::zigir::types::IrExpr> {
match stmt {
crate::zigir::types::IrStmt::Return { value, .. } => value.as_ref(),
crate::zigir::types::IrStmt::If { then, else_, .. } => {
Self::find_first_return_expr_in_block(then).or_else(|| {
else_
.as_ref()
.and_then(Self::find_first_return_expr_in_block)
})
}
crate::zigir::types::IrStmt::Block(b) => Self::find_first_return_expr_in_block(b),
_ => None,
}
}
/// Scan statements for the first ReturnStatement and infer its type.
fn scan_return_type_from_stmts(
&self,
stmts: &[Statement],
captured: &[(String, ZigType, bool)],
default_type: ZigType,
) -> ZigType {
for stmt in stmts {
if let Statement::ReturnStatement(rs) = stmt {
if let Some(ref arg) = rs.argument {
return self
.infer_arrow_expr_type_with_captures(arg, captured)
.unwrap_or(default_type);
}
return ZigType::Void;
}
}
ZigType::Void
}
/// Infer the return type of an arrow function.
pub(super) fn infer_arrow_return_type(
&self,
arrow: &ArrowFunctionExpression,
captured: &[(String, ZigType, bool)],
) -> ZigType {
// Only expression-body arrows (`() => expr`) return the expression value.
// Block-body arrows (`() => { expr; }`) return void unless they have an
// explicit `return` statement.
if arrow.expression
&& arrow.body.statements.len() == 1
&& let Statement::ExpressionStatement(es) = &arrow.body.statements[0]
{
return self
.infer_arrow_expr_type_with_captures(&es.expression, captured)
.unwrap_or(ZigType::JsAny);
}
self.scan_return_type_from_stmts(&arrow.body.statements, captured, ZigType::JsAny)
}
/// Infer the return type of a function expression by scanning return statements.
pub(super) fn infer_fn_expr_return_type(
&self,
fe: &Function,
captured: &[(String, ZigType, bool)],
) -> ZigType {
fe.body
.as_ref()
.map(|body| self.scan_return_type_from_stmts(&body.statements, captured, ZigType::Void))
.unwrap_or(ZigType::Void)
}
/// Best-effort type inference with captured variable fallback.
/// When a captured variable's type isn't in `var_types` (e.g., the variable
/// derives from an `anytype` parameter), we can look it up from the capture
/// list which was populated by `detect_fn_body_captures`.
pub(super) fn infer_arrow_expr_type_with_captures(
&self,
expr: &Expression,
captured: &[(String, ZigType, bool)],
) -> Option<ZigType> {
match expr {
Expression::NumericLiteral(nl) => {
if let Some(raw) = &nl.raw {
let s = raw.as_str();
if s.contains('.') || s.contains('e') || s.contains('E') {
Some(ZigType::F64)
} else {
Some(ZigType::I64)
}
} else {
Some(ZigType::I64)
}
}
Expression::StringLiteral(_) => Some(ZigType::Str),
Expression::BooleanLiteral(_) => Some(ZigType::Bool),
Expression::Identifier(id) => {
// Steps 1-3: delegate to infer_ident_type (exact, qualified, suffix)
if let Some(ty) = self.infer_ident_type(id.name.as_str()) {
return Some(ty);
}
// Step 4: captured variable fallback (handles anytype-derived vars)
for (name, ty, _is_mut) in captured {
if name == id.name.as_str() {
return Some(ty.clone());
}
}
None
}
Expression::BinaryExpression(be) => self
.infer_arrow_expr_type_with_captures(&be.left, captured)
.or_else(|| self.infer_arrow_expr_type_with_captures(&be.right, captured)),
Expression::UnaryExpression(ue) => {
self.infer_arrow_expr_type_with_captures(&ue.argument, captured)
}
Expression::CallExpression(ce) => {
match &ce.callee {
Expression::Identifier(id) => self
.type_info
.fn_return_types
.get(id.name.as_str())
.cloned(),
// IIFE: function(c){...}(1) — infer from the function body
Expression::FunctionExpression(fe) => fe.body.as_ref().map(|body| {
self.scan_return_type_from_stmts(&body.statements, captured, ZigType::Void)
}),
Expression::ArrowFunctionExpression(af) => {
Some(self.infer_arrow_return_type(af, captured))
}
_ => None,
}
}
Expression::StaticMemberExpression(sme) => {
let field = sme.property.name.as_str();
match field {
"length" | "len" => Some(ZigType::I64),
_ => None,
}
}
Expression::ConditionalExpression(ce) => self
.infer_arrow_expr_type_with_captures(&ce.consequent, captured)
.or_else(|| self.infer_arrow_expr_type_with_captures(&ce.alternate, captured)),
_ => None,
}
}
/// C5: Detect whether a function body references `this`.
///
/// Arrow functions inside class methods must capture the class instance
/// (`self` in Zig) as a synthetic `__self` capture variable, because
/// `IrExpr::This` (which emits `"self"`) would refer to the closure
/// struct itself, not the class instance.
///
/// Recursively scans statement and expression children, but stops at
/// function/arrow scope boundaries (their `this` is their own).
pub(super) fn detect_this_in_body(stmts: &[Statement]) -> bool {
let found = Cell::new(false);
for stmt in stmts {
Self::scan_stmt_for_this(stmt, &found);
if found.get() {
return true;
}
}
false
}
fn scan_stmt_for_this(stmt: &Statement, found: &Cell<bool>) {
if found.get() {
return;
}
crate::infer::ast_walk::for_each_stmt_child(
stmt,
&mut |s| Self::scan_stmt_for_this(s, found),
&mut |e| Self::scan_expr_for_this(e, found),
&mut |vd| {
crate::infer::ast_walk::for_each_var_decl_init(vd, &mut |init| {
Self::scan_expr_for_this(init, found);
});
},
);
}
fn scan_expr_for_this(expr: &Expression, found: &Cell<bool>) {
if found.get() {
return;
}
if matches!(expr, Expression::ThisExpression(_)) {
found.set(true);
return;
}
crate::infer::ast_walk::for_each_expr_child(
expr,
&mut |e| Self::scan_expr_for_this(e, found),
&mut |_| {}, // on_ident: not relevant
&mut |_| {}, // on_target: not relevant
&mut |_| {}, // on_simple_target: not relevant
&mut |_, _| {}, // on_fn_scope: stop — nested fn has its own this
);
}
}