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