Skip to main content

js2zig_core/zigir/lower/expr/
function.rs

1// zigir/lower/expr/function.rs
2// Arrow function and function expression lowering.
3
4use oxc_ast::ast::*;
5
6use crate::zigir::ident::IrIdent;
7use crate::zigir::types::IrBlock;
8
9use super::Lowerer;
10
11impl Lowerer {
12    /// Lower an arrow function expression.
13    ///
14    /// If the arrow captures variables from the enclosing scope, we produce
15    /// an `IrClosure` (struct + instance).  Otherwise we produce a plain
16    /// `IrArrowFn` (struct + static call — Zig 0.16 doesn't allow nested
17    /// fn declarations with return statements).
18    pub(super) fn lower_arrow_fn(
19        &mut self,
20        af: &ArrowFunctionExpression,
21    ) -> crate::zigir::types::IrExpr {
22        use crate::zigir::types::{IrArrowFn, IrCapture, IrClosure, IrExpr};
23
24        let captured = self.collect_arrow_captures(af);
25        let is_concise = af.body.statements.len() == 1
26            && matches!(af.body.statements[0], Statement::ExpressionStatement(_));
27        let return_type = self.infer_arrow_return_type(af, &captured);
28        let params = self.lower_arrow_params(af);
29
30        // Enter a temporary fn context so that lower_stmt / lower_expr can
31        // see captured-variable state.
32        let arrow_fn_label = format!("_arrow_{}", self.name_mangler.next_name("arrow"));
33        let saved_fn = self.enter_fn(&arrow_fn_label, false, Some(return_type.clone()));
34
35        // Set closure_mgr.current_captured so that lower_ident_expr can
36        // rewrite captured identifiers to self.xxx.
37        let saved_captured = self.closure_mgr.take_captured();
38        self.closure_mgr.current_captured = captured
39            .iter()
40            .map(|(n, t, m)| (n.clone(), t.clone(), *m))
41            .collect();
42
43        // Lower the body
44        let body = if is_concise {
45            if let Statement::ExpressionStatement(es) = &af.body.statements[0] {
46                let expr_ir = self.lower_expr(&es.expression);
47                IrBlock::new(vec![crate::zigir::types::IrStmt::Return {
48                    value: Some(expr_ir),
49                }])
50            } else {
51                self.lower_block(&af.body.statements)
52            }
53        } else {
54            self.lower_block(&af.body.statements)
55        };
56
57        // Restore closure state
58        self.closure_mgr.restore_captured(saved_captured);
59        self.exit_fn(saved_fn);
60
61        if !captured.is_empty() {
62            // Has captures → IrClosure
63            let idx = self.name_mangler.peek_count("closure");
64            let struct_name = IrIdent::new(&format!("Closure_{}", idx));
65            let instance_name = IrIdent::new(&format!("_cl_{}", idx));
66            self.name_mangler.next_name("closure"); // advance counter
67
68            let ir_captures: Vec<IrCapture> = captured
69                .into_iter()
70                .map(|(name, zig_type, is_mut)| IrCapture {
71                    name: self.make_ident(&name),
72                    zig_type,
73                    is_mut,
74                })
75                .collect();
76
77            // Register this as a closure instance
78            self.closure_mgr
79                .closure_instances
80                .insert(instance_name.zig_name.clone());
81
82            // Register the closure struct definition so the Emitter can emit it
83            // at module scope.
84            self.pending_arrow_structs
85                .push(crate::zigir::types::IrClosureStruct {
86                    name: struct_name.clone(),
87                    captured: ir_captures.clone(),
88                    fn_params: params.clone(),
89                    return_type: return_type.clone(),
90                    typeof_return_body: None,
91                    body: body.clone(),
92                });
93
94            IrExpr::Closure(IrClosure {
95                struct_name,
96                captured: ir_captures,
97                fn_params: params,
98                return_type,
99                body,
100                instance_name,
101            })
102        } else {
103            // No captures → IrArrowFn
104            IrExpr::ArrowFn(IrArrowFn {
105                params,
106                return_type,
107                body,
108                is_concise,
109            })
110        }
111    }
112
113    /// Lower a function expression.
114    ///
115    /// Like arrow functions, if the function captures variables we produce
116    /// an `IrClosure`; otherwise a plain `IrFnExpr`.
117    pub(super) fn lower_fn_expr(&mut self, fe: &Function) -> crate::zigir::types::IrExpr {
118        use crate::zigir::types::{IrCapture, IrClosure, IrExpr, IrFnExpr};
119
120        let name = fe
121            .id
122            .as_ref()
123            .map(|id| id.name.to_string())
124            .unwrap_or_else(|| {
125                let idx = self.name_mangler.peek_count("_fn_expr");
126                self.name_mangler.next_name("_fn_expr"); // advance counter
127                format!("_fn_expr_{}", idx)
128            });
129
130        let captured = self.detect_fn_body_captures(fe);
131        let return_type = self
132            .type_info
133            .fn_return_types
134            .get(&name)
135            .cloned()
136            .unwrap_or_else(|| self.infer_fn_expr_return_type(fe, &captured));
137
138        // Enter function context
139        let _has_throw = fe
140            .body
141            .as_ref()
142            .is_some_and(|b| Self::has_throw_in_stmts(&b.statements));
143        let saved_fn = self.enter_fn(&name, false, Some(return_type.clone()));
144
145        // Set captured variables for identifier rewriting
146        let saved_captured = self.closure_mgr.take_captured();
147        self.closure_mgr.current_captured = captured
148            .iter()
149            .map(|(n, t, m)| (n.clone(), t.clone(), *m))
150            .collect();
151
152        // Lower params
153        let params = self.lower_fn_params(fe, &name);
154
155        // Lower body
156        let body = fe
157            .body
158            .as_ref()
159            .map(|b| self.lower_block(&b.statements))
160            .unwrap_or_else(|| IrBlock::new(vec![]));
161
162        // Restore
163        self.closure_mgr.restore_captured(saved_captured);
164        self.exit_fn(saved_fn);
165
166        if !captured.is_empty() {
167            // Has captures → IrClosure
168            let struct_name = self.make_ident(&name);
169            let instance_name = IrIdent::new(&format!("_{}_inst", name));
170
171            let ir_captures: Vec<IrCapture> = captured
172                .into_iter()
173                .map(|(n, zig_type, is_mut)| IrCapture {
174                    name: self.make_ident(&n),
175                    zig_type,
176                    is_mut,
177                })
178                .collect();
179
180            self.closure_mgr
181                .closure_instances
182                .insert(instance_name.zig_name.clone());
183
184            // Register the closure struct definition so the Emitter can emit it
185            // at module scope.
186            self.pending_arrow_structs
187                .push(crate::zigir::types::IrClosureStruct {
188                    name: struct_name.clone(),
189                    captured: ir_captures.clone(),
190                    fn_params: params.clone(),
191                    return_type: return_type.clone(),
192                    typeof_return_body: None,
193                    body: body.clone(),
194                });
195
196            IrExpr::Closure(IrClosure {
197                struct_name,
198                captured: ir_captures,
199                fn_params: params,
200                return_type,
201                body,
202                instance_name,
203            })
204        } else {
205            // No captures → IrFnExpr
206            // Still register a closure struct so the Emitter emits the
207            // `const _fn_expr_N = struct { pub fn call() ... }` definition
208            // at module scope (the FnExpr reference only emits the name).
209            let struct_name = self.make_ident(&name);
210            self.pending_arrow_structs
211                .push(crate::zigir::types::IrClosureStruct {
212                    name: struct_name.clone(),
213                    captured: vec![],
214                    fn_params: params.clone(),
215                    return_type: return_type.clone(),
216                    typeof_return_body: None,
217                    body: body.clone(),
218                });
219
220            IrExpr::FnExpr(IrFnExpr {
221                name: Some(self.make_ident(&name)),
222                params,
223                return_type,
224                body,
225            })
226        }
227    }
228}