Skip to main content

js2zig_core/zigir/lower/
class.rs

1// zigir/lower/class.rs
2// Class declaration lowering: fields, methods, constructor, this-rewrite.
3
4use std::collections::HashSet;
5
6use oxc_ast::ast::*;
7
8use crate::types::ZigType;
9use crate::zigir::types::{IrBlock, IrParam};
10
11use super::Lowerer;
12use super::cabi::property_key_name;
13
14// ¨T¨T¨T¨T¨T¨T¨T¨T¨T¨T¨T¨T¨T¨T¨T¨T¨T¨T¨T¨T¨T¨T¨T¨T¨T¨T¨T¨T¨T¨T¨T¨T¨T¨T¨T¨T¨T¨T¨T¨T¨T¨T¨T¨T¨T¨T¨T¨T¨T¨T¨T¨T¨T¨T¨T
15//  Remaining stubs
16// ¨T¨T¨T¨T¨T¨T¨T¨T¨T¨T¨T¨T¨T¨T¨T¨T¨T¨T¨T¨T¨T¨T¨T¨T¨T¨T¨T¨T¨T¨T¨T¨T¨T¨T¨T¨T¨T¨T¨T¨T¨T¨T¨T¨T¨T¨T¨T¨T¨T¨T¨T¨T¨T¨T¨T
17
18impl Lowerer {
19    /// Generate a unique name for an anonymous class expression.
20    fn next_anon_class_name(&mut self) -> String {
21        let n = self.anon_class_counter;
22        self.anon_class_counter += 1;
23        format!("_AnonClass_{}", n)
24    }
25
26    /// Lower a class declaration into IrClassDecl.
27    ///
28    /// Extracts fields (from PropertyDefinition and implicit constructor `this.x = ...`),
29    /// constructor ¡ú IrClassMethod, regular methods ¡ú IrClassMethod, and static inits.
30    pub(super) fn lower_class_decl(
31        &mut self,
32        cd: &Class,
33    ) -> Option<crate::zigir::types::IrClassDecl> {
34        use crate::zigir::types::{IrClassDecl, IrClassField, IrClassMethod};
35
36        let class_name = cd
37            .id
38            .as_ref()
39            .map(|id| id.name.to_string())
40            .unwrap_or_else(|| {
41                // Anonymous class expression needs a unique name to avoid collisions
42                self.next_anon_class_name()
43            });
44
45        // Save/restore current_class — set early so that static blocks
46        // and field initializers can reference `this` correctly.
47        let saved_class = self.current_class.take();
48        self.current_class = Some(class_name.clone());
49
50        // Pre-scan: collect static field names so `this.field` in static blocks
51        // can be routed correctly via class_static_fields during lowering.
52        let mut pre_scan_static_names: HashSet<String> = HashSet::new();
53        for elem in &cd.body.body {
54            if let ClassElement::PropertyDefinition(pd) = elem
55                && pd.r#static
56                && !pd.computed
57                && let Some(name) = property_key_name(&pd.key)
58            {
59                pre_scan_static_names.insert(name);
60            }
61        }
62        if !pre_scan_static_names.is_empty() {
63            self.class_static_fields
64                .insert(class_name.clone(), pre_scan_static_names);
65        }
66
67        // ── First pass: collect explicit fields from PropertyDefinition ──
68        let mut field_names: Vec<String> = Vec::new();
69        let mut fields: Vec<IrClassField> = Vec::new();
70        let mut static_inits: Vec<(String, crate::zigir::types::IrExpr, ZigType)> = Vec::new();
71        let mut static_blocks: Vec<IrBlock> = Vec::new();
72        let mut has_constructor = false;
73        let mut constructor_func: Option<&Function> = None;
74
75        for elem in &cd.body.body {
76            match elem {
77                ClassElement::PropertyDefinition(pd) => {
78                    if pd.computed {
79                        continue;
80                    }
81                    let is_static = pd.r#static;
82                    if let Some(name) = property_key_name(&pd.key) {
83                        if is_static {
84                            if let Some(value) = &pd.value {
85                                let field_ty = self
86                                    .type_info
87                                    .class_field_types
88                                    .get(&class_name)
89                                    .and_then(|m| m.get(&name))
90                                    .cloned()
91                                    .unwrap_or(ZigType::JsAny);
92                                // Register static field type in var_types for Member target type inference
93                                let var_key = format!("__{}_{}", class_name, name);
94                                self.type_info.var_types.insert(var_key, field_ty.clone());
95                                static_inits.push((name.clone(), self.lower_expr(value), field_ty));
96                            }
97                        } else if !field_names.contains(&name) {
98                            let field_ty = self
99                                .type_info
100                                .class_field_types
101                                .get(&class_name)
102                                .and_then(|m| m.get(&name))
103                                .cloned()
104                                .unwrap_or(ZigType::JsAny);
105                            let default = pd.value.as_ref().map(|v| self.lower_expr(v));
106                            field_names.push(name.clone());
107                            fields.push(IrClassField {
108                                name,
109                                zig_type: field_ty,
110                                default,
111                            });
112                        }
113                    }
114                }
115                ClassElement::MethodDefinition(md) if Self::is_constructor_method(md) => {
116                    has_constructor = true;
117                    constructor_func = Some(&md.value);
118                }
119                ClassElement::StaticBlock(sb) => {
120                    // Lower static block — set in_static_block so `this` → ClassName
121                    let saved_static_block = self.in_static_block;
122                    self.in_static_block = true;
123                    let block = self.lower_block(&sb.body);
124                    self.in_static_block = saved_static_block;
125                    static_blocks.push(block);
126                }
127                _ => {}
128            }
129        }
130
131        // ── Second pass: scan constructor body for implicit `this.x = ...` fields ──
132        if let Some(func) = constructor_func
133            && let Some(body) = &func.body
134        {
135            self.collect_implicit_class_fields(
136                &body.statements,
137                &class_name,
138                &mut field_names,
139                &mut fields,
140            );
141        }
142
143        // ── Lower constructor ──
144        let constructor = if has_constructor {
145            constructor_func
146                .map(|func| self.lower_class_method(&class_name, &field_names, "init", func, false))
147        } else {
148            None
149        };
150
151        // ©¤©¤ Lower methods ©¤©¤
152        let mut methods: Vec<IrClassMethod> = Vec::new();
153        for elem in &cd.body.body {
154            if let ClassElement::MethodDefinition(md) = elem
155                && !Self::is_constructor_method(md)
156            {
157                let method_name =
158                    property_key_name(&md.key).unwrap_or_else(|| "anonymous".to_string());
159                let is_static = md.r#static;
160                let method = self.lower_class_method(
161                    &class_name,
162                    &field_names,
163                    &method_name,
164                    &md.value,
165                    is_static,
166                );
167                methods.push(method);
168            }
169        }
170
171        // ©¤©¤ Restore ©¤©¤
172        self.current_class = saved_class;
173
174        // ©¤©¤ extends ©¤©¤
175        let extends = cd.super_class.as_ref().and_then(|sc| {
176            if let Expression::Identifier(id) = sc {
177                Some(id.name.to_string())
178            } else {
179                None
180            }
181        });
182
183        // static field names already registered in class_static_fields during pre-scan
184
185        // Compute needs_deinit: true if any field is Map, Set, ArrayList, BigInt,
186        // or a NamedStruct that itself needs deinit (nested class).
187        let needs_deinit = fields.iter().any(|f| {
188            matches!(
189                f.zig_type,
190                ZigType::NamedStruct(ref n) if n == "Map" || n == "Set"
191            ) || matches!(f.zig_type, ZigType::ArrayList(_))
192                || matches!(f.zig_type, ZigType::BigInt)
193        });
194
195        Some(IrClassDecl {
196            name: self.make_ident(&class_name),
197            fields,
198            constructor,
199            methods,
200            static_inits,
201            static_blocks,
202            extends,
203            needs_deinit,
204        })
205    }
206
207    /// Check if a MethodDefinition is `constructor()`.
208    pub(super) fn is_constructor_method(md: &MethodDefinition) -> bool {
209        property_key_name(&md.key).is_some_and(|name| name == "constructor")
210    }
211
212    /// Scan constructor body for `this.x = ...` assignments and add
213    /// discovered fields if not already present.
214    pub(super) fn collect_implicit_class_fields(
215        &self,
216        stmts: &[Statement],
217        class_name: &str,
218        field_names: &mut Vec<String>,
219        fields: &mut Vec<crate::zigir::types::IrClassField>,
220    ) {
221        for stmt in stmts {
222            match stmt {
223                Statement::ExpressionStatement(es) => {
224                    if let Expression::AssignmentExpression(ae) = &es.expression
225                        && let AssignmentTarget::StaticMemberExpression(sme) = &ae.left
226                        && matches!(&sme.object, Expression::ThisExpression(_))
227                    {
228                        let fname = sme.property.name.to_string();
229                        if !field_names.contains(&fname) {
230                            let ftype = self
231                                .type_info
232                                .class_field_types
233                                .get(class_name)
234                                .and_then(|m| m.get(&fname))
235                                .cloned()
236                                .unwrap_or(ZigType::JsAny);
237                            field_names.push(fname.clone());
238                            fields.push(crate::zigir::types::IrClassField {
239                                name: fname,
240                                zig_type: ftype,
241                                default: None,
242                            });
243                        }
244                    }
245                }
246                Statement::IfStatement(is) => {
247                    self.collect_implicit_class_fields(
248                        std::slice::from_ref(&is.consequent),
249                        class_name,
250                        field_names,
251                        fields,
252                    );
253                    if let Some(alt) = &is.alternate {
254                        self.collect_implicit_class_fields(
255                            std::slice::from_ref(alt),
256                            class_name,
257                            field_names,
258                            fields,
259                        );
260                    }
261                }
262                Statement::BlockStatement(bs) => {
263                    self.collect_implicit_class_fields(&bs.body, class_name, field_names, fields);
264                }
265                _ => {}
266            }
267        }
268    }
269
270    /// Lower a class method (constructor or regular) into IrClassMethod.
271    pub(super) fn lower_class_method(
272        &mut self,
273        class_name: &str,
274        field_names: &[String],
275        method_name: &str,
276        func: &Function,
277        is_static: bool,
278    ) -> crate::zigir::types::IrClassMethod {
279        // For fully-qualified key lookups
280        let fq_method = format!("{}.{}", class_name, method_name);
281
282        let return_type = self
283            .type_info
284            .fn_return_types
285            .get(&fq_method)
286            .or_else(|| self.type_info.fn_return_types.get(method_name))
287            .cloned()
288            .unwrap_or(if method_name == "init" {
289                ZigType::NamedStruct(class_name.to_string())
290            } else {
291                ZigType::Void
292            });
293
294        // Parameters
295        let params = if method_name == "init" {
296            self.lower_fn_params(func, "init")
297        } else {
298            let param_types = self
299                .type_info
300                .fn_param_types
301                .get(&fq_method)
302                .or_else(|| self.type_info.fn_param_types.get(method_name))
303                .cloned();
304            if let Some(ptypes) = param_types {
305                let mut params = Vec::new();
306                for (pname, ptype) in &ptypes {
307                    params.push(IrParam {
308                        name: self.make_ident(pname),
309                        zig_type: ptype.clone(),
310                        is_unused: false,
311                        is_rest: false,
312                    });
313                }
314                params
315            } else {
316                self.lower_fn_params(func, method_name)
317            }
318        };
319
320        // Enter function context
321        let saved_fn = self.enter_fn(method_name, false, Some(return_type.clone()));
322
323        // Lower body
324        let body = func
325            .body
326            .as_ref()
327            .map(|b| {
328                if method_name == "init" {
329                    // Constructor: use this-rewrite lowering
330                    self.lower_block_with_this_rewrite(&b.statements, field_names)
331                } else {
332                    self.lower_block(&b.statements)
333                }
334            })
335            .unwrap_or_else(|| IrBlock::new(vec![]));
336
337        self.exit_fn(saved_fn);
338
339        crate::zigir::types::IrClassMethod {
340            name: method_name.to_string(),
341            params,
342            return_type,
343            body,
344            is_static,
345        }
346    }
347
348    /// Lower a block of statements with `this.x = value` rewriting.
349    ///
350    /// In constructors, `this.field = value` is rewritten as a local const binding
351    /// that the Emitter will use to build the struct return.
352    pub(super) fn lower_block_with_this_rewrite(
353        &mut self,
354        stmts: &[Statement],
355        field_names: &[String],
356    ) -> IrBlock {
357        let mut ir_stmts = Vec::new();
358        for stmt in stmts {
359            match stmt {
360                Statement::ExpressionStatement(es) => {
361                    // Check if this is `this.field = value`
362                    if let Expression::AssignmentExpression(ae) = &es.expression
363                        && let AssignmentTarget::StaticMemberExpression(sme) = &ae.left
364                        && matches!(&sme.object, Expression::ThisExpression(_))
365                    {
366                        let fname = sme.property.name.to_string();
367                        if field_names.contains(&fname) {
368                            // this.field = value ¡ú const field = value
369                            let value_ir = self.lower_expr(&ae.right);
370                            ir_stmts.push(crate::zigir::types::IrStmt::VarDecl(
371                                crate::zigir::types::IrVarDecl {
372                                    name: self.make_ident(&fname),
373                                    is_const: true,
374                                    zig_type: None,
375                                    init: Some(value_ir),
376                                    is_json_parse: false,
377                                    needs_var_suppression: false,
378                                    needs_deinit: false,
379                                },
380                            ));
381                            continue;
382                        }
383                    }
384                    // Fallback: lower as normal expression statement
385                    ir_stmts.push(self.lower_stmt(stmt));
386                }
387                Statement::IfStatement(is) => {
388                    // Recurse with this-rewrite for if branches
389                    let test_ir = self.lower_expr(&is.test);
390                    let consequent = self.lower_block_with_this_rewrite(
391                        std::slice::from_ref(&is.consequent),
392                        field_names,
393                    );
394                    let alternate = is.alternate.as_ref().map(|alt| {
395                        self.lower_block_with_this_rewrite(std::slice::from_ref(alt), field_names)
396                    });
397                    ir_stmts.push(crate::zigir::types::IrStmt::If {
398                        cond: test_ir,
399                        then: consequent,
400                        else_: alternate,
401                    });
402                }
403                Statement::BlockStatement(bs) => {
404                    let block = self.lower_block_with_this_rewrite(&bs.body, field_names);
405                    ir_stmts.push(crate::zigir::types::IrStmt::Block(block));
406                }
407                _ => {
408                    ir_stmts.push(self.lower_stmt(stmt));
409                }
410            }
411        }
412        IrBlock::new(ir_stmts)
413    }
414}