js2zig_core/zigir/lower/decl.rs
1// zigir/lower/decl.rs
2// Declaration lowering: variables, functions, parameters, nested functions.
3
4use 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
15/// Extract the binding name and whether it has a default value from a
16/// `BindingPattern`. Returns `None` for patterns we don't handle
17/// (e.g. nested destructuring).
18fn 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
29/// Intermediate result of entering a function context and lowering
30/// its parameters and body. Callers can inspect/modify the params
31/// and body while still inside the fn context, then call
32/// [`Lowerer::exit_fn_body`] to finalize.
33struct FnBodyScope {
34 saved: Option<FnContext>,
35 params: Vec<IrParam>,
36 body: IrBlock,
37}
38
39impl Lowerer {
40 // ── Shared query helpers ─────────────────────────────
41
42 /// Current function name, or `"__toplevel__"` if outside any function.
43 /// Used as a key prefix for `type_info.mutated_vars` / `reassigned_vars` lookups.
44 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 /// Check if a toplevel binding should be skipped.
76 /// At module level: unused const or non-const (var/let) are skipped.
77 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 /// Infer the type of a destructuring init expression (only supports identifiers).
88 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 /// Compute the source string for destructuring access patterns:
97 /// uses the temp variable if needed, otherwise the init identifier name,
98 /// or generates a fresh `_js_dest` name.
99 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 /// When the return type is `AnytypeReturn`, capture the first return
115 /// expression from the body so the Emitter can emit `@TypeOf(expr)`.
116 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 // ── Function body lowering pipeline ──────────────────
128
129 /// Phase 1: enter function context and lower params + body.
130 /// The caller still holds the active fn context and can do
131 /// additional work (e.g., `__arguments` injection, unused param
132 /// marking, reading fn_ctx flags).
133 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 mut params = self.lower_fn_params(fd, fn_name);
144
145 // ── Synthetic rest param for `arguments` support ──
146 // Non-export functions using `arguments` (but without explicit rest param)
147 // get a synthetic `...__arguments` rest param so `arguments` captures ALL
148 // runtime arguments, not just declared params.
149 let needs_synthetic_rest = !is_export
150 && fd.params.rest.is_none()
151 && self
152 .type_info
153 .functions_needing_synthetic_rest
154 .contains(fn_name);
155
156 if needs_synthetic_rest {
157 params.push(IrParam {
158 name: self.make_ident("__arguments"),
159 zig_type: ZigType::Anytype, // Rendered as []const JsAny by Emitter
160 is_unused: false,
161 is_rest: true,
162 });
163 }
164
165 // Set rest_param_name in fn_ctx so lower_ident_expr can rewrite
166 // `arguments` → rest param name (synthetic `__arguments` or explicit `args`).
167 let rest_param_name = if let Some(rname) = fd
168 .params
169 .rest
170 .as_ref()
171 .and_then(|r| crate::infer::binding_name(&r.rest.argument))
172 {
173 Some(rname.to_string())
174 } else if needs_synthetic_rest {
175 Some("__arguments".to_string())
176 } else {
177 None
178 };
179 if let Some(ctx) = self.fn_ctx.as_mut() {
180 ctx.rest_param_name = rest_param_name;
181 }
182
183 // Register parameter names in fn_scope_vars (for shadow detection)
184 if let Some(ctx) = self.fn_ctx.as_mut() {
185 for param in ¶ms {
186 ctx.add_scope_var(¶m.name.js_name);
187 }
188 }
189
190 let body = fd
191 .body
192 .as_ref()
193 .map(|b| self.lower_block(&b.statements))
194 .unwrap_or_else(|| IrBlock::new(vec![]));
195
196 FnBodyScope {
197 saved,
198 params,
199 body,
200 }
201 }
202
203 /// Phase 2: finalize function body lowering — run ownership transfer,
204 /// exit function context, and compute typeof_return_body.
205 fn exit_fn_body(
206 &mut self,
207 scope: FnBodyScope,
208 return_type: &ZigType,
209 ) -> (
210 Vec<IrParam>,
211 IrBlock,
212 Option<Box<crate::zigir::types::IrExpr>>,
213 ) {
214 let FnBodyScope {
215 saved,
216 params,
217 mut body,
218 } = scope;
219
220 Self::clear_deinit_for_returned_vars(&mut body);
221
222 self.name_mangler.pop_shadow_scope();
223 let _fn_ctx = self.exit_fn(saved);
224
225 let typeof_return_body = Self::resolve_typeof_return_body(return_type, &body);
226
227 (params, body, typeof_return_body)
228 }
229
230 /// Lower a variable declaration.
231 ///
232 /// Translates JS `const`/`var`/`let` into `IrDecl::Var`. The Lowerer
233 /// resolves semantic information (const vs var, type annotation, JSON.parse
234 /// special case) and defers all formatting to the Emitter.
235 ///
236 /// Shadow renaming is NOT done here ¡ª it's a scope-level concern handled
237 /// by the NameMangler during identifier resolution.
238 pub(super) fn lower_var_decl(
239 &mut self,
240 decl: &VariableDeclarator,
241 _vd_is_const: bool,
242 ) -> IrDecl {
243 let js_name = match crate::infer::binding_name(&decl.id) {
244 Some(n) => n,
245 None => {
246 return IrDecl::CompileError {
247 span: SourceSpan::default(),
248 msg: "unsupported binding pattern in variable declaration".to_string(),
249 };
250 }
251 };
252
253 // ©¤©¤ Shadow renaming: detect duplicate variable names ©¤©¤
254 // If the name already exists in fn_scope_vars, rename it to avoid
255 // Zig's "redeclaration" error. This handles cases like:
256 // let x = 10; { let x = 20; } ¡ú const x = 10; { const x_shadow_1 = 20; }
257 // Also handles: function f(data) { let data = 100; } ¡ú fn f(data: i64) { const data_shadow_1 = 100; }
258 let ident = if let Some(ctx) = self.fn_ctx.as_ref() {
259 if ctx.fn_scope_vars.contains(js_name) {
260 // Name is already declared in this function ¡ª generate a shadow name
261 let shadow_zig_name = format!(
262 "{}_shadow_{}",
263 js_name,
264 self.name_mangler.next_name("shadow")
265 );
266 self.name_mangler.record_shadow(js_name, shadow_zig_name);
267 // Also register the shadow name in fn_scope_vars to prevent further collisions
268 if let Some(ctx) = self.fn_ctx.as_mut() {
269 ctx.add_scope_var(js_name);
270 }
271 IrIdent::with_zig_name(js_name, self.name_mangler.resolve_name(js_name))
272 } else {
273 // First occurrence ¡ª register and use normal name resolution
274 if let Some(ctx) = self.fn_ctx.as_mut() {
275 ctx.add_scope_var(js_name);
276 }
277 self.make_ident(js_name)
278 }
279 } else {
280 self.make_ident(js_name)
281 };
282
283 // Determine const vs var based on mutation analysis (not JS keyword).
284 // Zig 'const' for never-mutated, 'var' for actually reassigned.
285 let is_actually_mutated = self.is_var_mutated(js_name);
286 // Check if the variable is *directly* reassigned (x = ..., not x.y = ...).
287 // This distinguishes "variable reassignment" from "property mutation".
288 let is_directly_reassigned = self.is_var_reassigned(js_name);
289 let is_const = !is_actually_mutated;
290
291 // Track JS-const variables that get directly reassigned — these need a
292 // runtime TypeError guard because JS throws on const reassignment but
293 // Zig uses `var`. Only direct reassignment (x = ...) triggers this,
294 // not property mutation (x.y = ...) which is legal on JS const objects.
295 if _vd_is_const
296 && is_directly_reassigned
297 && let Some(ctx) = self.fn_ctx.as_mut()
298 {
299 ctx.js_const_reassigned.insert(js_name.to_string());
300 }
301
302 // When a JS-const variable is directly reassigned (x = newValue), the
303 // reassignment is converted to a throw (TypeError). Since the Zig `var`
304 // is never actually assigned after initialization, Zig 0.16 reports
305 // "local variable is never mutated". We keep `var` (in case the value
306 // is used later, e.g., console.log after catch) and use needs_var_suppression
307 // to add `_ = &x;` to silence the warning.
308 let is_js_const_reassigned = _vd_is_const && is_directly_reassigned;
309
310 // Skip unused toplevel constants
311 let has_type_annotation = self.jsdoc_data.type_annotations.contains_key(js_name);
312 if self.fn_ctx.is_none()
313 && is_const
314 && !self.type_info.used_names.contains(js_name)
315 && !has_type_annotation
316 {
317 return IrDecl::CompileError {
318 span: SourceSpan::default(),
319 msg: format!("skipped unused toplevel const: {}", js_name),
320 };
321 }
322
323 // Toplevel var/let ¡ú error (only const allowed at module level)
324 if self.fn_ctx.is_none() && !is_const {
325 return IrDecl::CompileError {
326 span: SourceSpan::default(),
327 msg: format!("toplevel only allows 'const', not '{}'", js_name),
328 };
329 }
330
331 // Force 'var' for Map/Set/ArrayList/BigInt types (mutated via methods or needs deinit)
332 let is_const = if let Some(inferred_ty) = self.type_info.var_types.get(js_name) {
333 match inferred_ty {
334 ZigType::ArrayList(_) => false,
335 ZigType::NamedStruct(n) if n == "Map" || n == "Set" => false,
336 ZigType::BigInt => false,
337 _ => is_const,
338 }
339 } else {
340 is_const
341 };
342
343 // Type from inference
344 let zig_type = self.type_info.var_types.get(js_name).cloned();
345
346 // Record local variable type in fn_ctx for per-function scoping.
347 // This gives priority to the current function's variable types over
348 // global var_types (which can have stale entries from other functions).
349 // Use the init expression to infer type when var_types is unreliable.
350 let local_type: Option<ZigType> = if let Some(init_expr) = &decl.init {
351 self.infer_expr_type(init_expr).or(zig_type.clone())
352 } else {
353 zig_type.clone()
354 };
355 if let Some(ty) = local_type {
356 self.fn_ctx
357 .as_mut()
358 .map(|ctx| ctx.fn_local_types.insert(js_name.to_string(), ty));
359 }
360
361 // JSON.parse special case
362 let is_json_parse = self.type_info.has_json_parse_types.contains(js_name);
363
364 // std.json.parse (is_json_parse var decl) can fail at runtime — mark can_throw
365 if is_json_parse && let Some(ctx) = self.fn_ctx.as_mut() {
366 ctx.has_catchable_error = true;
367 }
368
369 // Needs var suppression (ArrayList/Map/Set method calls need `_= &var;`)
370 // Also for JS-const variables whose reassignment is replaced by a throw:
371 // the var is never mutated at the Zig level, so Zig 0.16 reports
372 // "local variable is never mutated". `_ = &x;` silences this.
373 let needs_var_suppression = (!is_const
374 && matches!(
375 zig_type,
376 Some(ZigType::ArrayList(_)) | Some(ZigType::NamedStruct(_))
377 ))
378 || is_js_const_reassigned;
379
380 // Lower initializer expression
381 let init = match decl.init.as_ref() {
382 Some(expr) => {
383 // Class expression: register the variable name in class_names
384 // so that `new VarName()` routes correctly.
385 if let Expression::ClassExpression(_) = expr {
386 self.class_names.insert(js_name.to_string());
387 // Set class_expr_var_name so lower_class_decl can look up
388 // field types stored under the variable name by the type inferrer.
389 self.class_expr_var_name = Some(js_name.to_string());
390 }
391 // Special case: arrow function / closure initializer.
392 // Instead of returning IrExpr::ArrowFn as init, we:
393 // 1. Register the struct definition in module.closure_structs
394 // 2. Return IrExpr::Ident pointing to the struct name
395 // This produces the output pattern:
396 // const _arrow_fn_0 = struct { ... };
397 // const double = _arrow_fn_0;
398 let ir = self.lower_expr(expr);
399 self.class_expr_var_name = None;
400 match ir {
401 crate::zigir::types::IrExpr::ArrowFn(ref arrow) => {
402 // Generate a unique struct name like _arrow_fn_0, _arrow_fn_1, ...
403 // Use name_mangler counter to get sequential numbering.
404 let idx = self.name_mangler.peek_count("arrow_fn");
405 self.name_mangler.next_name("arrow_fn"); // advance counter
406 let struct_name = format!("_arrow_fn_{}", idx);
407 let struct_ident = IrIdent::new(&struct_name);
408 // Register as closure struct (with empty captures)
409 self.pending_arrow_structs
410 .push(crate::zigir::types::IrClosureStruct {
411 name: struct_ident.clone(),
412 captured: vec![],
413 fn_params: arrow.params.clone(),
414 return_type: arrow.return_type.clone(),
415 typeof_return_body: None,
416 body: arrow.body.clone(),
417 });
418 Some(crate::zigir::types::IrExpr::Ident(struct_ident))
419 }
420 crate::zigir::types::IrExpr::Closure(ref closure) => {
421 // Struct already registered by lower_fn_expr / lower_arrow_fn.
422 // Closure instance: StructName { .captured = val, ... }
423 Some(crate::zigir::types::IrExpr::Closure(closure.clone()))
424 }
425 _ => Some(ir),
426 }
427 }
428 None => None,
429 };
430
431 // Register TypedArray variables (for suffix lookup in lower_call)
432 if let Some(ZigType::NamedStruct(n)) = &zig_type
433 && let Some(suffix) = Self::typedarray_type_suffix(n)
434 && let Some(ctx) = self.fn_ctx.as_mut()
435 {
436 ctx.add_typedarray_var(&ident.zig_name, suffix);
437 }
438
439 // Register RegExp variables (for .test()/.exec() method dispatch in lower_call)
440 if let Some(expr) = decl.init.as_ref()
441 && Self::is_regexp_expr(expr)
442 && let Some(ctx) = self.fn_ctx.as_mut()
443 {
444 ctx.add_regexp_var(&ident.zig_name);
445 }
446
447 // needs_deinit: true for Map/Set/BigInt/ArrayList types and will be checked for class
448 // instances by the Emitter using class_needs_deinit. Set to false for
449 // types that don't own resources.
450 let needs_deinit = matches!(
451 zig_type,
452 Some(ZigType::NamedStruct(ref n)) if n == "Map" || n == "Set"
453 ) || matches!(zig_type, Some(ZigType::BigInt))
454 || matches!(zig_type, Some(ZigType::ArrayList(_)));
455
456 IrDecl::Var(IrVarDecl {
457 name: ident,
458 is_const,
459 zig_type,
460 init,
461 is_json_parse,
462 needs_var_suppression,
463 needs_deinit,
464 })
465 }
466
467 /// Lower a destructuring variable declaration.
468 ///
469 /// Handles `const {a, b} = expr` and `const [a, b] = expr` by constructing
470 /// an `IrStmt::DestructureDecl` that the Emitter expands into temp variable
471 /// + individual const/var declarations.
472 pub(super) fn lower_destructure_decl(
473 &mut self,
474 decl: &VariableDeclarator,
475 ) -> crate::zigir::types::IrStmt {
476 use crate::zigir::types::{
477 IrDestructureAccess, IrDestructureBindingDecl, IrDestructureDecl, IrDestructureKind,
478 };
479
480 let Some(init_expr) = &decl.init else {
481 return crate::zigir::types::IrStmt::CompileError {
482 span: SourceSpan::default(),
483 msg: "destructuring requires an initializer".to_string(),
484 };
485 };
486
487 let init_ir = self.lower_expr(init_expr);
488
489 match &decl.id {
490 BindingPattern::ObjectPattern(op) => {
491 // ©¤©¤ Object destructuring ©¤©¤
492 let init_type = self.init_expr_type(init_expr);
493
494 let struct_field_names: Option<Vec<String>> = match &init_type {
495 Some(ZigType::Struct(fields)) if !fields.is_empty() => {
496 Some(fields.iter().map(|(n, _)| n.clone()).collect())
497 }
498 _ => None,
499 };
500 let is_struct = struct_field_names.is_some();
501
502 // Decide if we need a temp variable
503 let needs_temp = init_may_have_side_effects(init_expr) || op.properties.len() > 1;
504 let temp_name = self.name_mangler.next_name("_js_dest");
505
506 // Source for access patterns: temp var name or inline the init expr
507 let source = self.compute_destructure_source(needs_temp, &temp_name, init_expr);
508
509 // Phase 1: Collect binding metadata (no lower_expr calls yet)
510 struct RawObjBinding {
511 key_name: String,
512 bind_name: String,
513 has_default: bool,
514 default_index: usize, // index into op.properties if has_default
515 is_struct_field: bool,
516 is_const: bool,
517 }
518 let mut raw_bindings: Vec<RawObjBinding> = Vec::new();
519 let mut default_counter: usize = 0;
520 for prop in &op.properties {
521 let key_name = match property_key_name(&prop.key) {
522 Some(k) => k,
523 None => continue,
524 };
525
526 let (bind_name, has_default) = match binding_name_and_default(&prop.value) {
527 Some(pair) => pair,
528 None => continue,
529 };
530
531 let is_const = !self.is_var_mutated(bind_name);
532
533 if self.should_skip_toplevel_binding(bind_name, is_const) {
534 default_counter += if has_default { 1 } else { 0 };
535 continue;
536 }
537
538 let is_struct_field = struct_field_names
539 .as_ref()
540 .is_some_and(|names| names.contains(&key_name));
541
542 let di = default_counter;
543 default_counter += if has_default { 1 } else { 0 };
544
545 raw_bindings.push(RawObjBinding {
546 key_name,
547 bind_name: bind_name.to_string(),
548 has_default,
549 default_index: di,
550 is_struct_field,
551 is_const,
552 });
553 }
554
555 // Collect default expression references from AST
556 let default_exprs: Vec<&Expression> = op
557 .properties
558 .iter()
559 .filter_map(|prop| match &prop.value {
560 BindingPattern::AssignmentPattern(ap) => Some(&ap.right),
561 _ => None,
562 })
563 .collect();
564
565 // Phase 2: Build IrDestructureBindingDecl (can call self.lower_expr now)
566 let mut bindings = Vec::new();
567 for rb in raw_bindings {
568 let default_ir = if rb.has_default {
569 default_exprs
570 .get(rb.default_index)
571 .map(|e| self.lower_expr(e))
572 } else {
573 None
574 };
575 bindings.push(IrDestructureBindingDecl {
576 name: self.make_ident(&rb.bind_name),
577 is_const: rb.is_const,
578 access: IrDestructureAccess::ObjectField {
579 source: if needs_temp {
580 temp_name.clone()
581 } else {
582 source.clone()
583 },
584 key: rb.key_name,
585 is_struct_field: rb.is_struct_field,
586 },
587 default: default_ir,
588 });
589 }
590
591 crate::zigir::types::IrStmt::DestructureDecl(IrDestructureDecl {
592 temp_name: if needs_temp {
593 Some(temp_name.clone())
594 } else {
595 None
596 },
597 init: init_ir,
598 kind: IrDestructureKind::Object {
599 is_struct,
600 struct_field_names,
601 },
602 bindings,
603 })
604 }
605
606 BindingPattern::ArrayPattern(ap) => {
607 // ── Array destructuring ──
608 let init_type = self.init_expr_type(init_expr);
609 let is_arraylist = matches!(init_type, Some(ZigType::ArrayList(_)));
610
611 // Decide if we need a temp variable
612 let element_count = ap.elements.iter().filter(|e| e.is_some()).count();
613 let needs_temp = init_may_have_side_effects(init_expr) || element_count > 1;
614 let temp_name = self.name_mangler.next_name("_js_dest");
615
616 let source = self.compute_destructure_source(needs_temp, &temp_name, init_expr);
617
618 // Phase 1: Collect binding metadata
619 struct RawArrBinding {
620 bind_name: String,
621 index: usize,
622 has_default: bool,
623 default_index: usize,
624 is_const: bool,
625 }
626 let mut raw_bindings: Vec<RawArrBinding> = Vec::new();
627 let mut default_counter: usize = 0;
628 for (i, elem) in ap.elements.iter().enumerate() {
629 let Some(pattern) = elem else {
630 continue; // skip holes
631 };
632
633 let (bind_name, has_default) = match binding_name_and_default(pattern) {
634 Some(pair) => pair,
635 None => continue,
636 };
637
638 let is_const = !self.is_var_mutated(bind_name);
639
640 if self.should_skip_toplevel_binding(bind_name, is_const) {
641 default_counter += if has_default { 1 } else { 0 };
642 continue;
643 }
644
645 let di = default_counter;
646 default_counter += if has_default { 1 } else { 0 };
647
648 raw_bindings.push(RawArrBinding {
649 bind_name: bind_name.to_string(),
650 index: i,
651 has_default,
652 default_index: di,
653 is_const,
654 });
655 }
656
657 // Collect default expression references from AST
658 let default_exprs: Vec<&Expression> = ap
659 .elements
660 .iter()
661 .flatten()
662 .filter_map(|pattern| match pattern {
663 BindingPattern::AssignmentPattern(ap_inner) => Some(&ap_inner.right),
664 _ => None,
665 })
666 .collect();
667
668 // Phase 2: Build IrDestructureBindingDecl
669 let mut bindings = Vec::new();
670 for rb in raw_bindings {
671 let default_ir = if rb.has_default {
672 default_exprs
673 .get(rb.default_index)
674 .map(|e| self.lower_expr(e))
675 } else {
676 None
677 };
678 bindings.push(IrDestructureBindingDecl {
679 name: self.make_ident(&rb.bind_name),
680 is_const: rb.is_const,
681 access: IrDestructureAccess::ArrayIndex {
682 source: if needs_temp {
683 temp_name.clone()
684 } else {
685 source.clone()
686 },
687 index: rb.index,
688 },
689 default: default_ir,
690 });
691 }
692
693 crate::zigir::types::IrStmt::DestructureDecl(IrDestructureDecl {
694 temp_name: if needs_temp {
695 Some(temp_name.clone())
696 } else {
697 None
698 },
699 init: init_ir,
700 kind: IrDestructureKind::Array { is_arraylist },
701 bindings,
702 })
703 }
704
705 _ => crate::zigir::types::IrStmt::CompileError {
706 span: SourceSpan::default(),
707 msg: "unsupported binding pattern in variable declaration".to_string(),
708 },
709 }
710 }
711
712 /// Lower a function declaration.
713 ///
714 /// Translates JS `function foo(a, b) { ... }` into `IrDecl::Fn`.
715 /// Handles:
716 /// - export / C ABI determination
717 /// - async detection (from type_info.is_async)
718 /// - throw/catch detection (pre-scan body)
719 /// - parameter type resolution
720 /// - return type resolution (including AnytypeReturn ¡ú @TypeOf)
721 /// - shadow renaming for parameters
722 pub(super) fn lower_fn_decl(
723 &mut self,
724 fd: &Function,
725 is_export: bool,
726 ) -> Option<crate::zigir::types::IrFnDecl> {
727 let name = fd.id.as_ref().map(|id| id.name.as_str())?;
728
729 // Pre-scan: check if function contains throw or try-catch
730 let has_throw = fd.body.as_ref().is_some_and(|b| Self::has_throw_in_body(b));
731
732 // Check async from type_info
733 let is_async = self.type_info.is_async.get(name).copied().unwrap_or(false);
734
735 // Return type from inference
736 let return_type = self.lookup_fn_return_type(name);
737
738 // Enter function context and lower params + body
739 let mut scope = self.enter_fn_body(fd, name, is_export, &return_type);
740
741 // If the body references `arguments` (lowered as `__arguments`):
742 // - Non-export with synthetic rest: `__arguments` is a rest param (injected
743 // in enter_fn_body), no VarDecl needed.
744 // - Non-export with explicit rest (`...args`): body uses `args`, not
745 // `__arguments`, so no VarDecl needed.
746 // - Export function (or any function without rest): inject
747 // `const __arguments = &[_]JsAny{ JsAny.from(param0), ... }`
748 // with declared params.
749 {
750 let used_idents_pre = Self::collect_ir_idents_in_block(&scope.body);
751 let has_rest_param = scope.params.iter().any(|p| p.is_rest);
752 if used_idents_pre.contains("__arguments") && !has_rest_param {
753 let args_exprs: Vec<crate::zigir::types::IrExpr> = scope
754 .params
755 .iter()
756 .filter(|p| p.name.zig_name != "io" && !p.is_rest)
757 .map(|p| {
758 crate::zigir::types::IrExpr::Call(crate::zigir::types::IrCallExpr {
759 callee: Box::new(crate::zigir::types::IrExpr::FieldAccess {
760 object: Box::new(crate::zigir::types::IrExpr::Ident(IrIdent::new(
761 "JsAny",
762 ))),
763 field: "from".to_string(),
764 field_kind: crate::zigir::kinds::FieldKind::StructField,
765 }),
766 args: vec![crate::zigir::types::IrExpr::Ident(p.name.clone())],
767 call_kind: crate::zigir::kinds::CallKind::Direct,
768 })
769 })
770 .collect();
771 let arguments_init = crate::zigir::types::IrStmt::VarDecl(IrVarDecl {
772 name: IrIdent::new("__arguments"),
773 is_const: true,
774 zig_type: None,
775 init: Some(crate::zigir::types::IrExpr::ArrayLiteral(
776 crate::zigir::types::IrArrayLiteral {
777 elements: args_exprs,
778 spread_indices: vec![],
779 },
780 )),
781 is_json_parse: false,
782 needs_var_suppression: false,
783 needs_deinit: false,
784 });
785 scope.body.stmts.insert(0, arguments_init);
786 }
787 }
788
789 // Mark unused parameters: collect all identifier references in the body,
790 // then check which params don't appear. Also include identifiers from
791 // compile-time-resolved expressions (e.g., typeof x → "number") that
792 // were optimized away but still semantically reference the parameter.
793 let mut used_idents = Self::collect_ir_idents_in_block(&scope.body);
794 if let Some(ctx) = self.fn_ctx.as_ref() {
795 used_idents.extend(ctx.compile_time_referenced_idents.iter().cloned());
796 }
797 // For async functions, `io` is always used by await/async emission
798 if is_async {
799 used_idents.insert("io".to_string());
800 }
801 for param in &mut scope.params {
802 if !used_idents.contains(¶m.name.js_name) {
803 param.is_unused = true;
804 }
805 }
806
807 // Read has_bigint_div, has_catchable_error, and has_js_const_reassign BEFORE
808 // exiting the function context, since exit_fn() restores the outer context.
809 let has_bigint_div = self.fn_ctx.as_ref().is_some_and(|ctx| ctx.has_bigint_div);
810 let has_catchable_error = self
811 .fn_ctx
812 .as_ref()
813 .is_some_and(|ctx| ctx.has_catchable_error);
814 let has_js_const_reassign = self
815 .fn_ctx
816 .as_ref()
817 .is_some_and(|ctx| !ctx.js_const_reassigned.is_empty());
818
819 // Exit function context and finalize body
820 let (params, body, typeof_return_body) = self.exit_fn_body(scope, &return_type);
821
822 // Determine C ABI: export functions use `export fn` calling convention
823 let is_cabi = is_export;
824
825 Some(crate::zigir::types::IrFnDecl {
826 name: self.make_ident(name),
827 params,
828 return_type,
829 typeof_return_body,
830 body,
831 is_export,
832 is_async,
833 can_throw: has_throw || has_bigint_div || has_catchable_error || has_js_const_reassign,
834 is_cabi,
835 })
836 }
837
838 /// Lower a nested function declaration into struct+call() pattern.
839 ///
840 /// Zig doesn't allow nested function declarations with return statements,
841 /// so we emit `const name = struct { pub fn call(...) ... };` and rewrite
842 /// call sites to `name.call(args)`.
843 ///
844 /// For functions that capture variables from the enclosing scope:
845 /// `const _name_type = struct { x: i64, pub fn call(self: *@This(), ...) ... };`
846 /// `const name = _name_type{ .x = x };`
847 pub(super) fn lower_nested_fn_decl(&mut self, fd: &Function) -> crate::zigir::types::IrStmt {
848 use crate::zigir::types::{IrClosure, IrClosureStruct, IrStmt};
849
850 let fn_name = fd
851 .id
852 .as_ref()
853 .map(|id| id.name.as_str())
854 .unwrap_or("_anon_fn");
855
856 // Detect captures from enclosing scope (before entering fn context)
857 let captures = self.detect_fn_body_captures(fd);
858
859 // Return type from inference
860 let return_type = self.lookup_fn_return_type(fn_name);
861
862 // Enter function context and lower params + body, then exit
863 let scope = self.enter_fn_body(fd, fn_name, false, &return_type);
864 let (params, body, typeof_return_body) = self.exit_fn_body(scope, &return_type);
865
866 // Register as a nested function name (for call-site rewriting)
867 if let Some(ctx) = self.fn_ctx.as_mut() {
868 ctx.add_nested_fn(fn_name);
869 }
870
871 let fn_ident = self.make_ident(fn_name);
872
873 if !captures.is_empty() {
874 // ©¤©¤ Has captures: named type struct + instance ©¤©¤
875 // Generates:
876 // const _inner_type = struct { x: i64, pub fn call(self: *@This(), y: anytype) ... { ... } };
877 // const inner = _inner_type{ .x = x };
878 let type_name = format!("_{}_type", fn_ident.zig_name);
879 let type_ident = IrIdent::with_zig_name(fn_name, type_name.clone());
880 let instance_ident = fn_ident;
881
882 let ir_captures = self.make_ir_captures(captures.into_iter().collect());
883
884 // Create the struct definition (emitted inline in function body)
885 let closure_struct = IrClosureStruct {
886 name: type_ident.clone(),
887 captured: ir_captures.clone(),
888 fn_params: params,
889 return_type: return_type.clone(),
890 typeof_return_body: typeof_return_body.clone(),
891 body,
892 };
893
894 // Create the instance: TypeName { .x = x, ... }
895 let instance = IrClosure {
896 struct_name: type_ident,
897 captured: ir_captures,
898 fn_params: vec![], // already in struct def
899 return_type: return_type.clone(),
900 body: IrBlock::new(vec![]), // body already in struct def
901 instance_name: instance_ident,
902 };
903
904 IrStmt::NestedFnDecl {
905 struct_def: closure_struct,
906 instance: Some(instance),
907 }
908 } else {
909 // ©¤©¤ No captures: inline struct with static call method ©¤©¤
910 // Generates:
911 // const inner = struct { pub fn call(y: anytype) ... { ... } };
912 let closure_struct = IrClosureStruct {
913 name: fn_ident,
914 captured: vec![],
915 fn_params: params,
916 return_type,
917 typeof_return_body,
918 body,
919 };
920
921 IrStmt::NestedFnDecl {
922 struct_def: closure_struct,
923 instance: None,
924 }
925 }
926 }
927
928 /// Lower function parameters into IrParam list.
929 ///
930 /// Reads parameter types from type_info when available, falls back to
931 /// anytype for untyped parameters.
932 pub(super) fn lower_fn_params(&mut self, fd: &Function, fn_name: &str) -> Vec<IrParam> {
933 let mut params = Vec::new();
934 let is_async = self
935 .type_info
936 .is_async
937 .get(fn_name)
938 .copied()
939 .unwrap_or(false);
940
941 // Async functions get `io: AsyncIo` as the first parameter
942 if is_async {
943 params.push(IrParam {
944 name: self.make_ident("io"),
945 zig_type: ZigType::AsyncIo,
946 is_unused: false,
947 is_rest: false,
948 });
949 }
950
951 // Try to get param types from type_info
952 let param_types = self.type_info.fn_param_types.get(fn_name).cloned();
953
954 if let Some(ptypes) = param_types {
955 for (pname, ptype) in &ptypes {
956 // Skip 'io' param for async functions (it's already injected above)
957 if is_async && pname == "io" {
958 continue;
959 }
960 params.push(IrParam {
961 name: self.make_ident(pname),
962 zig_type: ptype.clone(),
963 is_unused: false, // set later in lower_fn_decl
964 is_rest: false,
965 });
966 }
967 } else {
968 // Fallback: generate params from AST with anytype
969 for param in &fd.params.items {
970 if let Some(pname) = crate::infer::binding_name(¶m.pattern) {
971 params.push(IrParam {
972 name: self.make_ident(pname),
973 zig_type: ZigType::Anytype,
974 is_unused: false, // set later in lower_fn_decl
975 is_rest: false,
976 });
977 }
978 }
979 }
980
981 // Handle rest parameter (...args) ¡ú []const JsAny
982 if let Some(rname) = fd
983 .params
984 .rest
985 .as_ref()
986 .and_then(|r| crate::infer::binding_name(&r.rest.argument))
987 {
988 params.push(IrParam {
989 name: self.make_ident(rname),
990 zig_type: ZigType::Anytype, // Will be rendered as []const JsAny by Emitter
991 is_unused: false, // set later in lower_fn_decl
992 is_rest: true,
993 });
994 }
995
996 params
997 }
998
999 /// Pre-scan: check if a function body contains `throw` or `try-catch`.
1000 ///
1001 /// This is needed to determine whether the return type should be an
1002 /// error union (`!T` vs `T`).
1003 pub(super) fn has_throw_in_body(body: &FunctionBody) -> bool {
1004 use super::helpers::stmt_has_throw;
1005 body.statements.iter().any(|s| stmt_has_throw(s))
1006 }
1007}