Skip to main content

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 params = self.lower_fn_params(fd, fn_name);
144
145        // Register parameter names in fn_scope_vars (for shadow detection)
146        if let Some(ctx) = self.fn_ctx.as_mut() {
147            for param in &params {
148                ctx.add_scope_var(&param.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    /// Phase 2: finalize function body lowering — run ownership transfer,
166    /// exit function context, and compute typeof_return_body.
167    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    /// Lower a variable declaration.
193    ///
194    /// Translates JS `const`/`var`/`let` into `IrDecl::Var`. The Lowerer
195    /// resolves semantic information (const vs var, type annotation, JSON.parse
196    /// special case) and defers all formatting to the Emitter.
197    ///
198    /// Shadow renaming is NOT done here ¡ª it's a scope-level concern handled
199    /// by the NameMangler during identifier resolution.
200    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        // ©¤©¤ Shadow renaming: detect duplicate variable names ©¤©¤
216        // If the name already exists in fn_scope_vars, rename it to avoid
217        // Zig's "redeclaration" error. This handles cases like:
218        //   let x = 10; { let x = 20; }  ¡ú  const x = 10; { const x_shadow_1 = 20; }
219        // Also handles: function f(data) { let data = 100; }  ¡ú  fn f(data: i64) { const data_shadow_1 = 100; }
220        let ident = if let Some(ctx) = self.fn_ctx.as_ref() {
221            if ctx.fn_scope_vars.contains(js_name) {
222                // Name is already declared in this function ¡ª generate a shadow name
223                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                // Also register the shadow name in fn_scope_vars to prevent further collisions
230                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                // First occurrence ¡ª register and use normal name resolution
236                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        // Determine const vs var based on mutation analysis (not JS keyword).
246        // Zig 'const' for never-mutated, 'var' for actually reassigned.
247        let is_actually_mutated = self.is_var_mutated(js_name);
248        // Check if the variable is *directly* reassigned (x = ..., not x.y = ...).
249        // This distinguishes "variable reassignment" from "property mutation".
250        let is_directly_reassigned = self.is_var_reassigned(js_name);
251        let is_const = !is_actually_mutated;
252
253        // Track JS-const variables that get directly reassigned — these need a
254        // runtime TypeError guard because JS throws on const reassignment but
255        // Zig uses `var`.  Only direct reassignment (x = ...) triggers this,
256        // not property mutation (x.y = ...) which is legal on JS const objects.
257        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        // When a JS-const variable is directly reassigned (x = newValue), the
265        // reassignment is converted to a throw (TypeError). Since the Zig `var`
266        // is never actually assigned after initialization, Zig 0.16 reports
267        // "local variable is never mutated".  We keep `var` (in case the value
268        // is used later, e.g., console.log after catch) and use needs_var_suppression
269        // to add `_ = &x;` to silence the warning.
270        let is_js_const_reassigned = _vd_is_const && is_directly_reassigned;
271
272        // Skip unused toplevel constants
273        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        // Toplevel var/let ¡ú error (only const allowed at module level)
286        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        // Force 'var' for Map/Set/ArrayList/BigInt types (mutated via methods or needs deinit)
294        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        // Type from inference
306        let zig_type = self.type_info.var_types.get(js_name).cloned();
307
308        // Record local variable type in fn_ctx for per-function scoping.
309        // This gives priority to the current function's variable types over
310        // global var_types (which can have stale entries from other functions).
311        // Use the init expression to infer type when var_types is unreliable.
312        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        // JSON.parse special case
324        let is_json_parse = self.type_info.has_json_parse_types.contains(js_name);
325
326        // Needs var suppression (ArrayList/Map/Set method calls need `_= &var;`)
327        // Also for JS-const variables whose reassignment is replaced by a throw:
328        // the var is never mutated at the Zig level, so Zig 0.16 reports
329        // "local variable is never mutated". `_ = &x;` silences this.
330        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        // Lower initializer expression
338        let init = match decl.init.as_ref() {
339            Some(expr) => {
340                // Special case: arrow function / closure initializer.
341                // Instead of returning IrExpr::ArrowFn as init, we:
342                // 1. Register the struct definition in module.closure_structs
343                // 2. Return IrExpr::Ident pointing to the struct name
344                // This produces the output pattern:
345                //   const _arrow_fn_0 = struct { ... };
346                //   const double = _arrow_fn_0;
347                let ir = self.lower_expr(expr);
348                match ir {
349                    crate::zigir::types::IrExpr::ArrowFn(ref arrow) => {
350                        // Generate a unique struct name like _arrow_fn_0, _arrow_fn_1, ...
351                        // Use name_mangler counter to get sequential numbering.
352                        let idx = self.name_mangler.peek_count("arrow_fn");
353                        self.name_mangler.next_name("arrow_fn"); // advance counter
354                        let struct_name = format!("_arrow_fn_{}", idx);
355                        let struct_ident = IrIdent::new(&struct_name);
356                        // Register as closure struct (with empty captures)
357                        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                        // Struct already registered by lower_fn_expr / lower_arrow_fn.
370                        // Closure instance: StructName { .captured = val, ... }
371                        Some(crate::zigir::types::IrExpr::Closure(closure.clone()))
372                    }
373                    _ => Some(ir),
374                }
375            }
376            None => None,
377        };
378
379        // Register TypedArray variables (for suffix lookup in lower_call)
380        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        // Register RegExp variables (for .test()/.exec() method dispatch in lower_call)
388        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        // needs_deinit: true for Map/Set/BigInt types and will be checked for class
396        // instances by the Emitter using class_needs_deinit. Set to false for
397        // types that don't own resources.
398        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    /// Lower a destructuring variable declaration.
415    ///
416    /// Handles `const {a, b} = expr` and `const [a, b] = expr` by constructing
417    /// an `IrStmt::DestructureDecl` that the Emitter expands into temp variable
418    /// + individual const/var declarations.
419    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                // ©¤©¤ Object destructuring ©¤©¤
439                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                // Decide if we need a temp variable
450                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                // Source for access patterns: temp var name or inline the init expr
454                let source = self.compute_destructure_source(needs_temp, &temp_name, init_expr);
455
456                // Phase 1: Collect binding metadata (no lower_expr calls yet)
457                struct RawObjBinding {
458                    key_name: String,
459                    bind_name: String,
460                    has_default: bool,
461                    default_index: usize, // index into op.properties if has_default
462                    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                // Collect default expression references from AST
503                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                // Phase 2: Build IrDestructureBindingDecl (can call self.lower_expr now)
513                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                // ── Array destructuring ──
555                let init_type = self.init_expr_type(init_expr);
556                let is_arraylist = matches!(init_type, Some(ZigType::ArrayList(_)));
557
558                // Decide if we need a temp variable
559                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                // Phase 1: Collect binding metadata
566                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; // skip holes
578                    };
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                // Collect default expression references from AST
605                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                // Phase 2: Build IrDestructureBindingDecl
616                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    /// Lower a function declaration.
660    ///
661    /// Translates JS `function foo(a, b) { ... }` into `IrDecl::Fn`.
662    /// Handles:
663    /// - export / C ABI determination
664    /// - async detection (from type_info.is_async)
665    /// - throw/catch detection (pre-scan body)
666    /// - parameter type resolution
667    /// - return type resolution (including AnytypeReturn ¡ú @TypeOf)
668    /// - shadow renaming for parameters
669    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        // Pre-scan: check if function contains throw or try-catch
677        let has_throw = fd.body.as_ref().is_some_and(|b| Self::has_throw_in_body(b));
678
679        // Check async from type_info
680        let is_async = self.type_info.is_async.get(name).copied().unwrap_or(false);
681
682        // Return type from inference
683        let return_type = self.lookup_fn_return_type(name);
684
685        // Enter function context and lower params + body
686        let mut scope = self.enter_fn_body(fd, name, is_export, &return_type);
687
688        // If the body references `arguments` (lowered as `__arguments`), inject
689        // `const __arguments = &[_]JsAny{ JsAny.from(param0), JsAny.from(param1), ... }`
690        // at the start of the function body.
691        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        // Mark unused parameters: collect all identifier references in the body,
729        // then check which params don't appear. Also include identifiers from
730        // compile-time-resolved expressions (e.g., typeof x → "number") that
731        // were optimized away but still semantically reference the parameter.
732        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        // For async functions, `io` is always used by await/async emission
737        if is_async {
738            used_idents.insert("io".to_string());
739        }
740        for param in &mut scope.params {
741            if !used_idents.contains(&param.name.js_name) {
742                param.is_unused = true;
743            }
744        }
745
746        // Read has_bigint_div and has_js_const_reassign BEFORE exiting the
747        // function context, since exit_fn() restores the outer context.
748        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        // Exit function context and finalize body
755        let (params, body, typeof_return_body) = self.exit_fn_body(scope, &return_type);
756
757        // Determine C ABI: export functions use `export fn` calling convention
758        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    /// Lower a nested function declaration into struct+call() pattern.
774    ///
775    /// Zig doesn't allow nested function declarations with return statements,
776    /// so we emit `const name = struct { pub fn call(...) ... };` and rewrite
777    /// call sites to `name.call(args)`.
778    ///
779    /// For functions that capture variables from the enclosing scope:
780    /// `const _name_type = struct { x: i64, pub fn call(self: *@This(), ...) ... };`
781    /// `const name = _name_type{ .x = x };`
782    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        // Detect captures from enclosing scope (before entering fn context)
792        let captures = self.detect_fn_body_captures(fd);
793
794        // Return type from inference
795        let return_type = self.lookup_fn_return_type(fn_name);
796
797        // Enter function context and lower params + body, then exit
798        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        // Register as a nested function name (for call-site rewriting)
802        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            // ©¤©¤ Has captures: named type struct + instance ©¤©¤
810            // Generates:
811            //   const _inner_type = struct { x: i64, pub fn call(self: *@This(), y: anytype) ... { ... } };
812            //   const inner = _inner_type{ .x = x };
813            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            // Create the struct definition (emitted inline in function body)
820            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            // Create the instance: TypeName { .x = x, ... }
830            let instance = IrClosure {
831                struct_name: type_ident,
832                captured: ir_captures,
833                fn_params: vec![], // already in struct def
834                return_type: return_type.clone(),
835                body: IrBlock::new(vec![]), // body already in struct def
836                instance_name: instance_ident,
837            };
838
839            IrStmt::NestedFnDecl {
840                struct_def: closure_struct,
841                instance: Some(instance),
842            }
843        } else {
844            // ©¤©¤ No captures: inline struct with static call method ©¤©¤
845            // Generates:
846            //   const inner = struct { pub fn call(y: anytype) ... { ... } };
847            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    /// Lower function parameters into IrParam list.
864    ///
865    /// Reads parameter types from type_info when available, falls back to
866    /// anytype for untyped parameters.
867    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        // Async functions get `io: AsyncIo` as the first parameter
877        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        // Try to get param types from type_info
887        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                // Skip 'io' param for async functions (it's already injected above)
892                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, // set later in lower_fn_decl
899                    is_rest: false,
900                });
901            }
902        } else {
903            // Fallback: generate params from AST with anytype
904            for param in &fd.params.items {
905                if let Some(pname) = crate::infer::binding_name(&param.pattern) {
906                    params.push(IrParam {
907                        name: self.make_ident(pname),
908                        zig_type: ZigType::Anytype,
909                        is_unused: false, // set later in lower_fn_decl
910                        is_rest: false,
911                    });
912                }
913            }
914        }
915
916        // Handle rest parameter (...args) ¡ú []const JsAny
917        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, // Will be rendered as []const JsAny by Emitter
926                is_unused: false,           // set later in lower_fn_decl
927                is_rest: true,
928            });
929        }
930
931        params
932    }
933
934    /// Pre-scan: check if a function body contains `throw` or `try-catch`.
935    ///
936    /// This is needed to determine whether the return type should be an
937    /// error union (`!T` vs `T`).
938    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}