Skip to main content

atmos/os_lib/ecma/interp/
eval_expr.rs

1// 分割: interp.rs の `impl Interp` から機械的に移動(2026-07-16 リファクタ フェーズ5)。
2// ロジック不変。メソッド可視性のみ pub(crate) へ昇格(別モジュールの impl Interp
3// からの self 呼び出しのため)。impl ブロックは型 Interp に自動で結合する。
4use super::*;
5use crate::os_lib::ecma::host::HostKeys;
6
7impl Interp {
8    pub fn eval(
9        &mut self,
10        expr: &Expression,
11        scope: &Rc<RefCell<Scope>>,
12        this: &Value,
13    ) -> EvalResult {
14        if self.tick() {
15            return Err(Value::Undefined);
16        }
17        match expr {
18            Expression::Number(n) => Ok(Value::Number(*n)),
19            Expression::BigIntLit(s) => match super::super::bigint::BigInt::parse_str(s) {
20                Some(b) => Ok(Value::bigint(b)),
21                None => Err(self.throw(format!("Invalid BigInt literal: {}", s))),
22            },
23            Expression::Str(s) => Ok(Value::str(s.clone())),
24            Expression::Bool(b) => Ok(Value::Bool(*b)),
25            Expression::Null => Ok(Value::Null),
26            Expression::Undefined | Expression::Elision => Ok(Value::Undefined),
27            Expression::This => self.resolve_this(scope, this),
28            Expression::TemplateLiteral { quasis, exprs } => {
29                self.eval_template_lit(quasis, exprs, scope, this)
30            }
31            Expression::TaggedTemplate {
32                tag,
33                quasis,
34                raw,
35                exprs,
36            } => self.eval_tagged_template(tag, quasis, raw, exprs, scope, this),
37            Expression::Identifier(name) => self.load_identifier(name, scope),
38            Expression::Array(items) => self.eval_array_lit(items, scope, this),
39            Expression::Object(props) => self.eval_object_lit(props, scope, this),
40            Expression::Spread(inner) => self.eval(inner, scope, this),
41            Expression::Class {
42                name,
43                superclass,
44                members,
45            } => self.eval_class(name, superclass, members, scope, this),
46            Expression::Super => {
47                // 単独 super は基底プロトタイプを返す(通常は super.x / super() で使う)。
48                self.super_proto(scope)
49            }
50            Expression::NewTarget => {
51                Ok(self.new_target_stack.last().cloned().unwrap_or(Value::Undefined))
52            }
53            Expression::Sequence(items) => {
54                let mut last = Value::Undefined;
55                for item in items {
56                    last = self.eval(item, scope, this)?;
57                }
58                Ok(last)
59            }
60            Expression::Regex(lit) => self.eval_regex_lit(lit),
61            Expression::Await(inner) => {
62                let v = self.eval(inner, scope, this)?;
63                self.await_value(v)
64            }
65            Expression::Yield { argument, delegate } => {
66                self.eval_yield(argument.as_deref(), *delegate, scope, this)
67            }
68            Expression::Function {
69                name,
70                params,
71                body,
72                is_arrow,
73                is_async,
74                is_generator,
75            } => self.eval_function_expr(
76                name,
77                params,
78                body,
79                *is_arrow,
80                *is_async,
81                *is_generator,
82                scope,
83                this,
84            ),
85            Expression::Unary { op, expr } => self.eval_unary(op, expr, scope, this),
86            Expression::Update { op, prefix, target } => {
87                self.eval_update(op, *prefix, target, scope, this)
88            }
89            Expression::Binary { op, left, right } => {
90                self.eval_binary_expr(op, left, right, scope, this)
91            }
92            Expression::Logical { op, left, right } => {
93                let l = self.eval(left, scope, this)?;
94                match op {
95                    LogicalOp::And => {
96                        if l.truthy() {
97                            self.eval(right, scope, this)
98                        } else {
99                            Ok(l)
100                        }
101                    }
102                    LogicalOp::Or => {
103                        if l.truthy() {
104                            Ok(l)
105                        } else {
106                            self.eval(right, scope, this)
107                        }
108                    }
109                    LogicalOp::Nullish => match l {
110                        Value::Undefined | Value::Null => self.eval(right, scope, this),
111                        _ => Ok(l),
112                    },
113                }
114            }
115            Expression::Conditional {
116                test,
117                consequent,
118                alternate,
119            } => {
120                if self.eval(test, scope, this)?.truthy() {
121                    self.eval(consequent, scope, this)
122                } else {
123                    self.eval(alternate, scope, this)
124                }
125            }
126            Expression::Assign { op, target, value } => {
127                self.eval_assign(op, target, value, scope, this)
128            }
129            Expression::Member {
130                object,
131                property,
132                optional,
133            } => self.eval_member(object, property, *optional, scope, this),
134            Expression::Index { object, index, optional } => {
135                self.eval_index(object, index, *optional, scope, this)
136            }
137            Expression::Call {
138                callee,
139                arguments,
140                optional,
141            } => self.eval_call(callee, arguments, *optional, scope, this),
142            Expression::New { callee, arguments } => self.eval_new(callee, arguments, scope, this),
143        }
144    }
145
146    // 【2026-10-28 スタックフレーム縮小】`eval` は式評価のたびに再帰するため、ローカル変数(Vec/String 等)が
147    // 大きいリテラル生成や冷たい分岐を `#[inline(never)]` ヘルパへ分離し、1 再帰あたりのネイティブスタック消費を抑える。
148
149    /// 変数を読む。スコープに無ければ `window` のプロパティを見る。
150    ///
151    /// 【2026-09-05】ブラウザでは `window.x = 1` の後に素の `x` で読める(グローバルオブジェクトの
152    /// プロパティ=グローバル変数)。この処理系は `window` を普通のオブジェクトとして持ち、グローバル変数とは
153    /// 別管理なので、`window.$ = ...` が素の `$` から見えなかった(jQuery 1.8.2 が
154    /// `$ is not defined` になっていた)。【2026-10-22 高速化】`self.global` から直接 O(1)。
155    #[inline]
156    pub(crate) fn resolve_this(&self, scope: &Rc<RefCell<Scope>>, fallback: &Value) -> EvalResult {
157        if let Some(cell) = super::scope_derived_this(scope) {
158            return match &*cell.borrow() {
159                Some(v) => Ok(v.clone()),
160                None => Err(self.reference_error(
161                    "Must call super constructor in derived class before accessing 'this' or returning from derived constructor",
162                )),
163            };
164        }
165        Ok(self.effective_this(fallback))
166    }
167
168    pub(crate) fn load_identifier(&mut self, name: &Rc<str>, scope: &Rc<RefCell<Scope>>) -> EvalResult {
169        if scope.borrow().has_with {
170            if let Some((wobj, had_unscopables)) = self.resolve_with_scope(scope, name)? {
171                return self.with_get_binding_value(&wobj, name, had_unscopables);
172            }
173        }
174        self.load_identifier_no_with(name, scope)
175    }
176
177    pub(crate) fn load_identifier_no_with(&mut self, name: &Rc<str>, scope: &Rc<RefCell<Scope>>) -> EvalResult {
178        match super::scope_get_tdz(scope, name) {
179            Err(()) => Err(self.reference_error(format!("Cannot access '{}' before initialization", name))),
180            Ok(Some(v)) => Ok(v),
181            Ok(None) => {
182                let window = self.global.borrow().vars.get("globalThis").cloned();
183                if let Some(Value::Object(w)) = &window {
184                    if let Some(v) = w.borrow().props.get(name) {
185                        return Ok(v.clone());
186                    }
187                    // `Object.defineProperty(window, "x", { get })` で付けたアクセサ。【2026-11-04】YouTube の文書は
188                    // `window.Polymer` をアクセサにして、素の `Polymer` で読む(読めず ReferenceError になり、
189                    // base_module_set の初期化が途中で止まっていた。TODO B0)。
190                    let getter = w.borrow().get_accessor(name).map(|a| a.get.clone());
191                    if let Some(getter) = getter {
192                        return match getter {
193                            Some(f) => self.call_value(&f, Value::Object(w.clone()), &[]),
194                            None => Ok(Value::Undefined),
195                        };
196                    }
197                }
198                Err(self.reference_error(format!("{} is not defined", name)))
199            }
200        }
201    }
202
203    #[inline(never)]
204    fn eval_binary_expr(
205        &mut self,
206        op: &BinaryOp,
207        left: &Expression,
208        right: &Expression,
209        scope: &Rc<RefCell<Scope>>,
210        this: &Value,
211    ) -> EvalResult {
212        // プライベートフィールドのブランドチェック `#x in obj`(ES2022)
213        if matches!(op, BinaryOp::In) {
214            if let Expression::Identifier(name) = left {
215                if name.starts_with('#') {
216                    let robj = self.eval(right, scope, this)?;
217                    return self.private_in(&robj, name, scope);
218                }
219            }
220        }
221        let l = self.eval(left, scope, this)?;
222        let r = self.eval(right, scope, this)?;
223        self.eval_binary(op, l, r)
224    }
225
226    #[inline(never)]
227    fn eval_member(
228        &mut self,
229        object: &Expression,
230        property: &Rc<str>,
231        optional: bool,
232        scope: &Rc<RefCell<Scope>>,
233        this: &Value,
234    ) -> EvalResult {
235        if matches!(object, Expression::Super) {
236            return self.super_get(scope, property, this);
237        }
238        let (obj, broke) = self.eval_chain_object(object, scope, this)?;
239        if broke {
240            return Ok(Value::Undefined);
241        }
242        if optional && matches!(obj, Value::Undefined | Value::Null) {
243            return Ok(Value::Undefined);
244        }
245        if property.starts_with('#') {
246            return self.private_get(&obj, property, scope);
247        }
248        self.get_property_of_expr(&obj, property, object)
249    }
250
251    #[inline(never)]
252    fn eval_index(
253        &mut self,
254        object: &Expression,
255        index: &Expression,
256        optional: bool,
257        scope: &Rc<RefCell<Scope>>,
258        this: &Value,
259    ) -> EvalResult {
260        if matches!(object, Expression::Super) {
261            let key = self.eval_key(index, scope, this)?;
262            return self.super_get(scope, &to_property_key(&key), this);
263        }
264        let (obj, broke) = self.eval_chain_object(object, scope, this)?;
265        if broke {
266            return Ok(Value::Undefined);
267        }
268        if optional && matches!(obj, Value::Undefined | Value::Null) {
269            return Ok(Value::Undefined);
270        }
271        let key = self.eval_key_for(&obj, index, scope, this)?;
272        if let Some(v) = self.get_index_fast(&obj, &key) {
273            return Ok(v);
274        }
275        let key_str = to_property_key(&key);
276        self.get_property(&obj, &key_str)
277    }
278
279    #[inline(never)]
280    fn eval_template_lit(
281        &mut self,
282        quasis: &[String],
283        exprs: &[Expression],
284        scope: &Rc<RefCell<Scope>>,
285        this: &Value,
286    ) -> EvalResult {
287        let mut s = String::new();
288        for (i, q) in quasis.iter().enumerate() {
289            s.push_str(q);
290            if let Some(e) = exprs.get(i) {
291                let v = self.eval(e, scope, this)?;
292                let v = self.to_string_value(v)?;
293                s.push_str(&v);
294            }
295        }
296        Ok(Value::str(s))
297    }
298
299    #[inline(never)]
300    fn eval_tagged_template(
301        &mut self,
302        tag: &Expression,
303        quasis: &[String],
304        raw: &[String],
305        exprs: &[Expression],
306        scope: &Rc<RefCell<Scope>>,
307        this: &Value,
308    ) -> EvalResult {
309        let (func, call_this, broke) = self.resolve_callee(tag, scope, this)?;
310        if broke {
311            return Ok(Value::Undefined);
312        }
313        let strings = Obj::array(quasis.iter().map(|s| Value::str(s.clone())).collect());
314        let raw_arr = Obj::array(raw.iter().map(|s| Value::str(s.clone())).collect());
315        strings
316            .borrow_mut()
317            .props
318            .insert(String::from("raw").into(), Value::Object(raw_arr));
319        // `raw` は列挙しない(仕様。`Object.keys(strings)` は添字だけ)。
320        strings.borrow_mut().hide_props(&["raw"]);
321        let mut args = Vec::with_capacity(exprs.len() + 1);
322        args.push(Value::Object(strings));
323        for e in exprs.iter() {
324            args.push(self.eval(e, scope, this)?);
325        }
326        self.call_value(&func, call_this, &args)
327    }
328
329    #[inline(never)]
330    fn eval_array_lit(
331        &mut self,
332        items: &[Expression],
333        scope: &Rc<RefCell<Scope>>,
334        this: &Value,
335    ) -> EvalResult {
336        let mut vals = Vec::with_capacity(items.len());
337        // 穴の位置(`[1,,3]`)。穴が無ければ確保しない。
338        let mut holes: Vec<usize> = Vec::new();
339        for it in items {
340            if let Expression::Spread(inner) = it {
341                let v = self.eval(inner, scope, this)?;
342                let spread_items = self.spread_values(&v)?;
343                vals.extend(spread_items);
344            } else if matches!(it, Expression::Elision) {
345                holes.push(vals.len());
346                vals.push(Value::Undefined);
347            } else {
348                vals.push(self.eval(it, scope, this)?);
349            }
350        }
351        let len = vals.len();
352        let arr = Obj::array(vals);
353        if !holes.is_empty() {
354            let mut mask = alloc::vec![false; len];
355            for h in holes {
356                if let Some(m) = mask.get_mut(h) {
357                    *m = true;
358                }
359            }
360            arr.borrow_mut().set_holes(Some(alloc::boxed::Box::new(mask)));
361        }
362        Ok(Value::Object(arr))
363    }
364
365    #[inline(never)]
366    fn eval_object_lit(
367        &mut self,
368        props: &[Property],
369        scope: &Rc<RefCell<Scope>>,
370        this: &Value,
371    ) -> EvalResult {
372        let o = Obj::plain();
373        // メソッド・アクセサの [[HomeObject]] はこのリテラル自身(ECMA-262 §15.4.4 DefineMethod /
374        // §13.2.5.5 PropertyDefinitionEvaluation)。関数を持つときだけ `__home__` を載せた子スコープを作る。【2026-11-19】
375        let mut home_scope: Option<Rc<RefCell<Scope>>> = None;
376        for p in props {
377            if &*p.key == OBJECT_SPREAD_KEY {
378                let src = self.eval(&p.value, scope, this)?;
379                self.object_spread_copy(&o, &src)?;
380                continue;
381            }
382            let key: PropKey = if let Some(ce) = &p.computed {
383                to_property_key(&self.eval_key(ce, scope, this)?).as_ref().into()
384            } else {
385                (&p.key).into()
386            };
387            if p.accessor.is_some() || matches!(p.value, Expression::Function { .. }) {
388                self.object_lit_func_prop(&o, p, key, scope, this, &mut home_scope)?;
389                continue;
390            }
391            let v = self.eval(&p.value, scope, this)?;
392            object_lit_put(&o, p, key, v);
393        }
394        Ok(Value::Object(o))
395    }
396
397    /// オブジェクトリテラルの `...src`(CopyDataProperties)。generator の VM と共用(2026-11-30 に切り出した)。
398    #[inline(never)]
399    pub(crate) fn object_spread_copy(&mut self, o: &ObjRef, src: &Value) -> Result<(), Value> {
400        // 【2026-11-17】`{..."ab"}` は文字列の添字を写す(以前は無視)。
401        if let Value::Str(st) = &src {
402            for (i, c) in st.chars().enumerate() {
403                o.borrow_mut().props.insert(i.to_string().into(), Value::str(c.to_string()));
404            }
405            return Ok(());
406        }
407        if let Value::Object(so) = &src {
408            let (kind_is_array, items, prop_entries, getters) = {
409                let b = so.borrow();
410                match &b.kind {
411                    ObjKind::Array(items) => {
412                        (true, items.clone(), Vec::new(), Vec::new())
413                    }
414                    ObjKind::Iter | ObjKind::GenReturn => (false, Vec::new(), Vec::new(), Vec::new()),
415                    ObjKind::HostRef(h) if !matches!((self.host.keys)(self, *h), HostKeys::Generic) => {
416                        (false, Vec::new(), Vec::new(), Vec::new())
417                    }
418                    _ => {
419                        let plain_entries: Vec<(String, Value)> = b
420                            .props
421                            .iter()
422                            .filter(|(k, _)| {
423                                if super::super::builtins::is_symbol_like_key(k) {
424                                    return false;
425                                }
426                                b.is_enumerable(k)
427                            })
428                            .map(|(k, v)| (k.to_string(), v.clone()))
429                            .collect();
430                        let mut prop_entries: Vec<(String, Value)> =
431                            super::super::builtins::spec_key_order(plain_entries);
432                        prop_entries.extend(
433                            b.props
434                                .iter()
435                                .filter(|(k, _)| {
436                                    super::super::builtins::is_symbol_like_key(k)
437                                        && b.is_enumerable(k)
438                                })
439                                .map(|(k, v)| (k.to_string(), v.clone())),
440                        );
441                        let getters: Vec<(String, Value)> =
442                            super::super::builtins::accessor_only_keys(&b)
443                                .into_iter()
444                                .filter(|k| b.is_enumerable(k))
445                                .filter_map(|k| {
446                                    b.get_getter(&k).map(|g| (k, g))
447                                })
448                                .collect();
449                        (false, Vec::new(), prop_entries, getters)
450                    }
451                }
452            };
453            if kind_is_array {
454                for (i, v) in items.iter().enumerate() {
455                    o.borrow_mut().props.insert(format!("{}", i).into(), v.clone());
456                }
457            } else {
458                for (k, v) in prop_entries {
459                    o.borrow_mut().props.insert(k.into(), v);
460                }
461                for (k, g) in getters {
462                    let v = self.call_value(&g, src.clone(), &[])?;
463                    o.borrow_mut().props.insert(k.into(), v);
464                }
465            }
466        }
467        Ok(())
468    }
469
470    /// オブジェクトリテラルの、値が関数の定義(メソッド・アクセサ・関数式)のプロパティ。
471    /// [[HomeObject]] のスコープ(`__home__`)で評価する。generator の VM と共用。
472    pub(crate) fn object_lit_func_prop(
473        &mut self,
474        o: &ObjRef,
475        p: &Property,
476        key: PropKey,
477        scope: &Rc<RefCell<Scope>>,
478        this: &Value,
479        home_scope: &mut Option<Rc<RefCell<Scope>>>,
480    ) -> Result<(), Value> {
481        let vscope = home_scope
482            .get_or_insert_with(|| {
483                let hs = Scope::child(scope.clone());
484                scope_declare(&hs, "__home__", Value::Object(o.clone()));
485                hs
486            })
487            .clone();
488        if let Some(is_getter) = p.accessor {
489            let f = self.eval(&p.value, &vscope, this)?;
490            if let Value::Object(fo) = &f {
491                if let ObjKind::Function(fd) = &mut fo.borrow_mut().kind {
492                    let nm = alloc::format!("{} {}", if is_getter { "get" } else { "set" }, super::fn_name_from_key(key.as_str()));
493                    fd.set_name(&nm);
494                }
495            }
496            let mut b = o.borrow_mut();
497            let entry = b
498                .accessors_mut()
499                .entry(key)
500                .or_insert(Accessor { get: None, set: None });
501            if is_getter {
502                entry.get = Some(f);
503            } else {
504                entry.set = Some(f);
505            }
506            return Ok(());
507        }
508        let v = self.eval(&p.value, &vscope, this)?;
509        object_lit_put(o, p, key, v);
510        Ok(())
511    }
512
513    #[inline(never)]
514    pub(crate) fn eval_regex_lit(&self, lit: &(String, String)) -> EvalResult {
515        let (pattern, flags) = lit;
516        let re = super::super::regex::Regex::new(pattern, flags);
517        Ok(Value::Object(Obj::regexp(super::super::regex::RegExpData {
518            re,
519            last_index: 0,
520        })))
521    }
522
523    /// リプレイで既通過の `yield` 引数を再評価してよいか判定するため、内側の関数境界を越えずに
524    /// `yield` / `await` の有無を調べる。
525    fn expr_contains_yield_or_await(expr: &Expression) -> bool {
526        match expr {
527            Expression::Await(_) | Expression::Yield { .. } => true,
528            Expression::Number(_)
529            | Expression::BigIntLit(_)
530            | Expression::Str(_)
531            | Expression::Bool(_)
532            | Expression::Null
533            | Expression::Undefined
534            | Expression::Identifier(_)
535            | Expression::This
536            | Expression::Elision
537            | Expression::Function { .. }
538            | Expression::Super
539            | Expression::NewTarget
540            | Expression::Regex(_) => false,
541            Expression::TemplateLiteral { exprs, .. } => exprs.iter().any(Self::expr_contains_yield_or_await),
542            Expression::TaggedTemplate { tag, exprs, .. } => {
543                Self::expr_contains_yield_or_await(tag) || exprs.iter().any(Self::expr_contains_yield_or_await)
544            }
545            Expression::Array(items) | Expression::Sequence(items) => {
546                items.iter().any(Self::expr_contains_yield_or_await)
547            }
548            Expression::Object(props) => props.iter().any(|p| {
549                p.computed.as_ref().is_some_and(Self::expr_contains_yield_or_await)
550                    || Self::expr_contains_yield_or_await(&p.value)
551            }),
552            Expression::Unary { expr, .. }
553            | Expression::Update { target: expr, .. }
554            | Expression::Spread(expr) => Self::expr_contains_yield_or_await(expr),
555            Expression::Binary { left, right, .. }
556            | Expression::Logical { left, right, .. }
557            | Expression::Assign { target: left, value: right, .. } => {
558                Self::expr_contains_yield_or_await(left) || Self::expr_contains_yield_or_await(right)
559            }
560            Expression::Conditional { test, consequent, alternate } => {
561                Self::expr_contains_yield_or_await(test)
562                    || Self::expr_contains_yield_or_await(consequent)
563                    || Self::expr_contains_yield_or_await(alternate)
564            }
565            Expression::Member { object, .. } => Self::expr_contains_yield_or_await(object),
566            Expression::Index { object, index, .. } => {
567                Self::expr_contains_yield_or_await(object) || Self::expr_contains_yield_or_await(index)
568            }
569            Expression::Call { callee, arguments, .. }
570            | Expression::New { callee, arguments } => {
571                Self::expr_contains_yield_or_await(callee)
572                    || arguments.iter().any(Self::expr_contains_yield_or_await)
573            }
574            Expression::Class { superclass, members, .. } => {
575                superclass.as_deref().is_some_and(Self::expr_contains_yield_or_await)
576                    || members.iter().any(|m| {
577                        m.computed_key.as_ref().is_some_and(Self::expr_contains_yield_or_await)
578                    })
579            }
580        }
581    }
582
583    #[inline(never)]
584    fn eval_yield(
585        &mut self,
586        argument: Option<&Expression>,
587        delegate: bool,
588        scope: &Rc<RefCell<Scope>>,
589        this: &Value,
590    ) -> EvalResult {
591        if delegate {
592            return self.eval_yield_delegate(argument, scope, this);
593        }
594        let skip_arg = matches!(
595            &self.gen_replay,
596            Some(r) if r.gen_depth == self.depth && r.counter < r.target
597        ) && argument.is_none_or(|e| !Self::expr_contains_yield_or_await(e));
598        let mut v = if skip_arg {
599            Value::Undefined
600        } else {
601            match argument {
602                Some(e) => self.eval(e, scope, this)?,
603                None => Value::Undefined,
604            }
605        };
606        if self.gen_replay.is_none() {
607            return Ok(Value::Undefined);
608        }
609        if self.gen_is_async(scope) {
610            v = self.gen_await_cached(scope, v)?;
611        }
612        self.do_yield(v)
613    }
614
615    #[inline(never)]
616    #[allow(clippy::too_many_arguments)]
617    pub(crate) fn eval_function_expr(
618        &self,
619        name: &Option<Rc<str>>,
620        params: &Rc<Vec<Param>>,
621        body: &Rc<FnBody>,
622        is_arrow: bool,
623        is_async: bool,
624        is_generator: bool,
625        scope: &Rc<RefCell<Scope>>,
626        this: &Value,
627    ) -> EvalResult {
628        if !is_arrow {
629            if let Some(n) = name {
630                if !n.is_empty() {
631                    let wrapper = Scope::child(scope.clone());
632                    let f = self.make_function(
633                        Some(String::from(&**n)),
634                        params.clone(),
635                        body.clone(),
636                        is_arrow,
637                        is_async,
638                        is_generator,
639                        &wrapper,
640                        this,
641                    );
642                    scope_declare(&wrapper, n, f.clone());
643                    return Ok(f);
644                }
645            }
646        }
647        Ok(self.make_function(
648            name.as_deref().map(String::from),
649            params.clone(),
650            body.clone(),
651            is_arrow,
652            is_async,
653            is_generator,
654            scope,
655            this,
656        ))
657    }
658
659    #[allow(clippy::too_many_arguments)]
660    pub(crate) fn make_function(
661        &self,
662        name: Option<String>,
663        params: Rc<Vec<Param>>,
664        body: Rc<FnBody>,
665        is_arrow: bool,
666        is_async: bool,
667        is_generator: bool,
668        scope: &Rc<RefCell<Scope>>,
669        this: &Value,
670    ) -> Value {
671        use crate::os_lib::ecma::value::{FN_FLAG_ARROW, FN_FLAG_ASYNC, FN_FLAG_GENERATOR};
672        let mut flags = 0u8;
673        if is_arrow { flags |= FN_FLAG_ARROW; }
674        if is_async { flags |= FN_FLAG_ASYNC; }
675        if is_generator { flags |= FN_FLAG_GENERATOR; }
676
677        let name_str = name.as_deref().unwrap_or("");
678        let shared = body.get_or_create_shared_info(name_str, &params, flags);
679        let fd = FunctionData {
680            shared,
681            closure: scope.clone(),
682            bound_this: if is_arrow {
683                Some(Rc::new(this.clone()))
684            } else {
685                None
686            },
687        };
688        let func_obj = Obj::function(fd);
689        Value::Object(func_obj)
690    }
691
692    /// 分割代入パターンへ値を束縛する(var 宣言・引数・for-of 共通)。
693    pub(crate) fn bind_pattern(
694        &mut self,
695        pat: &Pattern,
696        value: Value,
697        scope: &Rc<RefCell<Scope>>,
698        this: &Value,
699    ) -> Result<(), Value> {
700        match pat {
701            Pattern::Identifier(name) => {
702                // 名前は構文木の `Rc<str>` を共有する(宣言のたびに文字列を確保しない)。
703                scope.borrow_mut().vars.insert(name.clone(), value);
704                Ok(())
705            }
706            Pattern::Expr(target) => self.assign_to(target, value, scope, this),
707            Pattern::Object(props) => {
708                if matches!(value, Value::Undefined | Value::Null) {
709                    return Err(self.type_error(alloc::format!(
710                        "Cannot destructure property of '{}' as it is {}.",
711                        value.to_js_string(),
712                        value.to_js_string()
713                    )));
714                }
715                let has_rest = props.iter().any(|p| p.is_rest);
716                let mut consumed: Vec<String> = Vec::new();
717                for p in props {
718                    if p.is_rest {
719                        // rest: 未消費の自身プロパティを新オブジェクトへ集める(CopyDataProperties)。
720                        let rest = Obj::plain();
721                        super::super::builtins::copy_data_properties(self, &rest, &value, &consumed)?;
722                        self.bind_pattern(&p.value, Value::Object(rest), scope, this)?;
723                        continue;
724                    }
725                    let computed_val;
726                    let key: alloc::borrow::Cow<'_, str> = match &p.computed_key {
727                        Some(ce) => {
728                            computed_val = self.eval_key(ce, scope, this)?;
729                            to_property_key(&computed_val)
730                        }
731                        None => alloc::borrow::Cow::Borrowed(&*p.key),
732                    };
733                    if has_rest {
734                        consumed.push(key.as_ref().into());
735                    }
736                    let mut v = self.get_property(&value, key.as_ref())?;
737                    if matches!(v, Value::Undefined) {
738                        if let Some(def) = &p.default {
739                            v = self.eval(def, scope, this)?;
740                            super::name_default_value(&v, def, &p.value);
741                        }
742                    }
743                    self.bind_pattern(&p.value, v, scope, this)?;
744                }
745                Ok(())
746            }
747            Pattern::Array(elems) => self.bind_array_pattern(elems, &value, scope, this),
748        }
749    }
750
751    fn bind_array_pattern(
752        &mut self,
753        elems: &[ArrPatElem],
754        value: &Value,
755        scope: &Rc<RefCell<Scope>>,
756        this: &Value,
757    ) -> Result<(), Value> {
758        // 利用者定義の反復子は仕様どおり必要な分だけ引き、残っていれば IteratorClose(`return()`)を呼ぶ(Wave F)。
759        if let Some((iterator, next_fn)) = self.open_lazy_iterator(value)? {
760            return self.bind_array_pattern_lazy(elems, &iterator, &next_fn, scope, this);
761        }
762        // 配列オブジェクトであれば Vec 复制を行わず ObjKind::Array から直接参照する(ヒープ確保ゼロ)。
763        let mut owned_items: Option<Vec<Value>> = None;
764        let arr_obj = match value {
765            Value::Object(o) if matches!(o.borrow().kind, ObjKind::Array(_)) => Some(o),
766            _ => {
767                let need = if elems.iter().any(|e| e.is_rest) { None } else { Some(elems.len()) };
768                owned_items = Some(self.destructure_values(value, need)?);
769                None
770            }
771        };
772        for (i, el) in elems.iter().enumerate() {
773            if el.is_rest {
774                let rest: Vec<Value> = if let Some(o) = arr_obj {
775                    match &o.borrow().kind {
776                        ObjKind::Array(items) => items.get(i..).map(|s| s.to_vec()).unwrap_or_default(),
777                        _ => Vec::new(),
778                    }
779                } else {
780                    owned_items
781                        .as_deref()
782                        .and_then(|items| items.get(i..))
783                        .map(|s| s.to_vec())
784                        .unwrap_or_default()
785                };
786                if let Some(p) = &el.pattern {
787                    self.bind_pattern(p, Value::Object(Obj::array(rest)), scope, this)?;
788                }
789                break;
790            }
791            let Some(p) = &el.pattern else { continue };
792            let mut v = if let Some(o) = arr_obj {
793                match &o.borrow().kind {
794                    ObjKind::Array(items) => items.get(i).cloned().unwrap_or(Value::Undefined),
795                    _ => Value::Undefined,
796                }
797            } else {
798                owned_items
799                    .as_deref()
800                    .and_then(|items| items.get(i))
801                    .cloned()
802                    .unwrap_or(Value::Undefined)
803            };
804            if matches!(v, Value::Undefined) {
805                if let Some(def) = &el.default {
806                    v = self.eval(def, scope, this)?;
807                    super::name_default_value(&v, def, p);
808                }
809            }
810            self.bind_pattern(p, v, scope, this)?;
811        }
812        Ok(())
813    }
814
815    /// 配列の分割代入(利用者定義の反復子)。`next()` の例外は閉じずに、束縛・既定値の例外は IteratorClose してから伝える。
816    fn bind_array_pattern_lazy(
817        &mut self,
818        elems: &[ArrPatElem],
819        iterator: &Value,
820        next_fn: &Value,
821        scope: &Rc<RefCell<Scope>>,
822        this: &Value,
823    ) -> Result<(), Value> {
824        let mut done = false;
825        // Err((例外, 反復子から来た例外か))
826        let res = (|| -> Result<(), (Value, bool)> {
827            for el in elems {
828                if el.is_rest {
829                    let mut rest = Vec::new();
830                    while !done {
831                        match self.iter_step_once(next_fn, iterator) {
832                            Ok(Some(v)) => rest.push(v),
833                            Ok(None) => done = true,
834                            Err(e) => {
835                                done = true;
836                                return Err((e, true));
837                            }
838                        }
839                    }
840                    if let Some(p) = &el.pattern {
841                        self.bind_pattern(p, Value::Object(Obj::array(rest)), scope, this).map_err(|e| (e, false))?;
842                    }
843                    break;
844                }
845                let mut v = Value::Undefined;
846                if !done {
847                    match self.iter_step_once(next_fn, iterator) {
848                        Ok(Some(x)) => v = x,
849                        Ok(None) => done = true,
850                        Err(e) => {
851                            done = true;
852                            return Err((e, true));
853                        }
854                    }
855                }
856                let Some(p) = &el.pattern else { continue };
857                if matches!(v, Value::Undefined) {
858                    if let Some(def) = &el.default {
859                        v = self.eval(def, scope, this).map_err(|e| (e, false))?;
860                        super::name_default_value(&v, def, p);
861                    }
862                }
863                self.bind_pattern(p, v, scope, this).map_err(|e| (e, false))?;
864            }
865            Ok(())
866        })();
867        match res {
868            Ok(()) => {
869                if !done {
870                    self.iterator_close(iterator)?;
871                }
872                Ok(())
873            }
874            Err((e, _)) if done => Err(e),
875            Err((e, _)) => {
876                if !(self.aborted || self.is_suspending() || self.is_gen_returning()) {
877                    let _ = self.iterator_close(iterator);
878                }
879                Err(e)
880            }
881        }
882    }
883
884    /// クラス内のプライベート要素記述子(`__priv_#name`)をスコープ連鎖から引く。
885    fn lookup_private_desc(
886        &self,
887        scope: &Rc<RefCell<Scope>>,
888        name: &str,
889    ) -> Result<super::super::value::PrivateDescriptor, Value> {
890        let skey = alloc::format!("__priv_{}", name);
891        if let Some(Value::Object(o)) = scope_get(scope, &skey) {
892            if let ObjKind::PrivateDesc(pd) = &o.borrow().kind {
893                return Ok((**pd).clone());
894            }
895        }
896        Err(self.syntax_error(alloc::format!(
897            "Private field '{}' must be declared in an enclosing class",
898            name
899        )))
900    }
901
902    /// `obj.#name` の読み出し(フィールド/メソッド/getter、ブランド検査付き)。
903    pub(crate) fn private_get(
904        &mut self,
905        obj: &Value,
906        name: &str,
907        scope: &Rc<RefCell<Scope>>,
908    ) -> EvalResult {
909        let pd = self.lookup_private_desc(scope, name)?;
910        let Value::Object(o) = obj else {
911            return Err(self.type_error(alloc::format!(
912                "Cannot read private member {} from non-object",
913                name
914            )));
915        };
916        match &pd.kind {
917            super::super::value::PrivateKind::Field | super::super::value::PrivateKind::StaticField => {
918                if let Some(v) = o.borrow().get_private_field(pd.brand_id, &pd.name) {
919                    Ok(v.clone())
920                } else {
921                    Err(self.type_error(alloc::format!(
922                        "Cannot read private member {} from an object whose class did not declare it",
923                        name
924                    )))
925                }
926            }
927            super::super::value::PrivateKind::Method(f)
928            | super::super::value::PrivateKind::StaticMethod(f) => {
929                if o.borrow().has_private_brand(pd.brand_id) {
930                    Ok(f.clone())
931                } else {
932                    Err(self.type_error(alloc::format!(
933                        "Cannot read private member {} from an object whose class did not declare it",
934                        name
935                    )))
936                }
937            }
938            super::super::value::PrivateKind::Accessor { get, .. }
939            | super::super::value::PrivateKind::StaticAccessor { get, .. } => {
940                if !o.borrow().has_private_brand(pd.brand_id) {
941                    return Err(self.type_error(alloc::format!(
942                        "Cannot read private member {} from an object whose class did not declare it",
943                        name
944                    )));
945                }
946                match get {
947                    Some(g) => self.call_value(g, obj.clone(), &[]),
948                    None => Err(self.type_error(alloc::format!(
949                        "Private accessor {} was defined without a getter",
950                        name
951                    ))),
952                }
953            }
954        }
955    }
956
957    /// `obj.#name = val` の書き込み(フィールド/メソッド書込禁止/setter、ブランド検査付き)。
958    pub(crate) fn private_set(
959        &mut self,
960        obj: &Value,
961        name: &str,
962        val: Value,
963        scope: &Rc<RefCell<Scope>>,
964    ) -> Result<(), Value> {
965        let pd = self.lookup_private_desc(scope, name)?;
966        let Value::Object(o) = obj else {
967            return Err(self.type_error(alloc::format!(
968                "Cannot write private member {} to non-object",
969                name
970            )));
971        };
972        match &pd.kind {
973            super::super::value::PrivateKind::Field | super::super::value::PrivateKind::StaticField => {
974                if o.borrow_mut().set_private_field(pd.brand_id, &pd.name, val) {
975                    Ok(())
976                } else {
977                    Err(self.type_error(alloc::format!(
978                        "Cannot write private member {} to an object whose class did not declare it",
979                        name
980                    )))
981                }
982            }
983            super::super::value::PrivateKind::Method(_)
984            | super::super::value::PrivateKind::StaticMethod(_) => {
985                if !o.borrow().has_private_brand(pd.brand_id) {
986                    return Err(self.type_error(alloc::format!(
987                        "Cannot write private member {} to an object whose class did not declare it",
988                        name
989                    )));
990                }
991                Err(self.type_error(alloc::format!("Private method {} is not writable", name)))
992            }
993            super::super::value::PrivateKind::Accessor { set, .. }
994            | super::super::value::PrivateKind::StaticAccessor { set, .. } => {
995                if !o.borrow().has_private_brand(pd.brand_id) {
996                    return Err(self.type_error(alloc::format!(
997                        "Cannot write private member {} to an object whose class did not declare it",
998                        name
999                    )));
1000                }
1001                match set {
1002                    Some(s) => {
1003                        self.call_value(s, obj.clone(), &[val])?;
1004                        Ok(())
1005                    }
1006                    None => Err(self.type_error(alloc::format!(
1007                        "Private accessor {} was defined without a setter",
1008                        name
1009                    ))),
1010                }
1011            }
1012        }
1013    }
1014
1015    /// `#name in obj` のブランド/スロット存在検査。
1016    pub(crate) fn private_in(
1017        &mut self,
1018        obj: &Value,
1019        name: &str,
1020        scope: &Rc<RefCell<Scope>>,
1021    ) -> EvalResult {
1022        let Value::Object(o) = obj else {
1023            return Err(self.type_error(alloc::format!(
1024                "Cannot use 'in' operator to search for '{}' in {}",
1025                name,
1026                obj.to_js_string()
1027            )));
1028        };
1029        let pd = self.lookup_private_desc(scope, name)?;
1030        let present = match &pd.kind {
1031            super::super::value::PrivateKind::Field | super::super::value::PrivateKind::StaticField => {
1032                o.borrow().has_private_field(pd.brand_id, &pd.name)
1033            }
1034            super::super::value::PrivateKind::Method(_)
1035            | super::super::value::PrivateKind::StaticMethod(_)
1036            | super::super::value::PrivateKind::Accessor { .. }
1037            | super::super::value::PrivateKind::StaticAccessor { .. } => {
1038                o.borrow().has_private_brand(pd.brand_id)
1039            }
1040        };
1041        Ok(Value::Bool(present))
1042    }
1043
1044    /// `class` を評価し、コンストラクタ関数(prototype・静的メンバ・super 連携付き)を返す。
1045    pub(crate) fn eval_class(
1046        &mut self,
1047        name: &Option<String>,
1048        superclass: &Option<Box<Expression>>,
1049        members: &[ClassMember],
1050        scope: &Rc<RefCell<Scope>>,
1051        this: &Value,
1052    ) -> EvalResult {
1053        use super::super::value::{PrivateDescriptor, PrivateKind};
1054        let superclass_val = match superclass {
1055            Some(e) => Some(self.eval(e, scope, this)?),
1056            None => None,
1057        };
1058        // ClassHeritage(§15.7.14 step 8): null か構築できる関数でなければ TypeError。
1059        if let Some(sv) = &superclass_val {
1060            if !matches!(sv, Value::Null) && !super::calls::is_constructor(sv) {
1061                return Err(self.type_error("Class extends value is not a constructor or null"));
1062            }
1063        }
1064        // プロトタイプ(インスタンスメソッド置き場)。継承時は基底 prototype を proto に。
1065        let proto = Obj::plain();
1066        // `constructor` を先頭の位置に確保しておく(`Object.getOwnPropertyNames(C.prototype)` は constructor から始まる)。
1067        proto.borrow_mut().props.insert(String::from("constructor").into(), Value::Undefined);
1068        if let Some(sv) = &superclass_val {
1069            if matches!(sv, Value::Null) {
1070                proto.borrow_mut().set_null_proto(true);
1071            } else {
1072                let sp = self.get_property(sv, "prototype")?;
1073                match sp {
1074                    Value::Object(p) => {
1075                        proto.borrow_mut().proto = Some(p);
1076                    }
1077                    Value::Null => {
1078                        proto.borrow_mut().set_null_proto(true);
1079                    }
1080                    _ => {
1081                        return Err(self.type_error("Class extends value prototype is not an object or null"));
1082                    }
1083                }
1084            }
1085        }
1086        // メソッドの closure に __superclass__ / クラス名 / プライベート要素を持たせる。
1087        let class_scope = Scope::child(scope.clone());
1088        if let Some(sv) = &superclass_val {
1089            scope_declare(&class_scope, "__superclass__", sv.clone());
1090        }
1091        let inst_brand_id = self.next_private_brand_id();
1092        let static_brand_id = self.next_private_brand_id();
1093        // 【2026-11-19】[[HomeObject]](ECMA-262 §10.2.5 MakeMethod / §13.3.7 SuperProperty)。
1094        let proto_scope = Scope::child(class_scope.clone());
1095        scope_declare(&proto_scope, "__home__", Value::Object(proto.clone()));
1096        let static_scope = Scope::child(class_scope.clone());
1097
1098        enum StaticInit {
1099            Field {
1100                key: String,
1101                init: Option<Expression>,
1102                is_private: bool,
1103            },
1104            Block(Rc<FnBody>),
1105        }
1106
1107        let mut ctor_params: Rc<Vec<Param>> = Rc::new(Vec::new());
1108        let mut ctor_body: Option<Rc<FnBody>> = None;
1109        // (名前, 初期化式, プライベートか)
1110        let mut instance_field_inits: Vec<(String, Option<Expression>, bool)> = Vec::new();
1111        // (名前, 値, メソッドか)。静的メソッドのみ即座に保持(静的フィールドは初期化順のため static_inits へ)。
1112        let mut statics: Vec<(String, Value, bool)> = Vec::new();
1113        // static な get/set アクセサ(key, is_getter, function)。
1114        let mut static_accessors: Vec<(String, bool, Value)> = Vec::new();
1115        // static フィールド初期化と `static { ... }` を宣言順で実行するためのリスト。
1116        let mut static_inits: Vec<StaticInit> = Vec::new();
1117        let mut class_source: Option<Rc<FnBody>> = None;
1118        let mut has_inst_priv_brand = false;
1119        let mut has_static_priv_brand = false;
1120
1121        let register_priv_desc = |cs: &Rc<RefCell<Scope>>, key: &str, pd: PrivateDescriptor| {
1122            let skey = alloc::format!("__priv_{}", key);
1123            scope_declare(cs, &skey, Value::Object(Obj::private_desc(pd)));
1124        };
1125
1126        for m in members {
1127            if m.kind == MethodKind::ClassSource {
1128                class_source = Some(m.body.clone());
1129                continue;
1130            }
1131            if m.kind == MethodKind::StaticBlock {
1132                static_inits.push(StaticInit::Block(m.body.clone()));
1133                continue;
1134            }
1135            if m.kind == MethodKind::Field {
1136                let is_private = m.computed_key.is_none() && m.key.starts_with('#');
1137                // 算出名のフィールド `[expr] = v` の名前はクラス定義時に(宣言順で)一度だけ評価する。
1138                let field_key = match &m.computed_key {
1139                    Some(ce) => to_property_key(&self.eval_key(ce, &class_scope, this)?).into_owned(),
1140                    None => m.key.to_string(),
1141                };
1142                // フィールド名 "constructor"(算出含む)および static フィールド名 "prototype" は TypeError(§15.7.14 ClassFieldDefinitionEvaluation)。
1143                if (field_key == "constructor" && m.computed_key.is_none()) || (m.is_static && field_key == "prototype") {
1144                    return Err(self.type_error(alloc::format!("Classes may not have a field named '{}'", field_key)));
1145                }
1146                if is_private {
1147                    let (brand_id, kind) = if m.is_static {
1148                        (static_brand_id, PrivateKind::StaticField)
1149                    } else {
1150                        (inst_brand_id, PrivateKind::Field)
1151                    };
1152                    register_priv_desc(
1153                        &class_scope,
1154                        &field_key,
1155                        PrivateDescriptor {
1156                            brand_id,
1157                            name: Rc::from(field_key.as_str()),
1158                            kind,
1159                        },
1160                    );
1161                }
1162                if m.is_static {
1163                    // 静的フィールドの初期化式は全算出キー評価およびクラス構築の後に実行する。
1164                    static_inits.push(StaticInit::Field {
1165                        key: field_key,
1166                        init: m.field_init.clone(),
1167                        is_private,
1168                    });
1169                } else {
1170                    instance_field_inits.push((field_key, m.field_init.clone(), is_private));
1171                }
1172                continue;
1173            }
1174            if !m.is_static && m.kind == MethodKind::Constructor {
1175                // コンストラクタは function 化を後段(フィールド初期化の差し込み後)に回す。
1176                ctor_params = m.params.clone();
1177                ctor_body = Some(m.body.clone());
1178                continue;
1179            }
1180            let is_private = m.computed_key.is_none() && m.key.starts_with('#');
1181            // 算出メソッド名 `[expr](){}`(`[Symbol.iterator]` 等)はクラス定義時に評価する。
1182            let key = match &m.computed_key {
1183                Some(ce) => to_property_key(&self.eval_key(ce, &class_scope, this)?).into_owned(),
1184                None => m.key.to_string(),
1185            };
1186            // static メソッド/アクセサの名前が "prototype"(算出名)なら、非構成の自前プロパティと衝突して TypeError(§15.7.14)。
1187            if m.is_static && key == "prototype" && !is_private {
1188                return Err(self.type_error("Classes may not have a static property named 'prototype'"));
1189            }
1190            if matches!(m.kind, MethodKind::Getter | MethodKind::Setter) {
1191                let is_getter = m.kind == MethodKind::Getter;
1192                let f = self.make_function(
1193                    Some(alloc::format!("{} {}", if is_getter { "get" } else { "set" }, super::fn_name_from_key(&key))),
1194                    m.params.clone(),
1195                    m.body.clone(),
1196                    false,
1197                    false,
1198                    false,
1199                    if m.is_static { &static_scope } else { &proto_scope },
1200                    this,
1201                );
1202                if is_private {
1203                    if m.is_static {
1204                        has_static_priv_brand = true;
1205                    } else {
1206                        has_inst_priv_brand = true;
1207                    }
1208                    let skey = alloc::format!("__priv_{}", key);
1209                    let existing = class_scope.borrow().vars.get(&skey).cloned();
1210                    let mut updated = false;
1211                    if let Some(Value::Object(po)) = existing {
1212                        if let ObjKind::PrivateDesc(pd) = &mut po.borrow_mut().kind {
1213                            match &mut pd.kind {
1214                                PrivateKind::Accessor { get, set } | PrivateKind::StaticAccessor { get, set } => {
1215                                    if is_getter {
1216                                        *get = Some(f.clone());
1217                                    } else {
1218                                        *set = Some(f.clone());
1219                                    }
1220                                    updated = true;
1221                                }
1222                                _ => {}
1223                            }
1224                        }
1225                    }
1226                    if !updated {
1227                        let (get, set) = if is_getter { (Some(f), None) } else { (None, Some(f)) };
1228                        let (brand_id, kind) = if m.is_static {
1229                            (static_brand_id, PrivateKind::StaticAccessor { get, set })
1230                        } else {
1231                            (inst_brand_id, PrivateKind::Accessor { get, set })
1232                        };
1233                        register_priv_desc(
1234                            &class_scope,
1235                            &key,
1236                            PrivateDescriptor {
1237                                brand_id,
1238                                name: Rc::from(key.as_str()),
1239                                kind,
1240                            },
1241                        );
1242                    }
1243                    continue;
1244                }
1245                if m.is_static {
1246                    static_accessors.push((key, is_getter, f));
1247                } else {
1248                    let mut b = proto.borrow_mut();
1249                    let key_attr = key.clone();
1250                    let entry = b
1251                        .accessors_mut()
1252                        .entry(key.into())
1253                        .or_insert(Accessor { get: None, set: None });
1254                    if is_getter {
1255                        entry.get = Some(f);
1256                    } else {
1257                        entry.set = Some(f);
1258                    }
1259                    b.insert_attr(
1260                        key_attr,
1261                        super::super::value::PropertyAttributes { writable: true, configurable: true, enumerable: false },
1262                    );
1263                }
1264                continue;
1265            }
1266            let f = self.make_function(
1267                Some(super::fn_name_from_key(&key)),
1268                m.params.clone(),
1269                m.body.clone(),
1270                false,
1271                m.is_async,
1272                m.is_generator,
1273                if m.is_static { &static_scope } else { &proto_scope },
1274                this,
1275            );
1276            if is_private {
1277                if m.is_static {
1278                    has_static_priv_brand = true;
1279                    register_priv_desc(
1280                        &class_scope,
1281                        &key,
1282                        PrivateDescriptor {
1283                            brand_id: static_brand_id,
1284                            name: Rc::from(key.as_str()),
1285                            kind: PrivateKind::StaticMethod(f),
1286                        },
1287                    );
1288                } else {
1289                    has_inst_priv_brand = true;
1290                    register_priv_desc(
1291                        &class_scope,
1292                        &key,
1293                        PrivateDescriptor {
1294                            brand_id: inst_brand_id,
1295                            name: Rc::from(key.as_str()),
1296                            kind: PrivateKind::Method(f),
1297                        },
1298                    );
1299                }
1300                continue;
1301            }
1302            if m.is_static {
1303                statics.push((key, f, true));
1304            } else {
1305                proto.borrow_mut().props.insert(key.clone().into(), f);
1306                proto.borrow_mut().insert_attr(
1307                    key,
1308                    super::super::value::PropertyAttributes {
1309                        writable: true,
1310                        configurable: true,
1311                        enumerable: false,
1312                    },
1313                );
1314            }
1315        }
1316
1317        // インスタンス要素初期化文を組み立てる(プライベートブランド付与→各フィールド宣言順)。
1318        let mut field_stmts: Vec<Statement> = Vec::new();
1319        if has_inst_priv_brand {
1320            field_stmts.push(Statement::InitPrivateBrand(inst_brand_id));
1321        }
1322        for (key, init, is_private) in instance_field_inits {
1323            if is_private {
1324                field_stmts.push(Statement::InitPrivateField {
1325                    brand: inst_brand_id,
1326                    name: Rc::from(key.as_str()),
1327                    init: init.map(Box::new),
1328                });
1329            } else {
1330                field_stmts.push(Statement::InitPublicField {
1331                    key: Rc::from(key.as_str()),
1332                    init: init.map(Box::new),
1333                });
1334            }
1335        }
1336
1337        let mut all_priv_names: Vec<Rc<str>> = self
1338            .eval_ctx_stack
1339            .last()
1340            .map(|c| c.private_names.clone())
1341            .unwrap_or_default();
1342        for k in class_scope.borrow().vars.keys() {
1343            if let Some(pname) = k.strip_prefix("__priv_") {
1344                if !all_priv_names.iter().any(|x| &**x == pname) {
1345                    all_priv_names.push(Rc::from(pname));
1346                }
1347            }
1348        }
1349        let wrapped_fields: Vec<Statement> = if field_stmts.is_empty() {
1350            Vec::new()
1351        } else {
1352            alloc::vec![Statement::ClassFieldInit {
1353                stmts: field_stmts,
1354                priv_names: all_priv_names.clone(),
1355            }]
1356        };
1357
1358        // コンストラクタ本体を確定: ユーザー定義があればフィールド初期化を差し込み(継承時は先頭の super() の直後)、
1359        // 無ければデフォルト(継承時は super(...arguments) の後にフィールド初期化)。
1360        let (final_params, final_body): (Rc<Vec<Param>>, Rc<FnBody>) = match ctor_body {
1361            Some(user_body) if wrapped_fields.is_empty() => (ctor_params, user_body),
1362            Some(user_body) => {
1363                let ustmts = user_body.stmts();
1364                let insert_at = if superclass_val.is_some() {
1365                    ustmts
1366                        .iter()
1367                        .position(|s| {
1368                            matches!(
1369                                s,
1370                                Statement::Expression(Expression::Call { callee, .. })
1371                                    if matches!(**callee, Expression::Super)
1372                            )
1373                        })
1374                        .map(|i| i + 1)
1375                        .unwrap_or(0)
1376                } else {
1377                    0
1378                };
1379                let mut body = Vec::with_capacity(ustmts.len() + wrapped_fields.len());
1380                body.extend(ustmts[..insert_at].iter().cloned());
1381                body.extend(wrapped_fields);
1382                body.extend(ustmts[insert_at..].iter().cloned());
1383                let fb = FnBody::parsed_with(body, true);
1384                if let Some(ctx) = user_body.eval_ctx() {
1385                    fb.set_eval_ctx(ctx);
1386                } else {
1387                    fb.set_eval_ctx(crate::os_lib::ecma::ast::EvalSyntaxCtx {
1388                        in_function: true,
1389                        allow_super_call: superclass_val.is_some(),
1390                        allow_super_prop: true,
1391                        in_field_init: false,
1392                        in_static_block: false,
1393                        private_names: all_priv_names.clone(),
1394                    });
1395                }
1396                (ctor_params, fb)
1397            }
1398            None => {
1399                let mut body: Vec<Statement> = Vec::new();
1400                if superclass_val.is_some() {
1401                    body.push(Statement::Expression(Expression::Call {
1402                        callee: Box::new(Expression::Super),
1403                        arguments: alloc::vec![Expression::Spread(Box::new(
1404                            Expression::Identifier(alloc::rc::Rc::from("arguments"))
1405                        ))],
1406                        optional: false,
1407                    }));
1408                }
1409                body.extend(wrapped_fields);
1410                let fb = FnBody::parsed_with(body, true);
1411                fb.set_eval_ctx(crate::os_lib::ecma::ast::EvalSyntaxCtx {
1412                    in_function: true,
1413                    allow_super_call: superclass_val.is_some(),
1414                    allow_super_prop: true,
1415                    in_field_init: false,
1416                    in_static_block: false,
1417                    private_names: all_priv_names.clone(),
1418                });
1419                (Rc::new(Vec::new()), fb)
1420            }
1421        };
1422        // クラスの関数のソースはクラス全体(`class A { … }`)。
1423        if let Some(cs) = &class_source {
1424            final_body.copy_source_from(cs);
1425        }
1426        let ctor = self.make_function(
1427            name.clone(),
1428            final_params,
1429            final_body,
1430            false,
1431            false,
1432            false,
1433            &proto_scope,
1434            this,
1435        );
1436        scope_declare(&static_scope, "__home__", ctor.clone());
1437
1438        if let Value::Object(co) = &ctor {
1439            if has_static_priv_brand {
1440                co.borrow_mut().add_private_brand(static_brand_id);
1441            }
1442            co.borrow_mut()
1443                .props
1444                .insert(String::from("prototype").into(), Value::Object(proto.clone()));
1445            co.borrow_mut().insert_attr(
1446                String::from("prototype"),
1447                super::super::value::PropertyAttributes { writable: false, configurable: false, enumerable: false },
1448            );
1449            if let Some(sv) = &superclass_val {
1450                co.borrow_mut()
1451                    .props
1452                    .insert(String::from("__superclass__").into(), sv.clone());
1453                if let Value::Object(sc) = sv {
1454                    co.borrow_mut().proto = Some(sc.clone());
1455                }
1456            }
1457            for (k, v, is_method) in statics {
1458                if is_method {
1459                    co.borrow_mut().insert_attr(
1460                        k.clone(),
1461                        super::super::value::PropertyAttributes { writable: true, configurable: true, enumerable: false },
1462                    );
1463                }
1464                co.borrow_mut().props.insert(k.into(), v);
1465            }
1466            for (k, is_getter, f) in static_accessors {
1467                let mut b = co.borrow_mut();
1468                b.insert_attr(
1469                    k.clone(),
1470                    super::super::value::PropertyAttributes { writable: true, configurable: true, enumerable: false },
1471                );
1472                let entry = b
1473                    .accessors_mut()
1474                    .entry(k.into())
1475                    .or_insert(Accessor { get: None, set: None });
1476                if is_getter {
1477                    entry.get = Some(f);
1478                } else {
1479                    entry.set = Some(f);
1480                }
1481            }
1482            proto
1483                .borrow_mut()
1484                .props
1485                .insert(String::from("constructor").into(), ctor.clone());
1486            proto.borrow_mut().insert_attr(
1487                String::from("constructor"),
1488                super::super::value::PropertyAttributes {
1489                    writable: true,
1490                    configurable: true,
1491                    enumerable: false,
1492                },
1493            );
1494        }
1495        // クラス名を class_scope に束縛(静的フィールド・static {} ブロック・メソッド内から自身を参照可能に)。
1496        if let Some(n) = &name {
1497            scope_declare(&class_scope, n, ctor.clone());
1498        }
1499        // 静的フィールド初期化と `static { ... }` を宣言順に、`this` をコンストラクタ自身として実行する。
1500        for item in static_inits {
1501            match item {
1502                StaticInit::Field { key, init, is_private } => {
1503                    self.eval_ctx_stack.push(crate::os_lib::ecma::ast::EvalSyntaxCtx {
1504                        in_function: false,
1505                        allow_super_call: false,
1506                        allow_super_prop: true,
1507                        in_field_init: true,
1508                        in_static_block: false,
1509                        private_names: all_priv_names.clone(),
1510                    });
1511                    let static_init_expr = init.clone();
1512                    let v_res = match init {
1513                        Some(e) => self.eval(&e, &static_scope, &ctor),
1514                        None => Ok(Value::Undefined),
1515                    };
1516                    self.eval_ctx_stack.pop();
1517                    let v = v_res?;
1518                    if let Some(Expression::Function { name: None, .. } | Expression::Class { name: None, .. }) = &static_init_expr {
1519                        infer_function_name(&v, &super::fn_name_from_key(&key));
1520                    }
1521                    if is_private {
1522                        if let Value::Object(co) = &ctor {
1523                            if !co.borrow_mut().define_private_field(static_brand_id, Rc::from(key.as_str()), v) {
1524                                return Err(self.type_error(alloc::format!(
1525                                    "Cannot initialize static private field {} twice",
1526                                    key
1527                                )));
1528                            }
1529                        }
1530                    } else if let Value::Object(co) = &ctor {
1531                        co.borrow_mut().props.insert(key.into(), v);
1532                    }
1533                }
1534                StaticInit::Block(block) => {
1535                    let ctx = block.eval_ctx().unwrap_or_else(|| crate::os_lib::ecma::ast::EvalSyntaxCtx {
1536                        in_function: false,
1537                        allow_super_call: false,
1538                        allow_super_prop: true,
1539                        in_field_init: false,
1540                        in_static_block: true,
1541                        private_names: all_priv_names.clone(),
1542                    });
1543                    self.eval_ctx_stack.push(ctx);
1544                    // 各 static ブロックは独立した関数スコープ(`let`/`var` は他のブロックへ漏れない)。
1545                    let block_scope = Scope::child(static_scope.clone());
1546                    let res = self.exec_statements(&block.stmts(), &block_scope, &ctor);
1547                    self.eval_ctx_stack.pop();
1548                    res?;
1549                }
1550            }
1551        }
1552        Ok(ctor)
1553    }
1554
1555    /// 現在のスコープから基底クラスのコンストラクタを取得。
1556    pub(crate) fn super_ctor(&mut self, scope: &Rc<RefCell<Scope>>) -> EvalResult {
1557        match scope_get(scope, "__superclass__") {
1558            Some(v) => Ok(v),
1559            None => Err(self.reference_error("'super' keyword unexpected here")),
1560        }
1561    }
1562    /// `super.x` の探索の起点(ECMA-262 §13.3.7.3 MakeSuperPropertyReference:
1563    /// `baseValue = env.GetSuperBase()` = HomeObject.[[GetPrototypeOf]]())。
1564    /// 【2026-11-19】以前は「基底クラスの prototype」固定で、static メソッドや
1565    /// オブジェクトリテラルのメソッド(`{ __proto__: p, f() { super.x } }`)で使えなかった。
1566    pub(crate) fn super_proto(&mut self, scope: &Rc<RefCell<Scope>>) -> EvalResult {
1567        match scope_get(scope, "__home__") {
1568            Some(Value::Object(h)) => Ok(super::super::builtins::effective_proto(self, &h)),
1569            _ => Err(self.reference_error("'super' keyword unexpected here")),
1570        }
1571    }
1572
1573    /// `super[key]` / `super.key` の読み出し(§6.2.5.5 GetValue: 参照の thisValue = 現在の `this`)。
1574    /// 起点から原型の連鎖をたどり、アクセサ(getter)が先に見つかれば `this` を受け手にして呼ぶ。
1575    /// 【2026-11-19】以前は起点オブジェクトを受け手にしていて、getter の `this` が起点になっていた。
1576    pub(crate) fn super_get(&mut self, scope: &Rc<RefCell<Scope>>, key: &str, this: &Value) -> EvalResult {
1577        let base = self.super_proto(scope)?;
1578        let eff_this = self.resolve_this(scope, this)?;
1579        if let Value::Object(b) = &base {
1580            let mut cur = Some(b.clone());
1581            let mut guard = 0u32;
1582            while let Some(c) = cur {
1583                let (acc, has_data, next) = {
1584                    let bb = c.borrow();
1585                    (bb.get_accessor(key).map(|a| a.get.clone()), bb.props.contains_key(key), bb.proto.clone())
1586                };
1587                if let Some(g) = acc {
1588                    return match g {
1589                        Some(g) => self.call_value(&g, eff_this, &[]),
1590                        None => Ok(Value::Undefined),
1591                    };
1592                }
1593                guard += 1;
1594                if has_data || guard > 1000 {
1595                    break;
1596                }
1597                cur = next;
1598            }
1599        }
1600        self.get_property(&base, key)
1601    }
1602
1603    /// `super.key = v` の書き込み(§10.1.9.2 OrdinarySetWithOwnDescriptor, Receiver = 現在の `this`)。
1604    /// 起点の連鎖で setter が先に見つかれば `this` を受け手にして呼ぶ。データ値なら受け手 `this` の自身のプロパティに書く。
1605    pub(crate) fn super_set(&mut self, scope: &Rc<RefCell<Scope>>, key: &str, val: Value, this: &Value) -> Result<(), Value> {
1606        let base = self.super_proto(scope)?;
1607        let eff_this = self.resolve_this(scope, this)?;
1608        if let Value::Object(b) = &base {
1609            let mut cur = Some(b.clone());
1610            let mut guard = 0u32;
1611            while let Some(c) = cur {
1612                let (acc, has_data, next) = {
1613                    let bb = c.borrow();
1614                    (bb.get_accessor(key).map(|a| a.set.clone()), bb.props.contains_key(key), bb.proto.clone())
1615                };
1616                if let Some(st) = acc {
1617                    if let Some(st) = st {
1618                        self.call_value(&st, eff_this, &[val])?;
1619                    }
1620                    return Ok(());
1621                }
1622                guard += 1;
1623                if has_data || guard > 1000 {
1624                    break;
1625                }
1626                cur = next;
1627            }
1628        }
1629        if matches!(eff_this, Value::Undefined | Value::Null) {
1630            return Err(self.set_on_nullish_error(&eff_this, key));
1631        }
1632        self.put_value(&eff_this, key, val)
1633    }
1634
1635    // ============ Promise / マイクロタスク ============
1636
1637}
1638
1639/// オブジェクトリテラルの通常のプロパティ `key: v`(`__proto__: v` は原型の設定)。generator の VM と共用。
1640#[inline]
1641pub(crate) fn object_lit_put(o: &ObjRef, p: &Property, key: PropKey, v: Value) {
1642    if p.computed.is_none() && key.as_str() == "__proto__" {
1643        match v {
1644            Value::Object(proto) => o.borrow_mut().proto = Some(proto),
1645            // 【2026-11-17】`{__proto__: null}` は `Object.create(null)` と同じ(原型なしの印を付ける)。
1646            // 以前は印を付けず、`({__proto__:null}).toString` が組み込みの関数を返していた。
1647            Value::Null => {
1648                let mut b = o.borrow_mut();
1649                b.proto = None;
1650                b.set_null_proto(true);
1651            }
1652            _ => {}
1653        }
1654        return;
1655    }
1656    infer_function_name(&v, key.as_str());
1657    o.borrow_mut().props.insert(key, v);
1658}