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};
13
14impl Lowerer {
15    /// Lower a variable declaration.
16    ///
17    /// Translates JS `const`/`var`/`let` into `IrDecl::Var`. The Lowerer
18    /// resolves semantic information (const vs var, type annotation, JSON.parse
19    /// special case) and defers all formatting to the Emitter.
20    ///
21    /// Shadow renaming is NOT done here ¡ª it's a scope-level concern handled
22    /// by the NameMangler during identifier resolution.
23    pub(super) fn lower_var_decl(
24        &mut self,
25        decl: &VariableDeclarator,
26        _vd_is_const: bool,
27    ) -> IrDecl {
28        let js_name = match crate::infer::binding_name(&decl.id) {
29            Some(n) => n,
30            None => {
31                return IrDecl::CompileError {
32                    span: SourceSpan::default(),
33                    msg: "unsupported binding pattern in variable declaration".to_string(),
34                };
35            }
36        };
37
38        // ©¤©¤ Shadow renaming: detect duplicate variable names ©¤©¤
39        // If the name already exists in fn_scope_vars, rename it to avoid
40        // Zig's "redeclaration" error. This handles cases like:
41        //   let x = 10; { let x = 20; }  ¡ú  const x = 10; { const x_shadow_1 = 20; }
42        // Also handles: function f(data) { let data = 100; }  ¡ú  fn f(data: i64) { const data_shadow_1 = 100; }
43        let ident = if let Some(ctx) = self.fn_ctx.as_ref() {
44            if ctx.fn_scope_vars.contains(js_name) {
45                // Name is already declared in this function ¡ª generate a shadow name
46                let shadow_zig_name = format!(
47                    "{}_shadow_{}",
48                    js_name,
49                    self.name_mangler.next_name("shadow")
50                );
51                self.name_mangler.record_shadow(js_name, shadow_zig_name);
52                // Also register the shadow name in fn_scope_vars to prevent further collisions
53                if let Some(ctx) = self.fn_ctx.as_mut() {
54                    ctx.add_scope_var(js_name);
55                }
56                IrIdent::with_zig_name(js_name, self.name_mangler.resolve_name(js_name))
57            } else {
58                // First occurrence ¡ª register and use normal name resolution
59                if let Some(ctx) = self.fn_ctx.as_mut() {
60                    ctx.add_scope_var(js_name);
61                }
62                self.make_ident(js_name)
63            }
64        } else {
65            self.make_ident(js_name)
66        };
67
68        // Determine const vs var based on mutation analysis (not JS keyword).
69        // Zig 'const' for never-mutated, 'var' for actually reassigned.
70        let fn_prefix = self
71            .fn_ctx
72            .as_ref()
73            .map(|ctx| ctx.name.as_str())
74            .unwrap_or("__toplevel__");
75        let is_const = !self
76            .type_info
77            .mutated_vars
78            .contains(&format!("{}::{}", fn_prefix, js_name));
79
80        // Skip unused toplevel constants
81        let has_type_annotation = self.jsdoc_data.type_annotations.contains_key(js_name);
82        if self.fn_ctx.is_none()
83            && is_const
84            && !self.type_info.used_names.contains(js_name)
85            && !has_type_annotation
86        {
87            return IrDecl::CompileError {
88                span: SourceSpan::default(),
89                msg: format!("skipped unused toplevel const: {}", js_name),
90            };
91        }
92
93        // Toplevel var/let ¡ú error (only const allowed at module level)
94        if self.fn_ctx.is_none() && !is_const {
95            return IrDecl::CompileError {
96                span: SourceSpan::default(),
97                msg: format!("toplevel only allows 'const', not '{}'", js_name),
98            };
99        }
100
101        // Force 'var' for Map/Set/ArrayList types (mutated via methods)
102        let is_const = if let Some(inferred_ty) = self.type_info.var_types.get(js_name) {
103            match inferred_ty {
104                ZigType::ArrayList(_) => false,
105                ZigType::NamedStruct(n) if n == "Map" || n == "Set" => false,
106                _ => is_const,
107            }
108        } else {
109            is_const
110        };
111
112        // Type from inference
113        let zig_type = self.type_info.var_types.get(js_name).cloned();
114
115        // JSON.parse special case
116        let is_json_parse = self.type_info.has_json_parse_types.contains(js_name);
117
118        // Needs var suppression (ArrayList/Map/Set method calls need `_= &var;`)
119        let needs_var_suppression = !is_const
120            && matches!(
121                zig_type,
122                Some(ZigType::ArrayList(_)) | Some(ZigType::NamedStruct(_))
123            );
124
125        // Lower initializer expression
126        let init = match decl.init.as_ref() {
127            Some(expr) => {
128                // Special case: arrow function / closure initializer.
129                // Instead of returning IrExpr::ArrowFn as init, we:
130                // 1. Register the struct definition in module.closure_structs
131                // 2. Return IrExpr::Ident pointing to the struct name
132                // This produces the output pattern:
133                //   const _arrow_fn_0 = struct { ... };
134                //   const double = _arrow_fn_0;
135                let ir = self.lower_expr(expr);
136                match ir {
137                    crate::zigir::types::IrExpr::ArrowFn(ref arrow) => {
138                        // Generate a unique struct name like _arrow_fn_0, _arrow_fn_1, ...
139                        // Use name_mangler counter to get sequential numbering.
140                        let idx = self.name_mangler.peek_count("arrow_fn");
141                        self.name_mangler.next_name("arrow_fn"); // advance counter
142                        let struct_name = format!("_arrow_fn_{}", idx);
143                        let struct_ident = IrIdent::new(&struct_name);
144                        // Register as closure struct (with empty captures)
145                        self.pending_arrow_structs
146                            .push(crate::zigir::types::IrClosureStruct {
147                                name: struct_ident.clone(),
148                                captured: vec![],
149                                fn_params: arrow.params.clone(),
150                                return_type: arrow.return_type.clone(),
151                                typeof_return_body: None,
152                                body: arrow.body.clone(),
153                            });
154                        Some(crate::zigir::types::IrExpr::Ident(struct_ident))
155                    }
156                    crate::zigir::types::IrExpr::Closure(ref closure) => {
157                        // Struct already registered by lower_fn_expr / lower_arrow_fn.
158                        // Closure instance: StructName { .captured = val, ... }
159                        Some(crate::zigir::types::IrExpr::Closure(closure.clone()))
160                    }
161                    _ => Some(ir),
162                }
163            }
164            None => None,
165        };
166
167        // Register TypedArray variables (for suffix lookup in lower_call)
168        if let Some(ZigType::NamedStruct(n)) = &zig_type
169            && let Some(suffix) = Self::typedarray_type_suffix(n)
170            && let Some(ctx) = self.fn_ctx.as_mut()
171        {
172            ctx.add_typedarray_var(&ident.zig_name, suffix);
173        }
174
175        // Register RegExp variables (for .test()/.exec() method dispatch in lower_call)
176        if let Some(expr) = decl.init.as_ref()
177            && Self::is_regexp_expr(expr)
178            && let Some(ctx) = self.fn_ctx.as_mut()
179        {
180            ctx.add_regexp_var(&ident.zig_name);
181        }
182
183        IrDecl::Var(IrVarDecl {
184            name: ident,
185            is_const,
186            zig_type,
187            init,
188            is_json_parse,
189            needs_var_suppression,
190        })
191    }
192
193    /// Lower a destructuring variable declaration.
194    ///
195    /// Handles `const {a, b} = expr` and `const [a, b] = expr` by constructing
196    /// an `IrStmt::DestructureDecl` that the Emitter expands into temp variable
197    /// + individual const/var declarations.
198    pub(super) fn lower_destructure_decl(
199        &mut self,
200        decl: &VariableDeclarator,
201    ) -> crate::zigir::types::IrStmt {
202        use crate::zigir::types::{
203            IrDestructureAccess, IrDestructureBindingDecl, IrDestructureDecl, IrDestructureKind,
204        };
205
206        let Some(init_expr) = &decl.init else {
207            return crate::zigir::types::IrStmt::CompileError {
208                span: SourceSpan::default(),
209                msg: "destructuring requires an initializer".to_string(),
210            };
211        };
212
213        let init_ir = self.lower_expr(init_expr);
214
215        match &decl.id {
216            BindingPattern::ObjectPattern(op) => {
217                // ©¤©¤ Object destructuring ©¤©¤
218                let init_type = if let Expression::Identifier(id) = init_expr {
219                    self.type_info.var_types.get(id.name.as_str()).cloned()
220                } else {
221                    None
222                };
223
224                let struct_field_names: Option<Vec<String>> = match &init_type {
225                    Some(ZigType::Struct(fields)) if !fields.is_empty() => {
226                        Some(fields.iter().map(|(n, _)| n.clone()).collect())
227                    }
228                    _ => None,
229                };
230                let is_struct = struct_field_names.is_some();
231
232                // Decide if we need a temp variable
233                let needs_temp = init_may_have_side_effects(init_expr) || op.properties.len() > 1;
234                let temp_name = if needs_temp {
235                    Some(self.name_mangler.next_name("_js_dest"))
236                } else {
237                    None
238                };
239
240                // Source for access patterns: temp var name or inline the init expr
241                let source = if needs_temp {
242                    temp_name.clone().unwrap()
243                } else if let Expression::Identifier(id) = init_expr {
244                    id.name.to_string()
245                } else {
246                    self.name_mangler.next_name("_js_dest")
247                };
248
249                let fn_prefix = self
250                    .fn_ctx
251                    .as_ref()
252                    .map(|ctx| ctx.name.as_str())
253                    .unwrap_or("__toplevel__");
254
255                // Phase 1: Collect binding metadata (no lower_expr calls yet)
256                struct RawObjBinding {
257                    key_name: String,
258                    bind_name: String,
259                    has_default: bool,
260                    default_index: usize, // index into op.properties if has_default
261                    is_struct_field: bool,
262                    is_const: bool,
263                }
264                let mut raw_bindings: Vec<RawObjBinding> = Vec::new();
265                let mut default_counter: usize = 0;
266                for prop in &op.properties {
267                    let key_name = match property_key_name(&prop.key) {
268                        Some(k) => k,
269                        None => continue,
270                    };
271
272                    let (bind_name, has_default) = match &prop.value {
273                        BindingPattern::BindingIdentifier(id) => (id.name.as_str(), false),
274                        BindingPattern::AssignmentPattern(ap) => {
275                            let Some(name) = crate::infer::binding_name(&ap.left) else {
276                                continue;
277                            };
278                            (name, true)
279                        }
280                        _ => continue,
281                    };
282
283                    let is_const = !self
284                        .type_info
285                        .mutated_vars
286                        .contains(&format!("{}::{}", fn_prefix, bind_name));
287
288                    // Skip unused toplevel constants
289                    if self.fn_ctx.is_none()
290                        && is_const
291                        && !self.type_info.used_names.contains(bind_name)
292                    {
293                        default_counter += if has_default { 1 } else { 0 };
294                        continue;
295                    }
296                    if self.fn_ctx.is_none() && !is_const {
297                        default_counter += if has_default { 1 } else { 0 };
298                        continue;
299                    }
300
301                    let is_struct_field = struct_field_names
302                        .as_ref()
303                        .is_some_and(|names| names.contains(&key_name));
304
305                    let di = default_counter;
306                    default_counter += if has_default { 1 } else { 0 };
307
308                    raw_bindings.push(RawObjBinding {
309                        key_name,
310                        bind_name: bind_name.to_string(),
311                        has_default,
312                        default_index: di,
313                        is_struct_field,
314                        is_const,
315                    });
316                }
317
318                // Collect default expression references from AST
319                let default_exprs: Vec<&Expression> = op
320                    .properties
321                    .iter()
322                    .filter_map(|prop| match &prop.value {
323                        BindingPattern::AssignmentPattern(ap) => Some(&ap.right),
324                        _ => None,
325                    })
326                    .collect();
327
328                // Phase 2: Build IrDestructureBindingDecl (can call self.lower_expr now)
329                let mut bindings = Vec::new();
330                for rb in raw_bindings {
331                    let default_ir = if rb.has_default {
332                        default_exprs
333                            .get(rb.default_index)
334                            .map(|e| self.lower_expr(e))
335                    } else {
336                        None
337                    };
338                    bindings.push(IrDestructureBindingDecl {
339                        name: self.make_ident(&rb.bind_name),
340                        is_const: rb.is_const,
341                        access: IrDestructureAccess::ObjectField {
342                            source: if needs_temp {
343                                temp_name.clone().unwrap()
344                            } else {
345                                source.clone()
346                            },
347                            key: rb.key_name,
348                            is_struct_field: rb.is_struct_field,
349                        },
350                        default: default_ir,
351                    });
352                }
353
354                crate::zigir::types::IrStmt::DestructureDecl(IrDestructureDecl {
355                    temp_name: if needs_temp { temp_name } else { None },
356                    init: init_ir,
357                    kind: IrDestructureKind::Object {
358                        is_struct,
359                        struct_field_names,
360                    },
361                    bindings,
362                })
363            }
364
365            BindingPattern::ArrayPattern(ap) => {
366                // ©¤©¤ Array destructuring ©¤©¤
367                let init_type = if let Expression::Identifier(id) = init_expr {
368                    self.type_info.var_types.get(id.name.as_str()).cloned()
369                } else {
370                    None
371                };
372                let is_arraylist = matches!(init_type, Some(ZigType::ArrayList(_)));
373
374                // Decide if we need a temp variable
375                let element_count = ap.elements.iter().filter(|e| e.is_some()).count();
376                let needs_temp = init_may_have_side_effects(init_expr) || element_count > 1;
377                let temp_name = if needs_temp {
378                    Some(self.name_mangler.next_name("_js_dest"))
379                } else {
380                    None
381                };
382
383                let source = if needs_temp {
384                    temp_name.clone().unwrap()
385                } else if let Expression::Identifier(id) = init_expr {
386                    id.name.to_string()
387                } else {
388                    self.name_mangler.next_name("_js_dest")
389                };
390
391                let fn_prefix = self
392                    .fn_ctx
393                    .as_ref()
394                    .map(|ctx| ctx.name.as_str())
395                    .unwrap_or("__toplevel__");
396
397                // Phase 1: Collect binding metadata
398                struct RawArrBinding {
399                    bind_name: String,
400                    index: usize,
401                    has_default: bool,
402                    default_index: usize,
403                    is_const: bool,
404                }
405                let mut raw_bindings: Vec<RawArrBinding> = Vec::new();
406                let mut default_counter: usize = 0;
407                for (i, elem) in ap.elements.iter().enumerate() {
408                    let Some(pattern) = elem else {
409                        continue; // skip holes
410                    };
411
412                    let (bind_name, has_default) = match pattern {
413                        BindingPattern::BindingIdentifier(id) => (id.name.as_str(), false),
414                        BindingPattern::AssignmentPattern(ap_inner) => {
415                            let Some(name) = crate::infer::binding_name(&ap_inner.left) else {
416                                continue;
417                            };
418                            (name, true)
419                        }
420                        _ => continue,
421                    };
422
423                    let is_const = !self
424                        .type_info
425                        .mutated_vars
426                        .contains(&format!("{}::{}", fn_prefix, bind_name));
427
428                    if self.fn_ctx.is_none()
429                        && is_const
430                        && !self.type_info.used_names.contains(bind_name)
431                    {
432                        default_counter += if has_default { 1 } else { 0 };
433                        continue;
434                    }
435                    if self.fn_ctx.is_none() && !is_const {
436                        default_counter += if has_default { 1 } else { 0 };
437                        continue;
438                    }
439
440                    let di = default_counter;
441                    default_counter += if has_default { 1 } else { 0 };
442
443                    raw_bindings.push(RawArrBinding {
444                        bind_name: bind_name.to_string(),
445                        index: i,
446                        has_default,
447                        default_index: di,
448                        is_const,
449                    });
450                }
451
452                // Collect default expression references from AST
453                let default_exprs: Vec<&Expression> = ap
454                    .elements
455                    .iter()
456                    .flatten()
457                    .filter_map(|pattern| match pattern {
458                        BindingPattern::AssignmentPattern(ap_inner) => Some(&ap_inner.right),
459                        _ => None,
460                    })
461                    .collect();
462
463                // Phase 2: Build IrDestructureBindingDecl
464                let mut bindings = Vec::new();
465                for rb in raw_bindings {
466                    let default_ir = if rb.has_default {
467                        default_exprs
468                            .get(rb.default_index)
469                            .map(|e| self.lower_expr(e))
470                    } else {
471                        None
472                    };
473                    bindings.push(IrDestructureBindingDecl {
474                        name: self.make_ident(&rb.bind_name),
475                        is_const: rb.is_const,
476                        access: IrDestructureAccess::ArrayIndex {
477                            source: if needs_temp {
478                                temp_name.clone().unwrap()
479                            } else {
480                                source.clone()
481                            },
482                            index: rb.index,
483                        },
484                        default: default_ir,
485                    });
486                }
487
488                crate::zigir::types::IrStmt::DestructureDecl(IrDestructureDecl {
489                    temp_name: if needs_temp { temp_name } else { None },
490                    init: init_ir,
491                    kind: IrDestructureKind::Array { is_arraylist },
492                    bindings,
493                })
494            }
495
496            _ => crate::zigir::types::IrStmt::CompileError {
497                span: SourceSpan::default(),
498                msg: "unsupported binding pattern in variable declaration".to_string(),
499            },
500        }
501    }
502
503    /// Lower a function declaration.
504    ///
505    /// Translates JS `function foo(a, b) { ... }` into `IrDecl::Fn`.
506    /// Handles:
507    /// - export / C ABI determination
508    /// - async detection (from type_info.is_async)
509    /// - throw/catch detection (pre-scan body)
510    /// - parameter type resolution
511    /// - return type resolution (including AnytypeReturn ¡ú @TypeOf)
512    /// - shadow renaming for parameters
513    pub(super) fn lower_fn_decl(
514        &mut self,
515        fd: &Function,
516        is_export: bool,
517    ) -> Option<crate::zigir::types::IrFnDecl> {
518        let name = fd.id.as_ref().map(|id| id.name.as_str())?;
519
520        // Pre-scan: check if function contains throw or try-catch
521        let has_throw = fd.body.as_ref().is_some_and(|b| Self::has_throw_in_body(b));
522
523        // Check async from type_info
524        let is_async = self.type_info.is_async.get(name).copied().unwrap_or(false);
525
526        // Return type from inference
527        let return_type = self
528            .type_info
529            .fn_return_types
530            .get(name)
531            .cloned()
532            .unwrap_or(ZigType::Void);
533
534        // Enter function context
535        let saved = self.enter_fn(name, is_export, Some(return_type.clone()));
536
537        // Push shadow scope for function body (param renames live here)
538        self.name_mangler.push_shadow_scope();
539
540        // Lower parameters
541        let mut params = self.lower_fn_params(fd, name);
542
543        // Register parameter names in fn_scope_vars (for shadow detection)
544        if let Some(ctx) = self.fn_ctx.as_mut() {
545            for param in &params {
546                ctx.add_scope_var(&param.name.js_name);
547            }
548        }
549
550        // Lower function body
551        let body = fd
552            .body
553            .as_ref()
554            .map(|b| self.lower_block(&b.statements))
555            .unwrap_or_else(|| IrBlock::new(vec![]));
556
557        // Mark unused parameters: collect all identifier references in the body,
558        // then check which params don't appear. Also include identifiers from
559        // compile-time-resolved expressions (e.g., typeof x ¡ú "number") that
560        // were optimized away but still semantically reference the parameter.
561        let mut used_idents = Self::collect_ir_idents_in_block(&body);
562        if let Some(ctx) = self.fn_ctx.as_ref() {
563            used_idents.extend(ctx.compile_time_referenced_idents.iter().cloned());
564        }
565        // For async functions, `io` is always used by await/async emission
566        if is_async {
567            used_idents.insert("io".to_string());
568        }
569        for param in &mut params {
570            if !used_idents.contains(&param.name.js_name) {
571                param.is_unused = true;
572            }
573        }
574
575        // Exit function context and shadow scope
576        self.name_mangler.pop_shadow_scope();
577        let _fn_ctx = self.exit_fn(saved);
578
579        // Determine C ABI: export functions use `export fn` calling convention
580        let is_cabi = is_export;
581
582        // For AnytypeReturn: capture the first return expression so the Emitter
583        // can emit `@TypeOf(expr)` instead of the literal `anytype` keyword.
584        let typeof_return_body = if matches!(return_type, ZigType::AnytypeReturn) {
585            Self::find_first_return_expr_in_block(&body).map(|e| Box::new(e.clone()))
586        } else {
587            None
588        };
589
590        Some(crate::zigir::types::IrFnDecl {
591            name: self.make_ident(name),
592            params,
593            return_type,
594            typeof_return_body,
595            body,
596            is_export,
597            is_async,
598            can_throw: has_throw,
599            is_cabi,
600        })
601    }
602
603    /// Lower a nested function declaration into struct+call() pattern.
604    ///
605    /// Zig doesn't allow nested function declarations with return statements,
606    /// so we emit `const name = struct { pub fn call(...) ... };` and rewrite
607    /// call sites to `name.call(args)`.
608    ///
609    /// For functions that capture variables from the enclosing scope:
610    /// `const _name_type = struct { x: i64, pub fn call(self: *@This(), ...) ... };`
611    /// `const name = _name_type{ .x = x };`
612    pub(super) fn lower_nested_fn_decl(&mut self, fd: &Function) -> crate::zigir::types::IrStmt {
613        use crate::zigir::types::{IrCapture, IrClosure, IrClosureStruct, IrStmt};
614
615        let fn_name = fd
616            .id
617            .as_ref()
618            .map(|id| id.name.as_str())
619            .unwrap_or("_anon_fn");
620
621        // Detect captures from enclosing scope
622        let captures = self.detect_fn_body_captures(fd);
623
624        // Enter a sub-function context to lower the body
625        let return_type = self
626            .type_info
627            .fn_return_types
628            .get(fn_name)
629            .cloned()
630            .unwrap_or(ZigType::Void);
631
632        let saved = self.enter_fn(fn_name, false, Some(return_type.clone()));
633        self.name_mangler.push_shadow_scope();
634
635        let params = self.lower_fn_params(fd, fn_name);
636
637        // Register param names in fn_scope_vars
638        if let Some(ctx) = self.fn_ctx.as_mut() {
639            for param in &params {
640                ctx.add_scope_var(&param.name.js_name);
641            }
642        }
643
644        let body = fd
645            .body
646            .as_ref()
647            .map(|b| self.lower_block(&b.statements))
648            .unwrap_or_else(|| IrBlock::new(vec![]));
649
650        self.name_mangler.pop_shadow_scope();
651        let _fn_ctx = self.exit_fn(saved);
652
653        // For AnytypeReturn: capture the first return expression so the Emitter
654        // can emit `@TypeOf(expr)` instead of `anytype`.
655        let typeof_return_body = if matches!(return_type, ZigType::AnytypeReturn) {
656            Self::find_first_return_expr_in_block(&body).map(|e| Box::new(e.clone()))
657        } else {
658            None
659        };
660
661        // Register as a nested function name (for call-site rewriting)
662        if let Some(ctx) = self.fn_ctx.as_mut() {
663            ctx.add_nested_fn(fn_name);
664        }
665
666        let fn_ident = self.make_ident(fn_name);
667
668        if !captures.is_empty() {
669            // ©¤©¤ Has captures: named type struct + instance ©¤©¤
670            // Generates:
671            //   const _inner_type = struct { x: i64, pub fn call(self: *@This(), y: anytype) ... { ... } };
672            //   const inner = _inner_type{ .x = x };
673            let type_name = format!("_{}_type", fn_ident.zig_name);
674            let type_ident = IrIdent::with_zig_name(fn_name, type_name.clone());
675            let instance_ident = fn_ident;
676
677            let ir_captures: Vec<IrCapture> = captures
678                .into_iter()
679                .map(|(name, zig_type, is_mut)| IrCapture {
680                    name: self.make_ident(&name),
681                    zig_type,
682                    is_mut,
683                })
684                .collect();
685
686            // Create the struct definition (emitted inline in function body)
687            let closure_struct = IrClosureStruct {
688                name: type_ident.clone(),
689                captured: ir_captures.clone(),
690                fn_params: params,
691                return_type: return_type.clone(),
692                typeof_return_body: typeof_return_body.clone(),
693                body,
694            };
695
696            // Create the instance: TypeName { .x = x, ... }
697            let instance = IrClosure {
698                struct_name: type_ident,
699                captured: ir_captures,
700                fn_params: vec![], // already in struct def
701                return_type: return_type.clone(),
702                body: IrBlock::new(vec![]), // body already in struct def
703                instance_name: instance_ident,
704            };
705
706            IrStmt::NestedFnDecl {
707                struct_def: closure_struct,
708                instance: Some(instance),
709            }
710        } else {
711            // ©¤©¤ No captures: inline struct with static call method ©¤©¤
712            // Generates:
713            //   const inner = struct { pub fn call(y: anytype) ... { ... } };
714            let closure_struct = IrClosureStruct {
715                name: fn_ident,
716                captured: vec![],
717                fn_params: params,
718                return_type,
719                typeof_return_body,
720                body,
721            };
722
723            IrStmt::NestedFnDecl {
724                struct_def: closure_struct,
725                instance: None,
726            }
727        }
728    }
729
730    /// Lower function parameters into IrParam list.
731    ///
732    /// Reads parameter types from type_info when available, falls back to
733    /// anytype for untyped parameters.
734    pub(super) fn lower_fn_params(&mut self, fd: &Function, fn_name: &str) -> Vec<IrParam> {
735        let mut params = Vec::new();
736        let is_async = self
737            .type_info
738            .is_async
739            .get(fn_name)
740            .copied()
741            .unwrap_or(false);
742
743        // Async functions get `io: anytype` as the first parameter
744        if is_async {
745            params.push(IrParam {
746                name: self.make_ident("io"),
747                zig_type: ZigType::Anytype,
748                is_unused: false,
749                is_rest: false,
750            });
751        }
752
753        // Try to get param types from type_info
754        let param_types = self.type_info.fn_param_types.get(fn_name).cloned();
755
756        if let Some(ptypes) = param_types {
757            for (pname, ptype) in &ptypes {
758                // Skip 'io' param for async functions (it's already injected above)
759                if is_async && pname == "io" {
760                    continue;
761                }
762                params.push(IrParam {
763                    name: self.make_ident(pname),
764                    zig_type: ptype.clone(),
765                    is_unused: false, // set later in lower_fn_decl
766                    is_rest: false,
767                });
768            }
769        } else {
770            // Fallback: generate params from AST with anytype
771            for param in &fd.params.items {
772                if let Some(pname) = crate::infer::binding_name(&param.pattern) {
773                    params.push(IrParam {
774                        name: self.make_ident(pname),
775                        zig_type: ZigType::Anytype,
776                        is_unused: false, // set later in lower_fn_decl
777                        is_rest: false,
778                    });
779                }
780            }
781        }
782
783        // Handle rest parameter (...args) ¡ú []const JsAny
784        if let Some(rname) = fd
785            .params
786            .rest
787            .as_ref()
788            .and_then(|r| crate::infer::binding_name(&r.rest.argument))
789        {
790            params.push(IrParam {
791                name: self.make_ident(rname),
792                zig_type: ZigType::Anytype, // Will be rendered as []const JsAny by Emitter
793                is_unused: false,           // set later in lower_fn_decl
794                is_rest: true,
795            });
796        }
797
798        params
799    }
800
801    /// Pre-scan: check if a function body contains `throw` or `try-catch`.
802    ///
803    /// This is needed to determine whether the return type should be an
804    /// error union (`!T` vs `T`).
805    pub(super) fn has_throw_in_body(body: &FunctionBody) -> bool {
806        body.statements.iter().any(|s| Self::stmt_has_throw(s))
807    }
808
809    pub(super) fn stmt_has_throw(stmt: &Statement) -> bool {
810        match stmt {
811            Statement::ThrowStatement(_) => true,
812            Statement::BlockStatement(bs) => bs.body.iter().any(|s| Self::stmt_has_throw(s)),
813            Statement::IfStatement(is) => {
814                Self::stmt_has_throw(&is.consequent)
815                    || is
816                        .alternate
817                        .as_ref()
818                        .is_some_and(|a| Self::stmt_has_throw(a))
819            }
820            Statement::WhileStatement(ws) => Self::stmt_has_throw(&ws.body),
821            Statement::DoWhileStatement(dws) => Self::stmt_has_throw(&dws.body),
822            Statement::ForStatement(fs) => Self::stmt_has_throw(&fs.body),
823            Statement::ForOfStatement(fos) => Self::stmt_has_throw(&fos.body),
824            Statement::ForInStatement(fis) => Self::stmt_has_throw(&fis.body),
825            Statement::TryStatement(_) => true, // try-catch implies potential throw
826            Statement::SwitchStatement(ss) => ss
827                .cases
828                .iter()
829                .any(|c| c.consequent.iter().any(|s| Self::stmt_has_throw(s))),
830            _ => false,
831        }
832    }
833}