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 // Don't skip if the init expression would produce a CompileError when
313 // lowered — otherwise the user-facing `@compileError` (warning that an
314 // unsupported feature was used in source JS) gets silently dropped
315 // alongside the unused const, hiding the diagnostic. Tagged templates,
316 // `yield`, and `import.meta`/`new.target` always lower to CompileError.
317 let init_might_compile_error = decl.init.as_ref().is_some_and(|e| {
318 matches!(
319 e,
320 Expression::TaggedTemplateExpression(_)
321 | Expression::YieldExpression(_)
322 | Expression::MetaProperty(_)
323 )
324 });
325 if self.fn_ctx.is_none()
326 && is_const
327 && !self.type_info.used_names.contains(js_name)
328 && !has_type_annotation
329 && !init_might_compile_error
330 {
331 return IrDecl::CompileError {
332 span: SourceSpan::default(),
333 msg: format!("skipped unused toplevel const: {}", js_name),
334 };
335 }
336
337 // Toplevel var/let ¡ú error (only const allowed at module level)
338 if self.fn_ctx.is_none() && !is_const {
339 return IrDecl::CompileError {
340 span: SourceSpan::default(),
341 msg: format!("toplevel only allows 'const', not '{}'", js_name),
342 };
343 }
344
345 // Force 'var' for Map/Set/ArrayList/BigInt types (mutated via methods or needs deinit).
346 // R8-E5/C1: Also force 'var' for class instances (NamedStruct whose name
347 // is a registered class). Methods that mutate self take `*@This()`,
348 // which requires a mutable receiver. `_ = &x;` (via needs_var_suppression,
349 // already covering NamedStruct) silences Zig's "var never mutated" for
350 // instances that only call read-only methods.
351 let is_const = if let Some(inferred_ty) = self.type_info.var_types.get(js_name) {
352 match inferred_ty {
353 ZigType::ArrayList(_) => false,
354 ZigType::NamedStruct(n) if n == "Map" || n == "Set" || n == "RegExp" => false,
355 ZigType::NamedStruct(n) if self.class_names.contains(n) => false,
356 ZigType::BigInt => false,
357 _ => is_const,
358 }
359 } else {
360 is_const
361 };
362
363 // Type from inference
364 let zig_type = self.type_info.var_types.get(js_name).cloned();
365
366 // Record local variable type in fn_ctx for per-function scoping.
367 // This gives priority to the current function's variable types over
368 // global var_types (which can have stale entries from other functions).
369 // Use the init expression to infer type when var_types is unreliable.
370 let local_type: Option<ZigType> = if let Some(init_expr) = &decl.init {
371 self.infer_expr_type(init_expr).or(zig_type.clone())
372 } else {
373 zig_type.clone()
374 };
375 if let Some(ty) = local_type {
376 self.fn_ctx
377 .as_mut()
378 .map(|ctx| ctx.fn_local_types.insert(js_name.to_string(), ty));
379 }
380
381 // JSON.parse special case
382 let is_json_parse = self.type_info.has_json_parse_types.contains(js_name);
383
384 // std.json.parse (is_json_parse var decl) can fail at runtime — mark can_throw
385 if is_json_parse && let Some(ctx) = self.fn_ctx.as_mut() {
386 ctx.has_catchable_error = true;
387 }
388
389 // Needs var suppression (ArrayList/Map/Set method calls need `_= &var;`)
390 // Also for JS-const variables whose reassignment is replaced by a throw:
391 // the var is never mutated at the Zig level, so Zig 0.16 reports
392 // "local variable is never mutated". `_ = &x;` silences this.
393 let needs_var_suppression = (!is_const
394 && matches!(
395 zig_type,
396 Some(ZigType::ArrayList(_)) | Some(ZigType::NamedStruct(_))
397 ))
398 || is_js_const_reassigned;
399
400 // Lower initializer expression
401 let init = match decl.init.as_ref() {
402 Some(expr) => {
403 // Class expression: register the variable name in class_names
404 // so that `new VarName()` routes correctly.
405 if let Expression::ClassExpression(_) = expr {
406 self.class_names.insert(js_name.to_string());
407 // Set class_expr_var_name so lower_class_decl can look up
408 // field types stored under the variable name by the type inferrer.
409 self.class_expr_var_name = Some(js_name.to_string());
410 }
411 // Special case: arrow function / closure initializer.
412 // Instead of returning IrExpr::ArrowFn as init, we:
413 // 1. Register the struct definition in module.closure_structs
414 // 2. Return IrExpr::Ident pointing to the struct name
415 // This produces the output pattern:
416 // const _arrow_fn_0 = struct { ... };
417 // const double = _arrow_fn_0;
418 let ir = self.lower_expr(expr);
419 self.class_expr_var_name = None;
420 match ir {
421 crate::zigir::types::IrExpr::ArrowFn(ref arrow) => {
422 // Generate a unique struct name like _arrow_fn_0, _arrow_fn_1, ...
423 // Use name_mangler counter to get sequential numbering.
424 let idx = self.name_mangler.peek_count("arrow_fn");
425 self.name_mangler.next_name("arrow_fn"); // advance counter
426 let struct_name = format!("_arrow_fn_{}", idx);
427 let struct_ident = IrIdent::new(&struct_name);
428 // Register as closure struct (with empty captures)
429 self.pending_arrow_structs
430 .push(crate::zigir::types::IrClosureStruct {
431 name: struct_ident.clone(),
432 captured: vec![],
433 fn_params: arrow.params.clone(),
434 return_type: arrow.return_type.clone(),
435 typeof_return_body: None,
436 body: arrow.body.clone(),
437 });
438 Some(crate::zigir::types::IrExpr::Ident(struct_ident))
439 }
440 crate::zigir::types::IrExpr::Closure(ref closure) => {
441 // Struct already registered by lower_fn_expr / lower_arrow_fn.
442 // Closure instance: StructName { .captured = val, ... }
443 Some(crate::zigir::types::IrExpr::Closure(closure.clone()))
444 }
445 _ => Some(ir),
446 }
447 }
448 None => None,
449 };
450
451 // Register TypedArray variables (for suffix lookup in lower_call)
452 if let Some(ZigType::NamedStruct(n)) = &zig_type
453 && let Some(suffix) = Self::typedarray_type_suffix(n)
454 && let Some(ctx) = self.fn_ctx.as_mut()
455 {
456 ctx.add_typedarray_var(&ident.zig_name, suffix);
457 }
458
459 // Register RegExp variables (for .test()/.exec() method dispatch in lower_call)
460 if let Some(expr) = decl.init.as_ref()
461 && Self::is_regexp_expr(expr)
462 && let Some(ctx) = self.fn_ctx.as_mut()
463 {
464 ctx.add_regexp_var(&ident.zig_name);
465 }
466
467 // needs_deinit: true for Map/Set/BigInt/ArrayList types and will be checked for class
468 // instances by the Emitter using class_needs_deinit. Set to false for
469 // types that don't own resources.
470 let needs_deinit = matches!(
471 zig_type,
472 Some(ZigType::NamedStruct(ref n)) if n == "Map" || n == "Set"
473 ) || matches!(zig_type, Some(ZigType::BigInt))
474 || matches!(zig_type, Some(ZigType::ArrayList(_)));
475
476 IrDecl::Var(IrVarDecl {
477 name: ident,
478 is_const,
479 zig_type,
480 init,
481 is_json_parse,
482 needs_var_suppression,
483 needs_deinit,
484 })
485 }
486
487 /// Lower a destructuring variable declaration.
488 ///
489 /// Handles `const {a, b} = expr` and `const [a, b] = expr` by constructing
490 /// an `IrStmt::DestructureDecl` that the Emitter expands into temp variable
491 /// + individual const/var declarations.
492 pub(super) fn lower_destructure_decl(
493 &mut self,
494 decl: &VariableDeclarator,
495 ) -> crate::zigir::types::IrStmt {
496 use crate::zigir::types::{
497 IrDestructureAccess, IrDestructureBindingDecl, IrDestructureDecl, IrDestructureKind,
498 };
499
500 let Some(init_expr) = &decl.init else {
501 return crate::zigir::types::IrStmt::CompileError {
502 span: SourceSpan::default(),
503 msg: "destructuring requires an initializer".to_string(),
504 };
505 };
506
507 let init_ir = self.lower_expr(init_expr);
508
509 match &decl.id {
510 BindingPattern::ObjectPattern(op) => {
511 // ©¤©¤ Object destructuring ©¤©¤
512 let init_type = self.init_expr_type(init_expr);
513
514 let struct_field_names: Option<Vec<String>> = match &init_type {
515 Some(ZigType::Struct(fields)) if !fields.is_empty() => {
516 Some(fields.iter().map(|(n, _)| n.clone()).collect())
517 }
518 _ => None,
519 };
520 let is_struct = struct_field_names.is_some();
521
522 // Decide if we need a temp variable
523 let needs_temp = init_may_have_side_effects(init_expr) || op.properties.len() > 1;
524 let temp_name = self.name_mangler.next_name("_js_dest");
525
526 // Source for access patterns: temp var name or inline the init expr
527 let source = self.compute_destructure_source(needs_temp, &temp_name, init_expr);
528
529 // Phase 1: Collect binding metadata (no lower_expr calls yet)
530 struct RawObjBinding {
531 key_name: String,
532 bind_name: String,
533 has_default: bool,
534 default_index: usize, // index into op.properties if has_default
535 is_struct_field: bool,
536 is_const: bool,
537 }
538 let mut raw_bindings: Vec<RawObjBinding> = Vec::new();
539 let mut default_counter: usize = 0;
540 for prop in &op.properties {
541 let key_name = match property_key_name(&prop.key) {
542 Some(k) => k,
543 None => continue,
544 };
545
546 let (bind_name, has_default) = match binding_name_and_default(&prop.value) {
547 Some(pair) => pair,
548 None => continue,
549 };
550
551 let is_const = !self.is_var_mutated(bind_name);
552
553 if self.should_skip_toplevel_binding(bind_name, is_const) {
554 default_counter += if has_default { 1 } else { 0 };
555 continue;
556 }
557
558 let is_struct_field = struct_field_names
559 .as_ref()
560 .is_some_and(|names| names.contains(&key_name));
561
562 let di = default_counter;
563 default_counter += if has_default { 1 } else { 0 };
564
565 raw_bindings.push(RawObjBinding {
566 key_name,
567 bind_name: bind_name.to_string(),
568 has_default,
569 default_index: di,
570 is_struct_field,
571 is_const,
572 });
573 }
574
575 // Collect default expression references from AST
576 let default_exprs: Vec<&Expression> = op
577 .properties
578 .iter()
579 .filter_map(|prop| match &prop.value {
580 BindingPattern::AssignmentPattern(ap) => Some(&ap.right),
581 _ => None,
582 })
583 .collect();
584
585 // Phase 2: Build IrDestructureBindingDecl (can call self.lower_expr now)
586 let mut bindings = Vec::new();
587 for rb in raw_bindings {
588 let default_ir = if rb.has_default {
589 default_exprs
590 .get(rb.default_index)
591 .map(|e| self.lower_expr(e))
592 } else {
593 None
594 };
595 bindings.push(IrDestructureBindingDecl {
596 name: self.make_ident(&rb.bind_name),
597 is_const: rb.is_const,
598 access: IrDestructureAccess::ObjectField {
599 source: if needs_temp {
600 temp_name.clone()
601 } else {
602 source.clone()
603 },
604 key: rb.key_name,
605 is_struct_field: rb.is_struct_field,
606 },
607 default: default_ir,
608 });
609 }
610
611 crate::zigir::types::IrStmt::DestructureDecl(IrDestructureDecl {
612 temp_name: if needs_temp {
613 Some(temp_name.clone())
614 } else {
615 None
616 },
617 init: init_ir,
618 kind: IrDestructureKind::Object {
619 is_struct,
620 struct_field_names,
621 },
622 bindings,
623 })
624 }
625
626 BindingPattern::ArrayPattern(ap) => {
627 // ── Array destructuring ──
628 let init_type = self.init_expr_type(init_expr);
629 let is_arraylist = matches!(init_type, Some(ZigType::ArrayList(_)));
630
631 // Decide if we need a temp variable
632 let element_count = ap.elements.iter().filter(|e| e.is_some()).count();
633 let needs_temp = init_may_have_side_effects(init_expr) || element_count > 1;
634 let temp_name = self.name_mangler.next_name("_js_dest");
635
636 let source = self.compute_destructure_source(needs_temp, &temp_name, init_expr);
637
638 // Phase 1: Collect binding metadata
639 struct RawArrBinding {
640 bind_name: String,
641 index: usize,
642 has_default: bool,
643 default_index: usize,
644 is_const: bool,
645 }
646 let mut raw_bindings: Vec<RawArrBinding> = Vec::new();
647 let mut default_counter: usize = 0;
648 for (i, elem) in ap.elements.iter().enumerate() {
649 let Some(pattern) = elem else {
650 continue; // skip holes
651 };
652
653 let (bind_name, has_default) = match binding_name_and_default(pattern) {
654 Some(pair) => pair,
655 None => continue,
656 };
657
658 let is_const = !self.is_var_mutated(bind_name);
659
660 if self.should_skip_toplevel_binding(bind_name, is_const) {
661 default_counter += if has_default { 1 } else { 0 };
662 continue;
663 }
664
665 let di = default_counter;
666 default_counter += if has_default { 1 } else { 0 };
667
668 raw_bindings.push(RawArrBinding {
669 bind_name: bind_name.to_string(),
670 index: i,
671 has_default,
672 default_index: di,
673 is_const,
674 });
675 }
676
677 // Collect default expression references from AST
678 let default_exprs: Vec<&Expression> = ap
679 .elements
680 .iter()
681 .flatten()
682 .filter_map(|pattern| match pattern {
683 BindingPattern::AssignmentPattern(ap_inner) => Some(&ap_inner.right),
684 _ => None,
685 })
686 .collect();
687
688 // Phase 2: Build IrDestructureBindingDecl
689 let mut bindings = Vec::new();
690 for rb in raw_bindings {
691 let default_ir = if rb.has_default {
692 default_exprs
693 .get(rb.default_index)
694 .map(|e| self.lower_expr(e))
695 } else {
696 None
697 };
698 bindings.push(IrDestructureBindingDecl {
699 name: self.make_ident(&rb.bind_name),
700 is_const: rb.is_const,
701 access: IrDestructureAccess::ArrayIndex {
702 source: if needs_temp {
703 temp_name.clone()
704 } else {
705 source.clone()
706 },
707 index: rb.index,
708 },
709 default: default_ir,
710 });
711 }
712
713 crate::zigir::types::IrStmt::DestructureDecl(IrDestructureDecl {
714 temp_name: if needs_temp {
715 Some(temp_name.clone())
716 } else {
717 None
718 },
719 init: init_ir,
720 kind: IrDestructureKind::Array { is_arraylist },
721 bindings,
722 })
723 }
724
725 _ => crate::zigir::types::IrStmt::CompileError {
726 span: SourceSpan::default(),
727 msg: "unsupported binding pattern in variable declaration".to_string(),
728 },
729 }
730 }
731
732 /// Lower a function declaration.
733 ///
734 /// Translates JS `function foo(a, b) { ... }` into `IrDecl::Fn`.
735 /// Handles:
736 /// - export / C ABI determination
737 /// - async detection (from type_info.is_async)
738 /// - throw/catch detection (pre-scan body)
739 /// - parameter type resolution
740 /// - return type resolution (including AnytypeReturn ¡ú @TypeOf)
741 /// - shadow renaming for parameters
742 pub(super) fn lower_fn_decl(
743 &mut self,
744 fd: &Function,
745 is_export: bool,
746 ) -> Option<crate::zigir::types::IrFnDecl> {
747 let name = fd.id.as_ref().map(|id| id.name.as_str())?;
748
749 // Pre-scan: check if function contains throw or try-catch
750 let has_throw = fd.body.as_ref().is_some_and(|b| Self::has_throw_in_body(b));
751
752 // Check async from type_info
753 let is_async = self.type_info.is_async.get(name).copied().unwrap_or(false);
754
755 // Return type from inference
756 let return_type = self.lookup_fn_return_type(name);
757
758 // Enter function context and lower params + body
759 let mut scope = self.enter_fn_body(fd, name, is_export, &return_type);
760
761 // If the body references `arguments` (lowered as `__arguments`):
762 // - Non-export with synthetic rest: `__arguments` is a rest param (injected
763 // in enter_fn_body), no VarDecl needed.
764 // - Non-export with explicit rest (`...args`): body uses `args`, not
765 // `__arguments`, so no VarDecl needed.
766 // - Export function (or any function without rest): inject
767 // `const __arguments = &[_]JsAny{ JsAny.from(param0), ... }`
768 // with declared params.
769 {
770 let used_idents_pre = Self::collect_ir_idents_in_block(&scope.body);
771 let has_rest_param = scope.params.iter().any(|p| p.is_rest);
772 if used_idents_pre.contains("__arguments") && !has_rest_param {
773 let args_exprs: Vec<crate::zigir::types::IrExpr> = scope
774 .params
775 .iter()
776 .filter(|p| p.name.zig_name != "io" && !p.is_rest)
777 .map(|p| {
778 crate::zigir::types::IrExpr::Call(crate::zigir::types::IrCallExpr {
779 callee: Box::new(crate::zigir::types::IrExpr::FieldAccess {
780 object: Box::new(crate::zigir::types::IrExpr::Ident(IrIdent::new(
781 "JsAny",
782 ))),
783 field: "from".to_string(),
784 field_kind: crate::zigir::kinds::FieldKind::StructField,
785 }),
786 args: vec![crate::zigir::types::IrExpr::Ident(p.name.clone())],
787 call_kind: crate::zigir::kinds::CallKind::Direct,
788 })
789 })
790 .collect();
791 let arguments_init = crate::zigir::types::IrStmt::VarDecl(IrVarDecl {
792 name: IrIdent::new("__arguments"),
793 is_const: true,
794 zig_type: None,
795 init: Some(crate::zigir::types::IrExpr::ArrayLiteral(
796 crate::zigir::types::IrArrayLiteral {
797 elements: args_exprs,
798 spread_indices: vec![],
799 },
800 )),
801 is_json_parse: false,
802 needs_var_suppression: false,
803 needs_deinit: false,
804 });
805 scope.body.stmts.insert(0, arguments_init);
806 }
807 }
808
809 // Mark unused parameters: collect all identifier references in the body,
810 // then check which params don't appear. Also include identifiers from
811 // compile-time-resolved expressions (e.g., typeof x → "number") that
812 // were optimized away but still semantically reference the parameter.
813 let mut used_idents = Self::collect_ir_idents_in_block(&scope.body);
814 if let Some(ctx) = self.fn_ctx.as_ref() {
815 used_idents.extend(ctx.compile_time_referenced_idents.iter().cloned());
816 }
817 // For async functions, `io` is always used by await/async emission
818 if is_async {
819 used_idents.insert("io".to_string());
820 }
821 for param in &mut scope.params {
822 if !used_idents.contains(¶m.name.js_name) {
823 param.is_unused = true;
824 }
825 }
826
827 // Read has_bigint_div, has_catchable_error, and has_js_const_reassign BEFORE
828 // exiting the function context, since exit_fn() restores the outer context.
829 let has_bigint_div = self.fn_ctx.as_ref().is_some_and(|ctx| ctx.has_bigint_div);
830 let has_catchable_error = self
831 .fn_ctx
832 .as_ref()
833 .is_some_and(|ctx| ctx.has_catchable_error);
834 let has_js_const_reassign = self
835 .fn_ctx
836 .as_ref()
837 .is_some_and(|ctx| !ctx.js_const_reassigned.is_empty());
838
839 // Exit function context and finalize body
840 let (params, body, typeof_return_body) = self.exit_fn_body(scope, &return_type);
841
842 // Determine C ABI: export functions use `export fn` calling convention
843 let is_cabi = is_export;
844
845 Some(crate::zigir::types::IrFnDecl {
846 name: self.make_ident(name),
847 params,
848 return_type,
849 typeof_return_body,
850 body,
851 is_export,
852 is_async,
853 can_throw: has_throw || has_bigint_div || has_catchable_error || has_js_const_reassign,
854 is_cabi,
855 })
856 }
857
858 /// Lower a nested function declaration into struct+call() pattern.
859 ///
860 /// Zig doesn't allow nested function declarations with return statements,
861 /// so we emit `const name = struct { pub fn call(...) ... };` and rewrite
862 /// call sites to `name.call(args)`.
863 ///
864 /// For functions that capture variables from the enclosing scope:
865 /// `const _name_type = struct { x: i64, pub fn call(self: *@This(), ...) ... };`
866 /// `const name = _name_type{ .x = x };`
867 pub(super) fn lower_nested_fn_decl(&mut self, fd: &Function) -> crate::zigir::types::IrStmt {
868 use crate::zigir::types::{IrClosure, IrClosureStruct, IrStmt};
869
870 let fn_name = fd
871 .id
872 .as_ref()
873 .map(|id| id.name.as_str())
874 .unwrap_or("_anon_fn");
875
876 // Detect captures from enclosing scope (before entering fn context)
877 let captures = self.detect_fn_body_captures(fd);
878
879 // Return type from inference
880 let return_type = self.lookup_fn_return_type(fn_name);
881
882 // Enter function context and lower params + body, then exit
883 let scope = self.enter_fn_body(fd, fn_name, false, &return_type);
884 let (params, body, typeof_return_body) = self.exit_fn_body(scope, &return_type);
885
886 // Register as a nested function name (for call-site rewriting)
887 if let Some(ctx) = self.fn_ctx.as_mut() {
888 ctx.add_nested_fn(fn_name);
889 }
890
891 let fn_ident = self.make_ident(fn_name);
892
893 if !captures.is_empty() {
894 // ©¤©¤ Has captures: named type struct + instance ©¤©¤
895 // Generates:
896 // const _inner_type = struct { x: i64, pub fn call(self: *@This(), y: anytype) ... { ... } };
897 // const inner = _inner_type{ .x = x };
898 let type_name = format!("_{}_type", fn_ident.zig_name);
899 let type_ident = IrIdent::with_zig_name(fn_name, type_name.clone());
900 let instance_ident = fn_ident;
901
902 let ir_captures = self.make_ir_captures(captures.into_iter().collect());
903
904 // Create the struct definition (emitted inline in function body)
905 let closure_struct = IrClosureStruct {
906 name: type_ident.clone(),
907 captured: ir_captures.clone(),
908 fn_params: params,
909 return_type: return_type.clone(),
910 typeof_return_body: typeof_return_body.clone(),
911 body,
912 };
913
914 // Create the instance: TypeName { .x = x, ... }
915 let instance = IrClosure {
916 struct_name: type_ident,
917 captured: ir_captures,
918 fn_params: vec![], // already in struct def
919 return_type: return_type.clone(),
920 body: IrBlock::new(vec![]), // body already in struct def
921 instance_name: instance_ident,
922 };
923
924 IrStmt::NestedFnDecl {
925 struct_def: closure_struct,
926 instance: Some(instance),
927 }
928 } else {
929 // ©¤©¤ No captures: inline struct with static call method ©¤©¤
930 // Generates:
931 // const inner = struct { pub fn call(y: anytype) ... { ... } };
932 let closure_struct = IrClosureStruct {
933 name: fn_ident,
934 captured: vec![],
935 fn_params: params,
936 return_type,
937 typeof_return_body,
938 body,
939 };
940
941 IrStmt::NestedFnDecl {
942 struct_def: closure_struct,
943 instance: None,
944 }
945 }
946 }
947
948 /// Lower function parameters into IrParam list.
949 ///
950 /// Reads parameter types from type_info when available, falls back to
951 /// anytype for untyped parameters.
952 pub(super) fn lower_fn_params(&mut self, fd: &Function, fn_name: &str) -> Vec<IrParam> {
953 let mut params = Vec::new();
954 let is_async = self
955 .type_info
956 .is_async
957 .get(fn_name)
958 .copied()
959 .unwrap_or(false);
960
961 // Async functions get `io: AsyncIo` as the first parameter
962 if is_async {
963 params.push(IrParam {
964 name: self.make_ident("io"),
965 zig_type: ZigType::AsyncIo,
966 is_unused: false,
967 is_rest: false,
968 });
969 }
970
971 // Try to get param types from type_info
972 let param_types = self.type_info.fn_param_types.get(fn_name).cloned();
973
974 if let Some(ptypes) = param_types {
975 for (pname, ptype) in &ptypes {
976 // Skip 'io' param for async functions (it's already injected above)
977 if is_async && pname == "io" {
978 continue;
979 }
980 params.push(IrParam {
981 name: self.make_ident(pname),
982 zig_type: ptype.clone(),
983 is_unused: false, // set later in lower_fn_decl
984 is_rest: false,
985 });
986 }
987 } else {
988 // Fallback: generate params from AST with anytype
989 for param in &fd.params.items {
990 if let Some(pname) = crate::infer::binding_name(¶m.pattern) {
991 params.push(IrParam {
992 name: self.make_ident(pname),
993 zig_type: ZigType::Anytype,
994 is_unused: false, // set later in lower_fn_decl
995 is_rest: false,
996 });
997 }
998 }
999 }
1000
1001 // Handle rest parameter (...args) ¡ú []const JsAny
1002 if let Some(rname) = fd
1003 .params
1004 .rest
1005 .as_ref()
1006 .and_then(|r| crate::infer::binding_name(&r.rest.argument))
1007 {
1008 params.push(IrParam {
1009 name: self.make_ident(rname),
1010 zig_type: ZigType::Anytype, // Will be rendered as []const JsAny by Emitter
1011 is_unused: false, // set later in lower_fn_decl
1012 is_rest: true,
1013 });
1014 }
1015
1016 params
1017 }
1018
1019 /// Pre-scan: check if a function body contains `throw` or `try-catch`.
1020 ///
1021 /// This is needed to determine whether the return type should be an
1022 /// error union (`!T` vs `T`).
1023 pub(super) fn has_throw_in_body(body: &FunctionBody) -> bool {
1024 use super::helpers::stmt_has_throw;
1025 body.statements.iter().any(|s| stmt_has_throw(s))
1026 }
1027}