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};
13
14impl Lowerer {
15 pub(super) fn lower_var_decl(
24 &mut self,
25 decl: &VariableDeclarator,
26 _vd_is_const: bool,
27 ) -> IrDecl {
28 let js_name = match crate::infer::binding_name(&decl.id) {
29 Some(n) => n,
30 None => {
31 return IrDecl::CompileError {
32 span: SourceSpan::default(),
33 msg: "unsupported binding pattern in variable declaration".to_string(),
34 };
35 }
36 };
37
38 let ident = if let Some(ctx) = self.fn_ctx.as_ref() {
44 if ctx.fn_scope_vars.contains(js_name) {
45 let shadow_zig_name = format!(
47 "{}_shadow_{}",
48 js_name,
49 self.name_mangler.next_name("shadow")
50 );
51 self.name_mangler.record_shadow(js_name, shadow_zig_name);
52 if let Some(ctx) = self.fn_ctx.as_mut() {
54 ctx.add_scope_var(js_name);
55 }
56 IrIdent::with_zig_name(js_name, self.name_mangler.resolve_name(js_name))
57 } else {
58 if let Some(ctx) = self.fn_ctx.as_mut() {
60 ctx.add_scope_var(js_name);
61 }
62 self.make_ident(js_name)
63 }
64 } else {
65 self.make_ident(js_name)
66 };
67
68 let fn_prefix = self
71 .fn_ctx
72 .as_ref()
73 .map(|ctx| ctx.name.as_str())
74 .unwrap_or("__toplevel__");
75 let is_const = !self
76 .type_info
77 .mutated_vars
78 .contains(&format!("{}::{}", fn_prefix, js_name));
79
80 let has_type_annotation = self.jsdoc_data.type_annotations.contains_key(js_name);
82 if self.fn_ctx.is_none()
83 && is_const
84 && !self.type_info.used_names.contains(js_name)
85 && !has_type_annotation
86 {
87 return IrDecl::CompileError {
88 span: SourceSpan::default(),
89 msg: format!("skipped unused toplevel const: {}", js_name),
90 };
91 }
92
93 if self.fn_ctx.is_none() && !is_const {
95 return IrDecl::CompileError {
96 span: SourceSpan::default(),
97 msg: format!("toplevel only allows 'const', not '{}'", js_name),
98 };
99 }
100
101 let is_const = if let Some(inferred_ty) = self.type_info.var_types.get(js_name) {
103 match inferred_ty {
104 ZigType::ArrayList(_) => false,
105 ZigType::NamedStruct(n) if n == "Map" || n == "Set" => false,
106 _ => is_const,
107 }
108 } else {
109 is_const
110 };
111
112 let zig_type = self.type_info.var_types.get(js_name).cloned();
114
115 let is_json_parse = self.type_info.has_json_parse_types.contains(js_name);
117
118 let needs_var_suppression = !is_const
120 && matches!(
121 zig_type,
122 Some(ZigType::ArrayList(_)) | Some(ZigType::NamedStruct(_))
123 );
124
125 let init = match decl.init.as_ref() {
127 Some(expr) => {
128 let ir = self.lower_expr(expr);
136 match ir {
137 crate::zigir::types::IrExpr::ArrowFn(ref arrow) => {
138 let idx = self.name_mangler.peek_count("arrow_fn");
141 self.name_mangler.next_name("arrow_fn"); let struct_name = format!("_arrow_fn_{}", idx);
143 let struct_ident = IrIdent::new(&struct_name);
144 self.pending_arrow_structs
146 .push(crate::zigir::types::IrClosureStruct {
147 name: struct_ident.clone(),
148 captured: vec![],
149 fn_params: arrow.params.clone(),
150 return_type: arrow.return_type.clone(),
151 typeof_return_body: None,
152 body: arrow.body.clone(),
153 });
154 Some(crate::zigir::types::IrExpr::Ident(struct_ident))
155 }
156 crate::zigir::types::IrExpr::Closure(ref closure) => {
157 Some(crate::zigir::types::IrExpr::Closure(closure.clone()))
160 }
161 _ => Some(ir),
162 }
163 }
164 None => None,
165 };
166
167 if let Some(ZigType::NamedStruct(n)) = &zig_type
169 && let Some(suffix) = Self::typedarray_type_suffix(n)
170 && let Some(ctx) = self.fn_ctx.as_mut()
171 {
172 ctx.add_typedarray_var(&ident.zig_name, suffix);
173 }
174
175 if let Some(expr) = decl.init.as_ref()
177 && Self::is_regexp_expr(expr)
178 && let Some(ctx) = self.fn_ctx.as_mut()
179 {
180 ctx.add_regexp_var(&ident.zig_name);
181 }
182
183 IrDecl::Var(IrVarDecl {
184 name: ident,
185 is_const,
186 zig_type,
187 init,
188 is_json_parse,
189 needs_var_suppression,
190 })
191 }
192
193 pub(super) fn lower_destructure_decl(
199 &mut self,
200 decl: &VariableDeclarator,
201 ) -> crate::zigir::types::IrStmt {
202 use crate::zigir::types::{
203 IrDestructureAccess, IrDestructureBindingDecl, IrDestructureDecl, IrDestructureKind,
204 };
205
206 let Some(init_expr) = &decl.init else {
207 return crate::zigir::types::IrStmt::CompileError {
208 span: SourceSpan::default(),
209 msg: "destructuring requires an initializer".to_string(),
210 };
211 };
212
213 let init_ir = self.lower_expr(init_expr);
214
215 match &decl.id {
216 BindingPattern::ObjectPattern(op) => {
217 let init_type = if let Expression::Identifier(id) = init_expr {
219 self.type_info.var_types.get(id.name.as_str()).cloned()
220 } else {
221 None
222 };
223
224 let struct_field_names: Option<Vec<String>> = match &init_type {
225 Some(ZigType::Struct(fields)) if !fields.is_empty() => {
226 Some(fields.iter().map(|(n, _)| n.clone()).collect())
227 }
228 _ => None,
229 };
230 let is_struct = struct_field_names.is_some();
231
232 let needs_temp = init_may_have_side_effects(init_expr) || op.properties.len() > 1;
234 let temp_name = if needs_temp {
235 Some(self.name_mangler.next_name("_js_dest"))
236 } else {
237 None
238 };
239
240 let source = if needs_temp {
242 temp_name.clone().unwrap()
243 } else if let Expression::Identifier(id) = init_expr {
244 id.name.to_string()
245 } else {
246 self.name_mangler.next_name("_js_dest")
247 };
248
249 let fn_prefix = self
250 .fn_ctx
251 .as_ref()
252 .map(|ctx| ctx.name.as_str())
253 .unwrap_or("__toplevel__");
254
255 struct RawObjBinding {
257 key_name: String,
258 bind_name: String,
259 has_default: bool,
260 default_index: usize, is_struct_field: bool,
262 is_const: bool,
263 }
264 let mut raw_bindings: Vec<RawObjBinding> = Vec::new();
265 let mut default_counter: usize = 0;
266 for prop in &op.properties {
267 let key_name = match property_key_name(&prop.key) {
268 Some(k) => k,
269 None => continue,
270 };
271
272 let (bind_name, has_default) = match &prop.value {
273 BindingPattern::BindingIdentifier(id) => (id.name.as_str(), false),
274 BindingPattern::AssignmentPattern(ap) => {
275 let Some(name) = crate::infer::binding_name(&ap.left) else {
276 continue;
277 };
278 (name, true)
279 }
280 _ => continue,
281 };
282
283 let is_const = !self
284 .type_info
285 .mutated_vars
286 .contains(&format!("{}::{}", fn_prefix, bind_name));
287
288 if self.fn_ctx.is_none()
290 && is_const
291 && !self.type_info.used_names.contains(bind_name)
292 {
293 default_counter += if has_default { 1 } else { 0 };
294 continue;
295 }
296 if self.fn_ctx.is_none() && !is_const {
297 default_counter += if has_default { 1 } else { 0 };
298 continue;
299 }
300
301 let is_struct_field = struct_field_names
302 .as_ref()
303 .is_some_and(|names| names.contains(&key_name));
304
305 let di = default_counter;
306 default_counter += if has_default { 1 } else { 0 };
307
308 raw_bindings.push(RawObjBinding {
309 key_name,
310 bind_name: bind_name.to_string(),
311 has_default,
312 default_index: di,
313 is_struct_field,
314 is_const,
315 });
316 }
317
318 let default_exprs: Vec<&Expression> = op
320 .properties
321 .iter()
322 .filter_map(|prop| match &prop.value {
323 BindingPattern::AssignmentPattern(ap) => Some(&ap.right),
324 _ => None,
325 })
326 .collect();
327
328 let mut bindings = Vec::new();
330 for rb in raw_bindings {
331 let default_ir = if rb.has_default {
332 default_exprs
333 .get(rb.default_index)
334 .map(|e| self.lower_expr(e))
335 } else {
336 None
337 };
338 bindings.push(IrDestructureBindingDecl {
339 name: self.make_ident(&rb.bind_name),
340 is_const: rb.is_const,
341 access: IrDestructureAccess::ObjectField {
342 source: if needs_temp {
343 temp_name.clone().unwrap()
344 } else {
345 source.clone()
346 },
347 key: rb.key_name,
348 is_struct_field: rb.is_struct_field,
349 },
350 default: default_ir,
351 });
352 }
353
354 crate::zigir::types::IrStmt::DestructureDecl(IrDestructureDecl {
355 temp_name: if needs_temp { temp_name } else { None },
356 init: init_ir,
357 kind: IrDestructureKind::Object {
358 is_struct,
359 struct_field_names,
360 },
361 bindings,
362 })
363 }
364
365 BindingPattern::ArrayPattern(ap) => {
366 let init_type = if let Expression::Identifier(id) = init_expr {
368 self.type_info.var_types.get(id.name.as_str()).cloned()
369 } else {
370 None
371 };
372 let is_arraylist = matches!(init_type, Some(ZigType::ArrayList(_)));
373
374 let element_count = ap.elements.iter().filter(|e| e.is_some()).count();
376 let needs_temp = init_may_have_side_effects(init_expr) || element_count > 1;
377 let temp_name = if needs_temp {
378 Some(self.name_mangler.next_name("_js_dest"))
379 } else {
380 None
381 };
382
383 let source = if needs_temp {
384 temp_name.clone().unwrap()
385 } else if let Expression::Identifier(id) = init_expr {
386 id.name.to_string()
387 } else {
388 self.name_mangler.next_name("_js_dest")
389 };
390
391 let fn_prefix = self
392 .fn_ctx
393 .as_ref()
394 .map(|ctx| ctx.name.as_str())
395 .unwrap_or("__toplevel__");
396
397 struct RawArrBinding {
399 bind_name: String,
400 index: usize,
401 has_default: bool,
402 default_index: usize,
403 is_const: bool,
404 }
405 let mut raw_bindings: Vec<RawArrBinding> = Vec::new();
406 let mut default_counter: usize = 0;
407 for (i, elem) in ap.elements.iter().enumerate() {
408 let Some(pattern) = elem else {
409 continue; };
411
412 let (bind_name, has_default) = match pattern {
413 BindingPattern::BindingIdentifier(id) => (id.name.as_str(), false),
414 BindingPattern::AssignmentPattern(ap_inner) => {
415 let Some(name) = crate::infer::binding_name(&ap_inner.left) else {
416 continue;
417 };
418 (name, true)
419 }
420 _ => continue,
421 };
422
423 let is_const = !self
424 .type_info
425 .mutated_vars
426 .contains(&format!("{}::{}", fn_prefix, bind_name));
427
428 if self.fn_ctx.is_none()
429 && is_const
430 && !self.type_info.used_names.contains(bind_name)
431 {
432 default_counter += if has_default { 1 } else { 0 };
433 continue;
434 }
435 if self.fn_ctx.is_none() && !is_const {
436 default_counter += if has_default { 1 } else { 0 };
437 continue;
438 }
439
440 let di = default_counter;
441 default_counter += if has_default { 1 } else { 0 };
442
443 raw_bindings.push(RawArrBinding {
444 bind_name: bind_name.to_string(),
445 index: i,
446 has_default,
447 default_index: di,
448 is_const,
449 });
450 }
451
452 let default_exprs: Vec<&Expression> = ap
454 .elements
455 .iter()
456 .flatten()
457 .filter_map(|pattern| match pattern {
458 BindingPattern::AssignmentPattern(ap_inner) => Some(&ap_inner.right),
459 _ => None,
460 })
461 .collect();
462
463 let mut bindings = Vec::new();
465 for rb in raw_bindings {
466 let default_ir = if rb.has_default {
467 default_exprs
468 .get(rb.default_index)
469 .map(|e| self.lower_expr(e))
470 } else {
471 None
472 };
473 bindings.push(IrDestructureBindingDecl {
474 name: self.make_ident(&rb.bind_name),
475 is_const: rb.is_const,
476 access: IrDestructureAccess::ArrayIndex {
477 source: if needs_temp {
478 temp_name.clone().unwrap()
479 } else {
480 source.clone()
481 },
482 index: rb.index,
483 },
484 default: default_ir,
485 });
486 }
487
488 crate::zigir::types::IrStmt::DestructureDecl(IrDestructureDecl {
489 temp_name: if needs_temp { temp_name } else { None },
490 init: init_ir,
491 kind: IrDestructureKind::Array { is_arraylist },
492 bindings,
493 })
494 }
495
496 _ => crate::zigir::types::IrStmt::CompileError {
497 span: SourceSpan::default(),
498 msg: "unsupported binding pattern in variable declaration".to_string(),
499 },
500 }
501 }
502
503 pub(super) fn lower_fn_decl(
514 &mut self,
515 fd: &Function,
516 is_export: bool,
517 ) -> Option<crate::zigir::types::IrFnDecl> {
518 let name = fd.id.as_ref().map(|id| id.name.as_str())?;
519
520 let has_throw = fd.body.as_ref().is_some_and(|b| Self::has_throw_in_body(b));
522
523 let is_async = self.type_info.is_async.get(name).copied().unwrap_or(false);
525
526 let return_type = self
528 .type_info
529 .fn_return_types
530 .get(name)
531 .cloned()
532 .unwrap_or(ZigType::Void);
533
534 let saved = self.enter_fn(name, is_export, Some(return_type.clone()));
536
537 self.name_mangler.push_shadow_scope();
539
540 let mut params = self.lower_fn_params(fd, name);
542
543 if let Some(ctx) = self.fn_ctx.as_mut() {
545 for param in ¶ms {
546 ctx.add_scope_var(¶m.name.js_name);
547 }
548 }
549
550 let body = fd
552 .body
553 .as_ref()
554 .map(|b| self.lower_block(&b.statements))
555 .unwrap_or_else(|| IrBlock::new(vec![]));
556
557 let mut used_idents = Self::collect_ir_idents_in_block(&body);
562 if let Some(ctx) = self.fn_ctx.as_ref() {
563 used_idents.extend(ctx.compile_time_referenced_idents.iter().cloned());
564 }
565 if is_async {
567 used_idents.insert("io".to_string());
568 }
569 for param in &mut params {
570 if !used_idents.contains(¶m.name.js_name) {
571 param.is_unused = true;
572 }
573 }
574
575 self.name_mangler.pop_shadow_scope();
577 let _fn_ctx = self.exit_fn(saved);
578
579 let is_cabi = is_export;
581
582 let typeof_return_body = if matches!(return_type, ZigType::AnytypeReturn) {
585 Self::find_first_return_expr_in_block(&body).map(|e| Box::new(e.clone()))
586 } else {
587 None
588 };
589
590 Some(crate::zigir::types::IrFnDecl {
591 name: self.make_ident(name),
592 params,
593 return_type,
594 typeof_return_body,
595 body,
596 is_export,
597 is_async,
598 can_throw: has_throw,
599 is_cabi,
600 })
601 }
602
603 pub(super) fn lower_nested_fn_decl(&mut self, fd: &Function) -> crate::zigir::types::IrStmt {
613 use crate::zigir::types::{IrCapture, IrClosure, IrClosureStruct, IrStmt};
614
615 let fn_name = fd
616 .id
617 .as_ref()
618 .map(|id| id.name.as_str())
619 .unwrap_or("_anon_fn");
620
621 let captures = self.detect_fn_body_captures(fd);
623
624 let return_type = self
626 .type_info
627 .fn_return_types
628 .get(fn_name)
629 .cloned()
630 .unwrap_or(ZigType::Void);
631
632 let saved = self.enter_fn(fn_name, false, Some(return_type.clone()));
633 self.name_mangler.push_shadow_scope();
634
635 let params = self.lower_fn_params(fd, fn_name);
636
637 if let Some(ctx) = self.fn_ctx.as_mut() {
639 for param in ¶ms {
640 ctx.add_scope_var(¶m.name.js_name);
641 }
642 }
643
644 let body = fd
645 .body
646 .as_ref()
647 .map(|b| self.lower_block(&b.statements))
648 .unwrap_or_else(|| IrBlock::new(vec![]));
649
650 self.name_mangler.pop_shadow_scope();
651 let _fn_ctx = self.exit_fn(saved);
652
653 let typeof_return_body = if matches!(return_type, ZigType::AnytypeReturn) {
656 Self::find_first_return_expr_in_block(&body).map(|e| Box::new(e.clone()))
657 } else {
658 None
659 };
660
661 if let Some(ctx) = self.fn_ctx.as_mut() {
663 ctx.add_nested_fn(fn_name);
664 }
665
666 let fn_ident = self.make_ident(fn_name);
667
668 if !captures.is_empty() {
669 let type_name = format!("_{}_type", fn_ident.zig_name);
674 let type_ident = IrIdent::with_zig_name(fn_name, type_name.clone());
675 let instance_ident = fn_ident;
676
677 let ir_captures: Vec<IrCapture> = captures
678 .into_iter()
679 .map(|(name, zig_type, is_mut)| IrCapture {
680 name: self.make_ident(&name),
681 zig_type,
682 is_mut,
683 })
684 .collect();
685
686 let closure_struct = IrClosureStruct {
688 name: type_ident.clone(),
689 captured: ir_captures.clone(),
690 fn_params: params,
691 return_type: return_type.clone(),
692 typeof_return_body: typeof_return_body.clone(),
693 body,
694 };
695
696 let instance = IrClosure {
698 struct_name: type_ident,
699 captured: ir_captures,
700 fn_params: vec![], return_type: return_type.clone(),
702 body: IrBlock::new(vec![]), instance_name: instance_ident,
704 };
705
706 IrStmt::NestedFnDecl {
707 struct_def: closure_struct,
708 instance: Some(instance),
709 }
710 } else {
711 let closure_struct = IrClosureStruct {
715 name: fn_ident,
716 captured: vec![],
717 fn_params: params,
718 return_type,
719 typeof_return_body,
720 body,
721 };
722
723 IrStmt::NestedFnDecl {
724 struct_def: closure_struct,
725 instance: None,
726 }
727 }
728 }
729
730 pub(super) fn lower_fn_params(&mut self, fd: &Function, fn_name: &str) -> Vec<IrParam> {
735 let mut params = Vec::new();
736 let is_async = self
737 .type_info
738 .is_async
739 .get(fn_name)
740 .copied()
741 .unwrap_or(false);
742
743 if is_async {
745 params.push(IrParam {
746 name: self.make_ident("io"),
747 zig_type: ZigType::Anytype,
748 is_unused: false,
749 is_rest: false,
750 });
751 }
752
753 let param_types = self.type_info.fn_param_types.get(fn_name).cloned();
755
756 if let Some(ptypes) = param_types {
757 for (pname, ptype) in &ptypes {
758 if is_async && pname == "io" {
760 continue;
761 }
762 params.push(IrParam {
763 name: self.make_ident(pname),
764 zig_type: ptype.clone(),
765 is_unused: false, is_rest: false,
767 });
768 }
769 } else {
770 for param in &fd.params.items {
772 if let Some(pname) = crate::infer::binding_name(¶m.pattern) {
773 params.push(IrParam {
774 name: self.make_ident(pname),
775 zig_type: ZigType::Anytype,
776 is_unused: false, is_rest: false,
778 });
779 }
780 }
781 }
782
783 if let Some(rname) = fd
785 .params
786 .rest
787 .as_ref()
788 .and_then(|r| crate::infer::binding_name(&r.rest.argument))
789 {
790 params.push(IrParam {
791 name: self.make_ident(rname),
792 zig_type: ZigType::Anytype, is_unused: false, is_rest: true,
795 });
796 }
797
798 params
799 }
800
801 pub(super) fn has_throw_in_body(body: &FunctionBody) -> bool {
806 body.statements.iter().any(|s| Self::stmt_has_throw(s))
807 }
808
809 pub(super) fn stmt_has_throw(stmt: &Statement) -> bool {
810 match stmt {
811 Statement::ThrowStatement(_) => true,
812 Statement::BlockStatement(bs) => bs.body.iter().any(|s| Self::stmt_has_throw(s)),
813 Statement::IfStatement(is) => {
814 Self::stmt_has_throw(&is.consequent)
815 || is
816 .alternate
817 .as_ref()
818 .is_some_and(|a| Self::stmt_has_throw(a))
819 }
820 Statement::WhileStatement(ws) => Self::stmt_has_throw(&ws.body),
821 Statement::DoWhileStatement(dws) => Self::stmt_has_throw(&dws.body),
822 Statement::ForStatement(fs) => Self::stmt_has_throw(&fs.body),
823 Statement::ForOfStatement(fos) => Self::stmt_has_throw(&fos.body),
824 Statement::ForInStatement(fis) => Self::stmt_has_throw(&fis.body),
825 Statement::TryStatement(_) => true, Statement::SwitchStatement(ss) => ss
827 .cases
828 .iter()
829 .any(|c| c.consequent.iter().any(|s| Self::stmt_has_throw(s))),
830 _ => false,
831 }
832 }
833}