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,
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        });
193
194        Some(IrClassDecl {
195            name: self.make_ident(&class_name),
196            fields,
197            constructor,
198            methods,
199            static_inits,
200            static_blocks,
201            extends,
202            needs_deinit,
203        })
204    }
205
206    /// Check if a MethodDefinition is `constructor()`.
207    pub(super) fn is_constructor_method(md: &MethodDefinition) -> bool {
208        property_key_name(&md.key).is_some_and(|name| name == "constructor")
209    }
210
211    /// Scan constructor body for `this.x = ...` assignments and add
212    /// discovered fields if not already present.
213    pub(super) fn collect_implicit_class_fields(
214        &self,
215        stmts: &[Statement],
216        class_name: &str,
217        field_names: &mut Vec<String>,
218        fields: &mut Vec<crate::zigir::types::IrClassField>,
219    ) {
220        for stmt in stmts {
221            match stmt {
222                Statement::ExpressionStatement(es) => {
223                    if let Expression::AssignmentExpression(ae) = &es.expression
224                        && let AssignmentTarget::StaticMemberExpression(sme) = &ae.left
225                        && matches!(&sme.object, Expression::ThisExpression(_))
226                    {
227                        let fname = sme.property.name.to_string();
228                        if !field_names.contains(&fname) {
229                            let ftype = self
230                                .type_info
231                                .class_field_types
232                                .get(class_name)
233                                .and_then(|m| m.get(&fname))
234                                .cloned()
235                                .unwrap_or(ZigType::JsAny);
236                            field_names.push(fname.clone());
237                            fields.push(crate::zigir::types::IrClassField {
238                                name: fname,
239                                zig_type: ftype,
240                                default: None,
241                            });
242                        }
243                    }
244                }
245                Statement::IfStatement(is) => {
246                    self.collect_implicit_class_fields(
247                        std::slice::from_ref(&is.consequent),
248                        class_name,
249                        field_names,
250                        fields,
251                    );
252                    if let Some(alt) = &is.alternate {
253                        self.collect_implicit_class_fields(
254                            std::slice::from_ref(alt),
255                            class_name,
256                            field_names,
257                            fields,
258                        );
259                    }
260                }
261                Statement::BlockStatement(bs) => {
262                    self.collect_implicit_class_fields(&bs.body, class_name, field_names, fields);
263                }
264                _ => {}
265            }
266        }
267    }
268
269    /// Lower a class method (constructor or regular) into IrClassMethod.
270    pub(super) fn lower_class_method(
271        &mut self,
272        class_name: &str,
273        field_names: &[String],
274        method_name: &str,
275        func: &Function,
276        is_static: bool,
277    ) -> crate::zigir::types::IrClassMethod {
278        // For fully-qualified key lookups
279        let fq_method = format!("{}.{}", class_name, method_name);
280
281        let return_type = self
282            .type_info
283            .fn_return_types
284            .get(&fq_method)
285            .or_else(|| self.type_info.fn_return_types.get(method_name))
286            .cloned()
287            .unwrap_or(if method_name == "init" {
288                ZigType::NamedStruct(class_name.to_string())
289            } else {
290                ZigType::Void
291            });
292
293        // Parameters
294        let params = if method_name == "init" {
295            self.lower_fn_params(func, "init")
296        } else {
297            let param_types = self
298                .type_info
299                .fn_param_types
300                .get(&fq_method)
301                .or_else(|| self.type_info.fn_param_types.get(method_name))
302                .cloned();
303            if let Some(ptypes) = param_types {
304                let mut params = Vec::new();
305                for (pname, ptype) in &ptypes {
306                    params.push(IrParam {
307                        name: self.make_ident(pname),
308                        zig_type: ptype.clone(),
309                        is_unused: false,
310                        is_rest: false,
311                    });
312                }
313                params
314            } else {
315                self.lower_fn_params(func, method_name)
316            }
317        };
318
319        // Enter function context
320        let saved_fn = self.enter_fn(method_name, false, Some(return_type.clone()));
321
322        // Lower body
323        let body = func
324            .body
325            .as_ref()
326            .map(|b| {
327                if method_name == "init" {
328                    // Constructor: use this-rewrite lowering
329                    self.lower_block_with_this_rewrite(&b.statements, field_names)
330                } else {
331                    self.lower_block(&b.statements)
332                }
333            })
334            .unwrap_or_else(|| IrBlock::new(vec![]));
335
336        self.exit_fn(saved_fn);
337
338        crate::zigir::types::IrClassMethod {
339            name: method_name.to_string(),
340            params,
341            return_type,
342            body,
343            is_static,
344        }
345    }
346
347    /// Lower a block of statements with `this.x = value` rewriting.
348    ///
349    /// In constructors, `this.field = value` is rewritten as a local const binding
350    /// that the Emitter will use to build the struct return.
351    pub(super) fn lower_block_with_this_rewrite(
352        &mut self,
353        stmts: &[Statement],
354        field_names: &[String],
355    ) -> IrBlock {
356        let mut ir_stmts = Vec::new();
357        for stmt in stmts {
358            match stmt {
359                Statement::ExpressionStatement(es) => {
360                    // Check if this is `this.field = value`
361                    if let Expression::AssignmentExpression(ae) = &es.expression
362                        && let AssignmentTarget::StaticMemberExpression(sme) = &ae.left
363                        && matches!(&sme.object, Expression::ThisExpression(_))
364                    {
365                        let fname = sme.property.name.to_string();
366                        if field_names.contains(&fname) {
367                            // this.field = value ¡ú const field = value
368                            let value_ir = self.lower_expr(&ae.right);
369                            ir_stmts.push(crate::zigir::types::IrStmt::VarDecl(
370                                crate::zigir::types::IrVarDecl {
371                                    name: self.make_ident(&fname),
372                                    is_const: true,
373                                    zig_type: None,
374                                    init: Some(value_ir),
375                                    is_json_parse: false,
376                                    needs_var_suppression: false,
377                                    needs_deinit: false,
378                                },
379                            ));
380                            continue;
381                        }
382                    }
383                    // Fallback: lower as normal expression statement
384                    ir_stmts.push(self.lower_stmt(stmt));
385                }
386                Statement::IfStatement(is) => {
387                    // Recurse with this-rewrite for if branches
388                    let test_ir = self.lower_expr(&is.test);
389                    let consequent = self.lower_block_with_this_rewrite(
390                        std::slice::from_ref(&is.consequent),
391                        field_names,
392                    );
393                    let alternate = is.alternate.as_ref().map(|alt| {
394                        self.lower_block_with_this_rewrite(std::slice::from_ref(alt), field_names)
395                    });
396                    ir_stmts.push(crate::zigir::types::IrStmt::If {
397                        cond: test_ir,
398                        then: consequent,
399                        else_: alternate,
400                    });
401                }
402                Statement::BlockStatement(bs) => {
403                    let block = self.lower_block_with_this_rewrite(&bs.body, field_names);
404                    ir_stmts.push(crate::zigir::types::IrStmt::Block(block));
405                }
406                _ => {
407                    ir_stmts.push(self.lower_stmt(stmt));
408                }
409            }
410        }
411        IrBlock::new(ir_stmts)
412    }
413}