1use oxc_ast::ast::*;
5
6use crate::types::ZigType;
7use crate::zigir::ident::IrIdent;
8use crate::zigir::types::IrBlock;
9
10use super::Lowerer;
11
12impl Lowerer {
13 fn enter_closure_context(
18 &mut self,
19 name: &str,
20 return_type: ZigType,
21 captured: &[(String, ZigType, bool)],
22 ) -> (
23 Option<crate::zigir::lower::helpers::FnContext>,
24 Vec<(String, ZigType, bool)>,
25 ) {
26 let saved_fn = self.enter_fn(name, false, Some(return_type));
27 let saved_captured = self.closure_mgr.take_captured();
28 self.closure_mgr.current_captured = captured
29 .iter()
30 .map(|(n, t, m)| (n.clone(), t.clone(), *m))
31 .collect();
32 (saved_fn, saved_captured)
33 }
34
35 fn exit_closure_context(
37 &mut self,
38 body: &mut IrBlock,
39 saved_fn: Option<crate::zigir::lower::helpers::FnContext>,
40 saved_captured: Vec<(String, ZigType, bool)>,
41 ) {
42 Self::clear_deinit_for_returned_vars(body);
43 self.closure_mgr.restore_captured(saved_captured);
44 self.exit_fn(saved_fn);
45 }
46
47 fn build_closure_expr(
58 &mut self,
59 captured: Vec<(String, ZigType, bool)>,
60 params: Vec<crate::zigir::types::IrParam>,
61 return_type: ZigType,
62 body: IrBlock,
63 struct_name: IrIdent,
64 instance_name: IrIdent,
65 ) -> crate::zigir::types::IrExpr {
66 use crate::zigir::types::{IrClosure, IrExpr};
67
68 let ir_captures = self.make_ir_captures(captured.clone().into_iter().collect());
69
70 self.closure_mgr
71 .closure_instances
72 .insert(instance_name.zig_name.clone());
73
74 let mut body = body;
75
76 let nested = self.detect_nested_captures(&captured);
79
80 let own_capture_names: Vec<String> = ir_captures
85 .iter()
86 .map(|c| c.name.zig_name.clone())
87 .collect();
88 let overlap = Self::find_nested_closure_capture_overlap(&body, &own_capture_names);
89
90 if !nested.is_empty() || !overlap.is_empty() {
91 let mut parts = Vec::new();
92 if !nested.is_empty() {
93 parts.push(format!(
94 "variable(s) {} captured from enclosing closure",
95 nested.join(", ")
96 ));
97 }
98 if !overlap.is_empty() {
99 parts.push(format!(
100 "nested closure init uses own captured field(s) {}",
101 overlap.join(", ")
102 ));
103 }
104 let msg = format!(
105 "nested closure capture is not supported: {}",
106 parts.join("; ")
107 );
108 body.stmts.insert(
109 0,
110 crate::zigir::types::IrStmt::CompileError {
111 span: crate::zigir::source_span::SourceSpan::default(),
112 msg,
113 },
114 );
115 }
116
117 self.pending_arrow_structs
118 .push(crate::zigir::types::IrClosureStruct {
119 name: struct_name.clone(),
120 captured: ir_captures.clone(),
121 fn_params: params.clone(),
122 return_type: return_type.clone(),
123 typeof_return_body: None,
124 body: body.clone(),
125 });
126
127 IrExpr::Closure(IrClosure {
128 struct_name,
129 captured: ir_captures,
130 fn_params: params,
131 return_type,
132 body,
133 instance_name,
134 })
135 }
136
137 fn find_nested_closure_capture_overlap(
141 block: &IrBlock,
142 own_capture_names: &[String],
143 ) -> Vec<String> {
144 let mut overlap = std::collections::HashSet::new();
145 for stmt in &block.stmts {
146 Self::scan_stmt_for_closure_overlap(stmt, own_capture_names, &mut overlap);
147 }
148 let mut result: Vec<String> = overlap.into_iter().collect();
149 result.sort();
150 result
151 }
152
153 fn scan_stmt_for_closure_overlap(
154 stmt: &crate::zigir::types::IrStmt,
155 own: &[String],
156 overlap: &mut std::collections::HashSet<String>,
157 ) {
158 use crate::zigir::types::IrStmt;
159 match stmt {
160 IrStmt::Expr(expr) | IrStmt::Return { value: Some(expr) } => {
161 Self::scan_expr_for_closure_overlap(expr, own, overlap);
162 }
163 IrStmt::VarDecl(vd) => {
164 if let Some(init) = &vd.init {
165 Self::scan_expr_for_closure_overlap(init, own, overlap);
166 }
167 }
168 IrStmt::Assign { value, .. } => {
169 Self::scan_expr_for_closure_overlap(value, own, overlap);
170 }
171 IrStmt::If { then, else_, .. } => {
172 for s in &then.stmts {
173 Self::scan_stmt_for_closure_overlap(s, own, overlap);
174 }
175 if let Some(eb) = else_ {
176 for s in &eb.stmts {
177 Self::scan_stmt_for_closure_overlap(s, own, overlap);
178 }
179 }
180 }
181 IrStmt::Block(inner) => {
182 for s in &inner.stmts {
183 Self::scan_stmt_for_closure_overlap(s, own, overlap);
184 }
185 }
186 IrStmt::While { body, .. } | IrStmt::DoWhile { body, .. } => {
187 for s in &body.stmts {
188 Self::scan_stmt_for_closure_overlap(s, own, overlap);
189 }
190 }
191 IrStmt::For { body, .. } | IrStmt::ForOf { body, .. } => {
192 for s in &body.stmts {
193 Self::scan_stmt_for_closure_overlap(s, own, overlap);
194 }
195 }
196 IrStmt::Switch { cases, .. } => {
197 for case in cases {
198 for s in &case.body {
199 Self::scan_stmt_for_closure_overlap(s, own, overlap);
200 }
201 }
202 }
203 IrStmt::Try {
204 try_block,
205 catch_block,
206 finally,
207 ..
208 } => {
209 for s in &try_block.stmts {
210 Self::scan_stmt_for_closure_overlap(s, own, overlap);
211 }
212 for s in &catch_block.stmts {
213 Self::scan_stmt_for_closure_overlap(s, own, overlap);
214 }
215 if let Some(fb) = finally {
216 for s in &fb.stmts {
217 Self::scan_stmt_for_closure_overlap(s, own, overlap);
218 }
219 }
220 }
221 IrStmt::NestedFnDecl { .. } => {
222 if let IrStmt::NestedFnDecl {
224 instance: Some(cl), ..
225 } = stmt
226 {
227 for cap in &cl.captured {
228 if own.contains(&cap.name.zig_name) {
229 overlap.insert(cap.name.zig_name.clone());
230 }
231 }
232 }
233 }
234 _ => {}
236 }
237 }
238
239 fn scan_expr_for_closure_overlap(
240 expr: &crate::zigir::types::IrExpr,
241 own: &[String],
242 overlap: &mut std::collections::HashSet<String>,
243 ) {
244 use crate::zigir::types::IrExpr;
245 match expr {
246 IrExpr::Closure(c) => {
247 for cap in &c.captured {
248 if own.contains(&cap.name.zig_name) {
249 overlap.insert(cap.name.zig_name.clone());
250 }
251 }
252 for stmt in &c.body.stmts {
254 Self::scan_stmt_for_closure_overlap(stmt, own, overlap);
255 }
256 }
257 IrExpr::Binary { left, right, .. } => {
258 Self::scan_expr_for_closure_overlap(left, own, overlap);
259 Self::scan_expr_for_closure_overlap(right, own, overlap);
260 }
261 IrExpr::Call(call) => {
262 Self::scan_expr_for_closure_overlap(&call.callee, own, overlap);
263 for arg in &call.args {
264 Self::scan_expr_for_closure_overlap(arg, own, overlap);
265 }
266 }
267 IrExpr::FieldAccess { object, .. } | IrExpr::IndexAccess { object, .. } => {
268 Self::scan_expr_for_closure_overlap(object, own, overlap);
269 }
270 IrExpr::ArrowFn(af) => {
271 for stmt in &af.body.stmts {
272 Self::scan_stmt_for_closure_overlap(stmt, own, overlap);
273 }
274 }
275 IrExpr::FnExpr(fe) => {
276 for stmt in &fe.body.stmts {
277 Self::scan_stmt_for_closure_overlap(stmt, own, overlap);
278 }
279 }
280 IrExpr::ArrayLiteral(arr) => {
281 for el in &arr.elements {
282 Self::scan_expr_for_closure_overlap(el, own, overlap);
283 }
284 }
285 IrExpr::Conditional { cond, then, else_ } => {
286 Self::scan_expr_for_closure_overlap(cond, own, overlap);
287 Self::scan_expr_for_closure_overlap(then, own, overlap);
288 Self::scan_expr_for_closure_overlap(else_, own, overlap);
289 }
290 IrExpr::Paren(inner)
291 | IrExpr::Spread(inner)
292 | IrExpr::Typeof(inner)
293 | IrExpr::Void(inner) => {
294 Self::scan_expr_for_closure_overlap(inner, own, overlap);
295 }
296 IrExpr::Unary { operand, .. } => {
297 Self::scan_expr_for_closure_overlap(operand, own, overlap);
298 }
299 IrExpr::Logical { left, right, .. } => {
301 Self::scan_expr_for_closure_overlap(left, own, overlap);
302 Self::scan_expr_for_closure_overlap(right, own, overlap);
303 }
304 IrExpr::ObjectLiteral(obj) => {
305 for item in &obj.items {
306 match item {
307 crate::zigir::types::IrObjectItem::Field(f) => {
308 Self::scan_expr_for_closure_overlap(&f.value, own, overlap);
309 }
310 crate::zigir::types::IrObjectItem::Spread(expr) => {
311 Self::scan_expr_for_closure_overlap(expr, own, overlap);
312 }
313 }
314 }
315 }
316 IrExpr::TemplateLiteral { exprs, .. } => {
317 for e in exprs {
318 Self::scan_expr_for_closure_overlap(e, own, overlap);
319 }
320 }
321 IrExpr::BlockExpr { body, result, .. } => {
322 for stmt in body {
323 Self::scan_stmt_for_closure_overlap(stmt, own, overlap);
324 }
325 Self::scan_expr_for_closure_overlap(result, own, overlap);
326 }
327 _ => {}
329 }
330 }
331
332 pub(super) fn lower_arrow_fn(
339 &mut self,
340 af: &ArrowFunctionExpression,
341 ) -> crate::zigir::types::IrExpr {
342 use crate::zigir::types::{IrArrowFn, IrExpr};
343
344 let mut captured = self.collect_arrow_captures(af);
345
346 let captures_this = self.current_class.is_some()
355 && self.this_rewrite_fields.is_none()
356 && Self::detect_this_in_body(&af.body.statements);
357 if captures_this && let Some(class_name) = self.current_class.clone() {
358 captured.insert(
359 0,
360 ("__self".to_string(), ZigType::NamedStruct(class_name), true),
361 );
362 }
363
364 let is_concise = af.expression;
365 let return_type = self.infer_arrow_return_type(af, &captured);
366 let params = self.lower_arrow_params(af);
367 let arrow_fn_label = format!("_arrow_{}", self.name_mangler.next_name("arrow"));
368
369 let saved_closure_with_this = self.in_closure_with_this;
371 if captures_this {
372 self.in_closure_with_this = true;
373 }
374
375 let (saved_fn, saved_captured) =
377 self.enter_closure_context(&arrow_fn_label, return_type.clone(), &captured);
378
379 let mut body = if is_concise {
381 if let Statement::ExpressionStatement(es) = &af.body.statements[0] {
382 let expr_ir = self.lower_expr(&es.expression);
383 IrBlock::new(vec![crate::zigir::types::IrStmt::Return {
384 value: Some(expr_ir),
385 }])
386 } else {
387 self.lower_block(&af.body.statements)
388 }
389 } else {
390 self.lower_block(&af.body.statements)
391 };
392
393 self.exit_closure_context(&mut body, saved_fn, saved_captured);
394 self.in_closure_with_this = saved_closure_with_this;
395
396 if !captured.is_empty() {
397 let idx = self.name_mangler.peek_count("closure");
398 let struct_name = IrIdent::new(&format!("Closure_{}", idx));
399 let instance_name = IrIdent::new(&format!("_cl_{}", idx));
400 self.name_mangler.next_name("closure");
401
402 self.build_closure_expr(
403 captured,
404 params,
405 return_type,
406 body,
407 struct_name,
408 instance_name,
409 )
410 } else {
411 IrExpr::ArrowFn(IrArrowFn {
412 params,
413 return_type,
414 body,
415 is_concise,
416 })
417 }
418 }
419
420 pub(super) fn lower_fn_expr(&mut self, fe: &Function) -> crate::zigir::types::IrExpr {
425 use crate::zigir::types::{IrExpr, IrFnExpr};
426
427 let name = fe
428 .id
429 .as_ref()
430 .map(|id| id.name.to_string())
431 .unwrap_or_else(|| {
432 let idx = self.name_mangler.peek_count("_fn_expr");
433 self.name_mangler.next_name("_fn_expr");
434 format!("_fn_expr_{}", idx)
435 });
436
437 let mut captured = self.detect_fn_body_captures(fe);
438
439 let captures_this = if let Some(body) = &fe.body {
443 self.current_class.is_some()
444 && self.this_rewrite_fields.is_none()
445 && Self::detect_this_in_body(&body.statements)
446 } else {
447 false
448 };
449 if captures_this && let Some(class_name) = self.current_class.clone() {
450 captured.insert(
451 0,
452 ("__self".to_string(), ZigType::NamedStruct(class_name), true),
453 );
454 }
455
456 let return_type = self
457 .type_info
458 .fn_return_types
459 .get(&name)
460 .cloned()
461 .unwrap_or_else(|| self.infer_fn_expr_return_type(fe, &captured));
462
463 let params = self.lower_fn_params(fe, &name);
464
465 let saved_closure_with_this = self.in_closure_with_this;
467 if captures_this {
468 self.in_closure_with_this = true;
469 }
470
471 let (saved_fn, saved_captured) =
473 self.enter_closure_context(&name, return_type.clone(), &captured);
474
475 let mut body = fe
477 .body
478 .as_ref()
479 .map(|b| self.lower_block(&b.statements))
480 .unwrap_or_else(|| IrBlock::new(vec![]));
481
482 self.exit_closure_context(&mut body, saved_fn, saved_captured);
483 self.in_closure_with_this = saved_closure_with_this;
484
485 if !captured.is_empty() {
486 let struct_name = self.make_ident(&name);
487 let instance_name = IrIdent::new(&format!("_{}_inst", name));
488 self.build_closure_expr(
489 captured,
490 params,
491 return_type,
492 body,
493 struct_name,
494 instance_name,
495 )
496 } else {
497 let struct_name = self.make_ident(&name);
501 self.pending_arrow_structs
502 .push(crate::zigir::types::IrClosureStruct {
503 name: struct_name.clone(),
504 captured: vec![],
505 fn_params: params.clone(),
506 return_type: return_type.clone(),
507 typeof_return_body: None,
508 body: body.clone(),
509 });
510
511 IrExpr::FnExpr(IrFnExpr {
512 name: Some(self.make_ident(&name)),
513 params,
514 return_type,
515 body,
516 })
517 }
518 }
519}