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::ops::{AssignOp, BinOp, UpdateOp};
10use crate::zigir::types::{IrAssignTarget, IrBlock, IrExpr, IrParam, IrStmt};
11
12use super::Lowerer;
13use super::cabi::property_key_name;
14
15// ¨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
16//  Remaining stubs
17// ¨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
18
19impl Lowerer {
20    /// Generate a unique name for an anonymous class expression.
21    fn next_anon_class_name(&mut self) -> String {
22        let n = self.anon_class_counter;
23        self.anon_class_counter += 1;
24        format!("_AnonClass_{}", n)
25    }
26
27    /// Lower a class declaration into IrClassDecl.
28    ///
29    /// Extracts fields (from PropertyDefinition and implicit constructor `this.x = ...`),
30    /// constructor ¡ú IrClassMethod, regular methods ¡ú IrClassMethod, and static inits.
31    pub(super) fn lower_class_decl(
32        &mut self,
33        cd: &Class,
34    ) -> Option<crate::zigir::types::IrClassDecl> {
35        use crate::zigir::types::{IrClassDecl, IrClassField, IrClassMethod};
36
37        let class_name = cd
38            .id
39            .as_ref()
40            .map(|id| id.name.to_string())
41            .unwrap_or_else(|| {
42                // Anonymous class expression needs a unique name to avoid collisions
43                self.next_anon_class_name()
44            });
45
46        // Save/restore current_class — set early so that static blocks
47        // and field initializers can reference `this` correctly.
48        let saved_class = self.current_class.take();
49        self.current_class = Some(class_name.clone());
50
51        // Pre-scan: collect static field names so `this.field` in static blocks
52        // can be routed correctly via class_static_fields during lowering.
53        let mut pre_scan_static_names: HashSet<String> = HashSet::new();
54        for elem in &cd.body.body {
55            if let ClassElement::PropertyDefinition(pd) = elem
56                && pd.r#static
57                && !pd.computed
58                && let Some(name) = property_key_name(&pd.key)
59            {
60                pre_scan_static_names.insert(name);
61            }
62        }
63        if !pre_scan_static_names.is_empty() {
64            self.class_static_fields
65                .insert(class_name.clone(), pre_scan_static_names);
66        }
67
68        // ── First pass: collect explicit fields from PropertyDefinition ──
69        let mut field_names: Vec<String> = Vec::new();
70        let mut fields: Vec<IrClassField> = Vec::new();
71        let mut static_inits: Vec<(String, crate::zigir::types::IrExpr, ZigType)> = Vec::new();
72        let mut static_blocks: Vec<IrBlock> = Vec::new();
73        let mut has_constructor = false;
74        let mut constructor_func: Option<&Function> = None;
75
76        for elem in &cd.body.body {
77            match elem {
78                ClassElement::PropertyDefinition(pd) => {
79                    if pd.computed {
80                        continue;
81                    }
82                    let is_static = pd.r#static;
83                    if let Some(name) = property_key_name(&pd.key) {
84                        if is_static {
85                            if let Some(value) = &pd.value {
86                                let field_ty = self
87                                    .type_info
88                                    .class_field_types
89                                    .get(&class_name)
90                                    .and_then(|m| m.get(&name))
91                                    .cloned()
92                                    .or_else(|| {
93                                        // Fallback: for anonymous class expressions,
94                                        // field types are stored under the variable name
95                                        self.class_expr_var_name.as_ref().and_then(|vn| {
96                                            self.type_info
97                                                .class_field_types
98                                                .get(vn)
99                                                .and_then(|m| m.get(&name))
100                                                .cloned()
101                                        })
102                                    })
103                                    .unwrap_or(ZigType::JsAny);
104                                // Register static field type in var_types for Member target type inference
105                                let var_key = format!("__{}_{}", class_name, name);
106                                self.type_info.var_types.insert(var_key, field_ty.clone());
107                                static_inits.push((name.clone(), self.lower_expr(value), field_ty));
108                            }
109                        } else if !field_names.contains(&name) {
110                            let field_ty = self
111                                .type_info
112                                .class_field_types
113                                .get(&class_name)
114                                .and_then(|m| m.get(&name))
115                                .cloned()
116                                .or_else(|| {
117                                    // Fallback: for anonymous class expressions,
118                                    // field types are stored under the variable name
119                                    self.class_expr_var_name.as_ref().and_then(|vn| {
120                                        self.type_info
121                                            .class_field_types
122                                            .get(vn)
123                                            .and_then(|m| m.get(&name))
124                                            .cloned()
125                                    })
126                                })
127                                .unwrap_or(ZigType::JsAny);
128                            let default = pd.value.as_ref().map(|v| self.lower_expr(v));
129                            field_names.push(name.clone());
130                            fields.push(IrClassField {
131                                name,
132                                zig_type: field_ty,
133                                default,
134                            });
135                        }
136                    }
137                }
138                ClassElement::MethodDefinition(md) if Self::is_constructor_method(md) => {
139                    has_constructor = true;
140                    constructor_func = Some(&md.value);
141                }
142                ClassElement::StaticBlock(sb) => {
143                    // Lower static block — set in_static_block so `this` → ClassName
144                    let saved_static_block = self.in_static_block;
145                    self.in_static_block = true;
146                    let block = self.lower_block(&sb.body);
147                    self.in_static_block = saved_static_block;
148                    static_blocks.push(block);
149                }
150                _ => {}
151            }
152        }
153
154        // ── Second pass: scan constructor body for implicit `this.x = ...` fields ──
155        if let Some(func) = constructor_func
156            && let Some(body) = &func.body
157        {
158            self.collect_implicit_class_fields(
159                &body.statements,
160                &class_name,
161                &mut field_names,
162                &mut fields,
163            );
164        }
165
166        // ── Lower constructor ──
167        let constructor = if has_constructor {
168            constructor_func
169                .map(|func| self.lower_class_method(&class_name, &field_names, "init", func, false))
170        } else {
171            None
172        };
173
174        // ©¤©¤ Lower methods ©¤©¤
175        let mut methods: Vec<IrClassMethod> = Vec::new();
176        for elem in &cd.body.body {
177            if let ClassElement::MethodDefinition(md) = elem
178                && !Self::is_constructor_method(md)
179            {
180                let method_name =
181                    property_key_name(&md.key).unwrap_or_else(|| "anonymous".to_string());
182                let is_static = md.r#static;
183                let method = self.lower_class_method(
184                    &class_name,
185                    &field_names,
186                    &method_name,
187                    &md.value,
188                    is_static,
189                );
190                methods.push(method);
191            }
192        }
193
194        // ©¤©¤ Restore ©¤©¤
195        self.current_class = saved_class;
196
197        // ©¤©¤ extends ©¤©¤
198        let extends = cd.super_class.as_ref().and_then(|sc| {
199            if let Expression::Identifier(id) = sc {
200                Some(id.name.to_string())
201            } else {
202                None
203            }
204        });
205
206        // static field names already registered in class_static_fields during pre-scan
207
208        // Compute needs_deinit: true if any field is Map, Set, ArrayList, BigInt,
209        // or a NamedStruct that itself needs deinit (nested class).
210        let needs_deinit = fields.iter().any(|f| {
211            matches!(
212                f.zig_type,
213                ZigType::NamedStruct(ref n) if n == "Map" || n == "Set"
214            ) || matches!(f.zig_type, ZigType::ArrayList(_))
215                || matches!(f.zig_type, ZigType::BigInt)
216        });
217
218        Some(IrClassDecl {
219            name: self.make_ident(&class_name),
220            fields,
221            constructor,
222            methods,
223            static_inits,
224            static_blocks,
225            extends,
226            needs_deinit,
227        })
228    }
229
230    /// Check if a MethodDefinition is `constructor()`.
231    pub(super) fn is_constructor_method(md: &MethodDefinition) -> bool {
232        property_key_name(&md.key).is_some_and(|name| name == "constructor")
233    }
234
235    /// Scan constructor body for `this.x = ...` assignments and add
236    /// discovered fields if not already present.
237    pub(super) fn collect_implicit_class_fields(
238        &self,
239        stmts: &[Statement],
240        class_name: &str,
241        field_names: &mut Vec<String>,
242        fields: &mut Vec<crate::zigir::types::IrClassField>,
243    ) {
244        for stmt in stmts {
245            match stmt {
246                Statement::ExpressionStatement(es) => {
247                    if let Expression::AssignmentExpression(ae) = &es.expression {
248                        let maybe_fname = match &ae.left {
249                            AssignmentTarget::StaticMemberExpression(sme)
250                                if matches!(&sme.object, Expression::ThisExpression(_)) =>
251                            {
252                                Some(sme.property.name.to_string())
253                            }
254                            AssignmentTarget::PrivateFieldExpression(pfe)
255                                if matches!(&pfe.object, Expression::ThisExpression(_)) =>
256                            {
257                                Some(pfe.field.name.to_string())
258                            }
259                            _ => None,
260                        };
261                        if let Some(fname) = maybe_fname
262                            && !field_names.contains(&fname)
263                        {
264                            let ftype = self
265                                .type_info
266                                .class_field_types
267                                .get(class_name)
268                                .and_then(|m| m.get(&fname))
269                                .cloned()
270                                .or_else(|| {
271                                    // Fallback: for anonymous class expressions,
272                                    // field types are stored under the variable name
273                                    self.class_expr_var_name.as_ref().and_then(|vn| {
274                                        self.type_info
275                                            .class_field_types
276                                            .get(vn)
277                                            .and_then(|m| m.get(&fname))
278                                            .cloned()
279                                    })
280                                })
281                                .unwrap_or(ZigType::JsAny);
282                            field_names.push(fname.clone());
283                            fields.push(crate::zigir::types::IrClassField {
284                                name: fname,
285                                zig_type: ftype,
286                                default: None,
287                            });
288                        }
289                    }
290                }
291                Statement::IfStatement(is) => {
292                    self.collect_implicit_class_fields(
293                        std::slice::from_ref(&is.consequent),
294                        class_name,
295                        field_names,
296                        fields,
297                    );
298                    if let Some(alt) = &is.alternate {
299                        self.collect_implicit_class_fields(
300                            std::slice::from_ref(alt),
301                            class_name,
302                            field_names,
303                            fields,
304                        );
305                    }
306                }
307                Statement::BlockStatement(bs) => {
308                    self.collect_implicit_class_fields(&bs.body, class_name, field_names, fields);
309                }
310                // R8-C7: Recurse into loop/switch/try bodies so that
311                // `this.field = value` nested inside them is discovered as a
312                // class field (added to field_names) and later rewritten by
313                // try_rewrite_this_field_assignment during body lowering.
314                // Without this, such fields were silently dropped.
315                Statement::WhileStatement(ws) => {
316                    self.collect_implicit_class_fields(
317                        std::slice::from_ref(&ws.body),
318                        class_name,
319                        field_names,
320                        fields,
321                    );
322                }
323                Statement::DoWhileStatement(dws) => {
324                    self.collect_implicit_class_fields(
325                        std::slice::from_ref(&dws.body),
326                        class_name,
327                        field_names,
328                        fields,
329                    );
330                }
331                Statement::ForStatement(fs) => {
332                    self.collect_implicit_class_fields(
333                        std::slice::from_ref(&fs.body),
334                        class_name,
335                        field_names,
336                        fields,
337                    );
338                }
339                Statement::ForOfStatement(fos) => {
340                    self.collect_implicit_class_fields(
341                        std::slice::from_ref(&fos.body),
342                        class_name,
343                        field_names,
344                        fields,
345                    );
346                }
347                Statement::ForInStatement(fis) => {
348                    self.collect_implicit_class_fields(
349                        std::slice::from_ref(&fis.body),
350                        class_name,
351                        field_names,
352                        fields,
353                    );
354                }
355                Statement::LabeledStatement(ls) => {
356                    self.collect_implicit_class_fields(
357                        std::slice::from_ref(&ls.body),
358                        class_name,
359                        field_names,
360                        fields,
361                    );
362                }
363                Statement::SwitchStatement(ss) => {
364                    for case in &ss.cases {
365                        self.collect_implicit_class_fields(
366                            &case.consequent,
367                            class_name,
368                            field_names,
369                            fields,
370                        );
371                    }
372                }
373                Statement::TryStatement(ts) => {
374                    self.collect_implicit_class_fields(
375                        &ts.block.body,
376                        class_name,
377                        field_names,
378                        fields,
379                    );
380                    if let Some(handler) = &ts.handler {
381                        self.collect_implicit_class_fields(
382                            &handler.body.body,
383                            class_name,
384                            field_names,
385                            fields,
386                        );
387                    }
388                    if let Some(fin) = &ts.finalizer {
389                        self.collect_implicit_class_fields(
390                            &fin.body,
391                            class_name,
392                            field_names,
393                            fields,
394                        );
395                    }
396                }
397                _ => {}
398            }
399        }
400    }
401
402    /// Lower a class method (constructor or regular) into IrClassMethod.
403    pub(super) fn lower_class_method(
404        &mut self,
405        class_name: &str,
406        field_names: &[String],
407        method_name: &str,
408        func: &Function,
409        is_static: bool,
410    ) -> crate::zigir::types::IrClassMethod {
411        // For fully-qualified key lookups
412        let fq_method = format!("{}.{}", class_name, method_name);
413
414        let return_type = self
415            .type_info
416            .fn_return_types
417            .get(&fq_method)
418            .or_else(|| self.type_info.fn_return_types.get(method_name))
419            .or_else(|| {
420                // Fallback: for anonymous class expressions, return types are
421                // stored under the variable name (e.g. "Point.sum" not "_AnonClass_0.sum")
422                self.class_expr_var_name.as_ref().and_then(|vn| {
423                    let var_fq = format!("{}.{}", vn, method_name);
424                    self.type_info.fn_return_types.get(&var_fq)
425                })
426            })
427            .cloned()
428            .unwrap_or(if method_name == "init" {
429                ZigType::NamedStruct(class_name.to_string())
430            } else {
431                ZigType::Void
432            });
433
434        // Parameters
435        let params = if method_name == "init" {
436            self.lower_fn_params(func, "init")
437        } else {
438            let param_types = self
439                .type_info
440                .fn_param_types
441                .get(&fq_method)
442                .or_else(|| self.type_info.fn_param_types.get(method_name))
443                .or_else(|| {
444                    // Fallback: for anonymous class expressions
445                    self.class_expr_var_name.as_ref().and_then(|vn| {
446                        let var_fq = format!("{}.{}", vn, method_name);
447                        self.type_info.fn_param_types.get(&var_fq)
448                    })
449                })
450                .cloned();
451            if let Some(ptypes) = param_types {
452                let mut params = Vec::new();
453                for (pname, ptype) in &ptypes {
454                    params.push(IrParam {
455                        name: self.make_ident(pname),
456                        zig_type: ptype.clone(),
457                        is_unused: false,
458                        is_rest: false,
459                    });
460                }
461                params
462            } else {
463                self.lower_fn_params(func, method_name)
464            }
465        };
466
467        // Enter function context
468        let saved_fn = self.enter_fn(method_name, false, Some(return_type.clone()));
469
470        // For static methods, set in_static_block so `this` → ClassName
471        // (static methods don't have a `self` parameter in Zig).
472        let saved_static_block = self.in_static_block;
473        if is_static && method_name != "init" {
474            self.in_static_block = true;
475        }
476
477        // Lower body
478        let body = func
479            .body
480            .as_ref()
481            .map(|b| {
482                if method_name == "init" {
483                    // Constructor: set the this-rewrite flag so that
484                    // `this.field = value` statements (directly, or nested
485                    // inside if/loop/switch/try bodies) are rewritten to
486                    // `const field = value` for the Emitter's struct return.
487                    // `enter_fn` above already saved+cleared the flag; we set
488                    // it here and `exit_fn` will restore the (cleared) saved
489                    // value, scoping the flag to just this constructor body.
490                    self.this_rewrite_fields = Some(field_names.to_vec());
491                    self.lower_block(&b.statements)
492                } else {
493                    self.lower_block(&b.statements)
494                }
495            })
496            .unwrap_or_else(|| IrBlock::new(vec![]));
497
498        self.in_static_block = saved_static_block;
499        self.exit_fn(saved_fn);
500
501        crate::zigir::types::IrClassMethod {
502            name: method_name.to_string(),
503            params,
504            return_type,
505            body,
506            is_static,
507        }
508    }
509
510    /// R8-C7/C9: Rewrite `this.field` mutations into local `field` operations
511    /// that write to a pre-declared `var` in the constructor, so the Emitter
512    /// can collect field values for the struct return.
513    ///
514    /// Handles three categories:
515    /// 1. `this.field = value` → `Assign { target: Ident(field), op: Assign }`
516    /// 2. `this.field += value` (and all compound ops) → `Assign { target: Ident(field), op: <compound> }`
517    ///    - BigInt compound: expanded to `field = field <op> value` (no Zig += for BigInt)
518    /// 3. `this.field++` / `this.field--` → `Expr(Update { target: Ident(field), is_expr_stmt: true })`
519    ///    - BigInt ++/--: expanded to `field = field.add/sub(BigInt(1))`
520    ///
521    /// `**=` and `>>>=` are NOT handled (they expand to BlockExpr in
522    /// lower_assignment) — these rare cases fall through to normal lowering.
523    ///
524    /// Returns `Some(IrStmt)` when the expression is a rewriteable this-field
525    /// mutation whose name is in `field_names`; otherwise `None`.
526    ///
527    /// Invoked from `lower_stmt`'s ExpressionStatement arm and from
528    /// `lower_for_statement`'s init/update. The active field list lives on
529    /// `self.this_rewrite_fields` and is cleared inside nested function
530    /// contexts (via `enter_fn`) so that `this` in a nested function is not
531    /// confused with the constructor's `this`.
532    pub(super) fn try_rewrite_this_field_assignment(
533        &mut self,
534        expr: &Expression,
535        field_names: &[String],
536    ) -> Option<IrStmt> {
537        match expr {
538            // this.field = value / this.field += value / etc.
539            Expression::AssignmentExpression(ae) => {
540                let fname = self.extract_this_field_name_from_assign_target(&ae.left)?;
541                if !field_names.contains(&fname) {
542                    return None;
543                }
544                // **= and >>>= are expanded by lower_assignment into
545                // BlockExpr — let them fall through to normal lowering.
546                if matches!(
547                    ae.operator,
548                    AssignmentOperator::Exponential | AssignmentOperator::ShiftRightZeroFill
549                ) {
550                    return None;
551                }
552                // BigInt compound assignments need expansion to
553                // field = field <op> value (no Zig += for BigInt).
554                if ae.operator != AssignmentOperator::Assign
555                    && self.infer_assign_target_type(&ae.left) == Some(ZigType::BigInt)
556                {
557                    let bin_op = match ae.operator {
558                        AssignmentOperator::Addition => BinOp::Add,
559                        AssignmentOperator::Subtraction => BinOp::Sub,
560                        AssignmentOperator::Multiplication => BinOp::Mul,
561                        AssignmentOperator::Division => BinOp::Div,
562                        AssignmentOperator::Remainder => BinOp::Mod,
563                        AssignmentOperator::BitwiseAnd => BinOp::BitAnd,
564                        AssignmentOperator::BitwiseOR => BinOp::BitOr,
565                        AssignmentOperator::BitwiseXOR => BinOp::BitXor,
566                        AssignmentOperator::ShiftLeft => BinOp::Shl,
567                        AssignmentOperator::ShiftRight => BinOp::Shr,
568                        _ => return None,
569                    };
570                    let value_ir = self.lower_expr(&ae.right);
571                    let read_expr = IrExpr::Ident(self.make_ident(&fname));
572                    return Some(IrStmt::Assign {
573                        target: IrAssignTarget::Ident(self.make_ident(&fname)),
574                        op: AssignOp::Assign,
575                        value: IrExpr::Binary {
576                            op: bin_op,
577                            left: Box::new(read_expr),
578                            right: Box::new(value_ir),
579                            left_type: Some(ZigType::BigInt),
580                            right_type: Some(ZigType::BigInt),
581                        },
582                    });
583                }
584                // Non-BigInt compound or plain =: map operator directly.
585                let op = match ae.operator {
586                    AssignmentOperator::Assign => AssignOp::Assign,
587                    AssignmentOperator::Addition => AssignOp::Add,
588                    AssignmentOperator::Subtraction => AssignOp::Sub,
589                    AssignmentOperator::Multiplication => AssignOp::Mul,
590                    AssignmentOperator::Division => AssignOp::Div,
591                    AssignmentOperator::Remainder => AssignOp::Mod,
592                    AssignmentOperator::ShiftLeft => AssignOp::Shl,
593                    AssignmentOperator::ShiftRight => AssignOp::Shr,
594                    AssignmentOperator::BitwiseAnd => AssignOp::BitAnd,
595                    AssignmentOperator::BitwiseOR => AssignOp::BitOr,
596                    AssignmentOperator::BitwiseXOR => AssignOp::BitXor,
597                    AssignmentOperator::LogicalAnd => AssignOp::LogicAnd,
598                    AssignmentOperator::LogicalOr => AssignOp::LogicOr,
599                    AssignmentOperator::LogicalNullish => AssignOp::Nullish,
600                    _ => return None,
601                };
602                let value_ir = self.lower_expr(&ae.right);
603                Some(IrStmt::Assign {
604                    target: IrAssignTarget::Ident(self.make_ident(&fname)),
605                    op,
606                    value: value_ir,
607                })
608            }
609            // this.field++ / this.field-- / ++this.field / --this.field
610            Expression::UpdateExpression(ue) => {
611                let fname = self.extract_this_field_name_from_simple_target(&ue.argument)?;
612                if !field_names.contains(&fname) {
613                    return None;
614                }
615                // BigInt ++/-- needs expansion to field = field.add/sub(BigInt(1)).
616                // In statement context (which is the only context this function is
617                // called from), the return value is discarded, so prefix/postfix
618                // are equivalent — both just mutate the field.
619                if self.infer_simple_assign_target_type(&ue.argument) == Some(ZigType::BigInt) {
620                    let bin_op = if ue.operator == UpdateOperator::Increment {
621                        BinOp::Add
622                    } else {
623                        BinOp::Sub
624                    };
625                    let read_expr = IrExpr::Ident(self.make_ident(&fname));
626                    return Some(IrStmt::Assign {
627                        target: IrAssignTarget::Ident(self.make_ident(&fname)),
628                        op: AssignOp::Assign,
629                        value: IrExpr::Binary {
630                            op: bin_op,
631                            left: Box::new(read_expr),
632                            right: Box::new(IrExpr::BigIntLiteral("1".to_string())),
633                            left_type: Some(ZigType::BigInt),
634                            right_type: Some(ZigType::BigInt),
635                        },
636                    });
637                }
638                // Non-BigInt: emit field++ / field-- as a statement.
639                let op = if ue.operator == UpdateOperator::Increment {
640                    UpdateOp::Increment
641                } else {
642                    UpdateOp::Decrement
643                };
644                Some(IrStmt::Expr(IrExpr::Update {
645                    op,
646                    target: Box::new(IrAssignTarget::Ident(self.make_ident(&fname))),
647                    is_expr_stmt: true,
648                    prefix: ue.prefix,
649                }))
650            }
651            _ => None,
652        }
653    }
654
655    /// Extract field name from `this.field` in an AssignmentTarget (for
656    /// `this.field = ...` or `this.field += ...`).
657    fn extract_this_field_name_from_assign_target(
658        &self,
659        target: &AssignmentTarget,
660    ) -> Option<String> {
661        match target {
662            AssignmentTarget::StaticMemberExpression(sme)
663                if matches!(&sme.object, Expression::ThisExpression(_)) =>
664            {
665                Some(sme.property.name.to_string())
666            }
667            AssignmentTarget::PrivateFieldExpression(pfe)
668                if matches!(&pfe.object, Expression::ThisExpression(_)) =>
669            {
670                // PrivateIdentifier.name does NOT include the '#' prefix
671                Some(pfe.field.name.to_string())
672            }
673            _ => None,
674        }
675    }
676
677    /// Extract field name from `this.field` in a SimpleAssignmentTarget (for
678    /// `this.field++` / `++this.field`).
679    fn extract_this_field_name_from_simple_target(
680        &self,
681        target: &SimpleAssignmentTarget,
682    ) -> Option<String> {
683        match target {
684            SimpleAssignmentTarget::StaticMemberExpression(sme)
685                if matches!(&sme.object, Expression::ThisExpression(_)) =>
686            {
687                Some(sme.property.name.to_string())
688            }
689            SimpleAssignmentTarget::PrivateFieldExpression(pfe)
690                if matches!(&pfe.object, Expression::ThisExpression(_)) =>
691            {
692                Some(pfe.field.name.to_string())
693            }
694            _ => None,
695        }
696    }
697}