1use oxc_ast::ast::*;
5
6use crate::types::ZigType;
7use crate::zigir::ident::IrIdent;
8use crate::zigir::source_span::SourceSpan;
9use crate::zigir::types::{IrBlock, IrDecl, IrParam, IrVarDecl};
10
11use super::Lowerer;
12use super::cabi::{init_may_have_side_effects, property_key_name};
13use super::helpers::FnContext;
14
15fn binding_name_and_default<'a>(pattern: &'a BindingPattern<'a>) -> Option<(&'a str, bool)> {
19 match pattern {
20 BindingPattern::BindingIdentifier(id) => Some((id.name.as_str(), false)),
21 BindingPattern::AssignmentPattern(ap) => {
22 let name = crate::infer::binding_name(&ap.left)?;
23 Some((name, true))
24 }
25 _ => None,
26 }
27}
28
29struct FnBodyScope {
34 saved: Option<FnContext>,
35 params: Vec<IrParam>,
36 body: IrBlock,
37}
38
39impl Lowerer {
40 fn fn_prefix(&self) -> &str {
45 self.fn_ctx
46 .as_ref()
47 .map(|ctx| ctx.name.as_str())
48 .unwrap_or("__toplevel__")
49 }
50
51 fn qualified_var_key(&self, var_name: &str) -> String {
52 format!("{}::{}", self.fn_prefix(), var_name)
53 }
54
55 fn lookup_fn_return_type(&self, name: &str) -> ZigType {
56 self.type_info
57 .fn_return_types
58 .get(name)
59 .cloned()
60 .unwrap_or(ZigType::Void)
61 }
62
63 fn is_var_mutated(&self, var_name: &str) -> bool {
64 self.type_info
65 .mutated_vars
66 .contains(&self.qualified_var_key(var_name))
67 }
68
69 fn is_var_reassigned(&self, var_name: &str) -> bool {
70 self.type_info
71 .reassigned_vars
72 .contains(&self.qualified_var_key(var_name))
73 }
74
75 fn should_skip_toplevel_binding(&self, bind_name: &str, is_const: bool) -> bool {
78 if self.fn_ctx.is_none() && is_const && !self.type_info.used_names.contains(bind_name) {
79 return true;
80 }
81 if self.fn_ctx.is_none() && !is_const {
82 return true;
83 }
84 false
85 }
86
87 fn init_expr_type(&self, init_expr: &Expression) -> Option<ZigType> {
89 if let Expression::Identifier(id) = init_expr {
90 self.type_info.var_types.get(id.name.as_str()).cloned()
91 } else {
92 None
93 }
94 }
95
96 fn compute_destructure_source(
100 &mut self,
101 needs_temp: bool,
102 temp_name: &str,
103 init_expr: &Expression,
104 ) -> String {
105 if needs_temp {
106 temp_name.to_string()
107 } else if let Expression::Identifier(id) = init_expr {
108 id.name.to_string()
109 } else {
110 self.name_mangler.next_name("_js_dest")
111 }
112 }
113
114 fn resolve_typeof_return_body(
117 return_type: &ZigType,
118 body: &IrBlock,
119 ) -> Option<Box<crate::zigir::types::IrExpr>> {
120 if matches!(return_type, ZigType::AnytypeReturn) {
121 Self::find_first_return_expr_in_block(body).map(|e| Box::new(e.clone()))
122 } else {
123 None
124 }
125 }
126
127 fn enter_fn_body(
134 &mut self,
135 fd: &Function,
136 fn_name: &str,
137 is_export: bool,
138 return_type: &ZigType,
139 ) -> FnBodyScope {
140 let saved = self.enter_fn(fn_name, is_export, Some(return_type.clone()));
141 self.name_mangler.push_shadow_scope();
142
143 let params = self.lower_fn_params(fd, fn_name);
144
145 if let Some(ctx) = self.fn_ctx.as_mut() {
147 for param in ¶ms {
148 ctx.add_scope_var(¶m.name.js_name);
149 }
150 }
151
152 let body = fd
153 .body
154 .as_ref()
155 .map(|b| self.lower_block(&b.statements))
156 .unwrap_or_else(|| IrBlock::new(vec![]));
157
158 FnBodyScope {
159 saved,
160 params,
161 body,
162 }
163 }
164
165 fn exit_fn_body(
168 &mut self,
169 scope: FnBodyScope,
170 return_type: &ZigType,
171 ) -> (
172 Vec<IrParam>,
173 IrBlock,
174 Option<Box<crate::zigir::types::IrExpr>>,
175 ) {
176 let FnBodyScope {
177 saved,
178 params,
179 mut body,
180 } = scope;
181
182 Self::clear_deinit_for_returned_vars(&mut body);
183
184 self.name_mangler.pop_shadow_scope();
185 let _fn_ctx = self.exit_fn(saved);
186
187 let typeof_return_body = Self::resolve_typeof_return_body(return_type, &body);
188
189 (params, body, typeof_return_body)
190 }
191
192 pub(super) fn lower_var_decl(
201 &mut self,
202 decl: &VariableDeclarator,
203 _vd_is_const: bool,
204 ) -> IrDecl {
205 let js_name = match crate::infer::binding_name(&decl.id) {
206 Some(n) => n,
207 None => {
208 return IrDecl::CompileError {
209 span: SourceSpan::default(),
210 msg: "unsupported binding pattern in variable declaration".to_string(),
211 };
212 }
213 };
214
215 let ident = if let Some(ctx) = self.fn_ctx.as_ref() {
221 if ctx.fn_scope_vars.contains(js_name) {
222 let shadow_zig_name = format!(
224 "{}_shadow_{}",
225 js_name,
226 self.name_mangler.next_name("shadow")
227 );
228 self.name_mangler.record_shadow(js_name, shadow_zig_name);
229 if let Some(ctx) = self.fn_ctx.as_mut() {
231 ctx.add_scope_var(js_name);
232 }
233 IrIdent::with_zig_name(js_name, self.name_mangler.resolve_name(js_name))
234 } else {
235 if let Some(ctx) = self.fn_ctx.as_mut() {
237 ctx.add_scope_var(js_name);
238 }
239 self.make_ident(js_name)
240 }
241 } else {
242 self.make_ident(js_name)
243 };
244
245 let is_actually_mutated = self.is_var_mutated(js_name);
248 let is_directly_reassigned = self.is_var_reassigned(js_name);
251 let is_const = !is_actually_mutated;
252
253 if _vd_is_const
258 && is_directly_reassigned
259 && let Some(ctx) = self.fn_ctx.as_mut()
260 {
261 ctx.js_const_reassigned.insert(js_name.to_string());
262 }
263
264 let is_js_const_reassigned = _vd_is_const && is_directly_reassigned;
271
272 let has_type_annotation = self.jsdoc_data.type_annotations.contains_key(js_name);
274 if self.fn_ctx.is_none()
275 && is_const
276 && !self.type_info.used_names.contains(js_name)
277 && !has_type_annotation
278 {
279 return IrDecl::CompileError {
280 span: SourceSpan::default(),
281 msg: format!("skipped unused toplevel const: {}", js_name),
282 };
283 }
284
285 if self.fn_ctx.is_none() && !is_const {
287 return IrDecl::CompileError {
288 span: SourceSpan::default(),
289 msg: format!("toplevel only allows 'const', not '{}'", js_name),
290 };
291 }
292
293 let is_const = if let Some(inferred_ty) = self.type_info.var_types.get(js_name) {
295 match inferred_ty {
296 ZigType::ArrayList(_) => false,
297 ZigType::NamedStruct(n) if n == "Map" || n == "Set" => false,
298 ZigType::BigInt => false,
299 _ => is_const,
300 }
301 } else {
302 is_const
303 };
304
305 let zig_type = self.type_info.var_types.get(js_name).cloned();
307
308 let local_type: Option<ZigType> = if let Some(init_expr) = &decl.init {
313 self.infer_expr_type(init_expr).or(zig_type.clone())
314 } else {
315 zig_type.clone()
316 };
317 if let Some(ty) = local_type {
318 self.fn_ctx
319 .as_mut()
320 .map(|ctx| ctx.fn_local_types.insert(js_name.to_string(), ty));
321 }
322
323 let is_json_parse = self.type_info.has_json_parse_types.contains(js_name);
325
326 let needs_var_suppression = (!is_const
331 && matches!(
332 zig_type,
333 Some(ZigType::ArrayList(_)) | Some(ZigType::NamedStruct(_))
334 ))
335 || is_js_const_reassigned;
336
337 let init = match decl.init.as_ref() {
339 Some(expr) => {
340 let ir = self.lower_expr(expr);
348 match ir {
349 crate::zigir::types::IrExpr::ArrowFn(ref arrow) => {
350 let idx = self.name_mangler.peek_count("arrow_fn");
353 self.name_mangler.next_name("arrow_fn"); let struct_name = format!("_arrow_fn_{}", idx);
355 let struct_ident = IrIdent::new(&struct_name);
356 self.pending_arrow_structs
358 .push(crate::zigir::types::IrClosureStruct {
359 name: struct_ident.clone(),
360 captured: vec![],
361 fn_params: arrow.params.clone(),
362 return_type: arrow.return_type.clone(),
363 typeof_return_body: None,
364 body: arrow.body.clone(),
365 });
366 Some(crate::zigir::types::IrExpr::Ident(struct_ident))
367 }
368 crate::zigir::types::IrExpr::Closure(ref closure) => {
369 Some(crate::zigir::types::IrExpr::Closure(closure.clone()))
372 }
373 _ => Some(ir),
374 }
375 }
376 None => None,
377 };
378
379 if let Some(ZigType::NamedStruct(n)) = &zig_type
381 && let Some(suffix) = Self::typedarray_type_suffix(n)
382 && let Some(ctx) = self.fn_ctx.as_mut()
383 {
384 ctx.add_typedarray_var(&ident.zig_name, suffix);
385 }
386
387 if let Some(expr) = decl.init.as_ref()
389 && Self::is_regexp_expr(expr)
390 && let Some(ctx) = self.fn_ctx.as_mut()
391 {
392 ctx.add_regexp_var(&ident.zig_name);
393 }
394
395 let needs_deinit = matches!(
399 zig_type,
400 Some(ZigType::NamedStruct(ref n)) if n == "Map" || n == "Set"
401 ) || matches!(zig_type, Some(ZigType::BigInt));
402
403 IrDecl::Var(IrVarDecl {
404 name: ident,
405 is_const,
406 zig_type,
407 init,
408 is_json_parse,
409 needs_var_suppression,
410 needs_deinit,
411 })
412 }
413
414 pub(super) fn lower_destructure_decl(
420 &mut self,
421 decl: &VariableDeclarator,
422 ) -> crate::zigir::types::IrStmt {
423 use crate::zigir::types::{
424 IrDestructureAccess, IrDestructureBindingDecl, IrDestructureDecl, IrDestructureKind,
425 };
426
427 let Some(init_expr) = &decl.init else {
428 return crate::zigir::types::IrStmt::CompileError {
429 span: SourceSpan::default(),
430 msg: "destructuring requires an initializer".to_string(),
431 };
432 };
433
434 let init_ir = self.lower_expr(init_expr);
435
436 match &decl.id {
437 BindingPattern::ObjectPattern(op) => {
438 let init_type = self.init_expr_type(init_expr);
440
441 let struct_field_names: Option<Vec<String>> = match &init_type {
442 Some(ZigType::Struct(fields)) if !fields.is_empty() => {
443 Some(fields.iter().map(|(n, _)| n.clone()).collect())
444 }
445 _ => None,
446 };
447 let is_struct = struct_field_names.is_some();
448
449 let needs_temp = init_may_have_side_effects(init_expr) || op.properties.len() > 1;
451 let temp_name = self.name_mangler.next_name("_js_dest");
452
453 let source = self.compute_destructure_source(needs_temp, &temp_name, init_expr);
455
456 struct RawObjBinding {
458 key_name: String,
459 bind_name: String,
460 has_default: bool,
461 default_index: usize, is_struct_field: bool,
463 is_const: bool,
464 }
465 let mut raw_bindings: Vec<RawObjBinding> = Vec::new();
466 let mut default_counter: usize = 0;
467 for prop in &op.properties {
468 let key_name = match property_key_name(&prop.key) {
469 Some(k) => k,
470 None => continue,
471 };
472
473 let (bind_name, has_default) = match binding_name_and_default(&prop.value) {
474 Some(pair) => pair,
475 None => continue,
476 };
477
478 let is_const = !self.is_var_mutated(bind_name);
479
480 if self.should_skip_toplevel_binding(bind_name, is_const) {
481 default_counter += if has_default { 1 } else { 0 };
482 continue;
483 }
484
485 let is_struct_field = struct_field_names
486 .as_ref()
487 .is_some_and(|names| names.contains(&key_name));
488
489 let di = default_counter;
490 default_counter += if has_default { 1 } else { 0 };
491
492 raw_bindings.push(RawObjBinding {
493 key_name,
494 bind_name: bind_name.to_string(),
495 has_default,
496 default_index: di,
497 is_struct_field,
498 is_const,
499 });
500 }
501
502 let default_exprs: Vec<&Expression> = op
504 .properties
505 .iter()
506 .filter_map(|prop| match &prop.value {
507 BindingPattern::AssignmentPattern(ap) => Some(&ap.right),
508 _ => None,
509 })
510 .collect();
511
512 let mut bindings = Vec::new();
514 for rb in raw_bindings {
515 let default_ir = if rb.has_default {
516 default_exprs
517 .get(rb.default_index)
518 .map(|e| self.lower_expr(e))
519 } else {
520 None
521 };
522 bindings.push(IrDestructureBindingDecl {
523 name: self.make_ident(&rb.bind_name),
524 is_const: rb.is_const,
525 access: IrDestructureAccess::ObjectField {
526 source: if needs_temp {
527 temp_name.clone()
528 } else {
529 source.clone()
530 },
531 key: rb.key_name,
532 is_struct_field: rb.is_struct_field,
533 },
534 default: default_ir,
535 });
536 }
537
538 crate::zigir::types::IrStmt::DestructureDecl(IrDestructureDecl {
539 temp_name: if needs_temp {
540 Some(temp_name.clone())
541 } else {
542 None
543 },
544 init: init_ir,
545 kind: IrDestructureKind::Object {
546 is_struct,
547 struct_field_names,
548 },
549 bindings,
550 })
551 }
552
553 BindingPattern::ArrayPattern(ap) => {
554 let init_type = self.init_expr_type(init_expr);
556 let is_arraylist = matches!(init_type, Some(ZigType::ArrayList(_)));
557
558 let element_count = ap.elements.iter().filter(|e| e.is_some()).count();
560 let needs_temp = init_may_have_side_effects(init_expr) || element_count > 1;
561 let temp_name = self.name_mangler.next_name("_js_dest");
562
563 let source = self.compute_destructure_source(needs_temp, &temp_name, init_expr);
564
565 struct RawArrBinding {
567 bind_name: String,
568 index: usize,
569 has_default: bool,
570 default_index: usize,
571 is_const: bool,
572 }
573 let mut raw_bindings: Vec<RawArrBinding> = Vec::new();
574 let mut default_counter: usize = 0;
575 for (i, elem) in ap.elements.iter().enumerate() {
576 let Some(pattern) = elem else {
577 continue; };
579
580 let (bind_name, has_default) = match binding_name_and_default(pattern) {
581 Some(pair) => pair,
582 None => continue,
583 };
584
585 let is_const = !self.is_var_mutated(bind_name);
586
587 if self.should_skip_toplevel_binding(bind_name, is_const) {
588 default_counter += if has_default { 1 } else { 0 };
589 continue;
590 }
591
592 let di = default_counter;
593 default_counter += if has_default { 1 } else { 0 };
594
595 raw_bindings.push(RawArrBinding {
596 bind_name: bind_name.to_string(),
597 index: i,
598 has_default,
599 default_index: di,
600 is_const,
601 });
602 }
603
604 let default_exprs: Vec<&Expression> = ap
606 .elements
607 .iter()
608 .flatten()
609 .filter_map(|pattern| match pattern {
610 BindingPattern::AssignmentPattern(ap_inner) => Some(&ap_inner.right),
611 _ => None,
612 })
613 .collect();
614
615 let mut bindings = Vec::new();
617 for rb in raw_bindings {
618 let default_ir = if rb.has_default {
619 default_exprs
620 .get(rb.default_index)
621 .map(|e| self.lower_expr(e))
622 } else {
623 None
624 };
625 bindings.push(IrDestructureBindingDecl {
626 name: self.make_ident(&rb.bind_name),
627 is_const: rb.is_const,
628 access: IrDestructureAccess::ArrayIndex {
629 source: if needs_temp {
630 temp_name.clone()
631 } else {
632 source.clone()
633 },
634 index: rb.index,
635 },
636 default: default_ir,
637 });
638 }
639
640 crate::zigir::types::IrStmt::DestructureDecl(IrDestructureDecl {
641 temp_name: if needs_temp {
642 Some(temp_name.clone())
643 } else {
644 None
645 },
646 init: init_ir,
647 kind: IrDestructureKind::Array { is_arraylist },
648 bindings,
649 })
650 }
651
652 _ => crate::zigir::types::IrStmt::CompileError {
653 span: SourceSpan::default(),
654 msg: "unsupported binding pattern in variable declaration".to_string(),
655 },
656 }
657 }
658
659 pub(super) fn lower_fn_decl(
670 &mut self,
671 fd: &Function,
672 is_export: bool,
673 ) -> Option<crate::zigir::types::IrFnDecl> {
674 let name = fd.id.as_ref().map(|id| id.name.as_str())?;
675
676 let has_throw = fd.body.as_ref().is_some_and(|b| Self::has_throw_in_body(b));
678
679 let is_async = self.type_info.is_async.get(name).copied().unwrap_or(false);
681
682 let return_type = self.lookup_fn_return_type(name);
684
685 let mut scope = self.enter_fn_body(fd, name, is_export, &return_type);
687
688 let used_idents_pre = Self::collect_ir_idents_in_block(&scope.body);
692 if used_idents_pre.contains("__arguments") {
693 let args_exprs: Vec<crate::zigir::types::IrExpr> = scope
694 .params
695 .iter()
696 .filter(|p| p.name.zig_name != "io" && !p.is_rest)
697 .map(|p| {
698 crate::zigir::types::IrExpr::Call(crate::zigir::types::IrCallExpr {
699 callee: Box::new(crate::zigir::types::IrExpr::FieldAccess {
700 object: Box::new(crate::zigir::types::IrExpr::Ident(IrIdent::new(
701 "JsAny",
702 ))),
703 field: "from".to_string(),
704 field_kind: crate::zigir::kinds::FieldKind::StructField,
705 }),
706 args: vec![crate::zigir::types::IrExpr::Ident(p.name.clone())],
707 call_kind: crate::zigir::kinds::CallKind::Direct,
708 })
709 })
710 .collect();
711 let arguments_init = crate::zigir::types::IrStmt::VarDecl(IrVarDecl {
712 name: IrIdent::new("__arguments"),
713 is_const: true,
714 zig_type: None,
715 init: Some(crate::zigir::types::IrExpr::ArrayLiteral(
716 crate::zigir::types::IrArrayLiteral {
717 elements: args_exprs,
718 spread_indices: vec![],
719 },
720 )),
721 is_json_parse: false,
722 needs_var_suppression: false,
723 needs_deinit: false,
724 });
725 scope.body.stmts.insert(0, arguments_init);
726 }
727
728 let mut used_idents = Self::collect_ir_idents_in_block(&scope.body);
733 if let Some(ctx) = self.fn_ctx.as_ref() {
734 used_idents.extend(ctx.compile_time_referenced_idents.iter().cloned());
735 }
736 if is_async {
738 used_idents.insert("io".to_string());
739 }
740 for param in &mut scope.params {
741 if !used_idents.contains(¶m.name.js_name) {
742 param.is_unused = true;
743 }
744 }
745
746 let has_bigint_div = self.fn_ctx.as_ref().is_some_and(|ctx| ctx.has_bigint_div);
749 let has_js_const_reassign = self
750 .fn_ctx
751 .as_ref()
752 .is_some_and(|ctx| !ctx.js_const_reassigned.is_empty());
753
754 let (params, body, typeof_return_body) = self.exit_fn_body(scope, &return_type);
756
757 let is_cabi = is_export;
759
760 Some(crate::zigir::types::IrFnDecl {
761 name: self.make_ident(name),
762 params,
763 return_type,
764 typeof_return_body,
765 body,
766 is_export,
767 is_async,
768 can_throw: has_throw || has_bigint_div || has_js_const_reassign,
769 is_cabi,
770 })
771 }
772
773 pub(super) fn lower_nested_fn_decl(&mut self, fd: &Function) -> crate::zigir::types::IrStmt {
783 use crate::zigir::types::{IrClosure, IrClosureStruct, IrStmt};
784
785 let fn_name = fd
786 .id
787 .as_ref()
788 .map(|id| id.name.as_str())
789 .unwrap_or("_anon_fn");
790
791 let captures = self.detect_fn_body_captures(fd);
793
794 let return_type = self.lookup_fn_return_type(fn_name);
796
797 let scope = self.enter_fn_body(fd, fn_name, false, &return_type);
799 let (params, body, typeof_return_body) = self.exit_fn_body(scope, &return_type);
800
801 if let Some(ctx) = self.fn_ctx.as_mut() {
803 ctx.add_nested_fn(fn_name);
804 }
805
806 let fn_ident = self.make_ident(fn_name);
807
808 if !captures.is_empty() {
809 let type_name = format!("_{}_type", fn_ident.zig_name);
814 let type_ident = IrIdent::with_zig_name(fn_name, type_name.clone());
815 let instance_ident = fn_ident;
816
817 let ir_captures = self.make_ir_captures(captures.into_iter().collect());
818
819 let closure_struct = IrClosureStruct {
821 name: type_ident.clone(),
822 captured: ir_captures.clone(),
823 fn_params: params,
824 return_type: return_type.clone(),
825 typeof_return_body: typeof_return_body.clone(),
826 body,
827 };
828
829 let instance = IrClosure {
831 struct_name: type_ident,
832 captured: ir_captures,
833 fn_params: vec![], return_type: return_type.clone(),
835 body: IrBlock::new(vec![]), instance_name: instance_ident,
837 };
838
839 IrStmt::NestedFnDecl {
840 struct_def: closure_struct,
841 instance: Some(instance),
842 }
843 } else {
844 let closure_struct = IrClosureStruct {
848 name: fn_ident,
849 captured: vec![],
850 fn_params: params,
851 return_type,
852 typeof_return_body,
853 body,
854 };
855
856 IrStmt::NestedFnDecl {
857 struct_def: closure_struct,
858 instance: None,
859 }
860 }
861 }
862
863 pub(super) fn lower_fn_params(&mut self, fd: &Function, fn_name: &str) -> Vec<IrParam> {
868 let mut params = Vec::new();
869 let is_async = self
870 .type_info
871 .is_async
872 .get(fn_name)
873 .copied()
874 .unwrap_or(false);
875
876 if is_async {
878 params.push(IrParam {
879 name: self.make_ident("io"),
880 zig_type: ZigType::AsyncIo,
881 is_unused: false,
882 is_rest: false,
883 });
884 }
885
886 let param_types = self.type_info.fn_param_types.get(fn_name).cloned();
888
889 if let Some(ptypes) = param_types {
890 for (pname, ptype) in &ptypes {
891 if is_async && pname == "io" {
893 continue;
894 }
895 params.push(IrParam {
896 name: self.make_ident(pname),
897 zig_type: ptype.clone(),
898 is_unused: false, is_rest: false,
900 });
901 }
902 } else {
903 for param in &fd.params.items {
905 if let Some(pname) = crate::infer::binding_name(¶m.pattern) {
906 params.push(IrParam {
907 name: self.make_ident(pname),
908 zig_type: ZigType::Anytype,
909 is_unused: false, is_rest: false,
911 });
912 }
913 }
914 }
915
916 if let Some(rname) = fd
918 .params
919 .rest
920 .as_ref()
921 .and_then(|r| crate::infer::binding_name(&r.rest.argument))
922 {
923 params.push(IrParam {
924 name: self.make_ident(rname),
925 zig_type: ZigType::Anytype, is_unused: false, is_rest: true,
928 });
929 }
930
931 params
932 }
933
934 pub(super) fn has_throw_in_body(body: &FunctionBody) -> bool {
939 use super::helpers::stmt_has_throw;
940 body.statements.iter().any(|s| stmt_has_throw(s))
941 }
942}