1use oxc_ast::ast::*;
5use std::cell::{Cell, RefCell};
6use std::collections::HashSet;
7
8use crate::types::ZigType;
9use crate::zigir::types::{IrBlock, IrParam};
10
11use super::Lowerer;
12
13impl Lowerer {
18 pub(super) fn lower_closure_structs(&self) -> Vec<crate::zigir::types::IrClosureStruct> {
27 self.closure_mgr
28 .closure_vars
29 .iter()
30 .map(|(struct_name, captured)| {
31 let ir_captures = self.make_ir_captures(
32 captured
33 .iter()
34 .map(|(name, zig_type, is_mut)| (name.clone(), zig_type.clone(), *is_mut))
35 .collect(),
36 );
37 crate::zigir::types::IrClosureStruct {
38 name: self.make_ident(struct_name),
39 captured: ir_captures,
40 fn_params: vec![], return_type: ZigType::Void,
42 typeof_return_body: None,
43 body: IrBlock::new(vec![]),
44 }
45 })
46 .collect()
47 }
48}
49
50impl Lowerer {
55 pub(super) fn collect_arrow_captures(
60 &self,
61 arrow: &ArrowFunctionExpression,
62 ) -> Vec<(String, ZigType, bool)> {
63 let param_names = Self::collect_param_names(&arrow.params.items);
64 self.collect_captures_from_body(¶m_names, &arrow.body.statements, true)
65 }
66
67 pub(super) fn detect_fn_body_captures(&self, fd: &Function) -> Vec<(String, ZigType, bool)> {
72 let param_names = Self::collect_param_names(&fd.params.items);
73 fd.body
74 .as_ref()
75 .map(|body| self.collect_captures_from_body(¶m_names, &body.statements, true))
76 .unwrap_or_default()
77 }
78
79 fn collect_param_names(params: &oxc_allocator::Vec<'_, FormalParameter>) -> HashSet<String> {
81 params
82 .iter()
83 .filter_map(|p| crate::infer::binding_name(&p.pattern))
84 .map(|s| s.to_string())
85 .collect()
86 }
87
88 fn collect_captures_from_body(
90 &self,
91 param_names: &HashSet<String>,
92 stmts: &oxc_allocator::Vec<'_, Statement>,
93 include_local_decls: bool,
94 ) -> Vec<(String, ZigType, bool)> {
95 let captured = RefCell::new(Vec::new());
96 let seen = RefCell::new(HashSet::new());
97
98 let mut local_names = param_names.clone();
99 if include_local_decls {
100 local_names.extend(Self::collect_local_declarations(stmts));
101 }
102
103 for stmt in stmts {
104 Self::collect_idents_from_stmt(stmt, &captured, &seen, &local_names, &self.type_info);
105 }
106
107 let mut captured = captured.into_inner();
108 let mutated = Self::detect_mutated_vars_in_stmts(stmts);
109 for (name, _ztype, is_mut) in &mut captured {
110 *is_mut = mutated.contains(name);
111 }
112
113 captured
114 }
115
116 pub(super) fn collect_local_declarations(
121 stmts: &oxc_allocator::Vec<'_, Statement>,
122 ) -> HashSet<String> {
123 let names = RefCell::new(HashSet::new());
124 for stmt in stmts {
125 Self::collect_local_decls_from_stmt(stmt, &names);
126 }
127 names.into_inner()
128 }
129
130 fn collect_local_decls_from_stmt(stmt: &Statement, names: &RefCell<HashSet<String>>) {
131 crate::infer::ast_walk::for_each_stmt_child(
132 stmt,
133 &mut |s| Self::collect_local_decls_from_stmt(s, names),
134 &mut |_| {}, &mut |vd| {
136 for decl in &vd.declarations {
137 if let Some(name) = crate::infer::binding_name(&decl.id) {
138 names.borrow_mut().insert(name.to_string());
139 }
140 }
141 },
142 );
143 }
144
145 pub(super) fn detect_mutated_vars_in_stmts(stmts: &[Statement]) -> HashSet<String> {
147 let mutated = RefCell::new(HashSet::new());
148 for stmt in stmts {
149 Self::detect_mutated_in_stmt(stmt, &mutated);
150 }
151 mutated.into_inner()
152 }
153
154 pub(super) fn detect_mutated_in_stmt(stmt: &Statement, mutated: &RefCell<HashSet<String>>) {
155 crate::infer::ast_walk::for_each_stmt_child(
156 stmt,
157 &mut |s| Self::detect_mutated_in_stmt(s, mutated),
158 &mut |e| Self::detect_mutated_in_expr(e, mutated),
159 &mut |_vd| {
160 },
162 );
163 }
164
165 pub(super) fn detect_mutated_in_expr(expr: &Expression, mutated: &RefCell<HashSet<String>>) {
166 crate::infer::ast_walk::for_each_expr_child(
167 expr,
168 &mut |e| Self::detect_mutated_in_expr(e, mutated),
169 &mut |_| {}, &mut |target| {
171 if let AssignmentTarget::AssignmentTargetIdentifier(id) = target {
173 mutated.borrow_mut().insert(id.name.to_string());
174 }
175 },
176 &mut |simple_target| {
177 if let SimpleAssignmentTarget::AssignmentTargetIdentifier(id) = simple_target {
179 mutated.borrow_mut().insert(id.name.to_string());
180 }
181 },
182 &mut |_params, _stmts| {
183 },
187 );
188 }
189
190 fn collect_idents_from_fn_body(
195 params: &[FormalParameter],
196 stmts: &oxc_allocator::Vec<'_, Statement>,
197 captured: &RefCell<Vec<(String, ZigType, bool)>>,
198 seen: &RefCell<HashSet<String>>,
199 local_names: &HashSet<String>,
200 type_info: &crate::infer::TypeCheckResult,
201 ) {
202 let mut inner_locals = local_names.clone();
203 for param in params {
204 if let Some(pname) = crate::infer::binding_name(¶m.pattern) {
205 inner_locals.insert(pname.to_string());
206 }
207 }
208 inner_locals.extend(Self::collect_local_declarations(stmts));
211
212 for stmt in stmts {
213 Self::collect_idents_from_stmt(stmt, captured, seen, &inner_locals, type_info);
214 }
215 }
216
217 pub(super) fn collect_idents_from_stmt(
224 stmt: &Statement,
225 captured: &RefCell<Vec<(String, ZigType, bool)>>,
226 seen: &RefCell<HashSet<String>>,
227 local_names: &HashSet<String>,
228 type_info: &crate::infer::TypeCheckResult,
229 ) {
230 crate::infer::ast_walk::for_each_stmt_child(
231 stmt,
232 &mut |s| Self::collect_idents_from_stmt(s, captured, seen, local_names, type_info),
233 &mut |e| Self::collect_idents_from_expr(e, captured, seen, local_names, type_info),
234 &mut |vd| {
235 crate::infer::ast_walk::for_each_var_decl_init(vd, &mut |init| {
236 Self::collect_idents_from_expr(init, captured, seen, local_names, type_info);
237 });
238 },
239 );
240 }
241
242 pub(super) fn collect_idents_from_expr(
249 expr: &Expression,
250 captured: &RefCell<Vec<(String, ZigType, bool)>>,
251 seen: &RefCell<HashSet<String>>,
252 local_names: &HashSet<String>,
253 type_info: &crate::infer::TypeCheckResult,
254 ) {
255 crate::infer::ast_walk::for_each_expr_child(
256 expr,
257 &mut |e| Self::collect_idents_from_expr(e, captured, seen, local_names, type_info),
258 &mut |name| {
259 Self::check_and_add_capture(name, captured, seen, local_names, type_info);
260 },
261 &mut |target| {
262 match target {
263 AssignmentTarget::AssignmentTargetIdentifier(id) => {
264 Self::check_and_add_capture(
265 id.name.as_str(),
266 captured,
267 seen,
268 local_names,
269 type_info,
270 );
271 }
272 AssignmentTarget::StaticMemberExpression(mem) => {
273 Self::collect_idents_from_expr(
274 &mem.object,
275 captured,
276 seen,
277 local_names,
278 type_info,
279 );
280 }
281 AssignmentTarget::ComputedMemberExpression(mem) => {
282 Self::collect_idents_from_expr(
283 &mem.object,
284 captured,
285 seen,
286 local_names,
287 type_info,
288 );
289 Self::collect_idents_from_expr(
290 &mem.expression,
291 captured,
292 seen,
293 local_names,
294 type_info,
295 );
296 }
297 AssignmentTarget::PrivateFieldExpression(pfe) => {
298 Self::collect_idents_from_expr(
299 &pfe.object,
300 captured,
301 seen,
302 local_names,
303 type_info,
304 );
305 }
306 _ => {} }
308 },
309 &mut |simple_target| match simple_target {
310 SimpleAssignmentTarget::AssignmentTargetIdentifier(id) => {
311 Self::check_and_add_capture(
312 id.name.as_str(),
313 captured,
314 seen,
315 local_names,
316 type_info,
317 );
318 }
319 SimpleAssignmentTarget::StaticMemberExpression(mem) => {
320 Self::collect_idents_from_expr(
321 &mem.object,
322 captured,
323 seen,
324 local_names,
325 type_info,
326 );
327 }
328 SimpleAssignmentTarget::ComputedMemberExpression(mem) => {
329 Self::collect_idents_from_expr(
330 &mem.object,
331 captured,
332 seen,
333 local_names,
334 type_info,
335 );
336 Self::collect_idents_from_expr(
337 &mem.expression,
338 captured,
339 seen,
340 local_names,
341 type_info,
342 );
343 }
344 SimpleAssignmentTarget::PrivateFieldExpression(pfe) => {
345 Self::collect_idents_from_expr(
346 &pfe.object,
347 captured,
348 seen,
349 local_names,
350 type_info,
351 );
352 }
353 _ => {}
354 },
355 &mut |params, stmts| {
356 Self::collect_idents_from_fn_body(
357 params,
358 stmts,
359 captured,
360 seen,
361 local_names,
362 type_info,
363 );
364 },
365 );
366 }
367
368 fn check_and_add_capture(
372 name: &str,
373 captured: &RefCell<Vec<(String, ZigType, bool)>>,
374 seen: &RefCell<HashSet<String>>,
375 local_names: &HashSet<String>,
376 type_info: &crate::infer::TypeCheckResult,
377 ) {
378 if !local_names.contains(name)
379 && !seen.borrow().contains(name)
380 && !crate::native_builtins::is_js_builtin_identifier(name)
381 {
382 seen.borrow_mut().insert(name.to_string());
383 let ztype = type_info
384 .var_types
385 .get(name)
386 .cloned()
387 .unwrap_or(ZigType::JsAny);
388 captured.borrow_mut().push((name.to_string(), ztype, false));
389 }
390 }
391
392 pub(super) fn lower_arrow_params(&mut self, arrow: &ArrowFunctionExpression) -> Vec<IrParam> {
394 let mut params = Vec::new();
395 for param in &arrow.params.items {
396 if let Some(pname) = crate::infer::binding_name(¶m.pattern) {
397 let ptype = self
398 .type_info
399 .var_types
400 .get(pname)
401 .cloned()
402 .unwrap_or(ZigType::Anytype);
403 params.push(IrParam {
404 name: self.make_ident(pname),
405 zig_type: ptype,
406 is_unused: false,
407 is_rest: false,
408 });
409 }
410 }
411 params
412 }
413
414 pub(super) fn find_first_return_expr_in_block(
417 block: &IrBlock,
418 ) -> Option<&crate::zigir::types::IrExpr> {
419 for stmt in &block.stmts {
420 if let Some(expr) = Self::find_first_return_expr_in_stmt(stmt) {
421 return Some(expr);
422 }
423 }
424 None
425 }
426
427 pub(super) fn find_first_return_expr_in_stmt(
428 stmt: &crate::zigir::types::IrStmt,
429 ) -> Option<&crate::zigir::types::IrExpr> {
430 match stmt {
431 crate::zigir::types::IrStmt::Return { value, .. } => value.as_ref(),
432 crate::zigir::types::IrStmt::If { then, else_, .. } => {
433 Self::find_first_return_expr_in_block(then).or_else(|| {
434 else_
435 .as_ref()
436 .and_then(Self::find_first_return_expr_in_block)
437 })
438 }
439 crate::zigir::types::IrStmt::Block(b) => Self::find_first_return_expr_in_block(b),
440 _ => None,
441 }
442 }
443
444 fn scan_return_type_from_stmts(
446 &self,
447 stmts: &[Statement],
448 captured: &[(String, ZigType, bool)],
449 default_type: ZigType,
450 ) -> ZigType {
451 for stmt in stmts {
452 if let Statement::ReturnStatement(rs) = stmt {
453 if let Some(ref arg) = rs.argument {
454 return self
455 .infer_arrow_expr_type_with_captures(arg, captured)
456 .unwrap_or(default_type);
457 }
458 return ZigType::Void;
459 }
460 }
461 ZigType::Void
462 }
463
464 pub(super) fn infer_arrow_return_type(
466 &self,
467 arrow: &ArrowFunctionExpression,
468 captured: &[(String, ZigType, bool)],
469 ) -> ZigType {
470 if arrow.expression
474 && arrow.body.statements.len() == 1
475 && let Statement::ExpressionStatement(es) = &arrow.body.statements[0]
476 {
477 return self
478 .infer_arrow_expr_type_with_captures(&es.expression, captured)
479 .unwrap_or(ZigType::JsAny);
480 }
481 self.scan_return_type_from_stmts(&arrow.body.statements, captured, ZigType::JsAny)
482 }
483
484 pub(super) fn infer_fn_expr_return_type(
486 &self,
487 fe: &Function,
488 captured: &[(String, ZigType, bool)],
489 ) -> ZigType {
490 fe.body
491 .as_ref()
492 .map(|body| self.scan_return_type_from_stmts(&body.statements, captured, ZigType::Void))
493 .unwrap_or(ZigType::Void)
494 }
495
496 pub(super) fn infer_arrow_expr_type_with_captures(
501 &self,
502 expr: &Expression,
503 captured: &[(String, ZigType, bool)],
504 ) -> Option<ZigType> {
505 match expr {
506 Expression::NumericLiteral(nl) => {
507 if let Some(raw) = &nl.raw {
508 let s = raw.as_str();
509 if s.contains('.') || s.contains('e') || s.contains('E') {
510 Some(ZigType::F64)
511 } else {
512 Some(ZigType::I64)
513 }
514 } else {
515 Some(ZigType::I64)
516 }
517 }
518 Expression::StringLiteral(_) => Some(ZigType::Str),
519 Expression::BooleanLiteral(_) => Some(ZigType::Bool),
520 Expression::Identifier(id) => {
521 if let Some(ty) = self.infer_ident_type(id.name.as_str()) {
523 return Some(ty);
524 }
525 for (name, ty, _is_mut) in captured {
527 if name == id.name.as_str() {
528 return Some(ty.clone());
529 }
530 }
531 None
532 }
533 Expression::BinaryExpression(be) => self
534 .infer_arrow_expr_type_with_captures(&be.left, captured)
535 .or_else(|| self.infer_arrow_expr_type_with_captures(&be.right, captured)),
536 Expression::UnaryExpression(ue) => {
537 self.infer_arrow_expr_type_with_captures(&ue.argument, captured)
538 }
539 Expression::CallExpression(ce) => {
540 match &ce.callee {
541 Expression::Identifier(id) => self
542 .type_info
543 .fn_return_types
544 .get(id.name.as_str())
545 .cloned(),
546 Expression::FunctionExpression(fe) => fe.body.as_ref().map(|body| {
548 self.scan_return_type_from_stmts(&body.statements, captured, ZigType::Void)
549 }),
550 Expression::ArrowFunctionExpression(af) => {
551 Some(self.infer_arrow_return_type(af, captured))
552 }
553 _ => None,
554 }
555 }
556 Expression::StaticMemberExpression(sme) => {
557 let field = sme.property.name.as_str();
558 match field {
559 "length" | "len" => Some(ZigType::I64),
560 _ => None,
561 }
562 }
563 Expression::ConditionalExpression(ce) => self
564 .infer_arrow_expr_type_with_captures(&ce.consequent, captured)
565 .or_else(|| self.infer_arrow_expr_type_with_captures(&ce.alternate, captured)),
566 _ => None,
567 }
568 }
569
570 pub(super) fn detect_this_in_body(stmts: &[Statement]) -> bool {
580 let found = Cell::new(false);
581 for stmt in stmts {
582 Self::scan_stmt_for_this(stmt, &found);
583 if found.get() {
584 return true;
585 }
586 }
587 false
588 }
589
590 fn scan_stmt_for_this(stmt: &Statement, found: &Cell<bool>) {
591 if found.get() {
592 return;
593 }
594 crate::infer::ast_walk::for_each_stmt_child(
595 stmt,
596 &mut |s| Self::scan_stmt_for_this(s, found),
597 &mut |e| Self::scan_expr_for_this(e, found),
598 &mut |vd| {
599 crate::infer::ast_walk::for_each_var_decl_init(vd, &mut |init| {
600 Self::scan_expr_for_this(init, found);
601 });
602 },
603 );
604 }
605
606 fn scan_expr_for_this(expr: &Expression, found: &Cell<bool>) {
607 if found.get() {
608 return;
609 }
610 if matches!(expr, Expression::ThisExpression(_)) {
611 found.set(true);
612 return;
613 }
614 crate::infer::ast_walk::for_each_expr_child(
615 expr,
616 &mut |e| Self::scan_expr_for_this(e, found),
617 &mut |_| {}, &mut |_| {}, &mut |_| {}, &mut |_, _| {}, );
622 }
623}