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