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