Skip to main content

atmos/os_lib/ecma/
parser.rs

1//! 再帰下降 + 優先順位クライミングの JS パーサ。
2//!
3//! 全トークンを `Vec<Token>` に集めてインデックスで走査するため、アロー関数判定の
4//! ような任意先読みが容易。エラーは致命的にせずベストエフォートで継続する
5//! (失敗箇所は `Expression::Undefined` / `Statement::Empty` にフォールバック)。
6//! セミコロンは任意(改行ベースの ASI は簡易扱い)。
7
8use alloc::rc::Rc;
9use alloc::boxed::Box;
10use alloc::string::{String, ToString};
11use alloc::vec::Vec;
12use indexmap::IndexSet;
13
14use super::ast::*;
15use super::lexer::{Lexer, Token};
16
17type AtomSet = IndexSet<Rc<str>, core::hash::BuildHasherDefault<crate::os_lib::util::fnv::FnvHasher>>;
18
19/// 回復して解析を続けた構文エラー 1 件。
20///
21/// 【2026-07-28】本パーサは「エラーを致命的にせずベストエフォートで継続」する
22/// 方針だが、従来は**回復したことを誰にも伝えていなかった**ため、壊れた
23/// スクリプトが「正常に解析できた」のと区別できなかった(`expect_sym` は
24/// `let _ = self.eat_sym(s);` と、期待した記号が無い事実を捨てていた)。
25/// 実行はこれまでどおり継続しつつ、**何をどこで諦めたのかは必ず呼び出し側へ
26/// 返す**ためにこの記録を持つ。
27#[derive(Debug, Clone, PartialEq)]
28pub struct ParseError {
29    /// 何を期待して何が来たか。
30    pub message: String,
31    /// トークン列上の位置(`Parser` 内部のトークン索引)。
32    pub token_index: usize,
33}
34
35/// 記録する構文エラーの上限。壊れきった入力で無制限にメモリを食わないため。
36const MAX_RECORDED_ERRORS: usize = 64;
37
38/// エラーメッセージ用にトークンを短く説明する。
39fn describe_token(t: &Token) -> String {
40    match t {
41        Token::Keyword(k) => alloc::format!("keyword '{}'", k),
42        Token::Ident(i) => alloc::format!("identifier '{}'", i),
43        Token::Num(n) => alloc::format!("number {}", n),
44        Token::BigIntLit(s) => alloc::format!("bigint {}", s),
45        Token::Str(_) => String::from("string literal"),
46        Token::Template(_) => String::from("template literal"),
47        Token::Sym(s) => alloc::format!("'{}'", s),
48        Token::Regex(_) => String::from("regex literal"),
49        Token::LazyBody(..) => String::from("function body"),
50        Token::Eof => String::from("end of input"),
51    }
52}
53
54/// 固定長の塊を並べた追記専用の配列(索引で引ける)。
55///
56/// 【2026-10-19】YouTube の視聴ページの kevlar_base(10.8MB、約 320 万トークン)で、
57/// `Vec<Token>` が倍々に伸びて 128MB の連続領域を要求し、ヒープ(512MB、使用 325MB)で
58/// 確保に失敗していた。塊(`CHUNK` 個)ごとに確保すれば、大きな連続領域も、伸長時の
59/// 旧・新の二重持ちも要らない。
60pub struct ChunkedVec<T> {
61    chunks: Vec<Vec<T>>,
62    len: usize,
63}
64
65impl<T> ChunkedVec<T> {
66    const SHIFT: usize = 14;
67    const CHUNK: usize = 1 << Self::SHIFT;
68
69    pub fn new() -> Self {
70        ChunkedVec { chunks: Vec::new(), len: 0 }
71    }
72
73    pub fn push(&mut self, v: T) {
74        let need_new = match self.chunks.last() {
75            Some(c) => c.len() >= Self::CHUNK,
76            None => true,
77        };
78        if need_new {
79            self.chunks.push(Vec::with_capacity(Self::CHUNK));
80        }
81        if let Some(c) = self.chunks.last_mut() {
82            c.push(v);
83            self.len += 1;
84        }
85    }
86
87    pub fn len(&self) -> usize {
88        self.len
89    }
90
91    pub fn is_empty(&self) -> bool {
92        self.len == 0
93    }
94
95    pub fn get(&self, i: usize) -> Option<&T> {
96        self.chunks.get(i >> Self::SHIFT)?.get(i & (Self::CHUNK - 1))
97    }
98
99    /// 位置 `from` 以降を(位置, 要素)で順に返す。
100    pub fn iter_from(&self, from: usize) -> impl Iterator<Item = (usize, &T)> {
101        (from..self.len).filter_map(move |i| self.get(i).map(|t| (i, t)))
102    }
103}
104
105impl<T> Default for ChunkedVec<T> {
106    fn default() -> Self {
107        Self::new()
108    }
109}
110
111/// エラー文脈表示(`context_around` の前 6 個)のために保持する直前トークン数。
112const HISTORY_KEEP: usize = 8;
113/// 通常の固定先読み(`at(1)`〜`at(3)`)のために常時満たしておく先読みトークン数。
114const LOOKAHEAD_WINDOW: usize = 6;
115
116pub struct Parser {
117    /// 逐次読み出し用の字句解析器(トークン列全体を事前にメモリへ展開しない)。
118    lexer: Lexer,
119    /// スライディングウィンドウ: 論理位置 `base_pos` 以降の `(Token, start_byte, newline_before)`。
120    /// 通常時は直前 `HISTORY_KEEP` 個+先読み `LOOKAHEAD_WINDOW` 個(十数要素・数百バイト)のみを保持する。
121    buf: alloc::collections::VecDeque<(Token, u32, bool)>,
122    /// `buf[0]` に対応する論理トークン位置。
123    base_pos: usize,
124    /// 現在の論理トークン位置 (`pos >= base_pos`)。
125    pos: usize,
126    /// 投機的先読み(`for ([a,b] of ...)` / `for (o.p of ...)`)の巻き戻し起点。
127    pin_pos: Option<usize>,
128    lazy: bool,
129    /// 回復して解析を続けた構文エラーの記録(上限 `MAX_RECORDED_ERRORS` 件)。
130    errors: Vec<ParseError>,
131    /// 上限で切り捨てた分も含めた実際の検出件数。
132    error_count: usize,
133    /// いま解析している箇所が strict モードか(関数本体の `FnBody::strict` に記録する)。
134    pub(crate) strict: bool,
135    /// 直前に `parse_fn_body` が読んだ本体の閉じ `}` の直後のバイト位置(`record_fn_source` が使う)。
136    last_body_end: Option<u32>,
137    /// `const` への代入を見つけるための字句の枠(ブロック・関数ごと)。[`LexFrame`]。
138    lex_frames: Vec<LexFrame>,
139    /// 静的早期エラー判定用の構文文脈・スコープ状態。
140    in_function: u16,
141    eval_in_function: bool,
142    in_generator: bool,
143    in_async: bool,
144    in_param: bool,
145    allow_super_call: bool,
146    allow_super_prop: bool,
147    in_field_init: bool,
148    in_static_block: bool,
149    /// これから読むのがアロー関数の本体か(アローは `arguments` を持たないので、フィールド初期化子・静的ブロックの制約を引き継ぐ)。
150    arrow_body: bool,
151    in_class_body: bool,
152    loop_depth: u16,
153    switch_depth: u16,
154    labels: Vec<(Rc<str>, bool)>,
155    scopes: Vec<ScopeFrame>,
156    private_scopes: Vec<Vec<(Rc<str>, u8)>>,
157    pending_cover_inits: usize,
158    pending_dup_protos: usize,
159    pending_spread_trailing_commas: usize,
160    pending_paren_destr_targets: usize,
161    last_expr_was_paren: bool,
162    /// 直前の `parse_binary` が最上位で最後に組んだ演算子の種類(0=なし・論理以外, 1=`??`, 2=`||`/`&&`)。
163    /// 括弧なしで `??` と `||`/`&&` を混ぜる式(`a ?? b || c`)を構文エラーにするために使う。
164    bin_top_logical: u8,
165    has_concrete_super_scope: bool,
166    top_level_script_errors: Vec<ParseError>,
167    in_lazy_expanded_body: bool,
168}
169
170#[derive(Clone, Copy, PartialEq, Eq)]
171enum ScopeKind {
172    Script,
173    Function,
174    Block,
175    Switch,
176    ForHead,
177    Catch,
178}
179
180#[derive(Clone, Copy, PartialEq, Eq)]
181enum BindingKind {
182    Var,
183    Let,
184    Function { is_plain_sync: bool },
185    Param,
186    CatchParam,
187}
188
189struct ScopeFrame {
190    kind: ScopeKind,
191    bindings: Vec<(Rc<str>, BindingKind)>,
192    catch_simple_param: bool,
193    /// このスコープの `const` 宣言の名前(`bindings` にも `Let` として入っている)。
194    consts: Vec<Rc<str>>,
195}
196
197#[derive(Clone)]
198struct ParserCtx {
199    strict: bool,
200    in_function: u16,
201    eval_in_function: bool,
202    in_generator: bool,
203    in_async: bool,
204    in_param: bool,
205    allow_super_call: bool,
206    allow_super_prop: bool,
207    in_field_init: bool,
208    in_static_block: bool,
209    in_class_body: bool,
210    private_scopes: Vec<Vec<(Rc<str>, u8)>>,
211    has_concrete_super_scope: bool,
212    in_lazy_expanded_body: bool,
213}
214
215const PRIV_FIELD_OR_METHOD: u8 = 1 << 0;
216const PRIV_GETTER: u8 = 1 << 1;
217const PRIV_SETTER: u8 = 1 << 2;
218const PRIV_STATIC: u8 = 1 << 3;
219
220/// 字句の枠 1 つ(ブロック・`for` の頭・`catch`・関数の境界)。
221///
222/// 【2026-11-16】`const c = 1; c = 2;` が例外にならず書き換わっていた。同じ関数の中で、先に宣言した
223/// `const` へ文として代入する(`c = …;`・`c += …;`・`c++;`)箇所を解析のときに見つけ、
224/// `TypeError`(Assignment to constant variable.)を投げる式に置き換える。実行時の変数の表には
225/// 手を入れない(代入のたびの検査を増やさない)。関数の境界(`barrier`)より外の `const` と、
226/// 宣言より前に書かれた代入は見ない(見逃すだけで、誤って投げることはない)。
227/// `names` には `const` と、それを隠す同名の宣言(`let`・`var`・引数など)だけを入れる。
228struct LexFrame {
229    names: Vec<(Rc<str>, bool)>,
230    barrier: bool,
231}
232
233/// カバー文法(Cover Grammar)のカッコ内要素。
234enum CoverItem {
235    Rest(Pattern),
236    Expr(Expression),
237}
238
239impl Parser {
240    pub fn new(lexer: Lexer) -> Self {
241        Self::build(lexer, false)
242    }
243
244    /// 関数本体を遅延解析するパーサ(大きな本体は共有ソースと範囲だけ持ち、初回実行時に解析する)。
245    /// 本体の中の構文エラーは、その関数を初めて実行するときに報告される。
246    pub fn new_lazy(lexer: Lexer) -> Self {
247        Self::build(lexer, true)
248    }
249
250    /// 識別子・プロパティ名をインターンして共有 `Rc<str>` を返す。
251    #[inline]
252    pub fn intern(&mut self, s: &str) -> Rc<str> {
253        self.lexer.intern_ident(s)
254    }
255
256    fn build(lexer: Lexer, lazy: bool) -> Self {
257        let mut p = Self {
258            lexer,
259            buf: alloc::collections::VecDeque::with_capacity(32),
260            base_pos: 0,
261            pos: 0,
262            pin_pos: None,
263            lazy,
264            errors: Vec::new(),
265            error_count: 0,
266            strict: false,
267            last_body_end: None,
268            lex_frames: alloc::vec![LexFrame { names: Vec::new(), barrier: true }],
269            in_function: 0,
270            eval_in_function: false,
271            in_generator: false,
272            in_async: false,
273            in_param: false,
274            allow_super_call: false,
275            allow_super_prop: false,
276            in_field_init: false,
277            in_static_block: false,
278            arrow_body: false,
279            in_class_body: false,
280            loop_depth: 0,
281            switch_depth: 0,
282            labels: Vec::new(),
283            scopes: alloc::vec![ScopeFrame {
284                kind: ScopeKind::Script,
285                bindings: Vec::new(),
286                catch_simple_param: false,
287                consts: Vec::new(),
288            }],
289            private_scopes: Vec::new(),
290            pending_cover_inits: 0,
291            pending_dup_protos: 0,
292            pending_spread_trailing_commas: 0,
293            pending_paren_destr_targets: 0,
294            last_expr_was_paren: false,
295            bin_top_logical: 0,
296            has_concrete_super_scope: false,
297            top_level_script_errors: Vec::new(),
298            in_lazy_expanded_body: false,
299        };
300        p.ensure_pos(LOOKAHEAD_WINDOW);
301        p
302    }
303
304    fn ctx_snapshot(&self) -> ParserCtx {
305        ParserCtx {
306            strict: self.strict,
307            in_function: self.in_function,
308            eval_in_function: self.eval_in_function,
309            in_generator: self.in_generator,
310            in_async: self.in_async,
311            in_param: self.in_param,
312            allow_super_call: self.allow_super_call,
313            allow_super_prop: self.allow_super_prop,
314            in_field_init: self.in_field_init,
315            in_static_block: self.in_static_block,
316            in_class_body: self.in_class_body,
317            private_scopes: self.private_scopes.clone(),
318            has_concrete_super_scope: self.has_concrete_super_scope,
319            in_lazy_expanded_body: self.in_lazy_expanded_body,
320        }
321    }
322
323    fn new_sub(lexer: Lexer, ctx: ParserCtx) -> Self {
324        let mut p = Self::build(lexer, false);
325        p.strict = ctx.strict;
326        p.in_function = ctx.in_function;
327        p.eval_in_function = ctx.eval_in_function;
328        p.in_generator = ctx.in_generator;
329        p.in_async = ctx.in_async;
330        p.in_param = ctx.in_param;
331        p.allow_super_call = ctx.allow_super_call;
332        p.allow_super_prop = ctx.allow_super_prop;
333        p.in_field_init = ctx.in_field_init;
334        p.in_static_block = ctx.in_static_block;
335        p.in_class_body = ctx.in_class_body;
336        p.private_scopes = ctx.private_scopes;
337        p.has_concrete_super_scope = ctx.has_concrete_super_scope;
338        p.in_lazy_expanded_body = ctx.in_lazy_expanded_body;
339        p
340    }
341
342    pub(crate) fn current_eval_ctx(&self) -> crate::os_lib::ecma::ast::EvalSyntaxCtx {
343        let mut private_names = Vec::new();
344        for env in &self.private_scopes {
345            for (n, _) in env {
346                if !private_names.iter().any(|x| x == n) {
347                    private_names.push(n.clone());
348                }
349            }
350        }
351        crate::os_lib::ecma::ast::EvalSyntaxCtx {
352            in_function: self.in_function > 0 || self.eval_in_function,
353            allow_super_call: self.allow_super_call,
354            allow_super_prop: self.allow_super_prop,
355            in_field_init: self.in_field_init,
356            in_static_block: self.in_static_block,
357            private_names,
358        }
359    }
360
361    pub(crate) fn apply_eval_ctx(&mut self, ctx: &crate::os_lib::ecma::ast::EvalSyntaxCtx) {
362        self.in_function = 0;
363        self.eval_in_function = ctx.in_function;
364        self.allow_super_call = ctx.allow_super_call;
365        self.allow_super_prop = ctx.allow_super_prop;
366        self.in_field_init = ctx.in_field_init;
367        self.in_static_block = ctx.in_static_block;
368        self.private_scopes.clear();
369        if !ctx.private_names.is_empty() {
370            self.private_scopes.push(
371                ctx.private_names
372                    .iter()
373                    .map(|n| (n.clone(), 0u8))
374                    .collect(),
375            );
376        }
377    }
378
379    /// 字句解析器で発生したエラーを(投機的先読み中でなければ)パーサのエラー記録へ引き取る。
380    #[inline]
381    fn flush_lexer_errors(&mut self) {
382        if self.pin_pos.is_some() {
383            return;
384        }
385        let cnt = self.lexer.take_error_count();
386        if cnt == 0 {
387            return;
388        }
389        self.error_count += cnt;
390        for e in self.lexer.take_errors() {
391            if self.errors.len() < MAX_RECORDED_ERRORS {
392                self.errors.push(ParseError {
393                    message: e.message,
394                    token_index: 0,
395                });
396            }
397        }
398    }
399
400    /// 論理トークン位置 `target_pos` まで `buf` に読み込む。
401    #[inline]
402    fn ensure_pos(&mut self, target_pos: usize) {
403        while self.base_pos + self.buf.len() <= target_pos {
404            if matches!(self.buf.back(), Some((Token::Eof, _, _))) {
405                break;
406            }
407            let t = self.lexer.next_token();
408            let st = self.lexer.token_start() as u32;
409            let nl = self.lexer.token_newline_before();
410            self.buf.push_back((t, st, nl));
411        }
412        self.flush_lexer_errors();
413    }
414
415    /// 論理トークン位置 `abs` のトークンを参照する。
416    #[inline]
417    fn tok_at_abs(&self, abs: usize) -> Option<&Token> {
418        let idx = abs.checked_sub(self.base_pos)?;
419        self.buf.get(idx).map(|(t, _, _)| t)
420    }
421
422    /// 論理トークン位置 `abs` の開始バイト位置を返す。
423    #[inline]
424    fn token_start_at(&self, abs: usize) -> u32 {
425        abs.checked_sub(self.base_pos)
426            .and_then(|idx| self.buf.get(idx))
427            .map_or(0, |(_, st, _)| *st)
428    }
429
430    /// 論理トークン位置 `abs` の開始バイト位置(窓から外れていれば `None`)。
431    #[inline]
432    fn token_start_opt(&self, abs: usize) -> Option<u32> {
433        abs.checked_sub(self.base_pos).and_then(|idx| self.buf.get(idx)).map(|(_, st, _)| *st)
434    }
435
436    /// 論理トークン位置 `abs` の直前に行終端文字があったか。
437    #[inline]
438    fn nl_before_at_abs(&self, abs: usize) -> bool {
439        abs.checked_sub(self.base_pos)
440            .and_then(|idx| self.buf.get(idx))
441            .is_some_and(|(_, _, nl)| *nl)
442    }
443
444    /// 現在トークンの直前に行終端文字があったか(ASI 判定用)。
445    #[inline]
446    fn nl_before_cur(&self) -> bool {
447        self.nl_before_at_abs(self.pos)
448    }
449
450    /// 現在位置から `off` 個先のトークンの直前に行終端文字があったか。
451    #[inline]
452    fn nl_before_at(&self, off: usize) -> bool {
453        self.nl_before_at_abs(self.pos + off)
454    }
455
456    /// 直前に `parse_fn_body` が読んだ本体の閉じ `}` の直後のバイト位置を使い、`start` からの定義全体を
457    /// 本体に記録する(`Function.prototype.toString` 用)。
458    fn record_fn_source(&mut self, body: &Rc<FnBody>, start: Option<u32>) {
459        if let (Some(s), Some(e)) = (start, self.last_body_end.take()) {
460            if s < e {
461                body.set_source_text(self.lexer.src_rc().clone(), s, e);
462            }
463        }
464    }
465
466    /// `function` の定義の先頭のバイト位置(`async function` なら直前の `async` から)。
467    fn fn_source_start(&self, is_async: bool) -> Option<u32> {
468        if is_async {
469            match self.pos.checked_sub(1).and_then(|p| self.tok_at_abs(p)) {
470                Some(Token::Keyword(k)) if *k == "async" => return self.token_start_opt(self.pos - 1),
471                Some(Token::Ident(n)) if &**n == "async" => return self.token_start_opt(self.pos - 1),
472                _ => {}
473            }
474        }
475        self.token_start_opt(self.pos)
476    }
477
478    /// 現在位置を `new_pos` に進め(または戻し)、先読み窓の補充と古いトークンの破棄を行う。
479    #[inline]
480    fn set_pos(&mut self, new_pos: usize) {
481        self.pos = new_pos;
482        self.ensure_pos(self.pos + LOOKAHEAD_WINDOW);
483        let keep_from = self.pin_pos.unwrap_or(self.pos).saturating_sub(HISTORY_KEEP);
484        while self.base_pos < keep_from && self.buf.len() > 1 {
485            self.buf.pop_front();
486            self.base_pos += 1;
487        }
488    }
489
490    #[inline]
491    fn step(&mut self) {
492        self.set_pos(self.pos + 1);
493    }
494
495    /// `at` から始まる文の並びの先頭(指令プロローグ)に `"use strict"` があるか。
496    fn has_use_strict_directive(&mut self, mut at: usize) -> bool {
497        loop {
498            self.ensure_pos(at + 1);
499            let st = self.token_start_at(at) as usize;
500            let (is_str, is_use_strict) = match self.tok_at_abs(at) {
501                Some(Token::Str(s)) => {
502                    let exact = &**s == "use strict" && !self.lexer.string_has_escape_at(st);
503                    (true, exact)
504                }
505                _ => (false, false),
506            };
507            if !is_str {
508                return false;
509            }
510            let next_tok = self.tok_at_abs(at + 1);
511            let next_nl = self.nl_before_at_abs(at + 1);
512            let valid_stmt_end = matches!(next_tok, Some(Token::Sym(";")) | Some(Token::Sym("}")) | Some(Token::Eof))
513                || next_nl;
514            if is_use_strict && valid_stmt_end {
515                return true;
516            }
517            if !valid_stmt_end {
518                return false;
519            }
520            match next_tok {
521                Some(Token::Sym(";")) => at += 2,
522                Some(Token::Str(_)) => at += 1,
523                _ => return false,
524            }
525        }
526    }
527
528    /// 関数本体(`{ ... }`)。遅延モードで本体が大きければ、対応する `}` までトークンを貯めずに
529    /// 字句解析器を直接進めて共有ソースと範囲 (`start..end`) だけ持つ。
530    fn lex_push(&mut self, barrier: bool) {
531        self.lex_frames.push(LexFrame { names: Vec::new(), barrier });
532    }
533
534    fn lex_pop(&mut self) {
535        if self.lex_frames.len() > 1 {
536            self.lex_frames.pop();
537        }
538    }
539
540    /// `name` が同じ関数の中で見える `const` か。
541    fn lex_is_const(&self, name: &str) -> bool {
542        for f in self.lex_frames.iter().rev() {
543            if let Some((_, c)) = f.names.iter().rev().find(|(n, _)| &**n == name) {
544                return *c;
545            }
546            if f.barrier {
547                return false;
548            }
549        }
550        false
551    }
552
553    /// 宣言を今の枠へ記録する(`const` 以外は、同名の `const` を隠すときだけ)。
554    fn lex_declare(&mut self, name: &Rc<str>, is_const: bool) {
555        if !is_const && !self.lex_is_const(name) {
556            return;
557        }
558        if let Some(f) = self.lex_frames.last_mut() {
559            f.names.push((name.clone(), is_const));
560        }
561    }
562
563    fn lex_declare_pattern(&mut self, pat: &Pattern, is_const: bool) {
564        match pat {
565            Pattern::Identifier(n) => self.lex_declare(n, is_const),
566            Pattern::Object(props) => {
567                for p in props {
568                    self.lex_declare_pattern(&p.value, is_const);
569                }
570            }
571            Pattern::Array(elems) => {
572                for e in elems {
573                    if let Some(p) = &e.pattern {
574                        self.lex_declare_pattern(p, is_const);
575                    }
576                }
577            }
578            Pattern::Expr(_) => {}
579        }
580    }
581
582    /// 文が宣言する名前を今の枠へ記録する。
583    fn lex_note_stmt(&mut self, s: &Statement) {
584        match s {
585            Statement::VarDeclaration { kind, decls } => {
586                let is_const = matches!(kind, VarKind::Const);
587                for (p, _) in decls {
588                    self.lex_declare_pattern(p, is_const);
589                }
590            }
591            Statement::FunctionDeclaration { name, .. } => self.lex_declare(name, false),
592            _ => {}
593        }
594    }
595
596    /// `Assignment to constant variable.` の TypeError を投げる呼び出し式。
597    fn const_thrower(&mut self) -> Expression {
598        let throw = Statement::Throw(Expression::New {
599            callee: Box::new(Expression::Identifier(self.intern("TypeError"))),
600            arguments: alloc::vec![Expression::Str(String::from("Assignment to constant variable."))],
601        });
602        Expression::Call {
603            callee: Box::new(Expression::Function {
604                name: None,
605                params: Rc::new(Vec::new()),
606                body: FnBody::parsed_with(alloc::vec![throw], self.strict),
607                is_arrow: true,
608                is_async: false,
609                is_generator: false,
610            }),
611            arguments: Vec::new(),
612            optional: false,
613        }
614    }
615
616    /// 分割代入(や `for (x of …)` の頭)の代入先に含まれる `const` の識別子を、評価すると TypeError を投げる
617    /// メンバー参照(`(() => { throw … })().x`)へ置き換える。代入の時点(参照の評価)で投げる。
618    fn lex_guard_const_target(&mut self, e: Expression) -> Expression {
619        match e {
620            Expression::Identifier(n) if self.lex_is_const(&n) || self.scope_is_const(&n) => Expression::Member {
621                object: Box::new(self.const_thrower()),
622                property: self.intern("x"),
623                optional: false,
624            },
625            Expression::Array(items) => {
626                Expression::Array(items.into_iter().map(|i| self.lex_guard_const_target(i)).collect())
627            }
628            Expression::Object(props) => Expression::Object(
629                props
630                    .into_iter()
631                    .map(|mut p| {
632                        if p.accessor.is_none() {
633                            p.value = self.lex_guard_const_target(p.value);
634                        }
635                        p
636                    })
637                    .collect(),
638            ),
639            Expression::Spread(inner) => Expression::Spread(Box::new(self.lex_guard_const_target(*inner))),
640            Expression::Assign { op, target, value } if op == "=" => Expression::Assign {
641                op,
642                target: Box::new(self.lex_guard_const_target(*target)),
643                value,
644            },
645            other => other,
646        }
647    }
648
649    /// `lex_guard_const_target` の `Pattern` 版(`for ([c] of …)` の頭など)。
650    fn lex_guard_const_pattern(&mut self, p: Pattern) -> Pattern {
651        match p {
652            Pattern::Identifier(n) if self.lex_is_const(&n) || self.scope_is_const(&n) => {
653                Pattern::Expr(Box::new(self.lex_guard_const_target(Expression::Identifier(n))))
654            }
655            Pattern::Object(props) => Pattern::Object(
656                props
657                    .into_iter()
658                    .map(|mut q| {
659                        let v = core::mem::replace(&mut q.value, Pattern::Expr(Box::new(Expression::Null)));
660                        q.value = self.lex_guard_const_pattern(v);
661                        q
662                    })
663                    .collect(),
664            ),
665            Pattern::Array(elems) => Pattern::Array(
666                elems
667                    .into_iter()
668                    .map(|mut e| {
669                        e.pattern = e.pattern.take().map(|q| self.lex_guard_const_pattern(q));
670                        e
671                    })
672                    .collect(),
673            ),
674            Pattern::Expr(e) => Pattern::Expr(Box::new(self.lex_guard_const_target(*e))),
675            other => other,
676        }
677    }
678
679    /// `const` への代入(文)を、右辺を評価してから TypeError を投げる式に置き換える。
680    fn lex_check_const_assign(&mut self, e: Expression) -> Expression {
681        let name = match &e {
682            Expression::Assign { target, .. } | Expression::Update { target, .. } => match &**target {
683                Expression::Identifier(n) => n.clone(),
684                Expression::Array(_) | Expression::Object(_) if matches!(&e, Expression::Assign { op, .. } if *op == "=") => {
685                    if let Expression::Assign { op, target, value } = e {
686                        let target = Box::new(self.lex_guard_const_target(*target));
687                        return Expression::Assign { op, target, value };
688                    }
689                    unreachable!()
690                }
691                _ => return e,
692            },
693            _ => return e,
694        };
695        if !self.lex_is_const(&name) {
696            return e;
697        }
698        let thrower = self.const_thrower();
699        match e {
700            Expression::Assign { value, .. } => Expression::Sequence(alloc::vec![*value, thrower]),
701            _ => thrower,
702        }
703    }
704
705    fn parse_fn_body_with(&mut self, has_non_simple_params: bool) -> Rc<FnBody> {
706        self.last_body_end = None;
707        if self.lazy && self.pin_pos.is_none() && self.is_sym("{") {
708            let open_pos = self.pos;
709            let open_start = self.token_start_at(open_pos) as usize;
710            let mut depth = 1usize;
711            let mut off = 1usize;
712            let mut closed_early = false;
713            let mut hit_eof = false;
714            while off <= LAZY_MIN_TOKENS {
715                self.ensure_pos(open_pos + off);
716                match self.at(off) {
717                    Token::Sym("{") => depth += 1,
718                    Token::Sym("}") => {
719                        depth -= 1;
720                        if depth == 0 {
721                            closed_early = true;
722                            break;
723                        }
724                    }
725                    Token::Eof => {
726                        hit_eof = true;
727                        break;
728                    }
729                    _ => {}
730                }
731                off += 1;
732            }
733            if !closed_early && !hit_eof {
734                let has_dir = self.has_use_strict_directive(open_pos + 1);
735                if has_dir && has_non_simple_params {
736                    self.record_error(String::from("Illegal 'use strict' directive in function with non-simple parameter list"));
737                }
738                let strict = self.strict || has_dir;
739                let mut close_start: Option<usize> = None;
740                let buf_end_off = (self.base_pos + self.buf.len()).saturating_sub(open_pos);
741                while off < buf_end_off {
742                    match self.at(off) {
743                        Token::Sym("{") => depth += 1,
744                        Token::Sym("}") => {
745                            depth -= 1;
746                            if depth == 0 {
747                                close_start = Some(self.token_start_at(open_pos + off) as usize);
748                                self.set_pos(open_pos + off + 1);
749                                break;
750                            }
751                        }
752                        Token::Eof => {
753                            hit_eof = true;
754                            break;
755                        }
756                        _ => {}
757                    }
758                    off += 1;
759                }
760                if close_start.is_none() && !hit_eof {
761                    // 読み飛ばす間は識別子のインターンと文字列の中身の組み立てを省く(2026-11-04。字句解析が重い)。
762                    self.lexer.skim = true;
763                    let mut skim_steps = 0usize;
764                    while depth > 0 {
765                        skim_steps = skim_steps.wrapping_add(1);
766                        if (skim_steps & 0xFFF) == 0 {
767                            crate::os_lib::platform::kill_checkpoint();
768                        }
769                        let t = self.lexer.next_token();
770                        let st = self.lexer.token_start();
771                        match &t {
772                            Token::Sym("{") => depth += 1,
773                            Token::Sym("}") => {
774                                depth -= 1;
775                                if depth == 0 {
776                                    close_start = Some(st);
777                                    break;
778                                }
779                            }
780                            Token::Eof => {
781                                hit_eof = true;
782                                break;
783                            }
784                            _ => {}
785                        }
786                    }
787                    self.lexer.skim = false;
788                    // 読み飛ばした本体のトークン列を破棄し、閉じ `}` の直後から再開する。
789                    self.buf.clear();
790                    self.pos = open_pos + 1;
791                    self.base_pos = self.pos;
792                    if hit_eof {
793                        self.buf.push_back((Token::Eof, self.lexer.token_start() as u32, false));
794                    }
795                    self.ensure_pos(self.pos + LOOKAHEAD_WINDOW);
796                }
797                if let Some(b) = close_start {
798                    if strict && self.lexer.legacy_octal_between(open_start, b) {
799                        self.record_error(String::from("Octal literals and octal escape sequences are not allowed in strict mode"));
800                    }
801                    let a = open_start + 1;
802                    let src = self.lexer.src_rc().clone();
803                    if a <= b && b <= src.len() {
804                        self.last_body_end = Some(b as u32 + 1);
805                        let fb = FnBody::lazy_range(src, a as u32, b as u32, strict, Some(self.lexer.atoms()));
806                        let mut ctx = self.current_eval_ctx();
807                        ctx.in_function = true;
808                        if !self.arrow_body {
809                            ctx.in_field_init = false;
810                        }
811                        ctx.in_static_block = false;
812                        fb.set_eval_ctx(ctx);
813                        return fb;
814                    }
815                }
816                if hit_eof {
817                    self.record_error(String::from("expected '}' but found end of input"));
818                    return FnBody::parsed_with(Vec::new(), strict);
819                }
820            }
821        }
822        let body_start = self.token_start_at(self.pos) as usize;
823        let was_strict = self.strict;
824        let has_dir = self.is_sym("{") && self.has_use_strict_directive(self.pos + 1);
825        if has_dir && has_non_simple_params {
826            self.record_error(String::from("Illegal 'use strict' directive in function with non-simple parameter list"));
827        }
828        let strict = self.strict || has_dir;
829        let outer = core::mem::replace(&mut self.strict, strict);
830        let saved_loop = core::mem::replace(&mut self.loop_depth, 0);
831        let saved_switch = core::mem::replace(&mut self.switch_depth, 0);
832        let saved_labels = core::mem::take(&mut self.labels);
833        let keep_ctx = core::mem::replace(&mut self.arrow_body, false);
834        let saved_field = if keep_ctx { self.in_field_init } else { core::mem::replace(&mut self.in_field_init, false) };
835        let saved_static_blk = core::mem::replace(&mut self.in_static_block, false);
836        let saved_param = core::mem::replace(&mut self.in_param, false);
837        self.in_function += 1;
838        self.lex_push(true);
839        let body = self.parse_brace_body_no_scope();
840        let eval_ctx = self.current_eval_ctx();
841        self.lex_pop();
842        self.in_function -= 1;
843        self.in_param = saved_param;
844        self.in_static_block = saved_static_blk;
845        self.in_field_init = saved_field;
846        self.labels = saved_labels;
847        self.switch_depth = saved_switch;
848        self.loop_depth = saved_loop;
849        self.strict = outer;
850        // 閉じ `}`(直前のトークン)の直後。
851        self.last_body_end = self.pos.checked_sub(1).and_then(|p| self.token_start_opt(p)).map(|st| st + 1);
852        if strict && !was_strict {
853            if let Some(end_b) = self.last_body_end {
854                if self.lexer.legacy_octal_between(body_start, end_b as usize) {
855                    self.record_error(String::from("Octal literals and octal escape sequences are are not allowed in strict mode"));
856                }
857            }
858        }
859        let fb = FnBody::parsed_with(body, strict);
860        fb.set_eval_ctx(eval_ctx);
861        fb
862    }
863
864    fn parse_static_block_body(&mut self) -> Rc<FnBody> {
865        let saved_loop = core::mem::replace(&mut self.loop_depth, 0);
866        let saved_switch = core::mem::replace(&mut self.switch_depth, 0);
867        let saved_labels = core::mem::take(&mut self.labels);
868        let saved_field = core::mem::replace(&mut self.in_field_init, false);
869        let saved_static_blk = core::mem::replace(&mut self.in_static_block, true);
870        let saved_param = core::mem::replace(&mut self.in_param, false);
871        self.scope_push(ScopeKind::Function);
872        self.lex_push(true);
873        let body = self.parse_brace_body_no_scope();
874        let eval_ctx = self.current_eval_ctx();
875        self.lex_pop();
876        self.scope_pop();
877        self.in_param = saved_param;
878        self.in_static_block = saved_static_blk;
879        self.in_field_init = saved_field;
880        self.labels = saved_labels;
881        self.switch_depth = saved_switch;
882        self.loop_depth = saved_loop;
883        let fb = FnBody::parsed_with(body, true);
884        fb.set_eval_ctx(eval_ctx);
885        fb
886    }
887
888    fn parse_fn_body(&mut self) -> Rc<FnBody> {
889        self.scope_push(ScopeKind::Function);
890        let r = self.parse_fn_body_with(false);
891        self.scope_pop();
892        r
893    }
894
895    fn parse_fn_body_with_params(&mut self, params: &[Param]) -> Rc<FnBody> {
896        let non_simple = has_non_simple_params(params);
897        self.scope_push(ScopeKind::Function);
898        for p in params {
899            self.declare_pattern_bindings(&p.pattern, BindingKind::Param);
900        }
901        let r = self.parse_fn_body_with(non_simple);
902        self.scope_pop();
903        r
904    }
905
906    /// 関数や eval を除いたスクリプト頂点のみでエラーになる構文(direct eval との互換用)。
907    fn record_top_level_only_error(&mut self, message: String) {
908        if self.pin_pos.is_some() {
909            // 投機的先読み中は通常エラーと同様に残さないか、保存対象に含める。
910        }
911        let msg = alloc::format!("{} 付近: {}", message, self.context_around(self.pos));
912        self.top_level_script_errors.push(ParseError {
913            message: msg,
914            token_index: self.pos,
915        });
916    }
917
918    fn scope_push(&mut self, kind: ScopeKind) {
919        self.scopes.push(ScopeFrame {
920            kind,
921            bindings: Vec::new(),
922            catch_simple_param: false,
923            consts: Vec::new(),
924        });
925    }
926
927    /// `const` 宣言の名前を今のスコープへ記録する(関数の境界を越えた `const` への代入検出用)。
928    fn note_const_pattern(&mut self, pat: &Pattern) {
929        let mut names: Vec<Rc<str>> = Vec::new();
930        {
931            let mut refs: Vec<&Rc<str>> = Vec::new();
932            Self::collect_pattern_names(pat, &mut refs);
933            names.extend(refs.into_iter().cloned());
934        }
935        if let Some(f) = self.scopes.last_mut() {
936            f.consts.extend(names);
937        }
938    }
939
940    /// `name` を最も内側で宣言しているスコープが `const` か(関数の境界を越えて探す)。
941    /// 宣言より前に書かれた参照や、後ろで巻き上げられる `var`・関数は見えない(見逃すだけ)。
942    fn scope_is_const(&self, name: &str) -> bool {
943        for f in self.scopes.iter().rev() {
944            if f.bindings.iter().any(|(n, _)| &**n == name) {
945                return f.consts.iter().any(|n| &**n == name);
946            }
947        }
948        false
949    }
950
951    fn scope_pop(&mut self) {
952        if self.scopes.len() > 1 {
953            self.scopes.pop();
954        }
955    }
956
957    fn is_at_script_top_scope(&self) -> bool {
958        !self.in_static_block
959            && self.scopes.len() == 1
960            && matches!(self.scopes.first(), Some(s) if s.kind == ScopeKind::Script)
961    }
962
963    fn declare_binding(&mut self, name: &Rc<str>, kind: BindingKind) {
964        if name.is_empty() {
965            return;
966        }
967        match kind {
968            BindingKind::Let => {
969                let conflict = self.scopes.last().is_some_and(|f| {
970                    f.bindings.iter().any(|(n, _)| n == name)
971                });
972                if conflict {
973                    self.record_error(alloc::format!("Identifier '{}' has already been declared", name));
974                } else if let Some(f) = self.scopes.last_mut() {
975                    f.bindings.push((name.clone(), BindingKind::Let));
976                }
977            }
978            BindingKind::Param | BindingKind::CatchParam => {
979                if let Some(f) = self.scopes.last_mut() {
980                    f.bindings.push((name.clone(), kind));
981                }
982            }
983            BindingKind::Var => {
984                let mut target_idx = 0usize;
985                // 間のブロック類にも `var` の名前を残す(後に続く同名の `let`・`class`・`function` を
986                // VarDeclaredNames との重複として検出するため。`{ var f; let f }`)。
987                let mut pass_through: Vec<usize> = Vec::new();
988                for (i, f) in self.scopes.iter().enumerate().rev() {
989                    match f.kind {
990                        ScopeKind::Script | ScopeKind::Function => {
991                            if f.bindings.iter().any(|(n, k)| n == name && matches!(k, BindingKind::Let)) {
992                                self.record_error(alloc::format!("Identifier '{}' has already been declared", name));
993                                return;
994                            }
995                            target_idx = i;
996                            break;
997                        }
998                        ScopeKind::Catch => {
999                            if f.bindings.iter().any(|(n, k)| {
1000                                n == name
1001                                    && (matches!(k, BindingKind::Let | BindingKind::Function { .. })
1002                                        || (matches!(k, BindingKind::CatchParam) && !f.catch_simple_param))
1003                            }) {
1004                                self.record_error(alloc::format!("Identifier '{}' has already been declared", name));
1005                                return;
1006                            }
1007                            pass_through.push(i);
1008                        }
1009                        ScopeKind::Block | ScopeKind::Switch | ScopeKind::ForHead => {
1010                            if f.bindings.iter().any(|(n, k)| {
1011                                n == name && matches!(k, BindingKind::Let | BindingKind::Function { .. })
1012                            }) {
1013                                self.record_error(alloc::format!("Identifier '{}' has already been declared", name));
1014                                return;
1015                            }
1016                            pass_through.push(i);
1017                        }
1018                    }
1019                }
1020                for i in pass_through {
1021                    if let Some(f) = self.scopes.get_mut(i) {
1022                        if !f.bindings.iter().any(|(n, k)| n == name && matches!(k, BindingKind::Var)) {
1023                            f.bindings.push((name.clone(), BindingKind::Var));
1024                        }
1025                    }
1026                }
1027                if let Some(f) = self.scopes.get_mut(target_idx) {
1028                    if !f.bindings.iter().any(|(n, k)| n == name && matches!(k, BindingKind::Var)) {
1029                        f.bindings.push((name.clone(), BindingKind::Var));
1030                    }
1031                }
1032            }
1033            BindingKind::Function { is_plain_sync } => {
1034                let strict = self.strict;
1035                let conflict = self.scopes.last().is_some_and(|f| match f.kind {
1036                    ScopeKind::Script | ScopeKind::Function => f.bindings.iter().any(|(n, k)| {
1037                        n == name && matches!(k, BindingKind::Let)
1038                    }),
1039                    ScopeKind::Block | ScopeKind::Switch | ScopeKind::ForHead | ScopeKind::Catch => {
1040                        f.bindings.iter().any(|(n, k)| {
1041                            if n != name {
1042                                return false;
1043                            }
1044                            match k {
1045                                BindingKind::Function { is_plain_sync: prev_plain } => {
1046                                    strict || !is_plain_sync || !prev_plain
1047                                }
1048                                _ => true,
1049                            }
1050                        })
1051                    }
1052                });
1053                if conflict {
1054                    self.record_error(alloc::format!("Identifier '{}' has already been declared", name));
1055                } else if let Some(f) = self.scopes.last_mut() {
1056                    f.bindings.push((name.clone(), kind));
1057                }
1058            }
1059        }
1060    }
1061
1062    fn declare_pattern_bindings(&mut self, pat: &Pattern, kind: BindingKind) {
1063        match pat {
1064            Pattern::Identifier(n) => self.declare_binding(n, kind),
1065            Pattern::Object(props) => {
1066                for p in props {
1067                    self.declare_pattern_bindings(&p.value, kind);
1068                }
1069            }
1070            Pattern::Array(elems) => {
1071                for e in elems {
1072                    if let Some(p) = &e.pattern {
1073                        self.declare_pattern_bindings(p, kind);
1074                    }
1075                }
1076            }
1077            Pattern::Expr(_) => {}
1078        }
1079    }
1080
1081    fn collect_pattern_names<'a>(pat: &'a Pattern, out: &mut Vec<&'a Rc<str>>) {
1082        match pat {
1083            Pattern::Identifier(n) => {
1084                if !n.is_empty() {
1085                    out.push(n);
1086                }
1087            }
1088            Pattern::Object(props) => {
1089                for p in props {
1090                    Self::collect_pattern_names(&p.value, out);
1091                }
1092            }
1093            Pattern::Array(elems) => {
1094                for e in elems {
1095                    if let Some(p) = &e.pattern {
1096                        Self::collect_pattern_names(p, out);
1097                    }
1098                }
1099            }
1100            Pattern::Expr(_) => {}
1101        }
1102    }
1103
1104    fn check_lexical_disallows_let(&mut self, pat: &Pattern) {
1105        let mut names = Vec::new();
1106        Self::collect_pattern_names(pat, &mut names);
1107        if names.iter().any(|n| &***n == "let") {
1108            self.record_error(String::from("'let' is disallowed as a lexically bound name"));
1109        }
1110    }
1111
1112    fn check_params(&mut self, params: &[Param], require_unique: bool) {
1113        let mut names = Vec::new();
1114        for p in params {
1115            Self::collect_pattern_names(&p.pattern, &mut names);
1116        }
1117        if self.strict {
1118            for n in &names {
1119                if &***n == "eval" || &***n == "arguments" {
1120                    self.record_error(String::from("Unexpected eval or arguments in strict mode"));
1121                }
1122            }
1123        }
1124        if require_unique {
1125            for i in 0..names.len() {
1126                for j in (i + 1)..names.len() {
1127                    if names[i] == names[j] {
1128                        self.record_error(String::from("Duplicate parameter name not allowed in this context"));
1129                        return;
1130                    }
1131                }
1132            }
1133        }
1134    }
1135
1136    /// 本体の `"use strict"` で初めて strict になった関数の名前・引数を、strict の規則で見直す
1137    /// (`function eval() { "use strict" }`・`function f(a, a) { "use strict" }`)。
1138    fn check_retro_strict(&mut self, name: Option<&str>, params: &[Param], body: &Rc<FnBody>, was_strict: bool) {
1139        if was_strict || !body.strict {
1140            return;
1141        }
1142        if let Some(n) = name {
1143            if n == "eval" || n == "arguments" {
1144                self.record_error(String::from("Unexpected eval or arguments in strict mode"));
1145            } else if is_strict_reserved(n) {
1146                self.record_error(alloc::format!("Unexpected strict mode reserved word '{}'", n));
1147            }
1148        }
1149        let mut names = Vec::new();
1150        for p in params {
1151            Self::collect_pattern_names(&p.pattern, &mut names);
1152        }
1153        for (i, n) in names.iter().enumerate() {
1154            if &***n == "eval" || &***n == "arguments" {
1155                self.record_error(String::from("Unexpected eval or arguments in strict mode"));
1156                return;
1157            }
1158            if is_strict_reserved(n) {
1159                self.record_error(alloc::format!("Unexpected strict mode reserved word '{}'", n));
1160                return;
1161            }
1162            if names[i + 1..].iter().any(|m| m == n) {
1163                self.record_error(String::from("Duplicate parameter name not allowed in this context"));
1164                return;
1165            }
1166        }
1167    }
1168
1169    fn check_ident_allowed(&mut self, name: &str, is_binding: bool) {
1170        if name.starts_with('#') {
1171            self.record_error(alloc::format!("Private field '{}' cannot be used here", name));
1172            return;
1173        }
1174        if is_always_reserved(name) {
1175            self.record_error(alloc::format!("Unexpected reserved word '{}'", name));
1176            return;
1177        }
1178        if self.strict && is_strict_reserved(name) {
1179            self.record_error(alloc::format!("Unexpected strict mode reserved word '{}'", name));
1180            return;
1181        }
1182        if name == "await" && (self.in_async || self.in_static_block) {
1183            self.record_error(String::from("'await' is reserved in async function or class static block"));
1184            return;
1185        }
1186        if name == "yield" && self.in_generator && !self.in_lazy_expanded_body {
1187            self.record_error(String::from("'yield' is reserved in generator"));
1188            return;
1189        }
1190        if is_binding && self.strict && (name == "eval" || name == "arguments") {
1191            self.record_error(String::from("Unexpected eval or arguments in strict mode"));
1192            return;
1193        }
1194        if !is_binding && (self.in_field_init || self.in_static_block) && name == "arguments" {
1195            self.record_error(String::from("'arguments' is not allowed in class field initializer or static block"));
1196        }
1197    }
1198
1199    fn consume_binding_ident(&mut self, ctx_desc: &str, advance_on_err: bool) -> Rc<str> {
1200        match self.cur().clone() {
1201            Token::Ident(n) => {
1202                self.bump();
1203                self.check_ident_allowed(&n, true);
1204                self.intern(&n)
1205            }
1206            Token::Keyword(k) if matches!(k, "async" | "of" | "undefined" | "let" | "await" | "yield") => {
1207                self.bump();
1208                self.check_ident_allowed(k, true);
1209                self.intern(k)
1210            }
1211            other => {
1212                self.record_error(alloc::format!("expected identifier in {}, found {}", ctx_desc, describe_token(&other)));
1213                if advance_on_err && !self.is_eof() {
1214                    self.bump();
1215                }
1216                self.intern("")
1217            }
1218        }
1219    }
1220
1221    fn try_consume_opt_fn_ident(&mut self) -> Option<Rc<str>> {
1222        match self.cur().clone() {
1223            Token::Ident(n) => {
1224                self.bump();
1225                self.check_ident_allowed(&n, true);
1226                Some(n)
1227            }
1228            Token::Keyword(k) if matches!(k, "async" | "of" | "undefined" | "let" | "await" | "yield") => {
1229                self.bump();
1230                self.check_ident_allowed(k, true);
1231                Some(self.intern(k))
1232            }
1233            _ => None,
1234        }
1235    }
1236
1237    fn check_label_ident(&mut self, name: &str) {
1238        if name.starts_with('#') || is_always_reserved(name) {
1239            self.record_error(alloc::format!("Unexpected reserved word '{}' as label", name));
1240            return;
1241        }
1242        if self.strict && is_strict_reserved(name) {
1243            self.record_error(alloc::format!("Unexpected strict mode reserved word '{}' as label", name));
1244            return;
1245        }
1246        if name == "await" && (self.in_async || self.in_static_block) {
1247            self.record_error(String::from("'await' is not allowed as label here"));
1248            return;
1249        }
1250        if name == "yield" && self.in_generator && !self.in_lazy_expanded_body {
1251            self.record_error(String::from("'yield' is not allowed as label here"));
1252        }
1253    }
1254
1255    fn is_private_declared(&self, name: &str) -> bool {
1256        self.private_scopes.iter().rev().any(|env| env.iter().any(|(n, _)| &**n == name))
1257    }
1258
1259    fn check_private_declared(&mut self, name: &str) {
1260        if !self.is_private_declared(name) {
1261            if self.private_scopes.is_empty() {
1262                self.record_top_level_only_error(alloc::format!("Private field '{}' must be declared in an enclosing class", name));
1263            } else {
1264                self.record_error(alloc::format!("Private field '{}' must be declared in an enclosing class", name));
1265            }
1266        }
1267    }
1268
1269    fn expect_asi_semicolon(&mut self) {
1270        if self.eat_sym(";") {
1271            return;
1272        }
1273        if self.is_sym("}") || self.is_eof() || self.nl_before_cur() {
1274            return;
1275        }
1276        let found = describe_token(self.cur());
1277        self.record_error(alloc::format!("expected ';' or line break but found {}", found));
1278    }
1279
1280    fn check_accessor_params(&mut self, accessor_kind: Option<bool>, params: &[Param]) {
1281        match accessor_kind {
1282            Some(true) if !params.is_empty() => {
1283                self.record_error(String::from("Getter must not have any formal parameters"));
1284            }
1285            Some(false) if params.len() != 1 || params.first().is_some_and(|p| p.is_rest) => {
1286                self.record_error(String::from("Setter must have exactly one formal parameter"));
1287            }
1288            _ => {}
1289        }
1290    }
1291
1292    fn parse_decorators(&mut self) -> bool {
1293        let mut any = false;
1294        while self.eat_sym("@") {
1295            any = true;
1296            if self.is_sym("(") {
1297                let _ = self.parse_cover_paren_or_arrow(false);
1298            } else {
1299                let _ = self.consume_binding_ident("decorator", false);
1300                loop {
1301                    if self.eat_sym(".") {
1302                        match self.cur().clone() {
1303                            Token::Ident(n) if n.starts_with('#') => {
1304                                self.check_private_declared(&n);
1305                                self.bump();
1306                            }
1307                            _ => {
1308                                if self.ident_name().is_none() {
1309                                    self.record_error(String::from("expected property name in decorator"));
1310                                }
1311                            }
1312                        }
1313                    } else if self.is_sym("(") {
1314                        let _ = self.parse_arguments();
1315                        break;
1316                    } else {
1317                        break;
1318                    }
1319                }
1320            }
1321        }
1322        any
1323    }
1324
1325    fn validate_assignment_target(
1326        &mut self,
1327        expr: &Expression,
1328        allow_destructuring: bool,
1329        is_logical_assign: bool,
1330        was_paren: bool,
1331        spread_comma_increased: bool,
1332        paren_destr_increased: bool,
1333    ) {
1334        if was_paren && matches!(expr, Expression::Array(_) | Expression::Object(_)) {
1335            self.record_error(String::from("Invalid left-hand side in assignment"));
1336            return;
1337        }
1338        if paren_destr_increased {
1339            self.record_error(String::from("Invalid destructuring assignment target"));
1340            return;
1341        }
1342        if allow_destructuring && spread_comma_increased && matches!(expr, Expression::Array(_) | Expression::Object(_)) {
1343            self.record_error(String::from("Rest element may not have a trailing comma"));
1344            return;
1345        }
1346        match expr {
1347            Expression::Identifier(n) => {
1348                if !n.is_empty() && self.strict && (&**n == "eval" || &**n == "arguments") {
1349                    self.record_error(String::from("Assignment to eval or arguments is not allowed in strict mode"));
1350                }
1351            }
1352            Expression::Member { optional, .. } | Expression::Index { optional, .. } => {
1353                if *optional || has_optional_chain(expr) {
1354                    self.record_error(String::from("Invalid left-hand side in assignment"));
1355                }
1356            }
1357            Expression::Call { callee, .. } => {
1358                let is_import_call = matches!(
1359                    &**callee,
1360                    Expression::Identifier(n) if &**n == "\0import"
1361                );
1362                if self.strict || is_logical_assign || is_import_call || has_optional_chain(expr) {
1363                    self.record_error(String::from("Invalid left-hand side in assignment"));
1364                }
1365            }
1366            Expression::Array(items) if allow_destructuring => {
1367                self.validate_array_destr(items);
1368            }
1369            Expression::Object(props) if allow_destructuring => {
1370                self.validate_object_destr(props);
1371            }
1372            _ => {
1373                self.record_error(String::from("Invalid left-hand side in assignment"));
1374            }
1375        }
1376    }
1377
1378    fn validate_array_destr(&mut self, items: &[Expression]) {
1379        let len = items.len();
1380        for (i, item) in items.iter().enumerate() {
1381            match item {
1382                Expression::Elision => {}
1383                Expression::Spread(inner) => {
1384                    if i + 1 != len {
1385                        self.record_error(String::from("Rest element must be last element"));
1386                    }
1387                    if matches!(&**inner, Expression::Assign { .. }) {
1388                        self.record_error(String::from("Rest element may not have a default initializer"));
1389                    } else {
1390                        self.validate_assignment_target(inner, true, false, false, false, false);
1391                    }
1392                }
1393                Expression::Assign { op: "=", target, .. } => {
1394                    self.validate_assignment_target(target, true, false, false, false, false);
1395                }
1396                other => {
1397                    self.validate_assignment_target(other, true, false, false, false, false);
1398                }
1399            }
1400        }
1401    }
1402
1403    fn validate_object_destr(&mut self, props: &[Property]) {
1404        let len = props.len();
1405        for (i, p) in props.iter().enumerate() {
1406            if &*p.key == crate::os_lib::ecma::ast::OBJECT_SPREAD_KEY {
1407                if i + 1 != len {
1408                    self.record_error(String::from("Rest element must be last element"));
1409                }
1410                if matches!(p.value, Expression::Array(_) | Expression::Object(_) | Expression::Assign { .. }) {
1411                    self.record_error(String::from("Invalid rest element in object destructuring"));
1412                } else {
1413                    self.validate_assignment_target(&p.value, false, false, false, false, false);
1414                }
1415                continue;
1416            }
1417            if p.accessor.is_some() || matches!(p.value, Expression::Function { .. }) {
1418                self.record_error(String::from("Invalid destructuring assignment target"));
1419                continue;
1420            }
1421            match &p.value {
1422                Expression::Assign { op: "=", target, .. } => {
1423                    self.validate_assignment_target(target, true, false, false, false, false);
1424                }
1425                other => {
1426                    self.validate_assignment_target(other, true, false, false, false, false);
1427                }
1428            }
1429        }
1430    }
1431
1432    /// 記録済みの構文エラー(上限まで)。
1433    pub fn errors(&self) -> &[ParseError] {
1434        &self.errors
1435    }
1436
1437    /// 検出した構文エラーの総数(記録上限で切り捨てた分も含む)。
1438    pub fn error_count(&self) -> usize {
1439        self.error_count + self.lexer.error_count()
1440    }
1441
1442    /// 記録済みの構文エラーを取り出す(呼び出し側へ渡してログ出力する用途)。
1443    pub fn take_errors(&mut self) -> Vec<ParseError> {
1444        self.flush_lexer_errors();
1445        core::mem::take(&mut self.errors)
1446    }
1447
1448    fn record_error(&mut self, message: String) {
1449        self.error_count += 1;
1450        if self.errors.len() < MAX_RECORDED_ERRORS {
1451            // 【2026-09-05】トークン索引だけでは何が起きたか分からない。
1452            //
1453            // 実際に「`unexpected ':' in expression (token #34956)`」という
1454            // 報告から原因の構文を突き止められず、候補を 16 種類も
1455            // 試すはめになった(すべて外れ)。前後のトークンを添えれば
1456            // どの構文で落ちたかがその場で分かる。
1457            let msg = alloc::format!("{} 付近: {}", message, self.context_around(self.pos));
1458            self.errors.push(ParseError {
1459                message: msg,
1460                token_index: self.pos,
1461            });
1462        }
1463    }
1464
1465    /// エラー位置の前後のトークンを短い文字列にする。
1466    ///
1467    /// 前 6 個・後 3 個。落ちた位置は `»«` で囲む。
1468    fn context_around(&self, at: usize) -> String {
1469        let end_limit = self.base_pos + self.buf.len();
1470        let start = at.saturating_sub(6).max(self.base_pos);
1471        let end = (at + 4).min(end_limit);
1472        let mut out = String::new();
1473        for i in start..end {
1474            let Some(t) = self.tok_at_abs(i) else {
1475                break;
1476            };
1477            if i == at {
1478                out.push('»');
1479                out.push_str(&describe_token(t));
1480                out.push('«');
1481            } else {
1482                out.push_str(&describe_token(t));
1483            }
1484            out.push(' ');
1485        }
1486        out
1487    }
1488
1489    /// 別インスタンス(テンプレート補間式などの副パーサ)が検出したエラーを
1490    /// 自分の記録へ取り込む。位置は副パーサ内の索引なので、由来が分かるよう
1491    /// 印を付ける。
1492    fn absorb_errors(&mut self, mut sub: Parser) {
1493        for e in core::mem::take(&mut sub.top_level_script_errors) {
1494            self.top_level_script_errors.push(e);
1495        }
1496        let count = sub.error_count();
1497        if count == 0 {
1498            return;
1499        }
1500        for e in sub.take_errors() {
1501            self.record_error(alloc::format!("in template expression: {}", e.message));
1502        }
1503        // 記録上限を超えた分も総数には反映する。
1504        if count > MAX_RECORDED_ERRORS {
1505            self.error_count += count - MAX_RECORDED_ERRORS;
1506        }
1507    }
1508
1509    // --- トークンカーソル ---
1510    fn cur(&self) -> &Token {
1511        self.tok_at_abs(self.pos).unwrap_or(&Token::Eof)
1512    }
1513    fn at(&self, off: usize) -> &Token {
1514        self.tok_at_abs(self.pos + off).unwrap_or(&Token::Eof)
1515    }
1516    fn bump(&mut self) -> Token {
1517        let t = self.cur().clone();
1518        if !matches!(t, Token::Eof) {
1519            self.step();
1520        }
1521        t
1522    }
1523    fn is_eof(&self) -> bool {
1524        matches!(self.cur(), Token::Eof)
1525    }
1526    fn is_sym(&self, s: &str) -> bool {
1527        matches!(self.cur(), Token::Sym(x) if *x == s)
1528    }
1529    fn sym_at(&self, off: usize, s: &str) -> bool {
1530        matches!(self.at(off), Token::Sym(x) if *x == s)
1531    }
1532    fn ident_at(&self, off: usize, s: &str) -> bool {
1533        matches!(self.at(off), Token::Ident(x) if &**x == s)
1534    }
1535    fn kw_at(&self, off: usize, k: &str) -> bool {
1536        matches!(self.at(off), Token::Keyword(x) if *x == k)
1537    }
1538    /// `off` の位置がオブジェクト/クラスのプロパティ名になり得るトークン
1539    /// (識別子/予約語/文字列/数値)かどうか(`get`/`set` アクセサ判定の先読み用)。
1540    fn is_property_key_token(&self, off: usize) -> bool {
1541        matches!(
1542            self.at(off),
1543            Token::Ident(_) | Token::Keyword(_) | Token::Str(_) | Token::Num(_) | Token::BigIntLit(_)
1544        )
1545    }
1546
1547    /// エスケープを含むクラス要素名を見直す(`\u0023m`・`#\u0000`・`\u0000` は構文エラー)。
1548    /// 字句解析器は名前に使えない文字のエスケープも通すので、ここで ID_Start/ID_Continue を確かめる。
1549    fn check_escaped_element_name(&mut self, name: &str) {
1550        let st = self.token_start_at(self.pos) as usize;
1551        if !self.lexer.ident_has_escape_at(st) {
1552            return;
1553        }
1554        let src_private = self.lexer.src_rc().as_bytes().get(st) == Some(&b'#');
1555        if name.starts_with('#') && !src_private {
1556            self.record_error(String::from("The '#' of a private name cannot be written as an escape"));
1557            return;
1558        }
1559        let body = if src_private { name.get(1..).unwrap_or("") } else { name };
1560        let mut chars = body.chars();
1561        let ok = match chars.next() {
1562            Some(c) => {
1563                super::lexer::is_id_start_char(c)
1564                    && chars.all(|c| super::lexer::is_id_continue_char(c) || c == '\u{200c}' || c == '\u{200d}')
1565            }
1566            None => false,
1567        };
1568        if !ok {
1569            self.record_error(String::from("Invalid escaped character in class element name"));
1570        }
1571    }
1572
1573    /// BigInt リテラルのプロパティ名(十進の文字列。`{ 0x10n: 1 }` は `"16"`)。
1574    fn bigint_key(&mut self, s: &str) -> Rc<str> {
1575        match super::bigint::BigInt::parse_str(s) {
1576            Some(b) => {
1577                let d = b.to_decimal_string();
1578                self.intern(&d)
1579            }
1580            None => self.intern(s),
1581        }
1582    }
1583    fn eat_sym(&mut self, s: &str) -> bool {
1584        if self.is_sym(s) {
1585            self.step();
1586            true
1587        } else {
1588            false
1589        }
1590    }
1591    /// 記号 `s` を消費する。無ければ**回復して継続しつつ構文エラーとして記録**する
1592    /// (従来は `let _ =` で「無かった」事実ごと捨てていた)。
1593    fn expect_sym(&mut self, s: &str) {
1594        if !self.eat_sym(s) {
1595            let found = describe_token(self.cur());
1596            self.record_error(alloc::format!("expected '{}' but found {}", s, found));
1597        }
1598    }
1599    fn is_kw(&self, k: &str) -> bool {
1600        matches!(self.cur(), Token::Keyword(x) if *x == k)
1601    }
1602    fn eat_kw(&mut self, k: &str) -> bool {
1603        if self.is_kw(k) {
1604            self.step();
1605            true
1606        } else {
1607            false
1608        }
1609    }
1610    fn ident_name(&mut self) -> Option<String> {
1611        match self.cur().clone() {
1612            Token::Ident(n) => {
1613                self.step();
1614                Some(n.to_string())
1615            }
1616            // プロパティ名としてキーワードも許可 (obj.return 等)。
1617            Token::Keyword(n) => {
1618                self.step();
1619                Some(String::from(n))
1620            }
1621            _ => None,
1622        }
1623    }
1624
1625    fn save_err_state(&self) -> (usize, usize, usize, usize, usize, usize, usize) {
1626        (
1627            self.errors.len(),
1628            self.error_count,
1629            self.top_level_script_errors.len(),
1630            self.pending_cover_inits,
1631            self.pending_dup_protos,
1632            self.pending_spread_trailing_commas,
1633            self.pending_paren_destr_targets,
1634        )
1635    }
1636
1637    fn restore_err_state(&mut self, s: (usize, usize, usize, usize, usize, usize, usize)) {
1638        self.errors.truncate(s.0);
1639        self.error_count = s.1;
1640        self.top_level_script_errors.truncate(s.2);
1641        self.pending_cover_inits = s.3;
1642        self.pending_dup_protos = s.4;
1643        self.pending_spread_trailing_commas = s.5;
1644        self.pending_paren_destr_targets = s.6;
1645    }
1646
1647    // --- プログラム ---
1648    pub fn parse_program(&mut self) -> Program {
1649        let prog_start = self.token_start_at(self.pos) as usize;
1650        if self.has_use_strict_directive(self.pos) {
1651            self.strict = true;
1652        }
1653        let mut body = Vec::new();
1654        let mut stmt_steps = 0usize;
1655        while !self.is_eof() {
1656            stmt_steps = stmt_steps.wrapping_add(1);
1657            if (stmt_steps & 0x7F) == 0 {
1658                crate::os_lib::platform::kill_checkpoint();
1659            }
1660            let before = self.pos;
1661            if let Some(stmt) = self.parse_statement() {
1662                self.lex_note_stmt(&stmt);
1663                body.push(stmt);
1664            }
1665            // 前進保証(無限ループ防止)。ここへ来るのは「文として解釈できない
1666            // トークンを読み飛ばした」場合であり、明確な構文エラーなので記録する。
1667            if self.pos == before {
1668                let found = describe_token(self.cur());
1669                self.record_error(alloc::format!("unexpected {}", found));
1670                self.step();
1671            }
1672        }
1673        self.flush_lexer_errors();
1674        if self.pending_cover_inits > 0 {
1675            self.record_error(String::from("Invalid shorthand property initializer"));
1676            self.pending_cover_inits = 0;
1677        }
1678        if self.pending_dup_protos > 0 {
1679            self.record_error(String::from("Duplicate __proto__ fields are not allowed in object literals"));
1680            self.pending_dup_protos = 0;
1681        }
1682        if self.strict {
1683            let prog_end = self.token_start_at(self.pos) as usize;
1684            if self.lexer.legacy_octal_between(prog_start, prog_end) {
1685                self.record_error(String::from("Octal literals and octal escape sequences are not allowed in strict mode"));
1686            }
1687        }
1688        Program { body }
1689    }
1690
1691    /// パースし、**AST と構文エラーの両方**を返す。
1692    ///
1693    /// AST は従来どおり常に返る(ベストエフォート動作を変えない)ので、
1694    /// 呼び出し側は「実行はするが、壊れている事実は知っている」状態にできる。
1695    pub fn parse_program_reporting(&mut self) -> (Program, Vec<ParseError>) {
1696        let program = self.parse_program();
1697        if !self.top_level_script_errors.is_empty() {
1698            let extra = core::mem::take(&mut self.top_level_script_errors);
1699            self.error_count += extra.len();
1700            for e in extra {
1701                if self.errors.len() < MAX_RECORDED_ERRORS {
1702                    self.errors.push(e);
1703                }
1704            }
1705        }
1706        let errors = self.take_errors();
1707        (program, errors)
1708    }
1709
1710    // --- 文 ---
1711    fn parse_statement(&mut self) -> Option<Statement> {
1712        self.parse_statement_in(StmtPos::List)
1713    }
1714
1715    fn is_let_decl_start(&self) -> bool {
1716        match self.at(1) {
1717            Token::Ident(_) | Token::Sym("[" | "{") => true,
1718            Token::Keyword(k) => matches!(
1719                *k,
1720                "let" | "await" | "yield" | "async" | "of" | "undefined"
1721            ),
1722            _ => false,
1723        }
1724    }
1725
1726    fn is_using_decl_start(&self, off: usize) -> bool {
1727        if self.nl_before_at(off + 1) {
1728            return false;
1729        }
1730        match self.at(off + 1) {
1731            Token::Ident(_) => true,
1732            Token::Keyword(k) => matches!(
1733                *k,
1734                "let" | "await" | "yield" | "async" | "of" | "undefined"
1735            ),
1736            _ => false,
1737        }
1738    }
1739
1740    fn parse_statement_in(&mut self, pos_kind: StmtPos) -> Option<Statement> {
1741        // セミコロン単独は空文。
1742        if self.eat_sym(";") {
1743            return Some(Statement::Empty);
1744        }
1745        if self.is_sym("{") {
1746            return Some(self.parse_block());
1747        }
1748        if self.is_sym("@") {
1749            self.parse_decorators();
1750            if !self.is_kw("class") && !self.is_kw("export") {
1751                self.record_error(String::from("Decorators are only valid before class or class element"));
1752            }
1753        }
1754
1755        // `using`/`await using` 宣言(Explicit Resource Management、ES2023→ES2026ベースライン)。
1756        if self.ident_at(0, "using") && self.is_using_decl_start(0) {
1757            if pos_kind != StmtPos::List {
1758                self.record_error(String::from("Using declaration cannot appear in single-statement context"));
1759            }
1760            return self.parse_using_declaration(false);
1761        }
1762        if self.is_kw("await")
1763            && self.ident_at(1, "using")
1764            && !self.nl_before_at(1)
1765            && self.is_using_decl_start(1)
1766        {
1767            if pos_kind != StmtPos::List {
1768                self.record_error(String::from("Await using declaration cannot appear in single-statement context"));
1769            }
1770            self.bump(); // await
1771            return self.parse_using_declaration(true);
1772        }
1773
1774        // ラベル付き文 `label: statement`。
1775        let opt_label = match self.cur().clone() {
1776            Token::Ident(l) if self.sym_at(1, ":") => Some(l.to_string()),
1777            Token::Keyword(k)
1778                if matches!(k, "async" | "of" | "undefined" | "let" | "await" | "yield")
1779                    && self.sym_at(1, ":") =>
1780            {
1781                Some(String::from(k))
1782            }
1783            _ => None,
1784        };
1785        if let Some(label) = opt_label {
1786            self.check_label_ident(&label);
1787            let label_rc = self.intern(&label);
1788            // 先読みして直後に続くラベル連鎖の先が反復文か判定する。
1789            let mut look = 2usize;
1790            loop {
1791                let is_more_label = matches!(self.at(look), Token::Ident(_))
1792                    || matches!(self.at(look), Token::Keyword(k) if matches!(*k, "async" | "of" | "undefined" | "let" | "await" | "yield"));
1793                if is_more_label && self.sym_at(look + 1, ":") {
1794                    look += 2;
1795                } else {
1796                    break;
1797                }
1798            }
1799            let is_iter = matches!(self.at(look), Token::Keyword("while" | "do" | "for"));
1800            if self.labels.iter().any(|(n, _)| n == &label_rc) {
1801                self.record_error(alloc::format!("Label '{}' has already been declared", label_rc));
1802            }
1803            self.bump(); // label
1804            self.bump(); // ':'
1805            self.labels.push((label_rc.clone(), is_iter));
1806            let inner_pos = if matches!(pos_kind, StmtPos::IterationOrWith | StmtPos::IfBody) {
1807                StmtPos::IterationOrWith
1808            } else {
1809                StmtPos::IfOrLabel
1810            };
1811            let inner = self.parse_statement_in(inner_pos).unwrap_or(Statement::Empty);
1812            self.labels.pop();
1813            return Some(Statement::Labeled(label_rc, Box::new(inner)));
1814        }
1815
1816        match self.cur().clone() {
1817            Token::Keyword(kw) => match kw {
1818                "var" => self.parse_var_declaration(),
1819                "let"
1820                    if if pos_kind == StmtPos::List {
1821                        self.is_let_decl_start()
1822                    } else {
1823                        self.sym_at(1, "[") || (!self.nl_before_at(1) && self.is_let_decl_start())
1824                    } =>
1825                {
1826                    if pos_kind != StmtPos::List {
1827                        self.record_error(String::from("Lexical declaration cannot appear in a single-statement context"));
1828                    }
1829                    self.parse_var_declaration()
1830                }
1831                "let" => self.parse_expression_statement(),
1832                "const" => {
1833                    if pos_kind != StmtPos::List {
1834                        self.record_error(String::from("Lexical declaration cannot appear in a single-statement context"));
1835                    }
1836                    self.parse_var_declaration()
1837                }
1838                "if" => self.parse_if(),
1839                "while" => self.parse_while(),
1840                "do" => self.parse_do_while(),
1841                "for" => self.parse_for(),
1842                "function" => {
1843                    let is_gen = self.sym_at(1, "*");
1844                    if pos_kind == StmtPos::IterationOrWith
1845                        || (matches!(pos_kind, StmtPos::IfOrLabel | StmtPos::IfBody) && (self.strict || is_gen))
1846                    {
1847                        self.record_error(String::from("Function declaration cannot appear in a single-statement context"));
1848                    }
1849                    self.parse_function_declaration(false)
1850                }
1851                "async" if self.kw_at(1, "function") && !self.nl_before_at(1) => {
1852                    if pos_kind != StmtPos::List {
1853                        self.record_error(String::from("Async function declaration cannot appear in a single-statement context"));
1854                    }
1855                    self.bump(); // async
1856                    self.parse_function_declaration(true)
1857                }
1858                "return" => {
1859                    if (self.in_function == 0 && !self.in_lazy_expanded_body) || self.in_static_block {
1860                        self.record_error(String::from("Illegal return statement"));
1861                    }
1862                    self.bump();
1863                    if self.is_sym(";") || self.is_sym("}") || self.is_eof() || self.nl_before_cur() {
1864                        self.eat_sym(";");
1865                        Some(Statement::Return(None))
1866                    } else {
1867                        let e = self.parse_expression();
1868                        self.eat_sym(";");
1869                        Some(Statement::Return(Some(e)))
1870                    }
1871                }
1872                "break" => {
1873                    self.bump();
1874                    let label = if !self.nl_before_cur() {
1875                        match self.cur().clone() {
1876                            Token::Ident(n) => {
1877                                self.bump();
1878                                self.check_label_ident(&n);
1879                                Some(self.intern(&n))
1880                            }
1881                            Token::Keyword(k) if matches!(k, "async" | "of" | "undefined" | "let" | "await" | "yield") => {
1882                                self.bump();
1883                                self.check_label_ident(k);
1884                                Some(self.intern(k))
1885                            }
1886                            _ => None,
1887                        }
1888                    } else {
1889                        None
1890                    };
1891                    if let Some(ref lbl) = label {
1892                        if !self.labels.iter().any(|(n, _)| n == lbl) {
1893                            self.record_error(alloc::format!("Undefined label '{}'", lbl));
1894                        }
1895                    } else if self.loop_depth == 0 && self.switch_depth == 0 {
1896                        self.record_error(String::from("Illegal break statement"));
1897                    }
1898                    self.eat_sym(";");
1899                    Some(Statement::Break(label))
1900                }
1901                "continue" => {
1902                    self.bump();
1903                    let label = if !self.nl_before_cur() {
1904                        match self.cur().clone() {
1905                            Token::Ident(n) => {
1906                                self.bump();
1907                                self.check_label_ident(&n);
1908                                Some(self.intern(&n))
1909                            }
1910                            Token::Keyword(k) if matches!(k, "async" | "of" | "undefined" | "let" | "await" | "yield") => {
1911                                self.bump();
1912                                self.check_label_ident(k);
1913                                Some(self.intern(k))
1914                            }
1915                            _ => None,
1916                        }
1917                    } else {
1918                        None
1919                    };
1920                    if let Some(ref lbl) = label {
1921                        if !self.labels.iter().any(|(n, is_iter)| n == lbl && *is_iter) {
1922                            self.record_error(alloc::format!("Illegal continue statement: '{}' does not denote an iteration statement", lbl));
1923                        }
1924                    } else if self.loop_depth == 0 {
1925                        self.record_error(String::from("Illegal continue statement: no surrounding iteration statement"));
1926                    }
1927                    self.eat_sym(";");
1928                    Some(Statement::Continue(label))
1929                }
1930                "throw" => {
1931                    self.bump();
1932                    if self.nl_before_cur() {
1933                        self.record_error(String::from("Illegal newline after throw"));
1934                    }
1935                    let e = self.parse_expression();
1936                    self.eat_sym(";");
1937                    Some(Statement::Throw(e))
1938                }
1939                "debugger" => {
1940                    self.bump();
1941                    self.eat_sym(";");
1942                    Some(Statement::Empty)
1943                }
1944                "with" => {
1945                    if self.strict {
1946                        self.record_error(String::from("Strict mode code may not include a with statement"));
1947                    }
1948                    self.bump();
1949                    self.expect_sym("(");
1950                    let obj = self.parse_expression();
1951                    self.expect_sym(")");
1952                    let body = self.parse_statement_in(StmtPos::IterationOrWith).unwrap_or(Statement::Empty);
1953                    Some(Statement::With {
1954                        object: Box::new(obj),
1955                        body: Box::new(body),
1956                    })
1957                }
1958                "try" => self.parse_try(),
1959                "switch" => self.parse_switch(),
1960                "import" if self.sym_at(1, "(") || self.sym_at(1, ".") => self.parse_expression_statement(),
1961                "import" => self.parse_import(),
1962                "export" => self.parse_export(),
1963                "class" => {
1964                    if pos_kind != StmtPos::List {
1965                        self.record_error(String::from("Class declaration cannot appear in a single-statement context"));
1966                    }
1967                    // クラス宣言: `let Name = class ...` 相当に脱糖。
1968                    let cls = self.parse_class(true);
1969                    let name = if let Expression::Class { name: Some(n), .. } = &cls {
1970                        n.clone()
1971                    } else {
1972                        String::new()
1973                    };
1974                    self.eat_sym(";");
1975                    let name_rc = self.intern(&name);
1976                    self.declare_binding(&name_rc, BindingKind::Let);
1977                    Some(Statement::VarDeclaration {
1978                        kind: VarKind::Let,
1979                        decls: alloc::vec![(Pattern::Identifier(name_rc), Some(cls))],
1980                    })
1981                }
1982                _ => self.parse_expression_statement(),
1983            },
1984            _ => self.parse_expression_statement(),
1985        }
1986    }
1987
1988    fn parse_block(&mut self) -> Statement {
1989        self.scope_push(ScopeKind::Block);
1990        self.lex_push(false);
1991        let body = self.parse_brace_body_no_scope();
1992        self.lex_pop();
1993        self.scope_pop();
1994        Statement::Block(body)
1995    }
1996
1997    fn parse_brace_body(&mut self) -> Vec<Statement> {
1998        self.scope_push(ScopeKind::Block);
1999        self.lex_push(false);
2000        let body = self.parse_brace_body_no_scope();
2001        self.lex_pop();
2002        self.scope_pop();
2003        body
2004    }
2005
2006    fn parse_brace_body_no_scope(&mut self) -> Vec<Statement> {
2007        self.expect_sym("{");
2008        let mut body = Vec::new();
2009        while !self.is_sym("}") && !self.is_eof() {
2010            let before = self.pos;
2011            if let Some(s) = self.parse_statement() {
2012                self.lex_note_stmt(&s);
2013                body.push(s);
2014            }
2015            if self.pos == before {
2016                self.step();
2017            }
2018        }
2019        self.expect_sym("}");
2020        body
2021    }
2022
2023    fn parse_var_declaration(&mut self) -> Option<Statement> {
2024        let kind = match self.bump() {
2025            Token::Keyword(k) => match k {
2026                "let" => VarKind::Let,
2027                "const" => VarKind::Const,
2028                _ => VarKind::Var,
2029            },
2030            _ => VarKind::Var,
2031        };
2032        let bkind = if matches!(kind, VarKind::Var) {
2033            BindingKind::Var
2034        } else {
2035            BindingKind::Let
2036        };
2037        let mut decls = Vec::new();
2038        loop {
2039            if self.is_eof() || self.is_sym(";") {
2040                if decls.is_empty() {
2041                    self.record_error(String::from("Missing variable name in declaration"));
2042                }
2043                break;
2044            }
2045            let pat = self.parse_pattern();
2046            if !matches!(kind, VarKind::Var) {
2047                self.check_lexical_disallows_let(&pat);
2048            }
2049            self.declare_pattern_bindings(&pat, bkind);
2050            if matches!(kind, VarKind::Const) {
2051                self.note_const_pattern(&pat);
2052            }
2053            let init = if self.eat_sym("=") {
2054                Some(self.parse_assignment_top())
2055            } else {
2056                if matches!(kind, VarKind::Const) {
2057                    self.record_error(String::from("Missing initializer in const declaration"));
2058                }
2059                None
2060            };
2061            decls.push((pat, init));
2062            if !self.eat_sym(",") {
2063                break;
2064            }
2065        }
2066        self.eat_sym(";");
2067        Some(Statement::VarDeclaration { kind, decls })
2068    }
2069
2070    /// `using x = expr, y = expr2;` / `await using x = expr;`。
2071    /// 仕様上バインディングは単純な識別子のみ(分割代入パターンは不可)。
2072    fn parse_using_declaration(&mut self, is_await: bool) -> Option<Statement> {
2073        self.bump(); // "using"
2074        if is_await && !self.in_async && !self.in_lazy_expanded_body {
2075            self.record_error(String::from("'await using' is only allowed inside async functions"));
2076        }
2077        if self.is_at_script_top_scope() {
2078            self.record_error(String::from("'using' declaration is not allowed at top level of script or eval"));
2079        }
2080        let kind = if is_await {
2081            VarKind::AwaitUsing
2082        } else {
2083            VarKind::Using
2084        };
2085        let mut decls = Vec::new();
2086        loop {
2087            let name_rc = self.consume_binding_ident("using declaration", false);
2088            if &*name_rc == "let" {
2089                self.record_error(String::from("'let' is disallowed as a lexically bound name"));
2090            }
2091            self.declare_binding(&name_rc, BindingKind::Let);
2092            let init = if self.eat_sym("=") {
2093                Some(self.parse_assignment_top())
2094            } else {
2095                self.record_error(String::from("Missing initializer in using declaration"));
2096                None
2097            };
2098            decls.push((Pattern::Identifier(name_rc), init));
2099            if !self.eat_sym(",") {
2100                break;
2101            }
2102        }
2103        self.expect_asi_semicolon();
2104        Some(Statement::VarDeclaration { kind, decls })
2105    }
2106
2107    fn parse_if(&mut self) -> Option<Statement> {
2108        self.bump(); // if
2109        self.expect_sym("(");
2110        let test = self.parse_expression();
2111        self.expect_sym(")");
2112        self.scope_push(ScopeKind::Block);
2113        let consequent = Box::new(self.parse_statement_in(StmtPos::IfBody).unwrap_or(Statement::Empty));
2114        self.scope_pop();
2115        let alternate = if self.eat_kw("else") {
2116            self.scope_push(ScopeKind::Block);
2117            let alt = Some(Box::new(self.parse_statement_in(StmtPos::IfBody).unwrap_or(Statement::Empty)));
2118            self.scope_pop();
2119            alt
2120        } else {
2121            None
2122        };
2123        Some(Statement::If {
2124            test: Box::new(test),
2125            consequent,
2126            alternate,
2127        })
2128    }
2129
2130    fn parse_while(&mut self) -> Option<Statement> {
2131        self.bump();
2132        self.expect_sym("(");
2133        let test = self.parse_expression();
2134        self.expect_sym(")");
2135        self.loop_depth += 1;
2136        let body = Box::new(self.parse_statement_in(StmtPos::IterationOrWith).unwrap_or(Statement::Empty));
2137        self.loop_depth -= 1;
2138        Some(Statement::While { test, body })
2139    }
2140
2141    fn parse_do_while(&mut self) -> Option<Statement> {
2142        self.bump(); // do
2143        self.loop_depth += 1;
2144        let body = Box::new(self.parse_statement_in(StmtPos::IterationOrWith).unwrap_or(Statement::Empty));
2145        self.loop_depth -= 1;
2146        if !self.eat_kw("while") {
2147            self.record_error(String::from("expected 'while' after do statement"));
2148        }
2149        self.expect_sym("(");
2150        let test = self.parse_expression();
2151        self.expect_sym(")");
2152        self.eat_sym(";");
2153        Some(Statement::DoWhile { body, test })
2154    }
2155
2156    fn parse_for(&mut self) -> Option<Statement> {
2157        self.lex_push(false);
2158        let r = self.parse_for_inner();
2159        self.lex_pop();
2160        r
2161    }
2162
2163    fn parse_for_inner(&mut self) -> Option<Statement> {
2164        self.bump(); // for
2165        let is_await = self.eat_kw("await");
2166        if is_await && !self.in_async && !self.in_lazy_expanded_body {
2167            self.record_error(String::from("'for await' is only allowed inside async functions"));
2168        }
2169        self.expect_sym("(");
2170
2171        // `for (using x of ...)` / `for (await using x of ...)`(ただし `for (using of ...)` は識別子 `using`)
2172        // `of` を束縛名にできるのは C 形式(`for (using of = null;;)`)と `for (await using of of …)` だけ。
2173        let for_using = if self.ident_at(0, "using")
2174            && self.is_using_decl_start(0)
2175            && (!self.kw_at(1, "of") || self.sym_at(2, "="))
2176        {
2177            Some(false)
2178        } else if self.is_kw("await")
2179            && self.ident_at(1, "using")
2180            && !self.nl_before_at(1)
2181            && self.is_using_decl_start(1)
2182            && (!self.kw_at(2, "of") || self.kw_at(3, "of") || self.sym_at(3, "="))
2183        {
2184            self.bump(); // await
2185            Some(true)
2186        } else {
2187            None
2188        };
2189        if let Some(u_await) = for_using {
2190            self.bump(); // using
2191            if u_await && !self.in_async && !self.in_lazy_expanded_body {
2192                self.record_error(String::from("'await using' is only allowed inside async functions"));
2193            }
2194            self.scope_push(ScopeKind::ForHead);
2195            let name_rc = self.consume_binding_ident("for-of using declaration", false);
2196            if &*name_rc == "let" {
2197                self.record_error(String::from("'let' is disallowed as a lexically bound name"));
2198            }
2199            self.declare_binding(&name_rc, BindingKind::Let);
2200            // C 形式 `for (using x = a, y = b; …; …)`。
2201            if self.is_sym("=") || self.is_sym(",") || self.is_sym(";") {
2202                if is_await {
2203                    self.record_error(String::from("for-await cannot be used with C-style for loop"));
2204                }
2205                let mut decls = Vec::new();
2206                let mut name = name_rc;
2207                loop {
2208                    let init = if self.eat_sym("=") {
2209                        Some(self.parse_assignment_top())
2210                    } else {
2211                        self.record_error(String::from("Missing initializer in using declaration"));
2212                        None
2213                    };
2214                    decls.push((Pattern::Identifier(name), init));
2215                    if !self.eat_sym(",") {
2216                        break;
2217                    }
2218                    name = self.consume_binding_ident("using declaration", false);
2219                    if &*name == "let" {
2220                        self.record_error(String::from("'let' is disallowed as a lexically bound name"));
2221                    }
2222                    self.declare_binding(&name, BindingKind::Let);
2223                }
2224                self.expect_sym(";");
2225                let init = Some(Box::new(Statement::VarDeclaration {
2226                    kind: if u_await { VarKind::AwaitUsing } else { VarKind::Using },
2227                    decls,
2228                }));
2229                let res = self.finish_c_for(init);
2230                self.scope_pop();
2231                return res;
2232            }
2233            if self.is_kw("in") {
2234                self.record_error(String::from("'using' declaration is not allowed in for-in loop"));
2235            }
2236            let of = if self.eat_kw("of") {
2237                true
2238            } else {
2239                let _ = self.eat_kw("in");
2240                false
2241            };
2242            let object = if of { self.parse_assignment_top() } else { self.parse_expression() };
2243            self.expect_sym(")");
2244            self.loop_depth += 1;
2245            let body = Box::new(self.parse_statement_in(StmtPos::IterationOrWith).unwrap_or(Statement::Empty));
2246            self.loop_depth -= 1;
2247            self.scope_pop();
2248            return Some(Statement::ForIn {
2249                decl_kind: Some(if u_await { VarKind::AwaitUsing } else { VarKind::Using }),
2250                pattern: Pattern::Identifier(name_rc),
2251                object: Box::new(object),
2252                body,
2253                of,
2254                is_await,
2255            });
2256        }
2257
2258        // for-in / for-of を宣言形式で検出 (`var` / `let` / `const`)。
2259        let is_let_decl = self.is_kw("let") && (self.is_let_decl_start() || self.kw_at(1, "of"));
2260        if self.is_kw("var") || self.is_kw("const") || is_let_decl {
2261            let decl_kind = match self.bump() {
2262                Token::Keyword(k) => match k {
2263                    "let" => VarKind::Let,
2264                    "const" => VarKind::Const,
2265                    _ => VarKind::Var,
2266                },
2267                _ => VarKind::Var,
2268            };
2269            if matches!(decl_kind, VarKind::Let) && self.is_kw("of") {
2270                self.record_error(String::from("'let' is not allowed as binding in for-of"));
2271            }
2272            let pushed_for_scope = !matches!(decl_kind, VarKind::Var);
2273            if pushed_for_scope {
2274                self.scope_push(ScopeKind::ForHead);
2275            }
2276            let bkind = if pushed_for_scope { BindingKind::Let } else { BindingKind::Var };
2277            let pat = self.parse_pattern();
2278            if pushed_for_scope {
2279                self.check_lexical_disallows_let(&pat);
2280            }
2281            self.declare_pattern_bindings(&pat, bkind);
2282            if matches!(decl_kind, VarKind::Const) {
2283                self.note_const_pattern(&pat);
2284            }
2285            self.lex_declare_pattern(&pat, matches!(decl_kind, VarKind::Const));
2286            if self.eat_kw("of") || self.is_kw("in") {
2287                let of = !self.is_kw("in");
2288                if !of {
2289                    self.bump();
2290                    if is_await {
2291                        self.record_error(String::from("for-await cannot be used with for-in"));
2292                    }
2293                }
2294                let object = if of { self.parse_assignment_top() } else { self.parse_expression() };
2295                self.expect_sym(")");
2296                self.loop_depth += 1;
2297                let body = Box::new(self.parse_statement_in(StmtPos::IterationOrWith).unwrap_or(Statement::Empty));
2298                self.loop_depth -= 1;
2299                if pushed_for_scope {
2300                    self.scope_pop();
2301                }
2302                return Some(Statement::ForIn {
2303                    decl_kind: Some(decl_kind),
2304                    pattern: pat,
2305                    object: Box::new(object),
2306                    body,
2307                    of,
2308                    is_await,
2309                });
2310            }
2311            // C スタイル(あるいは不正な `for (let x = 1 in/of ...)` の可能性)。
2312            let init_expr = if self.eat_sym("=") {
2313                Some(self.parse_assignment_top())
2314            } else {
2315                if matches!(decl_kind, VarKind::Const) {
2316                    self.record_error(String::from("Missing initializer in const declaration"));
2317                }
2318                None
2319            };
2320            if self.eat_kw("of") || self.is_kw("in") {
2321                let of = !self.is_kw("in");
2322                if !of {
2323                    self.bump();
2324                }
2325                if of || pushed_for_scope || self.strict || !matches!(pat, Pattern::Identifier(_)) {
2326                    self.record_error(String::from("for-in/of loop variable declaration may not have an initializer"));
2327                }
2328                let object = if of { self.parse_assignment_top() } else { self.parse_expression() };
2329                self.expect_sym(")");
2330                self.loop_depth += 1;
2331                let body = Box::new(self.parse_statement_in(StmtPos::IterationOrWith).unwrap_or(Statement::Empty));
2332                self.loop_depth -= 1;
2333                if pushed_for_scope {
2334                    self.scope_pop();
2335                }
2336                return Some(Statement::ForIn {
2337                    decl_kind: Some(decl_kind),
2338                    pattern: pat,
2339                    object: Box::new(object),
2340                    body,
2341                    of,
2342                    is_await,
2343                });
2344            }
2345            if is_await {
2346                self.record_error(String::from("for-await cannot be used with C-style for loop"));
2347            }
2348            let mut decls = alloc::vec![(pat, init_expr)];
2349            while self.eat_sym(",") {
2350                let p = self.parse_pattern();
2351                if pushed_for_scope {
2352                    self.check_lexical_disallows_let(&p);
2353                }
2354                self.declare_pattern_bindings(&p, bkind);
2355                if matches!(decl_kind, VarKind::Const) {
2356                    self.note_const_pattern(&p);
2357                }
2358                let i = if self.eat_sym("=") {
2359                    Some(self.parse_assignment_top())
2360                } else {
2361                    if matches!(decl_kind, VarKind::Const) {
2362                        self.record_error(String::from("Missing initializer in const declaration"));
2363                    }
2364                    None
2365                };
2366                decls.push((p, i));
2367            }
2368            self.expect_sym(";");
2369            let init = Some(Box::new(Statement::VarDeclaration {
2370                kind: decl_kind,
2371                decls,
2372            }));
2373            let res = self.finish_c_for(init);
2374            if pushed_for_scope {
2375                self.scope_pop();
2376            }
2377            return res;
2378        }
2379
2380        // 非宣言形式の単純識別子 for-of/for-in: `for (x of arr)` / `for (x in obj)`。
2381        let opt_ident_lhs = match self.cur().clone() {
2382            Token::Ident(n) if self.kw_at(1, "of") || self.kw_at(1, "in") => Some(n.to_string()),
2383            Token::Keyword(k)
2384                if matches!(k, "async" | "of" | "undefined" | "let" | "await" | "yield")
2385                    && (self.kw_at(1, "of") || self.kw_at(1, "in")) =>
2386            {
2387                Some(String::from(k))
2388            }
2389            _ => None,
2390        };
2391        if let Some(name) = opt_ident_lhs {
2392            let of = self.kw_at(1, "of");
2393            if !is_await && of && name == "async" {
2394                self.record_error(String::from("The left-hand side of a for-of loop may not start with 'async'"));
2395            }
2396            if !of && is_await {
2397                self.record_error(String::from("for-await cannot be used with for-in"));
2398            }
2399            self.check_ident_allowed(&name, false);
2400            if self.strict && (name == "eval" || name == "arguments") {
2401                self.record_error(String::from("Assignment to eval or arguments is not allowed in strict mode"));
2402            }
2403            self.bump(); // ident
2404            self.bump(); // of/in
2405            let object = if of { self.parse_assignment_top() } else { self.parse_expression() };
2406            self.expect_sym(")");
2407            self.loop_depth += 1;
2408            let body = Box::new(self.parse_statement_in(StmtPos::IterationOrWith).unwrap_or(Statement::Empty));
2409            self.loop_depth -= 1;
2410            let name_rc = self.intern(&name);
2411            let head = self.lex_guard_const_pattern(Pattern::Identifier(name_rc));
2412            return Some(Statement::ForIn {
2413                decl_kind: None,
2414                pattern: head,
2415                object: Box::new(object),
2416                body,
2417                of,
2418                is_await,
2419            });
2420        }
2421
2422        // 非宣言形式の分割代入 for-of/for-in: `for ([a,b] of arr)` / `for ({a,b} of obj)`。
2423        if self.is_sym("[") || self.is_sym("{") {
2424            let save = self.pos;
2425            let prev_pin = self.pin_pos;
2426            if self.pin_pos.is_none() {
2427                self.pin_pos = Some(save);
2428            }
2429            let err_save = self.save_err_state();
2430            let pat = self.parse_pattern();
2431            if self.eat_kw("of") || self.is_kw("in") {
2432                self.pin_pos = prev_pin;
2433                self.flush_lexer_errors();
2434                let of = !self.is_kw("in");
2435                if !of {
2436                    self.bump();
2437                    if is_await {
2438                        self.record_error(String::from("for-await cannot be used with for-in"));
2439                    }
2440                }
2441                let object = if of { self.parse_assignment_top() } else { self.parse_expression() };
2442                self.expect_sym(")");
2443                self.loop_depth += 1;
2444                let body = Box::new(self.parse_statement_in(StmtPos::IterationOrWith).unwrap_or(Statement::Empty));
2445                self.loop_depth -= 1;
2446                let pat = self.lex_guard_const_pattern(pat);
2447                return Some(Statement::ForIn {
2448                    decl_kind: None,
2449                    pattern: pat,
2450                    object: Box::new(object),
2451                    body,
2452                    of,
2453                    is_await,
2454                });
2455            }
2456            self.pin_pos = prev_pin;
2457            self.restore_err_state(err_save);
2458            self.set_pos(save);
2459        }
2460
2461        // 非宣言形式の式 for-of/for-in(メンバー/添字/括弧付き識別子/sloppy呼出など)。
2462        // `for (; ...)` は init が空の C-for なので即スキップ。
2463        if !self.is_sym(";") {
2464            let save = self.pos;
2465            let prev_pin = self.pin_pos;
2466            if self.pin_pos.is_none() {
2467                self.pin_pos = Some(save);
2468            }
2469            let err_save = self.save_err_state();
2470            let cov_before = self.pending_cover_inits;
2471            let dup_proto_before = self.pending_dup_protos;
2472            let spread_before = self.pending_spread_trailing_commas;
2473            let paren_destr_before = self.pending_paren_destr_targets;
2474            let expr = self.parse_call_member(true);
2475            let was_paren = self.last_expr_was_paren;
2476            if self.eat_kw("of") || self.is_kw("in") {
2477                self.pin_pos = prev_pin;
2478                self.flush_lexer_errors();
2479                let of = !self.is_kw("in");
2480                if !of {
2481                    self.bump();
2482                    if is_await {
2483                        self.record_error(String::from("for-await cannot be used with for-in"));
2484                    }
2485                }
2486                if self.pending_cover_inits > cov_before {
2487                    self.record_error(String::from("Invalid shorthand property initializer"));
2488                    self.pending_cover_inits = cov_before;
2489                }
2490                if self.pending_dup_protos > dup_proto_before {
2491                    self.record_error(String::from("Duplicate __proto__ fields are not allowed in object literals"));
2492                    self.pending_dup_protos = dup_proto_before;
2493                }
2494                self.validate_assignment_target(
2495                    &expr,
2496                    true,
2497                    false,
2498                    was_paren,
2499                    self.pending_spread_trailing_commas > spread_before,
2500                    self.pending_paren_destr_targets > paren_destr_before,
2501                );
2502                self.pending_spread_trailing_commas = spread_before;
2503                self.pending_paren_destr_targets = paren_destr_before;
2504                let guarded_head = self.lex_guard_const_target(expr);
2505                let object = if of { self.parse_assignment_top() } else { self.parse_expression() };
2506                self.expect_sym(")");
2507                self.loop_depth += 1;
2508                let body = Box::new(self.parse_statement_in(StmtPos::IterationOrWith).unwrap_or(Statement::Empty));
2509                self.loop_depth -= 1;
2510                return Some(Statement::ForIn {
2511                    decl_kind: None,
2512                    pattern: Pattern::Expr(Box::new(guarded_head)),
2513                    object: Box::new(object),
2514                    body,
2515                    of,
2516                    is_await,
2517                });
2518            }
2519            self.pin_pos = prev_pin;
2520            self.restore_err_state(err_save);
2521            self.set_pos(save);
2522        }
2523
2524        if is_await {
2525            self.record_error(String::from("for-await cannot be used with C-style for loop"));
2526        }
2527        // init 式(無しの場合あり)
2528        let init = if self.is_sym(";") {
2529            None
2530        } else {
2531            let e = self.parse_expression();
2532            Some(Box::new(Statement::Expression(e)))
2533        };
2534        self.eat_sym(";");
2535        self.finish_c_for(init)
2536    }
2537
2538    fn finish_c_for(&mut self, init: Option<Box<Statement>>) -> Option<Statement> {
2539        let test = if self.is_sym(";") {
2540            None
2541        } else {
2542            Some(self.parse_expression())
2543        };
2544        self.eat_sym(";");
2545        let update = if self.is_sym(")") {
2546            None
2547        } else {
2548            Some(self.parse_expression())
2549        };
2550        self.expect_sym(")");
2551        self.loop_depth += 1;
2552        let body = Box::new(self.parse_statement_in(StmtPos::IterationOrWith).unwrap_or(Statement::Empty));
2553        self.loop_depth -= 1;
2554        Some(Statement::For {
2555            init,
2556            test: test.map(Box::new),
2557            update: update.map(Box::new),
2558            body,
2559        })
2560    }
2561
2562    fn parse_function_declaration(&mut self, is_async: bool) -> Option<Statement> {
2563        let src_start = self.fn_source_start(is_async);
2564        self.bump(); // function
2565        let is_generator = self.eat_sym("*");
2566        let name = self.consume_binding_ident("function declaration", false);
2567        self.declare_binding(
2568            &name,
2569            BindingKind::Function {
2570                is_plain_sync: !is_async && !is_generator,
2571            },
2572        );
2573        let saved_async = core::mem::replace(&mut self.in_async, is_async);
2574        let saved_gen = core::mem::replace(&mut self.in_generator, is_generator);
2575        let saved_super_call = core::mem::replace(&mut self.allow_super_call, false);
2576        let saved_super_prop = core::mem::replace(&mut self.allow_super_prop, false);
2577        let saved_concrete = core::mem::replace(&mut self.has_concrete_super_scope, true);
2578        let saved_static_blk = core::mem::replace(&mut self.in_static_block, false);
2579        let saved_param = core::mem::replace(&mut self.in_param, true);
2580        let params = self.parse_param_list();
2581        self.in_param = saved_param;
2582        let require_unique = self.strict || has_non_simple_params(&params) || is_async || is_generator;
2583        self.check_params(&params, require_unique);
2584        let body = self.parse_fn_body_with_params(&params);
2585        self.check_retro_strict(Some(&name), &params, &body, self.strict);
2586        self.in_static_block = saved_static_blk;
2587        self.has_concrete_super_scope = saved_concrete;
2588        self.allow_super_prop = saved_super_prop;
2589        self.allow_super_call = saved_super_call;
2590        self.in_generator = saved_gen;
2591        self.in_async = saved_async;
2592        self.record_fn_source(&body, src_start);
2593        Some(Statement::FunctionDeclaration {
2594            name,
2595            params: Rc::new(params),
2596            body,
2597            is_async,
2598            is_generator,
2599        })
2600    }
2601
2602    fn parse_try(&mut self) -> Option<Statement> {
2603        self.bump(); // try
2604        let block = self.parse_brace_body();
2605        let mut catch_param = None;
2606        let mut catch_block = None;
2607        let mut finally_block = None;
2608        if self.eat_kw("catch") {
2609            self.scope_push(ScopeKind::Catch);
2610            self.lex_push(false);
2611            if self.eat_sym("(") {
2612                if self.is_sym(")") {
2613                    self.record_error(String::from("Catch parameter cannot be empty"));
2614                } else {
2615                    let p = self.parse_pattern();
2616                    let is_simple = matches!(p, Pattern::Identifier(_));
2617                    if let Some(f) = self.scopes.last_mut() {
2618                        f.catch_simple_param = is_simple;
2619                    }
2620                    self.declare_pattern_bindings(&p, BindingKind::CatchParam);
2621                    self.lex_declare_pattern(&p, false);
2622                    let mut names = Vec::new();
2623                    Self::collect_pattern_names(&p, &mut names);
2624                    for i in 0..names.len() {
2625                        for j in (i + 1)..names.len() {
2626                            if names[i] == names[j] {
2627                                self.record_error(String::from("Duplicate identifier in catch parameter"));
2628                            }
2629                        }
2630                    }
2631                    if self.eat_sym("=") {
2632                        self.record_error(String::from("Catch parameter may not have an initializer"));
2633                        let _ = self.parse_assignment_top();
2634                    }
2635                    if self.eat_sym(",") {
2636                        self.record_error(String::from("Catch clause may only have one parameter"));
2637                        while !self.is_sym(")") && !self.is_eof() {
2638                            self.bump();
2639                        }
2640                    }
2641                    catch_param = Some(p);
2642                }
2643                self.expect_sym(")");
2644            }
2645            catch_block = Some(self.parse_brace_body_no_scope());
2646            self.lex_pop();
2647            self.scope_pop();
2648        }
2649        if self.eat_kw("finally") {
2650            finally_block = Some(self.parse_brace_body());
2651        }
2652        if catch_block.is_none() && finally_block.is_none() {
2653            self.record_error(String::from("Missing catch or finally after try"));
2654        }
2655        Some(Statement::Try(Box::new(super::ast::TryStmt {
2656            block,
2657            catch_param: catch_param.map(Box::new),
2658            catch_block,
2659            finally_block,
2660        })))
2661    }
2662
2663    /// 文字列指定子(module specifier)を読む。`from "mod"` の "mod" 部分など。
2664    fn parse_module_specifier(&mut self) -> String {
2665        match self.cur().clone() {
2666            Token::Str(s) => {
2667                self.bump();
2668                s.into_string()
2669            }
2670            _ => String::new(),
2671        }
2672    }
2673
2674    /// 文脈依存キーワード(`from`/`as`)を ident として消費する。一致したら true。
2675    fn eat_contextual(&mut self, word: &str) -> bool {
2676        if matches!(self.cur(), Token::Ident(x) if &**x == word) {
2677            self.step();
2678            true
2679        } else {
2680            false
2681        }
2682    }
2683
2684    /// `{ a, b as c }` の中身を (元名, ローカル名) ペアの列として読む。
2685    fn parse_named_specifiers(&mut self) -> Vec<(String, String)> {
2686        let mut out = Vec::new();
2687        self.expect_sym("{");
2688        while !self.is_sym("}") && !self.is_eof() {
2689            let orig = self.ident_name().unwrap_or_default();
2690            let local = if self.eat_contextual("as") {
2691                self.ident_name().unwrap_or_default()
2692            } else {
2693                orig.clone()
2694            };
2695            out.push((orig, local));
2696            if !self.eat_sym(",") {
2697                break;
2698            }
2699        }
2700        self.expect_sym("}");
2701        out
2702    }
2703
2704    /// `import` 宣言。
2705    /// 形態: `import "mod"` / `import def from "mod"` /
2706    /// `import * as ns from "mod"` / `import { a, b as c } from "mod"` /
2707    /// `import def, { a } from "mod"` / `import def, * as ns from "mod"`。
2708    fn parse_import(&mut self) -> Option<Statement> {
2709        self.bump(); // import
2710        let mut default = None;
2711        let mut namespace = None;
2712        let mut named = Vec::new();
2713
2714        // 副作用のみ: import "mod";
2715        if let Token::Str(s) = self.cur().clone() {
2716            self.bump();
2717            self.eat_sym(";");
2718            return Some(Statement::Import(Box::new(ImportDecl {
2719                source: s.into_string(),
2720                default: None,
2721                namespace: None,
2722                named: Vec::new(),
2723                side_effect_only: true,
2724            })));
2725        }
2726
2727        // default インポート(識別子)。
2728        if let Token::Ident(n) = self.cur().clone() {
2729            self.bump();
2730            default = Some(n.to_string());
2731            self.eat_sym(","); // default の後に名前空間/名前付きが続く場合
2732        }
2733
2734        // 名前空間 `* as ns`。
2735        if self.eat_sym("*") {
2736            self.eat_contextual("as");
2737            namespace = self.ident_name();
2738        } else if self.is_sym("{") {
2739            // 名前付き `{ a, b as c }`。
2740            named = self.parse_named_specifiers();
2741        }
2742
2743        self.eat_contextual("from");
2744        let source = self.parse_module_specifier();
2745        self.eat_sym(";");
2746        Some(Statement::Import(Box::new(ImportDecl {
2747            source,
2748            default,
2749            namespace,
2750            named,
2751            side_effect_only: false,
2752        })))
2753    }
2754
2755    /// `export` 宣言。
2756    /// 形態: `export default <expr>` / `export { a, b as c }` /
2757    /// `export { a } from "mod"` / `export * from "mod"` /
2758    /// `export var/let/const/function/class ...`。
2759    fn parse_export(&mut self) -> Option<Statement> {
2760        self.bump(); // export
2761
2762        // export default <expr>;
2763        if self.eat_kw("default") {
2764            // default の後は関数/クラス宣言または式。
2765            let expr = if self.is_kw("function") {
2766                self.parse_function_expression(false)
2767            } else if self.is_kw("async") && self.kw_at(1, "function") {
2768                self.bump(); // async
2769                self.parse_function_expression(true)
2770            } else if self.is_kw("class") {
2771                self.parse_class(false)
2772            } else {
2773                self.parse_assignment()
2774            };
2775            self.eat_sym(";");
2776            return Some(Statement::ExportDefault(expr));
2777        }
2778
2779        // export * from "mod";
2780        if self.eat_sym("*") {
2781            // export * as ns from "mod";
2782            if self.eat_contextual("as") {
2783                let name = self.ident_name().unwrap_or_default();
2784                self.eat_contextual("from");
2785                let source = self.parse_module_specifier();
2786                self.eat_sym(";");
2787                return Some(Statement::ExportNamed {
2788                    specifiers: alloc::vec![(String::from("*"), name)],
2789                    source: Some(source),
2790                });
2791            }
2792            self.eat_contextual("from");
2793            let source = self.parse_module_specifier();
2794            self.eat_sym(";");
2795            return Some(Statement::ExportAll { source });
2796        }
2797
2798        // export { a, b as c } [from "mod"];
2799        if self.is_sym("{") {
2800            // ここでの (orig, local) は (ローカル名, 公開名) に読み替える。
2801            let specs = self.parse_named_specifiers();
2802            let source = if self.eat_contextual("from") {
2803                Some(self.parse_module_specifier())
2804            } else {
2805                None
2806            };
2807            self.eat_sym(";");
2808            return Some(Statement::ExportNamed {
2809                specifiers: specs,
2810                source,
2811            });
2812        }
2813
2814        // export var/let/const/function/class ...
2815        let names = self.export_decl_names();
2816        let declaration = self.parse_statement().unwrap_or(Statement::Empty);
2817        Some(Statement::ExportDecl {
2818            declaration: Box::new(declaration),
2819            names,
2820        })
2821    }
2822
2823    /// `export` に続く宣言から公開すべき名前を先読みで収集する(カーソルは進めない)。
2824    fn export_decl_names(&mut self) -> Vec<String> {
2825        let mut names = Vec::new();
2826        match self.cur().clone() {
2827            Token::Keyword("function") => {
2828                // function [*] name
2829                let mut off = 1;
2830                if self.sym_at(off, "*") {
2831                    off += 1;
2832                }
2833                if let Token::Ident(n) = self.at(off) {
2834                    names.push(n.to_string());
2835                }
2836            }
2837            Token::Keyword("async") => {
2838                // async function [*] name
2839                let mut off = 2;
2840                if self.sym_at(off, "*") {
2841                    off += 1;
2842                }
2843                if let Token::Ident(n) = self.at(off) {
2844                    names.push(n.to_string());
2845                }
2846            }
2847            Token::Keyword("class") => {
2848                if let Token::Ident(n) = self.at(1) {
2849                    names.push(n.to_string());
2850                }
2851            }
2852            Token::Keyword(k) if k == "var" || k == "let" || k == "const" => {
2853                // 単純な識別子束縛のみ収集(分割代入は対象外)。
2854                let mut off = 1;
2855                loop {
2856                    self.ensure_pos(self.pos + off + 1);
2857                    let Token::Ident(n) = self.at(off) else { break };
2858                    names.push(n.to_string());
2859                    // 次が `,` なら継続。`=` 等が来たら打ち切る。
2860                    if self.sym_at(off + 1, ",") {
2861                        off += 2;
2862                    } else {
2863                        break;
2864                    }
2865                }
2866            }
2867            _ => {}
2868        }
2869        names
2870    }
2871
2872    fn parse_expression_statement(&mut self) -> Option<Statement> {
2873        let e = self.parse_expression();
2874        let e = self.lex_check_const_assign(e);
2875        self.eat_sym(";");
2876        Some(Statement::Expression(e))
2877    }
2878
2879    fn parse_switch(&mut self) -> Option<Statement> {
2880        self.eat_kw("switch");
2881        self.expect_sym("(");
2882        let discriminant = self.parse_expression();
2883        self.expect_sym(")");
2884        self.expect_sym("{");
2885        self.scope_push(ScopeKind::Switch);
2886        self.lex_push(false);
2887        self.switch_depth += 1;
2888        let mut cases = Vec::new();
2889        let mut seen_default = false;
2890        while !self.is_sym("}") && !self.is_eof() {
2891            let test = if self.eat_kw("case") {
2892                let t = self.parse_expression();
2893                self.expect_sym(":");
2894                Some(t)
2895            } else if self.eat_kw("default") {
2896                if seen_default {
2897                    self.record_error(String::from("More than one default clause in switch statement"));
2898                }
2899                seen_default = true;
2900                self.expect_sym(":");
2901                None
2902            } else {
2903                // 想定外トークンはスキップして無限ループを避ける。
2904                self.record_error(alloc::format!("unexpected {} in switch statement", describe_token(self.cur())));
2905                self.bump();
2906                continue;
2907            };
2908            // 次の case/default/} までを本体として収集。
2909            let mut body = Vec::new();
2910            while !self.is_kw("case")
2911                && !self.is_kw("default")
2912                && !self.is_sym("}")
2913                && !self.is_eof()
2914            {
2915                let before = self.pos;
2916                // `using`/`await using` は case・default 節の文の並びに直接置けない。
2917                if (self.ident_at(0, "using") && self.is_using_decl_start(0))
2918                    || (self.is_kw("await") && self.ident_at(1, "using") && !self.nl_before_at(1) && self.is_using_decl_start(1))
2919                {
2920                    self.record_error(String::from("Using declaration cannot appear directly in a case or default clause"));
2921                }
2922                if let Some(s) = self.parse_statement() {
2923                    self.lex_note_stmt(&s);
2924                    body.push(s);
2925                }
2926                if self.pos == before {
2927                    self.step();
2928                }
2929            }
2930            cases.push(crate::os_lib::ecma::ast::SwitchCase { test, body });
2931        }
2932        self.switch_depth -= 1;
2933        self.lex_pop();
2934        self.scope_pop();
2935        self.expect_sym("}");
2936        Some(Statement::Switch {
2937            discriminant: Box::new(discriminant),
2938            cases,
2939        })
2940    }
2941
2942    fn parse_param_list(&mut self) -> Vec<Param> {
2943        let mut params = Vec::new();
2944        if self.eat_sym("(") {
2945            while !self.is_sym(")") && !self.is_eof() {
2946                let is_rest = self.eat_sym("...");
2947                let pattern = self.parse_pattern();
2948                let default = if self.eat_sym("=") {
2949                    if is_rest {
2950                        self.record_error(String::from("Rest parameter may not have a default initializer"));
2951                    }
2952                    Some(self.parse_assignment_top())
2953                } else {
2954                    None
2955                };
2956                params.push(Param {
2957                    pattern,
2958                    default: default.map(Box::new),
2959                    is_rest,
2960                });
2961                let had_comma = self.eat_sym(",");
2962                if is_rest {
2963                    if had_comma {
2964                        self.record_error(String::from("Rest parameter must be last formal parameter"));
2965                    }
2966                    break;
2967                }
2968                if !had_comma {
2969                    break;
2970                }
2971            }
2972            self.expect_sym(")");
2973        }
2974        params
2975    }
2976
2977    /// 束縛パターンをパース(識別子 / `{...}` / `[...]`)。
2978    fn parse_pattern(&mut self) -> Pattern {
2979        if self.is_sym("{") {
2980            return self.parse_object_pattern();
2981        }
2982        if self.is_sym("[") {
2983            return self.parse_array_pattern();
2984        }
2985        let name = self.consume_binding_ident("binding pattern", false);
2986        Pattern::Identifier(name)
2987    }
2988
2989    fn parse_object_pattern(&mut self) -> Pattern {
2990        self.expect_sym("{");
2991        let mut props = Vec::new();
2992        while !self.is_sym("}") && !self.is_eof() {
2993            if self.eat_sym("...") {
2994                let target = self.parse_pattern();
2995                if !matches!(target, Pattern::Identifier(_)) {
2996                    self.record_error(String::from("Rest element in object binding pattern must be a simple identifier"));
2997                }
2998                if self.eat_sym("=") {
2999                    self.record_error(String::from("Rest element may not have a default initializer"));
3000                    let _ = self.parse_assignment_top();
3001                }
3002                if self.eat_sym(",") {
3003                    self.record_error(String::from("Rest element must be last element"));
3004                }
3005                props.push(ObjPatProp {
3006                    key: self.intern(""),
3007                    computed_key: None,
3008                    value: target,
3009                    default: None,
3010                    is_rest: true,
3011                });
3012                break; // rest は最後。
3013            }
3014            let (key, computed_key, is_ident_shorthand_ok) = if self.eat_sym("[") {
3015                let ce = self.parse_assignment_top();
3016                self.expect_sym("]");
3017                (self.intern(""), Some(ce), false)
3018            } else {
3019                match self.cur().clone() {
3020                    Token::Ident(n) => {
3021                        if n.starts_with('#') {
3022                            self.record_error(alloc::format!("Private name '{}' is not allowed in object pattern", n));
3023                        }
3024                        self.bump();
3025                        (self.intern(&n), None, true)
3026                    }
3027                    Token::Keyword(n) => {
3028                        self.bump();
3029                        let ok = matches!(n, "async" | "of" | "undefined" | "let" | "await" | "yield");
3030                        (self.intern(n), None, ok)
3031                    }
3032                    Token::Str(s) => {
3033                        self.bump();
3034                        (self.intern(&s), None, false)
3035                    }
3036                    Token::Num(n) => {
3037                        self.bump();
3038                        let s = super::value::fmt_number(n);
3039                        (self.intern(&s), None, false)
3040                    }
3041                    Token::BigIntLit(b) => {
3042                        self.bump();
3043                        (self.bigint_key(&b), None, false)
3044                    }
3045                    other => {
3046                        self.record_error(alloc::format!("unexpected {} in object pattern", describe_token(&other)));
3047                        break;
3048                    }
3049                }
3050            };
3051            let value = if self.eat_sym(":") {
3052                self.parse_pattern()
3053            } else {
3054                if !is_ident_shorthand_ok {
3055                    self.record_error(String::from("Expected ':' after property name in object pattern"));
3056                } else {
3057                    self.check_ident_allowed(&key, true);
3058                }
3059                Pattern::Identifier(key.clone())
3060            };
3061            let default = if self.eat_sym("=") {
3062                Some(self.parse_assignment_top())
3063            } else {
3064                None
3065            };
3066            props.push(ObjPatProp {
3067                key,
3068                computed_key,
3069                value,
3070                default,
3071                is_rest: false,
3072            });
3073            if !self.eat_sym(",") {
3074                break;
3075            }
3076        }
3077        self.expect_sym("}");
3078        Pattern::Object(props)
3079    }
3080
3081    fn parse_array_pattern(&mut self) -> Pattern {
3082        self.expect_sym("[");
3083        let mut elems = Vec::new();
3084        while !self.is_sym("]") && !self.is_eof() {
3085            if self.is_sym(",") {
3086                // 穴 [a, , b]
3087                elems.push(ArrPatElem {
3088                    pattern: None,
3089                    default: None,
3090                    is_rest: false,
3091                });
3092                self.bump();
3093                continue;
3094            }
3095            let is_rest = self.eat_sym("...");
3096            let pat = self.parse_pattern();
3097            let default = if self.eat_sym("=") {
3098                if is_rest {
3099                    self.record_error(String::from("Rest element may not have a default initializer"));
3100                }
3101                Some(self.parse_assignment_top())
3102            } else {
3103                None
3104            };
3105            elems.push(ArrPatElem {
3106                pattern: Some(pat),
3107                default,
3108                is_rest,
3109            });
3110            let had_comma = self.eat_sym(",");
3111            if is_rest {
3112                if had_comma {
3113                    self.record_error(String::from("Rest element may not have a trailing comma"));
3114                }
3115                break;
3116            }
3117            if !had_comma {
3118                break;
3119            }
3120        }
3121        self.expect_sym("]");
3122        Pattern::Array(elems)
3123    }
3124
3125    // --- 式 ---
3126    pub fn parse_expression(&mut self) -> Expression {
3127        let first = self.parse_assignment_top();
3128        if !self.is_sym(",") {
3129            return first;
3130        }
3131        // カンマ演算子
3132        self.last_expr_was_paren = false;
3133        let mut items = alloc::vec![first];
3134        while self.eat_sym(",") {
3135            items.push(self.parse_assignment_top());
3136        }
3137        Expression::Sequence(items)
3138    }
3139
3140    /// 括弧/配列/オブジェクトリテラルの外側の通常代入式境界。
3141    /// カバー文法の `{ x = 1 }` (CoverInitializedName) や `__proto__` 重複が残っていれば構文エラーにする。
3142    fn parse_assignment_top(&mut self) -> Expression {
3143        let cov_before = self.pending_cover_inits;
3144        let dup_proto_before = self.pending_dup_protos;
3145        let spread_before = self.pending_spread_trailing_commas;
3146        let paren_destr_before = self.pending_paren_destr_targets;
3147        let expr = self.parse_assignment();
3148        if self.pending_cover_inits > cov_before {
3149            self.record_error(String::from("Invalid shorthand property initializer"));
3150            self.pending_cover_inits = cov_before;
3151        }
3152        if self.pending_dup_protos > dup_proto_before {
3153            self.record_error(String::from("Duplicate __proto__ fields are not allowed in object literals"));
3154            self.pending_dup_protos = dup_proto_before;
3155        }
3156        self.pending_spread_trailing_commas = spread_before;
3157        self.pending_paren_destr_targets = paren_destr_before;
3158        expr
3159    }
3160
3161    fn parse_assignment(&mut self) -> Expression {
3162        // yield / yield* (generator 内、または遅延展開中の本体、assignment レベル)。
3163        if self.is_kw("yield") && (self.in_generator || self.in_lazy_expanded_body) {
3164            if self.in_param {
3165                self.record_error(String::from("Yield expression is not allowed in parameter default"));
3166            }
3167            self.bump();
3168            let delegate = self.is_sym("*") && !self.nl_before_cur();
3169            if delegate {
3170                self.bump();
3171            }
3172            // 引数なし yield(`yield;` / `yield)` / `yield\n` 等)を許容。
3173            let argument = if delegate {
3174                Some(Box::new(self.parse_assignment_top()))
3175            } else if self.nl_before_cur()
3176                || self.is_sym(";")
3177                || self.is_sym(")")
3178                || self.is_sym("]")
3179                || self.is_sym("}")
3180                || self.is_sym(",")
3181                || self.is_sym(":")
3182                || self.is_kw("in")
3183                || self.is_eof()
3184            {
3185                None
3186            } else {
3187                Some(Box::new(self.parse_assignment_top()))
3188            };
3189            self.last_expr_was_paren = false;
3190            return Expression::Yield { argument, delegate };
3191        }
3192        // 単一識別子のアロー関数(x => ... / async x => ...)を 1〜2 トークン先読みで判定。
3193        if let Some(arrow) = self.try_parse_single_ident_arrow() {
3194            self.last_expr_was_paren = false;
3195            return arrow;
3196        }
3197        let cov_before = self.pending_cover_inits;
3198        let dup_proto_before = self.pending_dup_protos;
3199        let spread_before = self.pending_spread_trailing_commas;
3200        let paren_destr_before = self.pending_paren_destr_targets;
3201        let left = self.parse_conditional();
3202        let left_was_paren = self.last_expr_was_paren;
3203        if let Token::Sym(op) = self.cur().clone() {
3204            if is_assign_op(op) {
3205                let is_eq = op == "=";
3206                let is_logical = matches!(op, "&&=" | "||=" | "??=");
3207                let cover_consumed = is_eq
3208                    && !left_was_paren
3209                    && matches!(left, Expression::Array(_) | Expression::Object(_));
3210                if cover_consumed {
3211                    self.pending_cover_inits = cov_before;
3212                    self.pending_dup_protos = dup_proto_before;
3213                } else {
3214                    if self.pending_cover_inits > cov_before {
3215                        self.record_error(String::from("Invalid shorthand property initializer"));
3216                        self.pending_cover_inits = cov_before;
3217                    }
3218                    if self.pending_dup_protos > dup_proto_before {
3219                        self.record_error(String::from("Duplicate __proto__ fields are not allowed in object literals"));
3220                        self.pending_dup_protos = dup_proto_before;
3221                    }
3222                }
3223                self.validate_assignment_target(
3224                    &left,
3225                    is_eq,
3226                    is_logical,
3227                    left_was_paren,
3228                    self.pending_spread_trailing_commas > spread_before,
3229                    self.pending_paren_destr_targets > paren_destr_before,
3230                );
3231                self.pending_spread_trailing_commas = spread_before;
3232                self.pending_paren_destr_targets = paren_destr_before;
3233                self.bump();
3234                let value = self.parse_assignment_top();
3235                self.last_expr_was_paren = false;
3236                if cover_consumed {
3237                    let left = self.lex_guard_const_target(left);
3238                    return Expression::Assign { op, target: Box::new(left), value: Box::new(value) };
3239                }
3240                if let Expression::Identifier(n) = &left {
3241                    if !left_was_paren && !is_logical && self.scope_is_const(n) {
3242                        // `const` への代入: 右辺を評価してから TypeError。
3243                        let thrower = self.const_thrower();
3244                        return Expression::Sequence(alloc::vec![value, thrower]);
3245                    }
3246                }
3247                return Expression::Assign {
3248                    op,
3249                    target: Box::new(left),
3250                    value: Box::new(value),
3251                };
3252            }
3253        }
3254        self.last_expr_was_paren = left_was_paren;
3255        left
3256    }
3257
3258    /// 単一識別子アロー関数(`x => ...` または `async x => ...`)。
3259    /// カッコ不要の形式であり、1〜2 トークン先読みのみで確定できる(バックトラックなし)。
3260    fn try_parse_single_ident_arrow(&mut self) -> Option<Expression> {
3261        let single_name = match self.cur() {
3262            Token::Ident(n) => Some(n.to_string()),
3263            Token::Keyword(k) if matches!(*k, "async" | "of" | "undefined" | "let" | "await" | "yield") => {
3264                Some(String::from(*k))
3265            }
3266            _ => None,
3267        };
3268        if let Some(name) = single_name {
3269            if self.sym_at(1, "=>") && !self.nl_before_at(1) {
3270                let src_start = self.token_start_opt(self.pos);
3271                self.bump(); // ident
3272                self.bump(); // =>
3273                self.check_ident_allowed(&name, true);
3274                let param_name = self.intern(&name);
3275                let params = alloc::vec![Param {
3276                    pattern: Pattern::Identifier(param_name),
3277                    default: None,
3278                    is_rest: false,
3279                }];
3280                let body = self.parse_arrow_body_ctx(src_start, false, &params);
3281                return Some(Expression::Function {
3282                    name: None,
3283                    params: Rc::new(params),
3284                    body,
3285                    is_arrow: true,
3286                    is_async: false,
3287                    is_generator: false,
3288                });
3289            }
3290        }
3291        // async x => ...
3292        if self.is_kw("async") && !self.kw_at(1, "function") && !self.nl_before_at(1) {
3293            let arg_name = match self.at(1) {
3294                Token::Ident(n) => Some(n.to_string()),
3295                Token::Keyword(k) if matches!(*k, "async" | "of" | "undefined" | "let" | "await" | "yield") => {
3296                    Some(String::from(*k))
3297                }
3298                _ => None,
3299            };
3300            if let Some(name) = arg_name {
3301                if self.sym_at(2, "=>") && !self.nl_before_at(2) {
3302                    let src_start = self.token_start_opt(self.pos);
3303                    self.bump(); // async
3304                    self.bump(); // ident
3305                    self.bump(); // =>
3306                    let saved_async = core::mem::replace(&mut self.in_async, true);
3307                    let saved_gen = core::mem::replace(&mut self.in_generator, false);
3308                    self.check_ident_allowed(&name, true);
3309                    let param_name = self.intern(&name);
3310                    let params = alloc::vec![Param {
3311                        pattern: Pattern::Identifier(param_name),
3312                        default: None,
3313                        is_rest: false,
3314                    }];
3315                    self.in_async = saved_async;
3316                    self.in_generator = saved_gen;
3317                    let body = self.parse_arrow_body_ctx(src_start, true, &params);
3318                    return Some(Expression::Function {
3319                        name: None,
3320                        params: Rc::new(params),
3321                        body,
3322                        is_arrow: true,
3323                        is_async: true,
3324                        is_generator: false,
3325                    });
3326                }
3327            }
3328        }
3329        None
3330    }
3331
3332    /// カッコ付き式またはアロー関数引数リストのカバー文法(Cover Grammar)。
3333    fn parse_cover_paren_or_arrow(&mut self, is_async: bool) -> Expression {
3334        let src_start = self.fn_source_start(is_async);
3335        self.expect_sym("(");
3336        let cov_before = self.pending_cover_inits;
3337        let dup_proto_before = self.pending_dup_protos;
3338        let spread_before = self.pending_spread_trailing_commas;
3339        let paren_destr_before = self.pending_paren_destr_targets;
3340        let mut items = Vec::new();
3341        let mut saw_trailing_comma = false;
3342        let mut bad_rest_comma = false;
3343        let mut bad_rest_default = false;
3344        if !self.is_sym(")") && !self.is_eof() {
3345            loop {
3346                if self.eat_sym("...") {
3347                    let pat = self.parse_pattern();
3348                    if self.eat_sym("=") {
3349                        bad_rest_default = true;
3350                        let _ = self.parse_assignment_top();
3351                    }
3352                    items.push(CoverItem::Rest(pat));
3353                    if self.eat_sym(",") {
3354                        bad_rest_comma = true;
3355                    }
3356                    break; // rest はパラメータの最後
3357                } else {
3358                    let expr = self.parse_assignment();
3359                    items.push(CoverItem::Expr(expr));
3360                    if !self.eat_sym(",") {
3361                        break;
3362                    }
3363                    if self.is_sym(")") {
3364                        saw_trailing_comma = true;
3365                        break;
3366                    }
3367                }
3368            }
3369        }
3370        self.expect_sym(")");
3371
3372        if self.is_sym("=>") {
3373            if self.nl_before_cur() {
3374                self.record_error(String::from("Illegal newline before '=>'"));
3375            }
3376            self.bump(); // =>
3377            if bad_rest_default {
3378                self.record_error(String::from("Rest parameter may not have a default initializer"));
3379            }
3380            if bad_rest_comma {
3381                self.record_error(String::from("Rest parameter must be last formal parameter"));
3382            }
3383            if self.pending_spread_trailing_commas > spread_before {
3384                self.record_error(String::from("Rest element may not have a trailing comma"));
3385            }
3386            if self.pending_paren_destr_targets > paren_destr_before {
3387                self.record_error(String::from("Invalid destructuring assignment target"));
3388            }
3389            self.pending_cover_inits = cov_before;
3390            self.pending_dup_protos = dup_proto_before;
3391            self.pending_spread_trailing_commas = spread_before;
3392            self.pending_paren_destr_targets = paren_destr_before;
3393
3394            let saved_async = core::mem::replace(&mut self.in_async, is_async);
3395            let saved_gen = core::mem::replace(&mut self.in_generator, false);
3396            let mut params = Vec::new();
3397            for item in items {
3398                match item {
3399                    CoverItem::Rest(pattern) => {
3400                        let mut pnames = Vec::new();
3401                        Self::collect_pattern_names(&pattern, &mut pnames);
3402                        for n in pnames {
3403                            self.check_ident_allowed(n, true);
3404                        }
3405                        params.push(Param {
3406                            pattern,
3407                            default: None,
3408                            is_rest: true,
3409                        });
3410                    }
3411                    CoverItem::Expr(expr) => {
3412                        match self.cover_expr_to_param(expr) {
3413                            Ok(param) => params.push(param),
3414                            Err(msg) => self.record_error(msg),
3415                        }
3416                    }
3417                }
3418            }
3419            self.check_params(&params, true);
3420            if is_async {
3421                for p in &params {
3422                    if let Some(def) = &p.default {
3423                        if expr_uses_await(def) {
3424                            self.record_error(String::from("'await' is not allowed in async arrow parameter default"));
3425                        }
3426                    }
3427                }
3428            }
3429            self.in_async = saved_async;
3430            self.in_generator = saved_gen;
3431            let body = self.parse_arrow_body_ctx(src_start, is_async, &params);
3432            self.last_expr_was_paren = false;
3433            return Expression::Function {
3434                name: None,
3435                params: Rc::new(params),
3436                body,
3437                is_arrow: true,
3438                is_async,
3439                is_generator: false,
3440            };
3441        }
3442
3443        // アロー関数ではなかった場合
3444        if self.pending_cover_inits > cov_before {
3445            self.record_error(String::from("Invalid shorthand property initializer"));
3446            self.pending_cover_inits = cov_before;
3447        }
3448        if self.pending_dup_protos > dup_proto_before {
3449            self.record_error(String::from("Duplicate __proto__ fields are not allowed in object literals"));
3450            self.pending_dup_protos = dup_proto_before;
3451        }
3452        self.pending_spread_trailing_commas = spread_before;
3453        if is_async {
3454            // async(...) 関数呼び出し(末尾カンマ ES2017 で可、ただし rest の後を除くが `...x,` も引数末尾カンマは実は合法!)
3455            if bad_rest_default {
3456                self.record_error(String::from("unexpected '=' in spread argument"));
3457            }
3458            let mut args = Vec::new();
3459            for item in items {
3460                match item {
3461                    CoverItem::Rest(p) => {
3462                        // async(...x) のように展開引数として再解釈できる範囲で扱うか、単一識別子なら Spread に変換
3463                        match p {
3464                            Pattern::Identifier(n) => args.push(Expression::Spread(Box::new(Expression::Identifier(n)))),
3465                            _ => self.record_error(String::from("unexpected '...' in call arguments")),
3466                        }
3467                    }
3468                    CoverItem::Expr(e) => args.push(e),
3469                }
3470            }
3471            self.last_expr_was_paren = false;
3472            Expression::Call {
3473                callee: Box::new(Expression::Identifier(self.intern("async"))),
3474                arguments: args,
3475                optional: false,
3476            }
3477        } else {
3478            // 通常の括弧式
3479            if saw_trailing_comma || bad_rest_comma {
3480                self.record_error(String::from("unexpected token ',' in parenthesized expression"));
3481            }
3482            if items.is_empty() {
3483                self.record_error(String::from("unexpected token ')'"));
3484                self.last_expr_was_paren = false;
3485                return Expression::Undefined;
3486            }
3487            let mut exprs = Vec::new();
3488            for item in items {
3489                match item {
3490                    CoverItem::Rest(_) => {
3491                        self.record_error(String::from("unexpected '...' in parenthesized expression"));
3492                    }
3493                    CoverItem::Expr(e) => exprs.push(e),
3494                }
3495            }
3496            self.last_expr_was_paren = true;
3497            if exprs.len() == 1 {
3498                let inner = exprs.pop().unwrap_or(Expression::Undefined);
3499                if matches!(inner, Expression::Array(_) | Expression::Object(_)) {
3500                    self.pending_paren_destr_targets += 1;
3501                }
3502                inner
3503            } else {
3504                Expression::Sequence(exprs)
3505            }
3506        }
3507    }
3508
3509    fn cover_expr_to_param(&mut self, expr: Expression) -> Result<Param, alloc::string::String> {
3510        match expr {
3511            Expression::Identifier(name) => {
3512                self.check_ident_allowed(&name, true);
3513                Ok(Param {
3514                    pattern: Pattern::Identifier(name),
3515                    default: None,
3516                    is_rest: false,
3517                })
3518            }
3519            Expression::Assign { op: "=", target, value } => {
3520                let pattern = self.cover_expr_to_pattern(*target)?;
3521                Ok(Param {
3522                    pattern,
3523                    default: Some(value),
3524                    is_rest: false,
3525                })
3526            }
3527            Expression::Object(props) => {
3528                let pattern = self.cover_object_to_pattern(props)?;
3529                Ok(Param {
3530                    pattern,
3531                    default: None,
3532                    is_rest: false,
3533                })
3534            }
3535            Expression::Array(exprs) => {
3536                let pattern = self.cover_array_to_pattern(exprs)?;
3537                Ok(Param {
3538                    pattern,
3539                    default: None,
3540                    is_rest: false,
3541                })
3542            }
3543            _ => Err("invalid arrow parameter".to_string()),
3544        }
3545    }
3546
3547    fn cover_expr_to_pattern(&mut self, expr: Expression) -> Result<Pattern, alloc::string::String> {
3548        match expr {
3549            Expression::Identifier(name) => {
3550                self.check_ident_allowed(&name, true);
3551                Ok(Pattern::Identifier(name))
3552            }
3553            Expression::Object(props) => self.cover_object_to_pattern(props),
3554            Expression::Array(exprs) => self.cover_array_to_pattern(exprs),
3555            _ => Err("invalid pattern in arrow parameters".to_string()),
3556        }
3557    }
3558
3559    fn cover_object_to_pattern(&mut self, props: Vec<Property>) -> Result<Pattern, alloc::string::String> {
3560        let len = props.len();
3561        let mut out = Vec::new();
3562        for (idx, p) in props.into_iter().enumerate() {
3563            let is_spread = &*p.key == crate::os_lib::ecma::ast::OBJECT_SPREAD_KEY;
3564            if is_spread {
3565                if idx + 1 != len {
3566                    return Err("Rest element must be last element".to_string());
3567                }
3568                let pat = match p.value {
3569                    Expression::Identifier(name) => {
3570                        self.check_ident_allowed(&name, true);
3571                        Pattern::Identifier(name)
3572                    }
3573                    _ => return Err("Rest element in object pattern must be an identifier".to_string()),
3574                };
3575                out.push(ObjPatProp {
3576                    key: self.intern(""),
3577                    computed_key: None,
3578                    value: pat,
3579                    default: None,
3580                    is_rest: true,
3581                });
3582            } else {
3583                if p.accessor.is_some() || matches!(p.value, Expression::Function { .. }) {
3584                    return Err("Invalid destructuring pattern element".to_string());
3585                }
3586                let (value_pat, default) = match p.value {
3587                    Expression::Assign { op: "=", target, value } => {
3588                        let pat = self.cover_expr_to_pattern(*target)?;
3589                        (pat, Some(*value))
3590                    }
3591                    other => (self.cover_expr_to_pattern(other)?, None),
3592                };
3593                out.push(ObjPatProp {
3594                    key: p.key,
3595                    computed_key: p.computed,
3596                    value: value_pat,
3597                    default,
3598                    is_rest: false,
3599                });
3600            }
3601        }
3602        Ok(Pattern::Object(out))
3603    }
3604
3605    fn cover_array_to_pattern(&mut self, exprs: Vec<Expression>) -> Result<Pattern, alloc::string::String> {
3606        let len = exprs.len();
3607        let mut out = Vec::new();
3608        for (idx, expr) in exprs.into_iter().enumerate() {
3609            match expr {
3610                Expression::Elision => out.push(ArrPatElem { pattern: None, default: None, is_rest: false }),
3611                Expression::Spread(inner) => {
3612                    if idx + 1 != len {
3613                        return Err("Rest element must be last element".to_string());
3614                    }
3615                    if matches!(&*inner, Expression::Assign { .. }) {
3616                        return Err("Rest element may not have a default initializer".to_string());
3617                    }
3618                    let pat = self.cover_expr_to_pattern(*inner)?;
3619                    out.push(ArrPatElem {
3620                        pattern: Some(pat),
3621                        default: None,
3622                        is_rest: true,
3623                    });
3624                }
3625                Expression::Assign { op: "=", target, value } => {
3626                    let pat = self.cover_expr_to_pattern(*target)?;
3627                    out.push(ArrPatElem {
3628                        pattern: Some(pat),
3629                        default: Some(*value),
3630                        is_rest: false,
3631                    });
3632                }
3633                other => {
3634                    let pat = self.cover_expr_to_pattern(other)?;
3635                    out.push(ArrPatElem {
3636                        pattern: Some(pat),
3637                        default: None,
3638                        is_rest: false,
3639                    });
3640                }
3641            }
3642        }
3643        Ok(Pattern::Array(out))
3644    }
3645
3646    fn parse_arrow_body_ctx(&mut self, src_start: Option<u32>, is_async: bool, params: &[Param]) -> Rc<FnBody> {
3647        let saved_async = core::mem::replace(&mut self.in_async, is_async);
3648        let saved_gen = core::mem::replace(&mut self.in_generator, false);
3649        let non_simple = has_non_simple_params(params);
3650        let body = if self.is_sym("{") {
3651            self.scope_push(ScopeKind::Function);
3652            for p in params {
3653                self.declare_pattern_bindings(&p.pattern, BindingKind::Param);
3654            }
3655            self.arrow_body = true;
3656            let b = self.parse_fn_body_with(non_simple);
3657            self.arrow_body = false;
3658            self.scope_pop();
3659            b
3660        } else {
3661            let saved_loop = core::mem::replace(&mut self.loop_depth, 0);
3662            let saved_switch = core::mem::replace(&mut self.switch_depth, 0);
3663            let saved_labels = core::mem::take(&mut self.labels);
3664            let saved_field = self.in_field_init;
3665            let saved_static_blk = core::mem::replace(&mut self.in_static_block, false);
3666            let saved_param = core::mem::replace(&mut self.in_param, false);
3667            self.in_function += 1;
3668            let e = self.parse_assignment_top();
3669            let eval_ctx = self.current_eval_ctx();
3670            self.in_function -= 1;
3671            self.in_param = saved_param;
3672            self.in_static_block = saved_static_blk;
3673            self.in_field_init = saved_field;
3674            self.labels = saved_labels;
3675            self.switch_depth = saved_switch;
3676            self.loop_depth = saved_loop;
3677            self.last_body_end = self.token_start_opt(self.pos).and_then(|st| {
3678                let from = src_start? as usize;
3679                let text = self.lexer.src_rc().get(from..st as usize)?;
3680                Some((from + text.trim_end().len()) as u32)
3681            });
3682            let fb = FnBody::parsed_with(alloc::vec![Statement::Return(Some(e))], self.strict);
3683            fb.set_eval_ctx(eval_ctx);
3684            fb
3685        };
3686        self.in_generator = saved_gen;
3687        self.in_async = saved_async;
3688        self.record_fn_source(&body, src_start);
3689        body
3690    }
3691
3692    fn parse_conditional(&mut self) -> Expression {
3693        let test = self.parse_binary(0);
3694        if self.eat_sym("?") {
3695            let consequent = self.parse_assignment_top();
3696            self.expect_sym(":");
3697            let alternate = self.parse_assignment_top();
3698            self.last_expr_was_paren = false;
3699            return Expression::Conditional {
3700                test: Box::new(test),
3701                consequent: Box::new(consequent),
3702                alternate: Box::new(alternate),
3703            };
3704        }
3705        test
3706    }
3707
3708    fn parse_binary(&mut self, min_prec: u8) -> Expression {
3709        // ES2022 `#priv in obj` (RelationalExpression)
3710        if min_prec <= 8 {
3711            if let Token::Ident(priv_name) = self.cur().clone() {
3712                if priv_name.starts_with('#') && self.kw_at(1, "in") {
3713                    self.check_private_declared(&priv_name);
3714                    self.bump(); // #priv
3715                    self.bump(); // in
3716                    let right = self.parse_binary(9);
3717                    self.last_expr_was_paren = false;
3718                    let mut left = Expression::Binary {
3719                        op: BinaryOp::In,
3720                        left: Box::new(Expression::Identifier(priv_name)),
3721                        right: Box::new(right),
3722                    };
3723                    while let Some(op) = self.current_binop_str() {
3724                        let prec = match bin_prec(&op) {
3725                            Some(p) => p,
3726                            None => break,
3727                        };
3728                        if prec < min_prec {
3729                            break;
3730                        }
3731                        self.bump();
3732                        let next_min = if is_right_assoc(&op) { prec } else { prec + 1 };
3733                        let right = self.parse_binary(next_min);
3734                        left = if let Some(lop) = to_logical(&op) {
3735                            Expression::Logical {
3736                                op: lop,
3737                                left: Box::new(left),
3738                                right: Box::new(right),
3739                            }
3740                        } else if let Some(bop) = to_binop(&op) {
3741                            Expression::Binary {
3742                                op: bop,
3743                                left: Box::new(left),
3744                                right: Box::new(right),
3745                            }
3746                        } else {
3747                            left
3748                        };
3749                    }
3750                    self.bin_top_logical = 0;
3751                    return left;
3752                }
3753            }
3754        }
3755        // 【2026-11-17】`-x ** y`・`typeof x ** y` は仕様上の構文エラー(括弧なしの単項式は `**` の左に置けない)。
3756        let starts_unary = matches!(self.cur(), Token::Sym("-" | "+" | "!" | "~"))
3757            || matches!(self.cur(), Token::Keyword("typeof" | "void" | "delete"))
3758            || (self.is_kw("await") && (self.in_async || self.in_static_block || self.in_lazy_expanded_body));
3759        let mut left = self.parse_unary();
3760        let mut first = true;
3761        let mut left_logical = 0u8;
3762        while let Some(op) = self.current_binop_str() {
3763            let prec = match bin_prec(&op) {
3764                Some(p) => p,
3765                None => break,
3766            };
3767            if prec < min_prec {
3768                break;
3769            }
3770            if first && starts_unary && op == "**" {
3771                self.record_error(String::from("Unary operator used immediately before exponentiation expression"));
3772            }
3773            first = false;
3774            self.last_expr_was_paren = false;
3775            self.bump(); // operator
3776            let next_min = if is_right_assoc(&op) { prec } else { prec + 1 };
3777            let right = self.parse_binary(next_min);
3778            let this_logical = match op.as_str() {
3779                "??" => 1u8,
3780                "||" | "&&" => 2,
3781                _ => 0,
3782            };
3783            let right_logical = self.bin_top_logical;
3784            if this_logical != 0
3785                && ((left_logical != 0 && left_logical != this_logical)
3786                    || (right_logical != 0 && right_logical != this_logical))
3787            {
3788                self.record_error(String::from("Cannot mix '??' with '||' or '&&' without parentheses"));
3789            }
3790            left_logical = this_logical;
3791            left = if let Some(lop) = to_logical(&op) {
3792                Expression::Logical {
3793                    op: lop,
3794                    left: Box::new(left),
3795                    right: Box::new(right),
3796                }
3797            } else if let Some(bop) = to_binop(&op) {
3798                Expression::Binary {
3799                    op: bop,
3800                    left: Box::new(left),
3801                    right: Box::new(right),
3802                }
3803            } else {
3804                left
3805            };
3806        }
3807        self.bin_top_logical = left_logical;
3808        left
3809    }
3810
3811    /// 現在のトークンが二項演算子なら、その文字列を返す(`instanceof`/`in` 含む)。
3812    fn current_binop_str(&self) -> Option<String> {
3813        match self.cur() {
3814            Token::Sym(s) if bin_prec(s).is_some() => Some(String::from(*s)),
3815            Token::Keyword(k) if *k == "instanceof" || *k == "in" => Some(String::from(*k)),
3816            _ => None,
3817        }
3818    }
3819
3820    fn parse_unary(&mut self) -> Expression {
3821        // 前置演算子
3822        if let Token::Sym(s) = self.cur().clone() {
3823            let uop = match s {
3824                "!" => Some(UnaryOp::Not),
3825                "-" => Some(UnaryOp::Neg),
3826                "+" => Some(UnaryOp::Pos),
3827                "~" => Some(UnaryOp::BitNot),
3828                _ => None,
3829            };
3830            if let Some(op) = uop {
3831                self.bump();
3832                let expr = self.parse_unary();
3833                self.last_expr_was_paren = false;
3834                return Expression::Unary {
3835                    op,
3836                    expr: Box::new(expr),
3837                };
3838            }
3839            if s == "++" || s == "--" {
3840                self.bump();
3841                let target = self.parse_unary();
3842                let target_was_paren = self.last_expr_was_paren;
3843                self.validate_assignment_target(&target, false, false, target_was_paren, false, false);
3844                self.last_expr_was_paren = false;
3845                return Expression::Update {
3846                    op: s,
3847                    prefix: true,
3848                    target: Box::new(target),
3849                };
3850            }
3851        }
3852        if let Token::Keyword(k) = self.cur().clone() {
3853            let uop = match k {
3854                "typeof" => Some(UnaryOp::TypeOf),
3855                "void" => Some(UnaryOp::Void),
3856                "delete" => Some(UnaryOp::Delete),
3857                _ => None,
3858            };
3859            if let Some(op) = uop {
3860                self.bump();
3861                let expr = self.parse_unary();
3862                if op == UnaryOp::Delete {
3863                    if self.strict && matches!(expr, Expression::Identifier(_)) {
3864                        self.record_error(String::from("Delete of an unqualified identifier in strict mode"));
3865                    }
3866                    if let Expression::Member { ref property, .. } = expr {
3867                        if property.starts_with('#') {
3868                            self.record_error(String::from("Private fields can not be deleted"));
3869                        }
3870                    }
3871                }
3872                self.last_expr_was_paren = false;
3873                return Expression::Unary {
3874                    op,
3875                    expr: Box::new(expr),
3876                };
3877            }
3878            if k == "await" && (self.in_async || self.in_static_block || self.in_lazy_expanded_body) {
3879                if self.in_param {
3880                    self.record_error(String::from("Await expression is not allowed in parameter default"));
3881                }
3882                if self.in_static_block {
3883                    self.record_error(String::from("'await' is not allowed in class static block"));
3884                }
3885                self.bump();
3886                let expr = self.parse_unary();
3887                self.last_expr_was_paren = false;
3888                return Expression::Await(Box::new(expr));
3889            }
3890            if k == "new" {
3891                return self.parse_new();
3892            }
3893        }
3894        self.parse_postfix()
3895    }
3896
3897    fn parse_new(&mut self) -> Expression {
3898        self.bump(); // new
3899        // `new.target`(MetaProperty)。
3900        if self.is_sym(".") && self.ident_at(1, "target") {
3901            self.bump(); // .
3902            self.bump(); // target
3903            if self.in_function == 0 && !self.eval_in_function && !self.in_field_init && !self.in_static_block && !self.in_lazy_expanded_body {
3904                self.record_top_level_only_error(String::from("new.target expression is not allowed here"));
3905            }
3906            return self.parse_call_member_tail(Expression::NewTarget, true);
3907        }
3908        if self.is_kw("import")
3909            && (self.sym_at(1, "(") || (self.sym_at(1, ".") && (self.ident_at(2, "defer") || self.ident_at(2, "source"))))
3910        {
3911            self.record_error(String::from("Cannot use new with import()"));
3912        }
3913        // callee は呼出を含まないメンバ式。
3914        let callee = self.parse_call_member(false);
3915        let arguments = if self.is_sym("(") {
3916            self.parse_arguments()
3917        } else {
3918            Vec::new()
3919        };
3920        let new_expr = Expression::New {
3921            callee: Box::new(callee),
3922            arguments,
3923        };
3924        self.last_expr_was_paren = false;
3925        // `new A(7).get()` の後続メンバ/呼出チェーンを継続。
3926        self.parse_call_member_tail(new_expr, true)
3927    }
3928
3929    fn parse_postfix(&mut self) -> Expression {
3930        let expr = self.parse_call_member(true);
3931        let expr_was_paren = self.last_expr_was_paren;
3932        if !self.nl_before_cur() {
3933            if let Token::Sym(s) = self.cur().clone() {
3934                if s == "++" || s == "--" {
3935                    self.bump();
3936                    self.validate_assignment_target(&expr, false, false, expr_was_paren, false, false);
3937                    self.last_expr_was_paren = false;
3938                    return Expression::Update {
3939                        op: s,
3940                        prefix: false,
3941                        target: Box::new(expr),
3942                    };
3943                }
3944            }
3945        }
3946        expr
3947    }
3948
3949    /// メンバ/添字/呼出のチェーン。`allow_call=false` で呼出を抑止(new 用)。
3950    fn parse_call_member(&mut self, allow_call: bool) -> Expression {
3951        let expr = self.parse_primary();
3952        self.parse_call_member_tail(expr, allow_call)
3953    }
3954
3955    /// 既存の式に続くメンバ/添字/呼出チェーンを消費する。
3956    fn parse_call_member_tail(&mut self, mut expr: Expression, allow_call: bool) -> Expression {
3957        // `({ set x(v){} }).x = 1` の `({...})` は、続けてメンバ・添字・呼出しの根になるなら分割代入の
3958        // 代入先の候補ではない(括弧つきパターンの数え上げを戻す。`({}).x = 1`・`[({}).x] = []` は有効)。
3959        if self.last_expr_was_paren
3960            && matches!(expr, Expression::Array(_) | Expression::Object(_))
3961            && (self.is_sym(".") || self.is_sym("[") || self.is_sym("?.") || (allow_call && self.is_sym("(")))
3962        {
3963            self.pending_paren_destr_targets = self.pending_paren_destr_targets.saturating_sub(1);
3964        }
3965        if matches!(expr, Expression::Super) {
3966            if self.eat_sym(".") {
3967                let raw_prop = match self.cur().clone() {
3968                    Token::Ident(n) if n.starts_with('#') => {
3969                        self.record_error(String::from("Private field access on super is not allowed"));
3970                        self.bump();
3971                        n.to_string()
3972                    }
3973                    _ => match self.ident_name() {
3974                        Some(p) => p,
3975                        None => {
3976                            self.record_error(String::from("expected property name after 'super.'"));
3977                            String::new()
3978                        }
3979                    },
3980                };
3981                if !self.allow_super_prop && !self.in_lazy_expanded_body {
3982                    if !self.has_concrete_super_scope {
3983                        self.record_top_level_only_error(String::from("'super' property access is unexpected here"));
3984                    } else {
3985                        self.record_error(String::from("'super' property access is unexpected here"));
3986                    }
3987                }
3988                let prop = self.intern(&raw_prop);
3989                self.last_expr_was_paren = false;
3990                expr = Expression::Member {
3991                    object: Box::new(expr),
3992                    property: prop,
3993                    optional: false,
3994                };
3995            } else if self.eat_sym("[") {
3996                let index = self.parse_expression();
3997                self.expect_sym("]");
3998                if !self.allow_super_prop && !self.in_lazy_expanded_body {
3999                    if !self.has_concrete_super_scope {
4000                        self.record_top_level_only_error(String::from("'super' property access is unexpected here"));
4001                    } else {
4002                        self.record_error(String::from("'super' property access is unexpected here"));
4003                    }
4004                }
4005                self.last_expr_was_paren = false;
4006                expr = Expression::Index {
4007                    object: Box::new(expr),
4008                    index: Box::new(index),
4009                    optional: false,
4010                };
4011            } else if allow_call && self.is_sym("(") {
4012                let arguments = self.parse_arguments();
4013                if !self.allow_super_call && !self.in_lazy_expanded_body {
4014                    if !self.has_concrete_super_scope {
4015                        self.record_top_level_only_error(String::from("'super()' call is unexpected here"));
4016                    } else {
4017                        self.record_error(String::from("'super()' call is unexpected here"));
4018                    }
4019                }
4020                self.last_expr_was_paren = false;
4021                expr = Expression::Call {
4022                    callee: Box::new(expr),
4023                    arguments,
4024                    optional: false,
4025                };
4026            } else {
4027                self.record_error(String::from("'super' keyword unexpected here"));
4028                return expr;
4029            }
4030        }
4031        loop {
4032            if self.eat_sym(".") {
4033                self.last_expr_was_paren = false;
4034                let raw_prop = match self.cur().clone() {
4035                    Token::Ident(n) if n.starts_with('#') => {
4036                        self.check_private_declared(&n);
4037                        self.bump();
4038                        n.to_string()
4039                    }
4040                    _ => match self.ident_name() {
4041                        Some(p) => p,
4042                        None => {
4043                            self.record_error(String::from("expected property name after '.'"));
4044                            String::new()
4045                        }
4046                    },
4047                };
4048                let prop = self.intern(&raw_prop);
4049                expr = Expression::Member {
4050                    object: Box::new(expr),
4051                    property: prop,
4052                    optional: false,
4053                };
4054            } else if self.is_sym("?.") {
4055                self.last_expr_was_paren = false;
4056                self.bump();
4057                if self.is_sym("(") && allow_call {
4058                    let arguments = self.parse_arguments();
4059                    expr = Expression::Call {
4060                        callee: Box::new(expr),
4061                        arguments,
4062                        optional: true,
4063                    };
4064                } else if self.is_sym("[") {
4065                    self.bump();
4066                    let index = self.parse_expression();
4067                    self.expect_sym("]");
4068                    expr = Expression::Index {
4069                        object: Box::new(expr),
4070                        index: Box::new(index),
4071                        optional: true,
4072                    };
4073                } else if matches!(self.cur(), Token::Template(_)) {
4074                    self.record_error(String::from("Invalid tagged template on optional chain"));
4075                    break;
4076                } else {
4077                    let raw_prop = match self.cur().clone() {
4078                        Token::Ident(n) if n.starts_with('#') => {
4079                            self.check_private_declared(&n);
4080                            self.bump();
4081                            n.to_string()
4082                        }
4083                        _ => match self.ident_name() {
4084                            Some(p) => p,
4085                            None => {
4086                                self.record_error(String::from("expected property name after '?.'"));
4087                                String::new()
4088                            }
4089                        },
4090                    };
4091                    let prop = self.intern(&raw_prop);
4092                    expr = Expression::Member {
4093                        object: Box::new(expr),
4094                        property: prop,
4095                        optional: true,
4096                    };
4097                }
4098            } else if self.eat_sym("[") {
4099                self.last_expr_was_paren = false;
4100                let index = self.parse_expression();
4101                self.expect_sym("]");
4102                expr = Expression::Index {
4103                    object: Box::new(expr),
4104                    index: Box::new(index),
4105                    optional: false,
4106                };
4107            } else if self.is_sym("(") && allow_call {
4108                self.last_expr_was_paren = false;
4109                let arguments = self.parse_arguments();
4110                expr = Expression::Call {
4111                    callee: Box::new(expr),
4112                    arguments,
4113                    optional: false,
4114                };
4115            } else if allow_call && matches!(self.cur(), Token::Template(_)) {
4116                self.last_expr_was_paren = false;
4117                if has_optional_chain(&expr) {
4118                    self.record_error(String::from("Invalid tagged template on optional chain"));
4119                }
4120                let parts = match self.cur().clone() {
4121                    Token::Template(p) => p.into_vec(),
4122                    _ => unreachable!(),
4123                };
4124                self.bump();
4125                let mut quasis = Vec::new();
4126                let mut raw = Vec::new();
4127                let mut exprs = Vec::new();
4128                for part in parts {
4129                    match part {
4130                        super::lexer::TemplatePart::Quasi(s, r) => {
4131                            quasis.push(s);
4132                            raw.push(r);
4133                        }
4134                        super::lexer::TemplatePart::Expr(src) => {
4135                            let mut sub = Parser::new_sub(Lexer::new(&src), self.ctx_snapshot());
4136                            exprs.push(sub.parse_expression());
4137                            if !sub.is_eof() {
4138                                let found = describe_token(sub.cur());
4139                                sub.record_error(alloc::format!("unexpected {} in template interpolation", found));
4140                            }
4141                            self.absorb_errors(sub);
4142                        }
4143                    }
4144                }
4145                expr = Expression::TaggedTemplate {
4146                    tag: Box::new(expr),
4147                    quasis: Box::new(quasis),
4148                    raw: Box::new(raw),
4149                    exprs: Box::new(exprs),
4150                };
4151            } else {
4152                break;
4153            }
4154        }
4155        expr
4156    }
4157
4158    fn parse_arguments(&mut self) -> Vec<Expression> {
4159        let mut args = Vec::new();
4160        self.expect_sym("(");
4161        while !self.is_sym(")") && !self.is_eof() {
4162            if self.eat_sym("...") {
4163                args.push(Expression::Spread(Box::new(self.parse_assignment_top())));
4164            } else {
4165                args.push(self.parse_assignment_top());
4166            }
4167            if !self.eat_sym(",") {
4168                break;
4169            }
4170        }
4171        self.expect_sym(")");
4172        args
4173    }
4174
4175    fn parse_primary(&mut self) -> Expression {
4176        self.last_expr_was_paren = false;
4177        match self.cur().clone() {
4178            Token::Num(n) => {
4179                self.bump();
4180                Expression::Number(n)
4181            }
4182            Token::BigIntLit(s) => {
4183                self.bump();
4184                Expression::BigIntLit(s.into_string())
4185            }
4186            Token::Str(s) => {
4187                self.bump();
4188                Expression::Str(s.into_string())
4189            }
4190            Token::Regex(rf) => {
4191                self.bump();
4192                let (p, f) = *rf;
4193                if super::regex_syntax::flags_error(&f) {
4194                    self.record_error(alloc::format!("Invalid regular expression flags '{}'", f));
4195                } else if let Some(m) = super::regex_syntax::pattern_error(&p, &f) {
4196                    self.record_error(m);
4197                }
4198                Expression::Regex(Box::new((p, f)))
4199            }
4200            Token::Template(parts) => {
4201                let tok_start = self.token_start_at(self.pos) as usize;
4202                if self.lexer.bad_template_escape_at(tok_start) {
4203                    self.record_error(String::from("Invalid Unicode escape sequence in untagged template literal"));
4204                }
4205                self.bump();
4206                let mut quasis = Vec::new();
4207                let mut exprs = Vec::new();
4208                for part in parts.into_vec() {
4209                    match part {
4210                        super::lexer::TemplatePart::Quasi(s, _raw) => quasis.push(s),
4211                        super::lexer::TemplatePart::Expr(src) => {
4212                            let mut sub = Parser::new_sub(Lexer::new(&src), self.ctx_snapshot());
4213                            exprs.push(sub.parse_expression());
4214                            if !sub.is_eof() {
4215                                let found = describe_token(sub.cur());
4216                                sub.record_error(alloc::format!("unexpected {} in template interpolation", found));
4217                            }
4218                            self.absorb_errors(sub);
4219                        }
4220                    }
4221                }
4222                Expression::TemplateLiteral { quasis: Box::new(quasis), exprs: Box::new(exprs) }
4223            }
4224            Token::Ident(name) => {
4225                self.bump();
4226                self.check_ident_allowed(&name, false);
4227                Expression::Identifier(name)
4228            }
4229            Token::Keyword(kw) => match kw {
4230                "true" => {
4231                    self.bump();
4232                    Expression::Bool(true)
4233                }
4234                "false" => {
4235                    self.bump();
4236                    Expression::Bool(false)
4237                }
4238                "null" => {
4239                    self.bump();
4240                    Expression::Null
4241                }
4242                "undefined" => {
4243                    self.bump();
4244                    Expression::Identifier(self.intern("undefined"))
4245                }
4246                "this" => {
4247                    self.bump();
4248                    Expression::This
4249                }
4250                "super" => {
4251                    self.bump();
4252                    Expression::Super
4253                }
4254                "function" => self.parse_function_expression(false),
4255                "async" if self.kw_at(1, "function") && !self.nl_before_at(1) => {
4256                    self.bump(); // async
4257                    self.parse_function_expression(true)
4258                }
4259                "async" if self.sym_at(1, "(") && !self.nl_before_at(1) => {
4260                    self.bump(); // async
4261                    self.parse_cover_paren_or_arrow(true)
4262                }
4263                "async" => {
4264                    self.bump();
4265                    Expression::Identifier(self.intern("async"))
4266                }
4267                "class" => self.parse_class(false),
4268                "import" if self.sym_at(1, ".") && (self.ident_at(2, "defer") || self.ident_at(2, "source")) => {
4269                    self.parse_import_phase_call()
4270                }
4271                "import" if self.sym_at(1, "(") => {
4272                    self.bump(); // import
4273                    let args = self.parse_arguments();
4274                    if args.is_empty()
4275                        || args.len() > 2
4276                        || args.iter().any(|a| matches!(a, Expression::Spread(_)))
4277                    {
4278                        self.record_error(String::from("Invalid arguments in dynamic import()"));
4279                    }
4280                    // 実行時は名前に NUL を含む組込み(`dynamic_import`)を呼ぶ(利用者の変数と衝突しない)。
4281                    let helper = Expression::Identifier(self.intern("\0import"));
4282                    Expression::Call {
4283                        callee: Box::new(helper),
4284                        arguments: args,
4285                        optional: false,
4286                    }
4287                }
4288                "of" => {
4289                    self.bump();
4290                    Expression::Identifier(self.intern("of"))
4291                }
4292                "await" if !self.in_async && !self.in_static_block => {
4293                    self.bump();
4294                    Expression::Identifier(self.intern("await"))
4295                }
4296                "yield" if !self.strict && !self.in_generator && !self.in_lazy_expanded_body => {
4297                    self.bump();
4298                    Expression::Identifier(self.intern("yield"))
4299                }
4300                "let" if !self.strict => {
4301                    self.bump();
4302                    Expression::Identifier(self.intern("let"))
4303                }
4304                other => {
4305                    let msg = alloc::format!("unexpected keyword '{}' in expression", other);
4306                    self.record_error(msg);
4307                    self.bump();
4308                    Expression::Undefined
4309                }
4310            },
4311            Token::Sym(s) => match s {
4312                "(" => self.parse_cover_paren_or_arrow(false),
4313                "[" => self.parse_array_literal(),
4314                "{" => self.parse_object_literal(),
4315                "@" => {
4316                    self.parse_decorators();
4317                    if self.is_kw("class") {
4318                        self.parse_class(false)
4319                    } else {
4320                        self.record_error(String::from("Decorators are only valid before class"));
4321                        Expression::Undefined
4322                    }
4323                }
4324                other => {
4325                    let msg = alloc::format!("unexpected '{}' in expression", other);
4326                    self.record_error(msg);
4327                    self.bump();
4328                    Expression::Undefined
4329                }
4330            },
4331            Token::Eof | Token::LazyBody(..) => Expression::Undefined,
4332        }
4333    }
4334
4335    /// `import.defer(x)`・`import.source(x)`(段階つきの動的 import。引数はちょうど 1 つ)。
4336    /// `defer` は通常の `import(x)` と同じ組込みを呼ぶ(読み込みを遅らせない)。
4337    /// `source` は ECMAScript のソーステキストのモジュールに source の表現が無いので、
4338    /// 指定子を ToString したうえで SyntaxError で拒否する Promise を返す(`(async (s) => { `${s}`; throw … })(x)`)。
4339    fn parse_import_phase_call(&mut self) -> Expression {
4340        self.bump(); // import
4341        self.bump(); // .
4342        let is_source = self.ident_at(0, "source");
4343        self.bump(); // defer / source
4344        if !self.is_sym("(") {
4345            self.record_error(String::from("import.defer / import.source must be called"));
4346            return Expression::Undefined;
4347        }
4348        let args = self.parse_arguments();
4349        if args.len() != 1 || args.iter().any(|a| matches!(a, Expression::Spread(_))) {
4350            self.record_error(String::from("Invalid arguments in import.defer() / import.source()"));
4351        }
4352        self.last_expr_was_paren = false;
4353        if !is_source {
4354            let helper = Expression::Identifier(self.intern("\0import"));
4355            return Expression::Call {
4356                callee: Box::new(helper),
4357                arguments: args,
4358                optional: false,
4359            };
4360        }
4361        let s_name = self.intern("\0spec");
4362        let to_string = Statement::Expression(Expression::TemplateLiteral {
4363            quasis: Box::new(alloc::vec![String::new(), String::new()]),
4364            exprs: Box::new(alloc::vec![Expression::Identifier(s_name.clone())]),
4365        });
4366        let throw = Statement::Throw(Expression::New {
4367            callee: Box::new(Expression::Identifier(self.intern("SyntaxError"))),
4368            arguments: alloc::vec![Expression::Str(String::from(
4369                "Source phase import is not available for ECMAScript source text modules"
4370            ))],
4371        });
4372        let thrower = Expression::Function {
4373            name: None,
4374            params: Rc::new(alloc::vec![Param {
4375                pattern: Pattern::Identifier(s_name),
4376                default: None,
4377                is_rest: false,
4378            }]),
4379            body: FnBody::parsed_with(alloc::vec![to_string, throw], true),
4380            is_arrow: true,
4381            is_async: true,
4382            is_generator: false,
4383        };
4384        Expression::Call {
4385            callee: Box::new(thrower),
4386            arguments: args,
4387            optional: false,
4388        }
4389    }
4390
4391    fn parse_function_expression(&mut self, is_async: bool) -> Expression {
4392        let src_start = self.fn_source_start(is_async);
4393        self.bump(); // function
4394        let is_generator = self.eat_sym("*");
4395        let saved_async = core::mem::replace(&mut self.in_async, is_async);
4396        let saved_gen = core::mem::replace(&mut self.in_generator, is_generator);
4397        let saved_super_call = core::mem::replace(&mut self.allow_super_call, false);
4398        let saved_super_prop = core::mem::replace(&mut self.allow_super_prop, false);
4399        let saved_concrete = core::mem::replace(&mut self.has_concrete_super_scope, true);
4400        let saved_static_blk = core::mem::replace(&mut self.in_static_block, false);
4401        let name = self.try_consume_opt_fn_ident();
4402        let saved_param = core::mem::replace(&mut self.in_param, true);
4403        let params = self.parse_param_list();
4404        self.in_param = saved_param;
4405        let require_unique = self.strict || has_non_simple_params(&params) || is_async || is_generator;
4406        self.check_params(&params, require_unique);
4407        let body = self.parse_fn_body_with_params(&params);
4408        self.check_retro_strict(name.as_deref(), &params, &body, self.strict);
4409        self.in_static_block = saved_static_blk;
4410        self.has_concrete_super_scope = saved_concrete;
4411        self.allow_super_prop = saved_super_prop;
4412        self.allow_super_call = saved_super_call;
4413        self.in_generator = saved_gen;
4414        self.in_async = saved_async;
4415        self.record_fn_source(&body, src_start);
4416        Expression::Function {
4417            name,
4418            params: Rc::new(params),
4419            body,
4420            is_arrow: false,
4421            is_async,
4422            is_generator,
4423        }
4424    }
4425
4426    /// クラス(本体は常に strict モード)。
4427    fn parse_class(&mut self, require_name: bool) -> Expression {
4428        let outer = core::mem::replace(&mut self.strict, true);
4429        let e = self.parse_class_inner(require_name);
4430        self.strict = outer;
4431        e
4432    }
4433
4434    fn scan_class_private_names(&mut self) -> Vec<(Rc<str>, u8)> {
4435        let mut out: Vec<(Rc<str>, u8)> = Vec::new();
4436        let start = self.pos;
4437        let mut depth = 1usize;
4438        let mut paren_depth = 0usize;
4439        let mut bracket_depth = 0usize;
4440        let mut off = 0usize; // `{` は消費済みで最初のメンバ位置から開始
4441        let mut at_elem_start = true;
4442        let mut cur_static = false;
4443        let mut cur_accessor: Option<bool> = None;
4444        let mut prev_can_end_field = false;
4445        while depth > 0 {
4446            self.ensure_pos(start + off + 3);
4447            let tok = self.at(off).clone();
4448            if depth == 1
4449                && paren_depth == 0
4450                && bracket_depth == 0
4451                && !at_elem_start
4452                && prev_can_end_field
4453                && self.nl_before_at_abs(start + off)
4454            {
4455                at_elem_start = true;
4456                cur_static = false;
4457                cur_accessor = None;
4458            }
4459            let can_end_now = !matches!(
4460                tok,
4461                Token::Sym("=" | "." | "?." | "," | "?" | ":" | "+" | "-" | "*" | "/" | "%" | "**" | "&" | "|" | "^" | "<<" | ">>" | ">>>" | "&&" | "||" | "??" | "==" | "!=" | "===" | "!==" | "<" | ">" | "<=" | ">=" | "+=" | "-=" | "*=" | "/=" | "%=" | "!" | "~" | "..." | "(" | "[")
4462                    | Token::Keyword("in" | "instanceof" | "typeof" | "void" | "delete" | "new")
4463            );
4464            match tok {
4465                Token::Eof => break,
4466                Token::Sym("(") => {
4467                    if depth == 1 {
4468                        paren_depth += 1;
4469                        at_elem_start = false;
4470                    }
4471                    off += 1;
4472                }
4473                Token::Sym(")") => {
4474                    if depth == 1 {
4475                        paren_depth = paren_depth.saturating_sub(1);
4476                    }
4477                    off += 1;
4478                }
4479                Token::Sym("[") => {
4480                    if depth == 1 {
4481                        bracket_depth += 1;
4482                        at_elem_start = false;
4483                    }
4484                    off += 1;
4485                }
4486                Token::Sym("]") => {
4487                    if depth == 1 {
4488                        bracket_depth = bracket_depth.saturating_sub(1);
4489                    }
4490                    off += 1;
4491                }
4492                Token::Sym("{") => {
4493                    depth += 1;
4494                    if depth == 2 {
4495                        at_elem_start = false;
4496                        cur_static = false;
4497                        cur_accessor = None;
4498                    }
4499                    off += 1;
4500                }
4501                Token::Sym("}") => {
4502                    depth -= 1;
4503                    if depth == 1 {
4504                        at_elem_start = true;
4505                        cur_static = false;
4506                        cur_accessor = None;
4507                    }
4508                    off += 1;
4509                }
4510                Token::Sym(";") if depth == 1 && paren_depth == 0 && bracket_depth == 0 => {
4511                    at_elem_start = true;
4512                    cur_static = false;
4513                    cur_accessor = None;
4514                    off += 1;
4515                }
4516                Token::Ident(n) if depth == 1 && paren_depth == 0 && bracket_depth == 0 && at_elem_start => {
4517                    if &*n == "static"
4518                        && (matches!(
4519                            self.at(off + 1),
4520                            Token::Ident(_) | Token::Keyword(_) | Token::Str(_) | Token::Num(_) | Token::Sym("[" | "*" | "{")
4521                        ))
4522                    {
4523                        cur_static = true;
4524                        prev_can_end_field = can_end_now;
4525                        off += 1;
4526                        continue;
4527                    }
4528                    if (&*n == "get" || &*n == "set")
4529                        && (matches!(self.at(off + 1), Token::Sym("["))
4530                            || (matches!(
4531                                self.at(off + 1),
4532                                Token::Ident(_) | Token::Keyword(_) | Token::Str(_) | Token::Num(_)
4533                            ) && matches!(self.at(off + 2), Token::Sym("("))))
4534                    {
4535                        cur_accessor = Some(&*n == "get");
4536                        prev_can_end_field = can_end_now;
4537                        off += 1;
4538                        continue;
4539                    }
4540                    if n.starts_with('#') {
4541                        let flag = match cur_accessor {
4542                            Some(true) => PRIV_GETTER,
4543                            Some(false) => PRIV_SETTER,
4544                            None => PRIV_FIELD_OR_METHOD,
4545                        };
4546                        let stat_bit = if cur_static { PRIV_STATIC } else { 0 };
4547                        let mut dup = false;
4548                        let mut found = false;
4549                        for (existing, mask) in &mut out {
4550                            if existing == &n {
4551                                found = true;
4552                                let same_static = (*mask & PRIV_STATIC) == stat_bit;
4553                                let only_getter_setter_pair = same_static
4554                                    && ((*mask & PRIV_FIELD_OR_METHOD) == 0)
4555                                    && (flag == PRIV_GETTER || flag == PRIV_SETTER)
4556                                    && ((*mask & flag) == 0);
4557                                if only_getter_setter_pair {
4558                                    *mask |= flag;
4559                                } else {
4560                                    dup = true;
4561                                }
4562                                break;
4563                            }
4564                        }
4565                        if dup {
4566                            self.record_error(alloc::format!("Identifier '{}' has already been declared", n));
4567                        } else if !found {
4568                            out.push((n, flag | stat_bit));
4569                        }
4570                    }
4571                    at_elem_start = false;
4572                    cur_static = false;
4573                    cur_accessor = None;
4574                    off += 1;
4575                }
4576                Token::Keyword("async")
4577                    if depth == 1
4578                        && paren_depth == 0
4579                        && bracket_depth == 0
4580                        && at_elem_start
4581                        && !self.nl_before_at_abs(start + off + 1)
4582                        && matches!(
4583                            self.at(off + 1),
4584                            Token::Ident(_) | Token::Keyword(_) | Token::Str(_) | Token::Num(_) | Token::Sym("[" | "*")
4585                        ) =>
4586                {
4587                    off += 1;
4588                }
4589                Token::Sym("*") if depth == 1 && paren_depth == 0 && bracket_depth == 0 && at_elem_start => {
4590                    off += 1;
4591                }
4592                Token::Sym("@") if depth == 1 && paren_depth == 0 && bracket_depth == 0 && at_elem_start => {
4593                    off += 1;
4594                    // デコレータ式 (@a.b / @f() / @(expr)) を読み飛ばして要素先頭を維持する
4595                    if matches!(self.at(off), Token::Sym("(")) {
4596                        let mut pd = 1usize;
4597                        off += 1;
4598                        while pd > 0 {
4599                            self.ensure_pos(start + off + 1);
4600                            match self.at(off) {
4601                                Token::Sym("(") => pd += 1,
4602                                Token::Sym(")") => pd -= 1,
4603                                Token::Eof => break,
4604                                _ => {}
4605                            }
4606                            off += 1;
4607                        }
4608                    } else {
4609                        if matches!(self.at(off), Token::Ident(_) | Token::Keyword(_)) {
4610                            off += 1;
4611                        }
4612                        while matches!(self.at(off), Token::Sym(".")) {
4613                            off += 1;
4614                            if matches!(self.at(off), Token::Ident(_) | Token::Keyword(_)) {
4615                                off += 1;
4616                            }
4617                        }
4618                        if matches!(self.at(off), Token::Sym("(")) {
4619                            let mut pd = 1usize;
4620                            off += 1;
4621                            while pd > 0 {
4622                                self.ensure_pos(start + off + 1);
4623                                match self.at(off) {
4624                                    Token::Sym("(") => pd += 1,
4625                                    Token::Sym(")") => pd -= 1,
4626                                    Token::Eof => break,
4627                                    _ => {}
4628                                }
4629                                off += 1;
4630                            }
4631                        }
4632                    }
4633                    continue;
4634                }
4635                _ => {
4636                    if depth == 1 {
4637                        at_elem_start = false;
4638                    }
4639                    off += 1;
4640                }
4641            }
4642            prev_can_end_field = can_end_now;
4643        }
4644        out
4645    }
4646
4647    fn parse_class_inner(&mut self, require_name: bool) -> Expression {
4648        let class_start = self.token_start_opt(self.pos);
4649        self.eat_kw("class");
4650        let name = if require_name {
4651            let n = self.consume_binding_ident("class declaration", false);
4652            if n.is_empty() { None } else { Some(n) }
4653        } else {
4654            self.try_consume_opt_fn_ident()
4655        };
4656        let superclass = if self.eat_kw("extends") {
4657            let e = self.parse_conditional();
4658            // ClassHeritage は LeftHandSideExpression(括弧なしのアロー関数は置けない)。
4659            if matches!(e, Expression::Function { is_arrow: true, .. }) && !self.last_expr_was_paren {
4660                self.record_error(String::from("Arrow function cannot be used as class heritage without parentheses"));
4661            }
4662            Some(Box::new(e))
4663        } else {
4664            None
4665        };
4666        let has_superclass = superclass.is_some();
4667        self.expect_sym("{");
4668        // クラス本体の内側の名前束縛は不変(`C = 1` は TypeError)。
4669        self.scope_push(ScopeKind::Block);
4670        if let Some(n) = &name {
4671            if let Some(f) = self.scopes.last_mut() {
4672                f.bindings.push((n.clone(), BindingKind::Let));
4673                f.consts.push(n.clone());
4674            }
4675        }
4676        let priv_names = self.scan_class_private_names();
4677        self.private_scopes.push(priv_names);
4678        let saved_in_class = core::mem::replace(&mut self.in_class_body, true);
4679        let mut members = Vec::new();
4680        let mut ctor_count = 0usize;
4681        while !self.is_sym("}") && !self.is_eof() {
4682            if self.eat_sym(";") {
4683                continue;
4684            }
4685            if self.is_sym("@") {
4686                self.parse_decorators();
4687                if self.is_sym("}") || self.eat_sym(";") {
4688                    self.record_error(String::from("Trailing decorator without class element"));
4689                    continue;
4690                }
4691            }
4692            let is_static = if let Token::Ident(n) = self.cur().clone() {
4693                &*n == "static"
4694                    && !self.lexer.ident_has_escape_at(self.token_start_at(self.pos) as usize)
4695                    && (self.is_property_key_token(1)
4696                        || self.sym_at(1, "[")
4697                        || self.sym_at(1, "*")
4698                        || self.sym_at(1, "{"))
4699            } else {
4700                false
4701            };
4702            if is_static {
4703                self.bump();
4704            }
4705            // `static { ... }`(ES2022 静的初期化ブロック)。
4706            if is_static && self.is_sym("{") {
4707                let saved_super_call = core::mem::replace(&mut self.allow_super_call, false);
4708                let saved_super_prop = core::mem::replace(&mut self.allow_super_prop, true);
4709                let saved_concrete = core::mem::replace(&mut self.has_concrete_super_scope, true);
4710                let saved_async = core::mem::replace(&mut self.in_async, false);
4711                let saved_gen = core::mem::replace(&mut self.in_generator, false);
4712                let body = self.parse_static_block_body();
4713                self.in_generator = saved_gen;
4714                self.in_async = saved_async;
4715                self.has_concrete_super_scope = saved_concrete;
4716                self.allow_super_prop = saved_super_prop;
4717                self.allow_super_call = saved_super_call;
4718                members.push(ClassMember {
4719                    key: self.intern(""),
4720                    computed_key: None,
4721                    kind: MethodKind::StaticBlock,
4722                    params: Rc::new(Vec::new()),
4723                    body,
4724                    is_static: true,
4725                    field_init: None,
4726                    is_async: false,
4727                    is_generator: false,
4728                });
4729                continue;
4730            }
4731            let is_auto_accessor = !is_static
4732                && matches!(self.cur(), Token::Ident(n) if &**n == "accessor")
4733                && !self.nl_before_at(1)
4734                && (self.is_property_key_token(1) || self.sym_at(1, "["));
4735            let is_auto_accessor = is_auto_accessor
4736                || (is_static
4737                    && matches!(self.cur(), Token::Ident(n) if &**n == "accessor")
4738                    && !self.nl_before_at(1)
4739                    && (self.is_property_key_token(1) || self.sym_at(1, "[")));
4740            if is_auto_accessor {
4741                self.bump();
4742            }
4743            let async_modifier_ok = !is_auto_accessor
4744                && !self.nl_before_at(1)
4745                && (self.is_property_key_token(1) || self.sym_at(1, "[") || self.sym_at(1, "*"));
4746            let m_start = self.token_start_opt(self.pos);
4747            let is_async = self.is_kw("async") && async_modifier_ok;
4748            if is_async {
4749                self.bump();
4750            }
4751            let is_generator = !is_auto_accessor && self.eat_sym("*");
4752            let accessor_kind = if let Token::Ident(n) = self.cur().clone() {
4753                if (&*n == "get" || &*n == "set")
4754                    && !self.lexer.ident_has_escape_at(self.token_start_at(self.pos) as usize)
4755                    && !is_auto_accessor
4756                    && !is_async
4757                    && !is_generator
4758                    && (self.sym_at(1, "[")
4759                        || (self.is_property_key_token(1) && self.sym_at(2, "(")))
4760                {
4761                    let is_get = &*n == "get";
4762                    self.bump();
4763                    Some(is_get)
4764                } else {
4765                    None
4766                }
4767            } else {
4768                None
4769            };
4770            let mut computed_key = None;
4771            let key = match self.cur().clone() {
4772                Token::Ident(n) => {
4773                    self.check_escaped_element_name(&n);
4774                    self.bump();
4775                    self.intern(&n)
4776                }
4777                Token::Keyword(n) => {
4778                    self.bump();
4779                    self.intern(n)
4780                }
4781                Token::Str(s) => {
4782                    self.bump();
4783                    self.intern(&s)
4784                }
4785                Token::Num(n) => {
4786                    self.bump();
4787                    let s = super::value::fmt_number(n);
4788                    self.intern(&s)
4789                }
4790                Token::BigIntLit(b) => {
4791                    self.bump();
4792                    self.bigint_key(&b)
4793                }
4794                Token::Sym("[") => {
4795                    self.bump();
4796                    computed_key = Some(self.parse_assignment_top());
4797                    self.expect_sym("]");
4798                    self.intern("")
4799                }
4800                other => {
4801                    self.record_error(alloc::format!("unexpected {} in class body", describe_token(&other)));
4802                    self.bump();
4803                    continue;
4804                }
4805            };
4806            if &*key == "#constructor" {
4807                self.record_error(String::from("Classes may not have a private element named '#constructor'"));
4808            }
4809            if is_static && computed_key.is_none() && &*key == "prototype" {
4810                self.record_error(String::from("Classes may not have a static property named 'prototype'"));
4811            }
4812            if self.is_sym("(") {
4813                if is_auto_accessor {
4814                    self.record_error(String::from("Auto-accessor field cannot be a method"));
4815                }
4816                let is_ctor = !is_static && computed_key.is_none() && &*key == "constructor";
4817                if is_ctor {
4818                    if accessor_kind.is_some() || is_async || is_generator {
4819                        self.record_error(String::from("Class constructor may not be an accessor, async, or generator"));
4820                    } else {
4821                        ctor_count += 1;
4822                        if ctor_count > 1 {
4823                            self.record_error(String::from("A class may only have one constructor"));
4824                        }
4825                    }
4826                }
4827                let kind = match accessor_kind {
4828                    Some(true) => MethodKind::Getter,
4829                    Some(false) => MethodKind::Setter,
4830                    None if is_ctor => MethodKind::Constructor,
4831                    None => MethodKind::Method,
4832                };
4833                let saved_async = core::mem::replace(&mut self.in_async, is_async);
4834                let saved_gen = core::mem::replace(&mut self.in_generator, is_generator);
4835                let saved_super_call = core::mem::replace(&mut self.allow_super_call, is_ctor && has_superclass);
4836                let saved_super_prop = core::mem::replace(&mut self.allow_super_prop, true);
4837                let saved_concrete = core::mem::replace(&mut self.has_concrete_super_scope, true);
4838                let saved_static_blk = core::mem::replace(&mut self.in_static_block, false);
4839                let saved_param = core::mem::replace(&mut self.in_param, true);
4840                let params = self.parse_param_list();
4841                self.in_param = saved_param;
4842                self.check_params(&params, true);
4843                self.check_accessor_params(accessor_kind, &params);
4844                let body = self.parse_fn_body_with_params(&params);
4845                self.check_retro_strict(None, &params, &body, self.strict);
4846                self.in_static_block = saved_static_blk;
4847                self.has_concrete_super_scope = saved_concrete;
4848                self.allow_super_prop = saved_super_prop;
4849                self.allow_super_call = saved_super_call;
4850                self.in_generator = saved_gen;
4851                self.in_async = saved_async;
4852                self.record_fn_source(&body, m_start);
4853                if !is_ctor {
4854                    body.mark_method();
4855                }
4856                members.push(ClassMember {
4857                    key,
4858                    computed_key,
4859                    kind,
4860                    params: Rc::new(params),
4861                    body,
4862                    is_static,
4863                    field_init: None,
4864                    is_async,
4865                    is_generator,
4866                });
4867            } else {
4868                if is_async || is_generator || accessor_kind.is_some() {
4869                    self.record_error(String::from("expected '(' after method modifier"));
4870                }
4871                if computed_key.is_none() && &*key == "constructor" {
4872                    self.record_error(String::from("Classes may not have a field named 'constructor'"));
4873                }
4874                let init = if self.eat_sym("=") {
4875                    let saved_field = core::mem::replace(&mut self.in_field_init, true);
4876                    let saved_super_call = core::mem::replace(&mut self.allow_super_call, false);
4877                    let saved_super_prop = core::mem::replace(&mut self.allow_super_prop, true);
4878                    let saved_concrete = core::mem::replace(&mut self.has_concrete_super_scope, true);
4879                    let saved_async = core::mem::replace(&mut self.in_async, false);
4880                    let saved_gen = core::mem::replace(&mut self.in_generator, false);
4881                    let e = self.parse_assignment_top();
4882                    self.in_generator = saved_gen;
4883                    self.in_async = saved_async;
4884                    self.has_concrete_super_scope = saved_concrete;
4885                    self.allow_super_prop = saved_super_prop;
4886                    self.allow_super_call = saved_super_call;
4887                    self.in_field_init = saved_field;
4888                    Some(e)
4889                } else {
4890                    None
4891                };
4892                self.expect_asi_semicolon();
4893                members.push(ClassMember {
4894                    key,
4895                    computed_key,
4896                    kind: MethodKind::Field,
4897                    params: Rc::new(Vec::new()),
4898                    body: FnBody::parsed_with(Vec::new(), true),
4899                    is_static,
4900                    field_init: init,
4901                    is_async: false,
4902                    is_generator: false,
4903                });
4904            }
4905        }
4906        self.in_class_body = saved_in_class;
4907        self.private_scopes.pop();
4908        self.scope_pop();
4909        self.expect_sym("}");
4910        let class_end = self.pos.checked_sub(1).and_then(|p| self.token_start_opt(p)).map(|st| st + 1);
4911        if let (Some(a), Some(b)) = (class_start, class_end) {
4912            if a < b {
4913                let body = FnBody::parsed_with(Vec::new(), true);
4914                body.set_source_text(self.lexer.src_rc().clone(), a, b);
4915                members.push(ClassMember {
4916                    key: self.intern(""),
4917                    computed_key: None,
4918                    kind: MethodKind::ClassSource,
4919                    params: Rc::new(Vec::new()),
4920                    body,
4921                    is_static: false,
4922                    field_init: None,
4923                    is_async: false,
4924                    is_generator: false,
4925                });
4926            }
4927        }
4928        Expression::Class {
4929            name: name.map(|n| n.to_string()),
4930            superclass,
4931            members: Box::new(members),
4932        }
4933    }
4934
4935    fn parse_array_literal(&mut self) -> Expression {
4936        self.expect_sym("[");
4937        let mut items = Vec::new();
4938        while !self.is_sym("]") && !self.is_eof() {
4939            if self.is_sym(",") {
4940                // 穴あき配列 [1,,3]。
4941                items.push(Expression::Elision);
4942                self.bump();
4943                continue;
4944            }
4945            let is_spread = self.eat_sym("...");
4946            if is_spread {
4947                items.push(Expression::Spread(Box::new(self.parse_assignment())));
4948            } else {
4949                let item = self.parse_assignment();
4950                if self.last_expr_was_paren && matches!(item, Expression::Array(_) | Expression::Object(_)) {
4951                    self.pending_paren_destr_targets += 1;
4952                }
4953                items.push(item);
4954            }
4955            if !self.eat_sym(",") {
4956                break;
4957            }
4958            if is_spread && self.is_sym("]") {
4959                self.pending_spread_trailing_commas += 1;
4960            }
4961        }
4962        self.expect_sym("]");
4963        self.last_expr_was_paren = false;
4964        Expression::Array(items)
4965    }
4966
4967    fn parse_object_literal(&mut self) -> Expression {
4968        self.expect_sym("{");
4969        let mut props = Vec::new();
4970        let mut has_proto_prop = false;
4971        while !self.is_sym("}") && !self.is_eof() {
4972            // オブジェクトスプレッド {...o}
4973            if self.eat_sym("...") {
4974                let value = self.parse_assignment();
4975                props.push(Property {
4976                    key: self.intern(crate::os_lib::ecma::ast::OBJECT_SPREAD_KEY),
4977                    value,
4978                    computed: None,
4979                    accessor: None,
4980                });
4981                if !self.eat_sym(",") {
4982                    break;
4983                }
4984                if self.is_sym("}") {
4985                    self.pending_spread_trailing_commas += 1;
4986                }
4987                continue;
4988            }
4989            let async_modifier_ok = !self.nl_before_at(1)
4990                && (self.is_property_key_token(1) || self.sym_at(1, "[") || self.sym_at(1, "*"));
4991            let m_start = self.token_start_opt(self.pos);
4992            let is_async = self.is_kw("async") && async_modifier_ok;
4993            if is_async {
4994                self.bump();
4995            }
4996            let is_generator = self.eat_sym("*");
4997            let accessor_kind = if let Token::Ident(n) = self.cur().clone() {
4998                if (&*n == "get" || &*n == "set")
4999                    && !self.lexer.ident_has_escape_at(self.token_start_at(self.pos) as usize)
5000                    && !is_async
5001                    && !is_generator
5002                    && (self.sym_at(1, "[")
5003                        || (self.is_property_key_token(1) && self.sym_at(2, "(")))
5004                {
5005                    let is_get = &*n == "get";
5006                    self.bump();
5007                    Some(is_get)
5008                } else {
5009                    None
5010                }
5011            } else {
5012                None
5013            };
5014            let mut computed = None;
5015            let mut is_ident_key = false;
5016            let mut is_ident_ref_ok = false;
5017            let key = match self.cur().clone() {
5018                Token::Ident(n) => {
5019                    if n.starts_with('#') {
5020                        self.record_error(alloc::format!("Private name '{}' is not allowed in object literal", n));
5021                    }
5022                    is_ident_key = true;
5023                    is_ident_ref_ok = true;
5024                    self.bump();
5025                    self.intern(&n)
5026                }
5027                Token::Keyword(n) => {
5028                    is_ident_ref_ok = matches!(n, "async" | "of" | "undefined" | "let" | "await" | "yield");
5029                    is_ident_key = is_ident_ref_ok;
5030                    self.bump();
5031                    self.intern(n)
5032                }
5033                Token::Str(s) => {
5034                    self.bump();
5035                    self.intern(&s)
5036                }
5037                Token::Num(n) => {
5038                    self.bump();
5039                    let s = super::value::fmt_number(n);
5040                    self.intern(&s)
5041                }
5042                Token::BigIntLit(b) => {
5043                    self.bump();
5044                    self.bigint_key(&b)
5045                }
5046                Token::Sym("[") => {
5047                    self.bump();
5048                    computed = Some(self.parse_assignment_top());
5049                    self.expect_sym("]");
5050                    self.intern("")
5051                }
5052                other => {
5053                    self.record_error(alloc::format!("unexpected {} in object literal", describe_token(&other)));
5054                    break;
5055                }
5056            };
5057            let value = if self.eat_sym(":") {
5058                if is_async || is_generator || accessor_kind.is_some() {
5059                    self.record_error(String::from("Unexpected ':' after method modifier"));
5060                }
5061                if computed.is_none() && &*key == "__proto__" {
5062                    if has_proto_prop {
5063                        self.pending_dup_protos += 1;
5064                    } else {
5065                        has_proto_prop = true;
5066                    }
5067                }
5068                let val = self.parse_assignment();
5069                if self.last_expr_was_paren && matches!(val, Expression::Array(_) | Expression::Object(_)) {
5070                    self.pending_paren_destr_targets += 1;
5071                }
5072                val
5073            } else if self.is_sym("(") {
5074                let saved_async = core::mem::replace(&mut self.in_async, is_async);
5075                let saved_gen = core::mem::replace(&mut self.in_generator, is_generator);
5076                let saved_super_call = core::mem::replace(&mut self.allow_super_call, false);
5077                let saved_super_prop = core::mem::replace(&mut self.allow_super_prop, true);
5078                let saved_concrete = core::mem::replace(&mut self.has_concrete_super_scope, true);
5079                let saved_static_blk = core::mem::replace(&mut self.in_static_block, false);
5080                let saved_param = core::mem::replace(&mut self.in_param, true);
5081                let params = self.parse_param_list();
5082                self.in_param = saved_param;
5083                self.check_params(&params, true);
5084                self.check_accessor_params(accessor_kind, &params);
5085                let body = self.parse_fn_body_with_params(&params);
5086                self.check_retro_strict(None, &params, &body, self.strict);
5087                self.in_static_block = saved_static_blk;
5088                self.has_concrete_super_scope = saved_concrete;
5089                self.allow_super_prop = saved_super_prop;
5090                self.allow_super_call = saved_super_call;
5091                self.in_generator = saved_gen;
5092                self.in_async = saved_async;
5093                self.record_fn_source(&body, m_start);
5094                body.mark_method();
5095                Expression::Function {
5096                    name: Some(key.clone()),
5097                    params: Rc::new(params),
5098                    body,
5099                    is_arrow: false,
5100                    is_async,
5101                    is_generator,
5102                }
5103            } else if computed.is_none() && self.is_sym("=") {
5104                if is_async || is_generator || accessor_kind.is_some() || !is_ident_key {
5105                    self.record_error(String::from("Invalid cover initialized property"));
5106                } else {
5107                    self.check_ident_allowed(&key, true);
5108                    self.pending_cover_inits += 1;
5109                }
5110                self.bump();
5111                let def = self.parse_assignment_top();
5112                Expression::Assign {
5113                    op: "=",
5114                    target: Box::new(Expression::Identifier(key.clone())),
5115                    value: Box::new(def),
5116                }
5117            } else {
5118                if !is_ident_ref_ok || is_async || is_generator || accessor_kind.is_some() || computed.is_some() {
5119                    self.record_error(String::from("Expected ':' after property name in object literal"));
5120                } else {
5121                    self.check_ident_allowed(&key, false);
5122                }
5123                Expression::Identifier(key.clone())
5124            };
5125            props.push(Property {
5126                key,
5127                value,
5128                computed,
5129                accessor: accessor_kind,
5130            });
5131            if !self.eat_sym(",") {
5132                break;
5133            }
5134        }
5135        self.expect_sym("}");
5136        self.last_expr_was_paren = false;
5137        Expression::Object(props)
5138    }
5139}
5140
5141fn pattern_has_ident(pat: &Pattern, target: &str) -> bool {
5142    match pat {
5143        Pattern::Identifier(n) => &**n == target,
5144        Pattern::Object(props) => props.iter().any(|p| {
5145            pattern_has_ident(&p.value, target)
5146                || p.computed_key.as_ref().is_some_and(expr_uses_await)
5147                || p.default.as_ref().is_some_and(expr_uses_await)
5148        }),
5149        Pattern::Array(elems) => elems.iter().any(|e| {
5150            e.pattern.as_ref().is_some_and(|p| pattern_has_ident(p, target))
5151                || e.default.as_ref().is_some_and(expr_uses_await)
5152        }),
5153        Pattern::Expr(e) => expr_uses_await(e),
5154    }
5155}
5156
5157fn stmt_uses_await(s: &Statement) -> bool {
5158    match s {
5159        Statement::Expression(e) | Statement::Throw(e) => expr_uses_await(e),
5160        Statement::Return(Some(e)) => expr_uses_await(e),
5161        Statement::Block(b) => b.iter().any(stmt_uses_await),
5162        Statement::If { test, consequent, alternate } => {
5163            expr_uses_await(test)
5164                || stmt_uses_await(consequent)
5165                || alternate.as_ref().is_some_and(|a| stmt_uses_await(a))
5166        }
5167        Statement::While { test, body } | Statement::DoWhile { body, test } => {
5168            expr_uses_await(test) || stmt_uses_await(body)
5169        }
5170        Statement::For { init, test, update, body } => {
5171            init.as_ref().is_some_and(|i| stmt_uses_await(i))
5172                || test.as_ref().is_some_and(|t| expr_uses_await(t))
5173                || update.as_ref().is_some_and(|u| expr_uses_await(u))
5174                || stmt_uses_await(body)
5175        }
5176        Statement::ForIn { pattern, object, body, .. } => {
5177            pattern_has_ident(pattern, "await") || expr_uses_await(object) || stmt_uses_await(body)
5178        }
5179        Statement::VarDeclaration { decls, .. } => decls.iter().any(|(p, i)| {
5180            pattern_has_ident(p, "await") || i.as_ref().is_some_and(expr_uses_await)
5181        }),
5182        Statement::Labeled(_, inner) => stmt_uses_await(inner),
5183        Statement::With { object, body } => expr_uses_await(object) || stmt_uses_await(body),
5184        Statement::ClassFieldInit { stmts, .. } => stmts.iter().any(stmt_uses_await),
5185        Statement::Try(t) => {
5186            t.block.iter().any(stmt_uses_await)
5187                || t.catch_param.as_ref().is_some_and(|p| pattern_has_ident(p, "await"))
5188                || t.catch_block.as_ref().is_some_and(|b| b.iter().any(stmt_uses_await))
5189                || t.finally_block.as_ref().is_some_and(|b| b.iter().any(stmt_uses_await))
5190        }
5191        Statement::Switch { discriminant, cases } => {
5192            expr_uses_await(discriminant)
5193                || cases.iter().any(|c| {
5194                    c.test.as_ref().is_some_and(expr_uses_await)
5195                        || c.body.iter().any(stmt_uses_await)
5196                })
5197        }
5198        _ => false,
5199    }
5200}
5201
5202fn expr_uses_await(e: &Expression) -> bool {
5203    match e {
5204        Expression::Await(_) => true,
5205        Expression::Identifier(n) => &**n == "await",
5206        Expression::Function { params, body, is_arrow, is_async, .. } if *is_arrow && !*is_async => {
5207            params.iter().any(|p| {
5208                pattern_has_ident(&p.pattern, "await")
5209                    || p.default.as_deref().is_some_and(expr_uses_await)
5210            }) || (!body.is_lazy() && body.stmts().iter().any(stmt_uses_await))
5211        }
5212        Expression::Array(items) => items.iter().any(expr_uses_await),
5213        Expression::Object(props) => props.iter().any(|p| expr_uses_await(&p.value) || p.computed.as_ref().is_some_and(expr_uses_await)),
5214        Expression::Assign { target, value, .. } => expr_uses_await(target) || expr_uses_await(value),
5215        Expression::Binary { left, right, .. } | Expression::Logical { left, right, .. } => expr_uses_await(left) || expr_uses_await(right),
5216        Expression::Unary { expr, .. } | Expression::Update { target: expr, .. } | Expression::Spread(expr) => expr_uses_await(expr),
5217        Expression::Conditional { test, consequent, alternate } => expr_uses_await(test) || expr_uses_await(consequent) || expr_uses_await(alternate),
5218        Expression::Call { callee, arguments, .. } => expr_uses_await(callee) || arguments.iter().any(expr_uses_await),
5219        Expression::Member { object, .. } => expr_uses_await(object),
5220        Expression::Index { object, index, .. } => expr_uses_await(object) || expr_uses_await(index),
5221        Expression::Sequence(items) => items.iter().any(expr_uses_await),
5222        Expression::New { callee, arguments } => expr_uses_await(callee) || arguments.iter().any(expr_uses_await),
5223        Expression::TemplateLiteral { exprs, .. } | Expression::TaggedTemplate { exprs, .. } => exprs.iter().any(expr_uses_await),
5224        _ => false,
5225    }
5226}
5227
5228#[derive(Clone, Copy, PartialEq, Eq)]
5229enum StmtPos {
5230    List,
5231    IfOrLabel,
5232    /// `if` の本体(関数宣言は sloppy なら可だが、ラベル付きの関数宣言は不可)。
5233    IfBody,
5234    IterationOrWith,
5235}
5236
5237fn is_always_reserved(name: &str) -> bool {
5238    matches!(
5239        name,
5240        "break"
5241            | "case"
5242            | "catch"
5243            | "class"
5244            | "const"
5245            | "continue"
5246            | "debugger"
5247            | "default"
5248            | "delete"
5249            | "do"
5250            | "else"
5251            | "enum"
5252            | "export"
5253            | "extends"
5254            | "false"
5255            | "finally"
5256            | "for"
5257            | "function"
5258            | "if"
5259            | "import"
5260            | "in"
5261            | "instanceof"
5262            | "new"
5263            | "null"
5264            | "return"
5265            | "super"
5266            | "switch"
5267            | "this"
5268            | "throw"
5269            | "true"
5270            | "try"
5271            | "typeof"
5272            | "var"
5273            | "void"
5274            | "while"
5275            | "with"
5276    )
5277}
5278
5279fn is_strict_reserved(name: &str) -> bool {
5280    matches!(
5281        name,
5282        "implements"
5283            | "interface"
5284            | "let"
5285            | "package"
5286            | "private"
5287            | "protected"
5288            | "public"
5289            | "static"
5290            | "yield"
5291    )
5292}
5293
5294fn has_optional_chain(expr: &Expression) -> bool {
5295    match expr {
5296        Expression::Member { object, optional, .. } | Expression::Index { object, optional, .. } => {
5297            *optional || has_optional_chain(object)
5298        }
5299        Expression::Call { callee, optional, .. } => *optional || has_optional_chain(callee),
5300        _ => false,
5301    }
5302}
5303
5304fn has_non_simple_params(params: &[Param]) -> bool {
5305    params
5306        .iter()
5307        .any(|p| p.is_rest || p.default.is_some() || !matches!(p.pattern, Pattern::Identifier(_)))
5308}
5309
5310// --- 演算子テーブル ---
5311
5312fn is_assign_op(op: &str) -> bool {
5313    matches!(
5314        op,
5315        "=" | "+="
5316            | "-="
5317            | "*="
5318            | "/="
5319            | "%="
5320            | "**="
5321            | "&="
5322            | "|="
5323            | "^="
5324            | "<<="
5325            | ">>="
5326            | ">>>="
5327            | "&&="
5328            | "||="
5329            | "??="
5330    )
5331}
5332
5333fn bin_prec(op: &str) -> Option<u8> {
5334    Some(match op {
5335        "??" => 1,
5336        "||" => 2,
5337        "&&" => 3,
5338        "|" => 4,
5339        "^" => 5,
5340        "&" => 6,
5341        "==" | "!=" | "===" | "!==" => 7,
5342        "<" | ">" | "<=" | ">=" | "instanceof" | "in" => 8,
5343        "<<" | ">>" | ">>>" => 9,
5344        "+" | "-" => 10,
5345        "*" | "/" | "%" => 11,
5346        "**" => 12,
5347        _ => return None,
5348    })
5349}
5350
5351fn is_right_assoc(op: &str) -> bool {
5352    op == "**"
5353}
5354
5355fn to_logical(op: &str) -> Option<LogicalOp> {
5356    match op {
5357        "&&" => Some(LogicalOp::And),
5358        "||" => Some(LogicalOp::Or),
5359        "??" => Some(LogicalOp::Nullish),
5360        _ => None,
5361    }
5362}
5363
5364fn to_binop(op: &str) -> Option<BinaryOp> {
5365    Some(match op {
5366        "+" => BinaryOp::Add,
5367        "-" => BinaryOp::Sub,
5368        "*" => BinaryOp::Mul,
5369        "/" => BinaryOp::Div,
5370        "%" => BinaryOp::Mod,
5371        "**" => BinaryOp::Pow,
5372        "==" => BinaryOp::Eq,
5373        "!=" => BinaryOp::NotEq,
5374        "===" => BinaryOp::StrictEq,
5375        "!==" => BinaryOp::StrictNotEq,
5376        "<" => BinaryOp::Lt,
5377        ">" => BinaryOp::Gt,
5378        "<=" => BinaryOp::LtEq,
5379        ">=" => BinaryOp::GtEq,
5380        "&" => BinaryOp::BitAnd,
5381        "|" => BinaryOp::BitOr,
5382        "^" => BinaryOp::BitXor,
5383        "<<" => BinaryOp::Shl,
5384        ">>" => BinaryOp::Shr,
5385        ">>>" => BinaryOp::UShr,
5386        "instanceof" => BinaryOp::InstanceOf,
5387        "in" => BinaryOp::In,
5388        _ => return None,
5389    })
5390}
5391
5392/// これ未満のトークン数の関数本体は遅延させずにその場で解析する(小さい関数は保持コストの方が大きい)。
5393const LAZY_MIN_TOKENS: usize = 24;
5394
5395/// 遅延した関数本体のソース(`{` と `}` の内側)を解析する。入れ子の関数もまた遅延する。
5396pub fn parse_function_body_source(src: &str, strict: bool) -> Vec<Statement> {
5397    let rc: Rc<str> = Rc::from(src);
5398    let len = rc.len();
5399    parse_function_body_range(rc, 0, len, strict, None)
5400}
5401
5402/// 共有ソース `src` の範囲 `start..end`(`{` と `}` の内側)を複製なしで解析する。
5403/// 【一時診断】解析した文字数([0]=関数本体の遅延解析・[1]=eval 等・[2]=スクリプト全体)と回数([3]〜[5])。
5404pub static PARSE_STATS: [core::sync::atomic::AtomicU64; 6] = [const { core::sync::atomic::AtomicU64::new(0) }; 6];
5405
5406pub(crate) fn note_parse(kind: usize, bytes: usize) {
5407    if let (Some(b), Some(n)) = (PARSE_STATS.get(kind), PARSE_STATS.get(kind + 3)) {
5408        b.fetch_add(bytes as u64, core::sync::atomic::Ordering::Relaxed);
5409        n.fetch_add(1, core::sync::atomic::Ordering::Relaxed);
5410    }
5411}
5412
5413pub fn parse_function_body_range(
5414    src: Rc<str>,
5415    start: usize,
5416    end: usize,
5417    strict: bool,
5418    atoms: Option<super::lexer::SharedAtoms>,
5419) -> Vec<Statement> {
5420    note_parse(0, end.saturating_sub(start));
5421    let lexer = match atoms {
5422        Some(a) => Lexer::from_rc_range_shared(src, start, end, a),
5423        None => Lexer::from_rc_range(src, start, end),
5424    };
5425    let mut p = Parser::new_lazy(lexer);
5426    p.strict = strict;
5427    p.in_function = 1;
5428    p.allow_super_prop = true;
5429    p.allow_super_call = true;
5430    p.in_lazy_expanded_body = true;
5431    if let Some(f) = p.scopes.first_mut() {
5432        f.kind = ScopeKind::Function;
5433    }
5434    let mut body = Vec::new();
5435    while !p.is_eof() {
5436        let before = p.pos;
5437        if let Some(s) = p.parse_statement() {
5438            p.lex_note_stmt(&s);
5439            body.push(s);
5440        }
5441        if p.pos == before {
5442            p.step();
5443        }
5444    }
5445    p.flush_lexer_errors();
5446    if p.error_count() > 0 {
5447        crate::warn!("[JS] {} syntax error(s) in lazily parsed function body", p.error_count());
5448    }
5449    body
5450}