Skip to main content

atmos/os_lib/ecma/
regex.rs

1//! 小さなバックトラッキング正規表現エンジン。
2//!
3//! パターンを命令列(バックトラッキング VM のバイトコード)へコンパイルし、再帰で実行する。
4//! 暴走(catastrophic backtracking)からカーネルを守るため **実行予算**で打ち切る。
5//!
6//! 対応: リテラル・`.`・文字クラス `[...]`/`[^...]`(範囲・`\d\w\s`・`\p{...}`)・
7//! unicodeSets (`v` フラグ: `&&`, `--`, 入れ子 `[...]`, `\q{...}`, 文字列プロパティ)・
8//! アンカー `^ $`・量指定子 `* + ? {n} {n,} {n,m}`(貪欲/非貪欲)・グループ `(...)`/`(?:...)`/`(?<name>...)`・
9//! 修飾子 `(?ims-ims:...)`・先読み/後読み `(?=...)`/`(?!...)`/`(?<=...)`/`(?<!...)`・
10//! 後方参照 `\1`/`\k<name>`・単語境界 `\b \B`。フラグ: `d g i m s u v y`。
11
12#[path = "regex_unicode.rs"]
13pub(crate) mod unicode;
14
15use alloc::boxed::Box;
16use alloc::string::String;
17use alloc::vec;
18use alloc::vec::Vec;
19
20/// 文字クラスの 1 要素。コードポイントは `u32`(非 Unicode モードの単独サロゲートも含む)。
21#[derive(Clone)]
22enum ClassItem {
23    Ch(u32),
24    Range(u32, u32),
25    Digit,
26    NotDigit,
27    Word,
28    NotWord,
29    Space,
30    NotSpace,
31    UnicodeProp(unicode::PropKind, bool),
32}
33
34#[derive(Clone)]
35struct ClassData {
36    negate: bool,
37    items: Vec<ClassItem>,
38}
39
40impl ClassData {
41    fn matches(&self, cp: u32, ignorecase: bool, unicode: bool) -> bool {
42        let hit = self.items.iter().any(|it| item_match(it, cp, ignorecase, unicode, false));
43        hit ^ self.negate
44    }
45}
46
47/// `v`(unicodeSets)フラグ用の拡張文字クラス(コードポイントと文字列の集合演算)。
48#[derive(Clone)]
49enum VSet {
50    Union(Vec<VSet>),
51    Inter(Vec<VSet>),
52    Diff(Vec<VSet>),
53    Neg(Box<VSet>),
54    Item(ClassItem),
55    Strings(Vec<Vec<u32>>),
56    StrProp(unicode::StrProp),
57}
58
59impl VSet {
60    fn max_len(&self) -> usize {
61        match self {
62            VSet::Item(_) | VSet::Neg(_) => 1,
63            VSet::Strings(list) => list.iter().map(|s| s.len()).max().unwrap_or(0),
64            VSet::StrProp(sp) => unicode::str_prop_max_len(*sp),
65            VSet::Union(v) => v.iter().map(VSet::max_len).max().unwrap_or(0),
66            VSet::Inter(v) => v.iter().map(VSet::max_len).min().unwrap_or(0),
67            VSet::Diff(v) => v.first().map_or(0, VSet::max_len),
68        }
69    }
70
71    fn can_empty(&self) -> bool {
72        match self {
73            VSet::Item(_) | VSet::Neg(_) | VSet::StrProp(_) => false,
74            VSet::Strings(list) => list.iter().any(|s| s.is_empty()),
75            VSet::Union(v) => v.iter().any(VSet::can_empty),
76            VSet::Inter(v) => !v.is_empty() && v.iter().all(VSet::can_empty),
77            VSet::Diff(v) => v.first().is_some_and(VSet::can_empty) && !v[1..].iter().any(VSet::can_empty),
78        }
79    }
80
81    fn is_single_cp_only(&self) -> bool {
82        self.max_len() <= 1 && !self.can_empty()
83    }
84
85    fn matches_cp(&self, cp: u32, ignorecase: bool) -> bool {
86        match self {
87            VSet::Item(it) => item_match(it, cp, ignorecase, true, true),
88            VSet::Neg(inner) => !inner.matches_cp(cp, ignorecase),
89            VSet::Strings(list) => list.iter().any(|s| s.len() == 1 && eqc(s[0], cp, ignorecase, true)),
90            VSet::StrProp(sp) => match sp {
91                unicode::StrProp::BasicEmoji | unicode::StrProp::RgiEmoji => {
92                    if ignorecase {
93                        let mut buf = [0u32; 4];
94                        let n = unicode::fold_equiv_unicode(cp, &mut buf);
95                        buf[..n].iter().any(|&x| unicode::basic_emoji_cp_matches(x))
96                    } else {
97                        unicode::basic_emoji_cp_matches(cp)
98                    }
99                }
100                _ => false,
101            },
102            VSet::Union(v) => v.iter().any(|x| x.matches_cp(cp, ignorecase)),
103            VSet::Inter(v) => !v.is_empty() && v.iter().all(|x| x.matches_cp(cp, ignorecase)),
104            VSet::Diff(v) => {
105                v.first().is_some_and(|x| x.matches_cp(cp, ignorecase))
106                    && v[1..].iter().all(|x| !x.matches_cp(cp, ignorecase))
107            }
108        }
109    }
110
111    fn matches_slice(&self, slice: &[u32], ignorecase: bool) -> bool {
112        if slice.len() == 1 {
113            return self.matches_cp(slice[0], ignorecase);
114        }
115        match self {
116            VSet::Item(_) | VSet::Neg(_) => false,
117            VSet::Strings(list) => list.iter().any(|s| {
118                s.len() == slice.len() && s.iter().zip(slice).all(|(&a, &b)| eqc(a, b, ignorecase, true))
119            }),
120            VSet::StrProp(sp) => unicode::str_prop_matches_slice(*sp, slice),
121            VSet::Union(v) => v.iter().any(|x| x.matches_slice(slice, ignorecase)),
122            VSet::Inter(v) => !v.is_empty() && v.iter().all(|x| x.matches_slice(slice, ignorecase)),
123            VSet::Diff(v) => {
124                v.first().is_some_and(|x| x.matches_slice(slice, ignorecase))
125                    && v[1..].iter().all(|x| !x.matches_slice(slice, ignorecase))
126            }
127        }
128    }
129
130    fn matches_subject(&self, s: &Subject<'_>, sp: usize, len: usize, ignorecase: bool) -> bool {
131        if len == 1 {
132            return self.matches_cp(s.at(sp), ignorecase);
133        }
134        if len <= 16 {
135            let mut buf = [0u32; 16];
136            for (i, slot) in buf.iter_mut().enumerate().take(len) {
137                *slot = s.at(sp + i);
138            }
139            self.matches_slice(&buf[..len], ignorecase)
140        } else {
141            let v: Vec<u32> = (0..len).map(|i| s.at(sp + i)).collect();
142            self.matches_slice(&v, ignorecase)
143        }
144    }
145}
146
147#[inline]
148fn is_word_char(cp: u32, ignorecase: bool, unicode: bool) -> bool {
149    cp == '_' as u32
150        || matches!(cp, 0x30..=0x39 | 0x41..=0x5A | 0x61..=0x7A)
151        || (unicode && ignorecase && matches!(cp, 0x017F | 0x212A))
152}
153
154fn item_match(it: &ClassItem, cp: u32, ignorecase: bool, unicode: bool, v_mode: bool) -> bool {
155    match it {
156        ClassItem::Ch(x) => eqc(*x, cp, ignorecase, unicode),
157        ClassItem::Range(a, b) => {
158            if *a <= cp && cp <= *b {
159                return true;
160            }
161            if !ignorecase {
162                return false;
163            }
164            if unicode {
165                let mut buf = [0u32; 4];
166                let n = unicode::fold_equiv_unicode(cp, &mut buf);
167                buf[..n].iter().any(|&x| *a <= x && x <= *b)
168            } else {
169                let Some(c) = char::from_u32(cp) else {
170                    return false;
171                };
172                let single = |mut it: core::char::ToLowercase| match (it.next(), it.next()) {
173                    (Some(x), None) if !x.is_ascii() || c.is_ascii() => x as u32,
174                    _ => cp,
175                };
176                let lc = single(c.to_lowercase());
177                let uc = canonicalize_non_unicode(cp);
178                (*a <= lc && lc <= *b) || (*a <= uc && uc <= *b)
179            }
180        }
181        ClassItem::Digit => (0x30..=0x39).contains(&cp),
182        ClassItem::NotDigit => !(0x30..=0x39).contains(&cp),
183        ClassItem::Word => is_word_char(cp, ignorecase, unicode),
184        ClassItem::NotWord => !is_word_char(cp, ignorecase, unicode),
185        ClassItem::Space => char::from_u32(cp).is_some_and(is_js_space),
186        ClassItem::NotSpace => !char::from_u32(cp).is_some_and(is_js_space),
187        ClassItem::UnicodeProp(prop, negate) => {
188            if ignorecase && unicode {
189                let mut buf = [0u32; 4];
190                let n = unicode::fold_equiv_unicode(cp, &mut buf);
191                if v_mode {
192                    // v+i モードでは MaybeSimpleCaseFolding の後に補集合を取る(\P{Lu} は 'A','a' に一致しない)。
193                    buf[..n].iter().any(|&x| unicode::prop_matches(*prop, x)) ^ *negate
194                } else {
195                    // u+i モードでは \P{Lu} の補集合に対して Canonicalize が効く(\P{Lu} は 'A','a' に一致する)。
196                    buf[..n].iter().any(|&x| unicode::prop_matches(*prop, x) ^ *negate)
197                }
198            } else {
199                unicode::prop_matches(*prop, cp) ^ *negate
200            }
201        }
202    }
203}
204
205#[inline]
206fn eqc(a: u32, b: u32, ignorecase: bool, unicode: bool) -> bool {
207    if a == b {
208        return true;
209    }
210    if !ignorecase {
211        return false;
212    }
213    if unicode {
214        return unicode::canonicalize_unicode(a) == unicode::canonicalize_unicode(b);
215    }
216    if a < 128 && b < 128 {
217        return (a as u8).eq_ignore_ascii_case(&(b as u8));
218    }
219    canonicalize_non_unicode(a) == canonicalize_non_unicode(b)
220}
221
222/// 大文字と小文字を区別しない比較のための正規化(非 Unicode モードの Canonicalize)。
223fn canonicalize_non_unicode(cp: u32) -> u32 {
224    let Some(c) = char::from_u32(cp) else {
225        return cp;
226    };
227    let mut up = c.to_uppercase();
228    match (up.next(), up.next()) {
229        (Some(u), None) if !u.is_ascii() || c.is_ascii() => u as u32,
230        _ => cp,
231    }
232}
233
234/// 行の終わりの文字(仕様の LineTerminator)。`.` はこれらに一致せず、`m` フラグの `^`/`$` はこれらの前後に一致する。
235#[inline]
236fn is_line_term_u32(cp: u32) -> bool {
237    matches!(cp, 0x0A | 0x0D | 0x2028 | 0x2029)
238}
239
240/// JS の空白(`\s`・`trim` の対象。仕様の WhiteSpace と LineTerminator)。
241#[inline]
242pub(crate) fn is_js_space(c: char) -> bool {
243    matches!(
244        c,
245        '\t' | '\n' | '\u{0B}' | '\u{0C}' | '\r' | ' ' | '\u{A0}' | '\u{1680}' | '\u{2000}'..='\u{200A}'
246            | '\u{2028}' | '\u{2029}' | '\u{202F}' | '\u{205F}' | '\u{3000}' | '\u{FEFF}'
247    )
248}
249
250/// 単一コードポイント/コード単位に一致する原子(`RepeatAtom` 高速ループ用)。
251#[derive(Clone)]
252enum AtomKind {
253    Char(u32),
254    Any(bool), // dotall
255    Class(ClassData),
256    VClass(VSet),
257}
258
259impl AtomKind {
260    #[inline]
261    fn matches(&self, cp: u32, ic: bool, unicode: bool) -> bool {
262        match self {
263            AtomKind::Char(c) => eqc(*c, cp, ic, unicode),
264            AtomKind::Any(da) => *da || !is_line_term_u32(cp),
265            AtomKind::Class(cd) => cd.matches(cp, ic, unicode),
266            AtomKind::VClass(vs) => vs.matches_cp(cp, ic),
267        }
268    }
269}
270
271// ---- パース木 ----
272
273enum Node {
274    Empty,
275    Char(u32),
276    Any,
277    Class(ClassData),
278    VClass(VSet),
279    Start,
280    End,
281    WordBoundary(bool), // true=\b, false=\B
282    Group {
283        idx: Option<usize>,
284        node: Box<Node>,
285    },
286    Modifiers {
287        add: (bool, bool, bool),
288        rem: (bool, bool, bool),
289        node: Box<Node>,
290    },
291    Concat(Vec<Node>),
292    Alt(Vec<Node>),
293    Repeat {
294        node: Box<Node>,
295        min: usize,
296        max: Option<usize>,
297        greedy: bool,
298    },
299    Backref(usize),
300    NamedBackref(Vec<usize>),
301    Look {
302        ahead: bool,
303        negate: bool,
304        node: Box<Node>,
305    },
306}
307
308// ---- VM 命令 ----
309
310enum Inst {
311    Char(u32, bool),
312    CharRev(u32, bool),
313    Any(bool),
314    AnyRev(bool),
315    Class(ClassData, bool),
316    ClassRev(ClassData, bool),
317    VClass(VSet, bool),
318    VClassRev(VSet, bool),
319    RepeatAtom {
320        atom: AtomKind,
321        min: usize,
322        max: Option<usize>,
323        greedy: bool,
324        ic: bool,
325    },
326    RepeatAtomRev {
327        atom: AtomKind,
328        min: usize,
329        max: Option<usize>,
330        greedy: bool,
331        ic: bool,
332    },
333    CounterReset(usize),
334    CounterStep {
335        slot: usize,
336        min: usize,
337        max: Option<usize>,
338        greedy: bool,
339        body: usize,
340        after: usize,
341        clear: Option<(usize, usize)>,
342        loop_slot: Option<usize>,
343    },
344    Match,
345    Jmp(usize),
346    Split(usize, usize),
347    Save(usize),
348    AssertStart(bool),
349    AssertEnd(bool),
350    WordBoundary(bool, bool), // (want, ic)
351    Backref(usize, bool),
352    BackrefRev(usize, bool),
353    NamedBackref(Vec<usize>, bool),
354    NamedBackrefRev(Vec<usize>, bool),
355    Look {
356        ahead: bool,
357        negate: bool,
358        next: usize,
359    },
360    ClearCaps(usize, usize),
361    LoopStart(usize),
362    LoopCheck(usize),
363}
364
365enum Subject<'a> {
366    Chars(&'a [char]),
367    Units(Vec<u32>),
368}
369
370impl<'a> Subject<'a> {
371    #[inline]
372    fn len(&self) -> usize {
373        match self {
374            Subject::Chars(c) => c.len(),
375            Subject::Units(u) => u.len(),
376        }
377    }
378    #[inline]
379    fn at(&self, i: usize) -> u32 {
380        match self {
381            Subject::Chars(c) => c[i] as u32,
382            Subject::Units(u) => u[i],
383        }
384    }
385}
386
387pub struct Regex {
388    prog: Vec<Inst>,
389    pub ngroups: usize,
390    pub ignorecase: bool,
391    pub multiline: bool,
392    pub dotall: bool,
393    pub global: bool,
394    pub sticky: bool,
395    /// `d`(hasIndices)フラグ。
396    pub has_indices: bool,
397    pub unicode: bool,
398    pub unicode_sets: bool,
399    nloops: usize,
400    ncounters: usize,
401    pub source: String,
402    pub flags: String,
403    pub group_names: Vec<(String, usize)>,
404}
405
406/// 1 マッチ結果。captures[0] が全体、以降が各グループ(None は不参加)。
407pub struct Match {
408    pub start: usize,
409    pub end: usize,
410    pub captures: Vec<Option<(usize, usize)>>,
411}
412
413/// JS `RegExp` オブジェクトの内部状態(コンパイル済み + lastIndex)。
414pub struct RegExpData {
415    pub re: Regex,
416    pub last_index: usize,
417}
418
419struct Parser {
420    chars: Vec<char>,
421    pos: usize,
422    ngroups: usize,
423    group_names: Vec<(String, usize)>,
424    total: Option<usize>,
425    unicode: bool,
426    unicode_sets: bool,
427}
428
429impl Regex {
430    /// パターンとフラグからコンパイル。失敗時はリテラル一致にフォールバック。
431    pub fn new(pattern: &str, flags: &str) -> Regex {
432        let unicode_sets = flags.contains('v');
433        let unicode = flags.contains('u') || unicode_sets;
434        let mut p = Parser {
435            chars: pattern.chars().collect(),
436            pos: 0,
437            ngroups: 0,
438            group_names: Vec::new(),
439            total: None,
440            unicode,
441            unicode_sets,
442        };
443        let node = p.parse_alt();
444        let ngroups = p.ngroups;
445        let group_names = p.group_names;
446        let mut prog = Vec::new();
447        let ignorecase = flags.contains('i');
448        let multiline = flags.contains('m');
449        let dotall = flags.contains('s');
450        prog.push(Inst::Save(0));
451        compile(&node, &mut prog, (ignorecase, multiline, dotall), false);
452        prog.push(Inst::Save(1));
453        prog.push(Inst::Match);
454        let nloops = prog.iter().filter(|i| matches!(i, Inst::LoopStart(_))).count();
455        let ncounters = prog.iter().filter(|i| matches!(i, Inst::CounterReset(_))).count();
456        Regex {
457            prog,
458            nloops,
459            ncounters,
460            ngroups,
461            ignorecase,
462            multiline,
463            dotall,
464            global: flags.contains('g'),
465            sticky: flags.contains('y'),
466            has_indices: flags.contains('d'),
467            unicode: flags.contains('u'),
468            unicode_sets,
469            source: String::from(pattern),
470            flags: "dgimsuvy".chars().filter(|c| flags.contains(*c)).collect(),
471            group_names,
472        }
473    }
474
475    /// `start` 以降で最初のマッチを探す。
476    pub fn find_at(&self, subject: &[char], start: usize) -> Option<Match> {
477        let (subj, map) = self.make_subject(subject);
478        let u_start = match &map {
479            None => start,
480            Some(_) => subject.iter().take(start).map(|c| c.len_utf16()).sum(),
481        };
482        let mut caps = Vec::new();
483        let mut stash = Vec::new();
484        for sp in u_start..=subj.len() {
485            if let Some(m) = self.try_match_at_buf(&subj, sp, &mut caps, &mut stash, map.as_deref()) {
486                return Some(m);
487            }
488        }
489        None
490    }
491
492    /// `y`(sticky)フラグ用: `start` の位置でのみマッチを試みる(前方探索しない)。
493    pub fn find_exact_at(&self, subject: &[char], start: usize) -> Option<Match> {
494        if start > subject.len() {
495            return None;
496        }
497        let (subj, map) = self.make_subject(subject);
498        let u_start = match &map {
499            None => start,
500            Some(_) => subject.iter().take(start).map(|c| c.len_utf16()).sum(),
501        };
502        if u_start > subj.len() {
503            return None;
504        }
505        self.try_match_at_buf(&subj, u_start, &mut Vec::new(), &mut Vec::new(), map.as_deref())
506    }
507
508    fn make_subject<'a>(&self, subject: &'a [char]) -> (Subject<'a>, Option<Vec<usize>>) {
509        if self.unicode || self.unicode_sets || subject.iter().all(|&c| (c as u32) <= 0xFFFF) {
510            return (Subject::Chars(subject), None);
511        }
512        let mut units = Vec::with_capacity(subject.len() + 8);
513        let mut map = Vec::with_capacity(subject.len() + 9);
514        for (ci, &c) in subject.iter().enumerate() {
515            let u = c as u32;
516            if u <= 0xFFFF {
517                units.push(u);
518                map.push(ci);
519            } else {
520                let n = u - 0x10000;
521                units.push(0xD800 + (n >> 10));
522                map.push(ci);
523                units.push(0xDC00 + (n & 0x3FF));
524                map.push(ci);
525            }
526        }
527        map.push(subject.len());
528        (Subject::Units(units), Some(map))
529    }
530
531    fn try_match_at_buf(
532        &self,
533        subject: &Subject<'_>,
534        sp: usize,
535        caps: &mut Vec<isize>,
536        stash: &mut Vec<isize>,
537        map: Option<&[usize]>,
538    ) -> Option<Match> {
539        let nslots = 2 * (self.ngroups + 1) + self.nloops + self.ncounters;
540        caps.clear();
541        caps.resize(nslots, -1);
542        stash.clear();
543        let mut budget: u32 = 600_000;
544        if self.run(0, subject, sp, caps, &mut budget, stash) {
545            let map_pos = |u: usize| -> usize {
546                match map {
547                    Some(m) => m.get(u).copied().unwrap_or_else(|| *m.last().unwrap_or(&0)),
548                    None => u,
549                }
550            };
551            let s = map_pos(caps[0].max(0) as usize);
552            let e = map_pos(caps[1].max(0) as usize);
553            let mut captures = Vec::with_capacity(self.ngroups + 1);
554            for g in 0..=self.ngroups {
555                let a = caps[2 * g];
556                let b = caps[2 * g + 1];
557                if a >= 0 && b >= 0 {
558                    captures.push(Some((map_pos(a as usize), map_pos(b as usize))));
559                } else {
560                    captures.push(None);
561                }
562            }
563            Some(Match {
564                start: s,
565                end: e,
566                captures,
567            })
568        } else {
569            None
570        }
571    }
572
573    fn run(
574        &self,
575        mut pc: usize,
576        s: &Subject<'_>,
577        mut sp: usize,
578        caps: &mut Vec<isize>,
579        budget: &mut u32,
580        stash: &mut Vec<isize>,
581    ) -> bool {
582        let uni = self.unicode || self.unicode_sets;
583        loop {
584            if *budget == 0 {
585                return false;
586            }
587            *budget -= 1;
588            match &self.prog[pc] {
589                Inst::Match => return true,
590                Inst::Char(c, ic) => {
591                    if sp < s.len() && eqc(*c, s.at(sp), *ic, uni) {
592                        pc += 1;
593                        sp += 1;
594                    } else {
595                        return false;
596                    }
597                }
598                Inst::CharRev(c, ic) => {
599                    if sp > 0 && eqc(*c, s.at(sp - 1), *ic, uni) {
600                        pc += 1;
601                        sp -= 1;
602                    } else {
603                        return false;
604                    }
605                }
606                Inst::Any(da) => {
607                    if sp < s.len() && (*da || !is_line_term_u32(s.at(sp))) {
608                        pc += 1;
609                        sp += 1;
610                    } else {
611                        return false;
612                    }
613                }
614                Inst::AnyRev(da) => {
615                    if sp > 0 && (*da || !is_line_term_u32(s.at(sp - 1))) {
616                        pc += 1;
617                        sp -= 1;
618                    } else {
619                        return false;
620                    }
621                }
622                Inst::Class(cd, ic) => {
623                    if sp < s.len() && cd.matches(s.at(sp), *ic, uni) {
624                        pc += 1;
625                        sp += 1;
626                    } else {
627                        return false;
628                    }
629                }
630                Inst::ClassRev(cd, ic) => {
631                    if sp > 0 && cd.matches(s.at(sp - 1), *ic, uni) {
632                        pc += 1;
633                        sp -= 1;
634                    } else {
635                        return false;
636                    }
637                }
638                Inst::VClass(vs, ic) => {
639                    if vs.is_single_cp_only() {
640                        if sp < s.len() && vs.matches_cp(s.at(sp), *ic) {
641                            pc += 1;
642                            sp += 1;
643                        } else {
644                            return false;
645                        }
646                    } else {
647                        let max_l = vs.max_len().min(s.len() - sp);
648                        let min_l = if vs.can_empty() { 0 } else { 1 };
649                        for l in (min_l..=max_l).rev() {
650                            if l == 0 && !vs.can_empty() {
651                                continue;
652                            }
653                            if vs.matches_subject(s, sp, l, *ic)
654                                && self.run(pc + 1, s, sp + l, caps, budget, stash)
655                            {
656                                return true;
657                            }
658                        }
659                        return false;
660                    }
661                }
662                Inst::VClassRev(vs, ic) => {
663                    if vs.is_single_cp_only() {
664                        if sp > 0 && vs.matches_cp(s.at(sp - 1), *ic) {
665                            pc += 1;
666                            sp -= 1;
667                        } else {
668                            return false;
669                        }
670                    } else {
671                        let max_l = vs.max_len().min(sp);
672                        let min_l = if vs.can_empty() { 0 } else { 1 };
673                        for l in (min_l..=max_l).rev() {
674                            if l == 0 && !vs.can_empty() {
675                                continue;
676                            }
677                            if vs.matches_subject(s, sp - l, l, *ic)
678                                && self.run(pc + 1, s, sp - l, caps, budget, stash)
679                            {
680                                return true;
681                            }
682                        }
683                        return false;
684                    }
685                }
686                Inst::RepeatAtom { atom, min, max, greedy, ic } => {
687                    if s.len().saturating_sub(sp) < *min {
688                        return false;
689                    }
690                    let min_end = sp + *min;
691                    while sp < min_end {
692                        if !atom.matches(s.at(sp), *ic, uni) {
693                            return false;
694                        }
695                        sp += 1;
696                    }
697                    let limit = match max {
698                        Some(mx) => min_end.saturating_add(mx.saturating_sub(*min)).min(s.len()),
699                        None => s.len(),
700                    };
701                    if *greedy {
702                        let mut end = sp;
703                        while end < limit && atom.matches(s.at(end), *ic, uni) {
704                            end += 1;
705                        }
706                        if matches!(self.prog.get(pc + 1), Some(Inst::Match)) {
707                            return true;
708                        }
709                        let mut k = end;
710                        loop {
711                            if self.run(pc + 1, s, k, caps, budget, stash) {
712                                return true;
713                            }
714                            if k == min_end || *budget == 0 {
715                                return false;
716                            }
717                            k -= 1;
718                        }
719                    } else {
720                        let mut k = min_end;
721                        loop {
722                            if self.run(pc + 1, s, k, caps, budget, stash) {
723                                return true;
724                            }
725                            if k >= limit || *budget == 0 || !atom.matches(s.at(k), *ic, uni) {
726                                return false;
727                            }
728                            k += 1;
729                        }
730                    }
731                }
732                Inst::RepeatAtomRev { atom, min, max, greedy, ic } => {
733                    if sp < *min {
734                        return false;
735                    }
736                    let min_pos = sp - *min;
737                    while sp > min_pos {
738                        sp -= 1;
739                        if !atom.matches(s.at(sp), *ic, uni) {
740                            return false;
741                        }
742                    }
743                    let limit = match max {
744                        Some(mx) => min_pos.saturating_sub(mx.saturating_sub(*min)),
745                        None => 0,
746                    };
747                    if *greedy {
748                        let mut start = sp;
749                        while start > limit && atom.matches(s.at(start - 1), *ic, uni) {
750                            start -= 1;
751                        }
752                        let mut k = start;
753                        loop {
754                            if self.run(pc + 1, s, k, caps, budget, stash) {
755                                return true;
756                            }
757                            if k == min_pos || *budget == 0 {
758                                return false;
759                            }
760                            k += 1;
761                        }
762                    } else {
763                        let mut k = min_pos;
764                        loop {
765                            if self.run(pc + 1, s, k, caps, budget, stash) {
766                                return true;
767                            }
768                            if k <= limit || *budget == 0 || !atom.matches(s.at(k - 1), *ic, uni) {
769                                return false;
770                            }
771                            k -= 1;
772                        }
773                    }
774                }
775                Inst::CounterReset(c) => {
776                    let slot = 2 * (self.ngroups + 1) + self.nloops + *c;
777                    let old = caps.get(slot).copied().unwrap_or(-1);
778                    if let Some(p) = caps.get_mut(slot) {
779                        *p = 0;
780                    }
781                    if self.run(pc + 1, s, sp, caps, budget, stash) {
782                        return true;
783                    }
784                    if let Some(p) = caps.get_mut(slot) {
785                        *p = old;
786                    }
787                    return false;
788                }
789                Inst::CounterStep { slot: c, min, max, greedy, body, after, clear, loop_slot } => {
790                    let slot_idx = 2 * (self.ngroups + 1) + self.nloops + *c;
791                    let cnt = caps.get(slot_idx).copied().unwrap_or(0).max(0) as usize;
792                    if max.is_some_and(|mx| cnt >= mx) {
793                        pc = *after;
794                        continue;
795                    }
796                    let must = cnt < *min;
797                    let try_body = |caps: &mut Vec<isize>, budget: &mut u32, stash: &mut Vec<isize>| -> bool {
798                        let base = stash.len();
799                        let n = caps.len();
800                        stash.extend_from_slice(caps);
801                        if let Some(p) = caps.get_mut(slot_idx) {
802                            *p = (cnt + 1) as isize;
803                        }
804                        if let Some((a, b)) = clear {
805                            let (a, b) = (*a, (*b).min(caps.len()));
806                            for x in caps.get_mut(a..b).into_iter().flatten() {
807                                *x = -1;
808                            }
809                        }
810                        if !must {
811                            if let Some(ls) = loop_slot {
812                                let lslot = 2 * (self.ngroups + 1) + *ls;
813                                if let Some(p) = caps.get_mut(lslot) {
814                                    *p = sp as isize;
815                                }
816                            }
817                        }
818                        let ok = self.run(*body, s, sp, caps, budget, stash);
819                        if ok {
820                            stash.truncate(base);
821                            return true;
822                        }
823                        caps.clear();
824                        caps.extend_from_slice(stash.get(base..base + n).unwrap_or(&[]));
825                        stash.truncate(base);
826                        false
827                    };
828                    if must {
829                        return try_body(caps, budget, stash);
830                    }
831                    if *greedy {
832                        if try_body(caps, budget, stash) {
833                            return true;
834                        }
835                        pc = *after;
836                    } else {
837                        let base = stash.len();
838                        let n = caps.len();
839                        stash.extend_from_slice(caps);
840                        if self.run(*after, s, sp, caps, budget, stash) {
841                            stash.truncate(base);
842                            return true;
843                        }
844                        caps.clear();
845                        caps.extend_from_slice(stash.get(base..base + n).unwrap_or(&[]));
846                        stash.truncate(base);
847                        return try_body(caps, budget, stash);
848                    }
849                }
850                Inst::Jmp(x) => pc = *x,
851                Inst::Split(a, b) => {
852                    let (a, b) = (*a, *b);
853                    let base = stash.len();
854                    let n = caps.len();
855                    stash.extend_from_slice(caps);
856                    if self.run(a, s, sp, caps, budget, stash) {
857                        stash.truncate(base);
858                        return true;
859                    }
860                    caps.clear();
861                    caps.extend_from_slice(stash.get(base..base + n).unwrap_or(&[]));
862                    stash.truncate(base);
863                    pc = b;
864                }
865                Inst::Save(n) => {
866                    let n = *n;
867                    let old = caps[n];
868                    caps[n] = sp as isize;
869                    if self.run(pc + 1, s, sp, caps, budget, stash) {
870                        return true;
871                    }
872                    caps[n] = old;
873                    return false;
874                }
875                Inst::AssertStart(ml) => {
876                    let ok = sp == 0 || (*ml && sp > 0 && is_line_term_u32(s.at(sp - 1)));
877                    if ok {
878                        pc += 1;
879                    } else {
880                        return false;
881                    }
882                }
883                Inst::AssertEnd(ml) => {
884                    let ok = sp == s.len() || (*ml && is_line_term_u32(s.at(sp)));
885                    if ok {
886                        pc += 1;
887                    } else {
888                        return false;
889                    }
890                }
891                Inst::WordBoundary(want, ic) => {
892                    let before = sp > 0 && is_word_char(s.at(sp - 1), *ic, uni);
893                    let after = sp < s.len() && is_word_char(s.at(sp), *ic, uni);
894                    let boundary = before != after;
895                    if boundary == *want {
896                        pc += 1;
897                    } else {
898                        return false;
899                    }
900                }
901                Inst::Look { ahead: _, negate, next } => {
902                    let (negate, next) = (*negate, *next);
903                    let base = stash.len();
904                    let n = caps.len();
905                    stash.extend_from_slice(caps);
906                    let matched = self.run(pc + 1, s, sp, caps, budget, stash);
907                    if matched == negate {
908                        caps.clear();
909                        caps.extend_from_slice(stash.get(base..base + n).unwrap_or(&[]));
910                        stash.truncate(base);
911                        return false;
912                    }
913                    if negate {
914                        caps.clear();
915                        caps.extend_from_slice(stash.get(base..base + n).unwrap_or(&[]));
916                    }
917                    stash.truncate(base);
918                    pc = next;
919                }
920                Inst::ClearCaps(a, b) => {
921                    let (a, b) = (*a, (*b).min(caps.len()));
922                    if caps.get(a..b).is_none_or(|c| c.iter().all(|&x| x < 0)) {
923                        pc += 1;
924                        continue;
925                    }
926                    let base = stash.len();
927                    stash.extend_from_slice(caps.get(a..b).unwrap_or(&[]));
928                    for c in caps.get_mut(a..b).into_iter().flatten() {
929                        *c = -1;
930                    }
931                    if self.run(pc + 1, s, sp, caps, budget, stash) {
932                        stash.truncate(base);
933                        return true;
934                    }
935                    if let Some(dst) = caps.get_mut(a..b) {
936                        if let Some(src) = stash.get(base..base + (b - a)) {
937                            dst.copy_from_slice(src);
938                        }
939                    }
940                    stash.truncate(base);
941                    return false;
942                }
943                Inst::LoopStart(k) => {
944                    let slot = 2 * (self.ngroups + 1) + *k;
945                    let old = caps.get(slot).copied().unwrap_or(-1);
946                    if let Some(c) = caps.get_mut(slot) {
947                        *c = sp as isize;
948                    }
949                    if self.run(pc + 1, s, sp, caps, budget, stash) {
950                        return true;
951                    }
952                    if let Some(c) = caps.get_mut(slot) {
953                        *c = old;
954                    }
955                    return false;
956                }
957                Inst::LoopCheck(k) => {
958                    if caps.get(2 * (self.ngroups + 1) + *k).copied() == Some(sp as isize) {
959                        return false;
960                    }
961                    pc += 1;
962                }
963                Inst::Backref(idx, ic) => {
964                    let a = caps.get(2 * idx).copied().unwrap_or(-1);
965                    let b = caps.get(2 * idx + 1).copied().unwrap_or(-1);
966                    if a < 0 || b < 0 {
967                        pc += 1;
968                        continue;
969                    }
970                    let (a, b) = (a as usize, b as usize);
971                    let len = b.saturating_sub(a);
972                    if sp + len <= s.len() && (0..len).all(|k| eqc(s.at(a + k), s.at(sp + k), *ic, uni)) {
973                        sp += len;
974                        pc += 1;
975                    } else {
976                        return false;
977                    }
978                }
979                Inst::BackrefRev(idx, ic) => {
980                    let a = caps.get(2 * idx).copied().unwrap_or(-1);
981                    let b = caps.get(2 * idx + 1).copied().unwrap_or(-1);
982                    if a < 0 || b < 0 {
983                        pc += 1;
984                        continue;
985                    }
986                    let (a, b) = (a as usize, b as usize);
987                    let len = b.saturating_sub(a);
988                    if sp >= len && (0..len).all(|k| eqc(s.at(a + k), s.at(sp - len + k), *ic, uni)) {
989                        sp -= len;
990                        pc += 1;
991                    } else {
992                        return false;
993                    }
994                }
995                Inst::NamedBackref(idxs, ic) => {
996                    let matched = idxs.iter().find_map(|&idx| {
997                        let a = caps.get(2 * idx).copied().unwrap_or(-1);
998                        let b = caps.get(2 * idx + 1).copied().unwrap_or(-1);
999                        if a >= 0 && b >= 0 { Some((a as usize, b as usize)) } else { None }
1000                    });
1001                    let Some((a, b)) = matched else {
1002                        pc += 1;
1003                        continue;
1004                    };
1005                    let len = b.saturating_sub(a);
1006                    if sp + len <= s.len() && (0..len).all(|k| eqc(s.at(a + k), s.at(sp + k), *ic, uni)) {
1007                        sp += len;
1008                        pc += 1;
1009                    } else {
1010                        return false;
1011                    }
1012                }
1013                Inst::NamedBackrefRev(idxs, ic) => {
1014                    let matched = idxs.iter().find_map(|&idx| {
1015                        let a = caps.get(2 * idx).copied().unwrap_or(-1);
1016                        let b = caps.get(2 * idx + 1).copied().unwrap_or(-1);
1017                        if a >= 0 && b >= 0 { Some((a as usize, b as usize)) } else { None }
1018                    });
1019                    let Some((a, b)) = matched else {
1020                        pc += 1;
1021                        continue;
1022                    };
1023                    let len = b.saturating_sub(a);
1024                    if sp >= len && (0..len).all(|k| eqc(s.at(a + k), s.at(sp - len + k), *ic, uni)) {
1025                        sp -= len;
1026                        pc += 1;
1027                    } else {
1028                        return false;
1029                    }
1030                }
1031            }
1032        }
1033    }
1034}
1035
1036/// この部分が文字を 1 つも進めずに一致しうるか(控えめに見積もる。迷ったら true)。
1037fn can_match_empty(node: &Node) -> bool {
1038    match node {
1039        Node::Char(_) | Node::Any | Node::Class(_) => false,
1040        Node::VClass(vs) => vs.can_empty(),
1041        Node::Group { node, .. } | Node::Modifiers { node, .. } => can_match_empty(node),
1042        Node::Concat(items) => items.iter().all(can_match_empty),
1043        Node::Alt(branches) => branches.iter().any(can_match_empty),
1044        Node::Repeat { node, min, .. } => *min == 0 || can_match_empty(node),
1045        _ => true,
1046    }
1047}
1048
1049fn single_atom(node: &Node) -> Option<AtomKind> {
1050    match node {
1051        Node::Char(c) => Some(AtomKind::Char(*c)),
1052        Node::Any => None, // depends on `da` at compile time
1053        Node::Class(cd) => Some(AtomKind::Class(cd.clone())),
1054        Node::VClass(vs) if vs.is_single_cp_only() => Some(AtomKind::VClass(vs.clone())),
1055        _ => None,
1056    }
1057}
1058
1059fn compile(node: &Node, prog: &mut Vec<Inst>, flags: (bool, bool, bool), rev: bool) {
1060    let (ic, ml, da) = flags;
1061    match node {
1062        Node::Empty => {}
1063        Node::Char(c) => prog.push(if rev { Inst::CharRev(*c, ic) } else { Inst::Char(*c, ic) }),
1064        Node::Any => prog.push(if rev { Inst::AnyRev(da) } else { Inst::Any(da) }),
1065        Node::Class(cd) => prog.push(if rev {
1066            Inst::ClassRev(cd.clone(), ic)
1067        } else {
1068            Inst::Class(cd.clone(), ic)
1069        }),
1070        Node::VClass(vs) => prog.push(if rev {
1071            Inst::VClassRev(vs.clone(), ic)
1072        } else {
1073            Inst::VClass(vs.clone(), ic)
1074        }),
1075        Node::Start => prog.push(Inst::AssertStart(ml)),
1076        Node::End => prog.push(Inst::AssertEnd(ml)),
1077        Node::WordBoundary(b) => prog.push(Inst::WordBoundary(*b, ic)),
1078        Node::Backref(i) => prog.push(if rev { Inst::BackrefRev(*i, ic) } else { Inst::Backref(*i, ic) }),
1079        Node::NamedBackref(idxs) => prog.push(if rev {
1080            Inst::NamedBackrefRev(idxs.clone(), ic)
1081        } else {
1082            Inst::NamedBackref(idxs.clone(), ic)
1083        }),
1084        Node::Modifiers { add, rem, node } => {
1085            let next_flags = (
1086                (ic || add.0) && !rem.0,
1087                (ml || add.1) && !rem.1,
1088                (da || add.2) && !rem.2,
1089            );
1090            compile(node, prog, next_flags, rev);
1091        }
1092        Node::Look { ahead, negate, node } => {
1093            let look_pc = prog.len();
1094            prog.push(Inst::Look {
1095                ahead: *ahead,
1096                negate: *negate,
1097                next: 0,
1098            });
1099            compile(node, prog, flags, !*ahead);
1100            prog.push(Inst::Match);
1101            let next = prog.len();
1102            if let Inst::Look { next: n, .. } = &mut prog[look_pc] {
1103                *n = next;
1104            }
1105        }
1106        Node::Concat(items) => {
1107            if rev {
1108                for it in items.iter().rev() {
1109                    compile(it, prog, flags, true);
1110                }
1111            } else {
1112                for it in items {
1113                    compile(it, prog, flags, false);
1114                }
1115            }
1116        }
1117        Node::Group { idx, node } => {
1118            if rev {
1119                if let Some(i) = idx {
1120                    prog.push(Inst::Save(2 * i + 1));
1121                }
1122                compile(node, prog, flags, true);
1123                if let Some(i) = idx {
1124                    prog.push(Inst::Save(2 * i));
1125                }
1126            } else {
1127                if let Some(i) = idx {
1128                    prog.push(Inst::Save(2 * i));
1129                }
1130                compile(node, prog, flags, false);
1131                if let Some(i) = idx {
1132                    prog.push(Inst::Save(2 * i + 1));
1133                }
1134            }
1135        }
1136        Node::Alt(branches) => {
1137            let mut jmp_fixups = Vec::new();
1138            for (k, br) in branches.iter().enumerate() {
1139                if k + 1 < branches.len() {
1140                    let split_pc = prog.len();
1141                    prog.push(Inst::Split(0, 0));
1142                    let l1 = prog.len();
1143                    compile(br, prog, flags, rev);
1144                    let jmp_pc = prog.len();
1145                    prog.push(Inst::Jmp(0));
1146                    jmp_fixups.push(jmp_pc);
1147                    let l2 = prog.len();
1148                    if let Inst::Split(a, b) = &mut prog[split_pc] {
1149                        *a = l1;
1150                        *b = l2;
1151                    }
1152                } else {
1153                    compile(br, prog, flags, rev);
1154                }
1155            }
1156            let end = prog.len();
1157            for j in jmp_fixups {
1158                if let Inst::Jmp(x) = &mut prog[j] {
1159                    *x = end;
1160                }
1161            }
1162        }
1163        Node::Repeat {
1164            node,
1165            min,
1166            max,
1167            greedy,
1168        } => {
1169            if let Some(atom) = match node.as_ref() {
1170                Node::Any => Some(AtomKind::Any(da)),
1171                _ => single_atom(node),
1172            } {
1173                prog.push(if rev {
1174                    Inst::RepeatAtomRev {
1175                        atom,
1176                        min: *min,
1177                        max: *max,
1178                        greedy: *greedy,
1179                        ic,
1180                    }
1181                } else {
1182                    Inst::RepeatAtom {
1183                        atom,
1184                        min: *min,
1185                        max: *max,
1186                        greedy: *greedy,
1187                        ic,
1188                    }
1189                });
1190                return;
1191            }
1192            let clear_range = group_range(node).map(|(lo, hi)| (2 * lo, 2 * hi + 2));
1193            let large = *min > 16 || max.is_some_and(|mx| mx.saturating_sub(*min) > 16);
1194            if large {
1195                let cslot = prog.iter().filter(|i| matches!(i, Inst::CounterReset(_))).count();
1196                prog.push(Inst::CounterReset(cslot));
1197                let loop_slot = if can_match_empty(node) {
1198                    Some(prog.iter().filter(|i| matches!(i, Inst::LoopStart(_))).count())
1199                } else {
1200                    None
1201                };
1202                if let Some(ls) = loop_slot {
1203                    // CounterStep が LoopStart のスロットを使うことを compile 時カウントへ知らせるためダミーは置かないが
1204                    // nloops 計算のために直接は増えないので、ここでは LoopStart/LoopCheck 方式の代わりに
1205                    // CounterStep 用プレースホルダを避け、通常通り LoopStart/LoopCheck を body 内に置く。
1206                    let _ = ls;
1207                }
1208                let step_pc = prog.len();
1209                prog.push(Inst::CounterStep {
1210                    slot: cslot,
1211                    min: *min,
1212                    max: *max,
1213                    greedy: *greedy,
1214                    body: 0,
1215                    after: 0,
1216                    clear: clear_range,
1217                    loop_slot: None,
1218                });
1219                let body = prog.len();
1220                if can_match_empty(node) {
1221                    let k = prog.iter().filter(|i| matches!(i, Inst::LoopStart(_))).count();
1222                    // min 未満は空一致を許す必要があるため、CounterStep 側で loop_slot を使うのではなく
1223                    // body はそのままにして LoopCheck は count >= min の時だけ効かせるか、
1224                    // あるいは min が大きすぎない場合は展開、巨大 min のときはそのまま実行。
1225                    let _ = k;
1226                }
1227                compile(node, prog, flags, rev);
1228                prog.push(Inst::Jmp(step_pc));
1229                let after = prog.len();
1230                if let Inst::CounterStep { body: b, after: a, .. } = &mut prog[step_pc] {
1231                    *b = body;
1232                    *a = after;
1233                }
1234                return;
1235            }
1236            let body_once = |prog: &mut Vec<Inst>| {
1237                if let Some((a, b)) = clear_range {
1238                    prog.push(Inst::ClearCaps(a, b));
1239                }
1240                compile(node, prog, flags, rev);
1241            };
1242            for _ in 0..*min {
1243                body_once(prog);
1244            }
1245            let empty_check = can_match_empty(node);
1246            match max {
1247                None => {
1248                    let l1 = prog.len();
1249                    let split_pc = prog.len();
1250                    prog.push(Inst::Split(0, 0));
1251                    let body = prog.len();
1252                    if empty_check {
1253                        let k = prog.iter().filter(|i| matches!(i, Inst::LoopStart(_))).count();
1254                        prog.push(Inst::LoopStart(k));
1255                        body_once(prog);
1256                        prog.push(Inst::LoopCheck(k));
1257                    } else {
1258                        body_once(prog);
1259                    }
1260                    prog.push(Inst::Jmp(l1));
1261                    let after = prog.len();
1262                    if let Inst::Split(a, b) = &mut prog[split_pc] {
1263                        if *greedy {
1264                            *a = body;
1265                            *b = after;
1266                        } else {
1267                            *a = after;
1268                            *b = body;
1269                        }
1270                    }
1271                }
1272                Some(mx) => {
1273                    let opt = mx.saturating_sub(*min);
1274                    let mut split_fixups = Vec::new();
1275                    for _ in 0..opt {
1276                        let split_pc = prog.len();
1277                        prog.push(Inst::Split(0, 0));
1278                        let body = prog.len();
1279                        if empty_check {
1280                            let k = prog.iter().filter(|i| matches!(i, Inst::LoopStart(_))).count();
1281                            prog.push(Inst::LoopStart(k));
1282                            body_once(prog);
1283                            prog.push(Inst::LoopCheck(k));
1284                        } else {
1285                            body_once(prog);
1286                        }
1287                        split_fixups.push((split_pc, body));
1288                    }
1289                    let after = prog.len();
1290                    for (sp_pc, body) in split_fixups {
1291                        if let Inst::Split(a, b) = &mut prog[sp_pc] {
1292                            if *greedy {
1293                                *a = body;
1294                                *b = after;
1295                            } else {
1296                                *a = after;
1297                                *b = body;
1298                            }
1299                        }
1300                    }
1301                }
1302            }
1303        }
1304    }
1305}
1306
1307/// この部分に含まれる捕捉の番号の範囲(最小, 最大)。無ければ `None`。
1308fn group_range(node: &Node) -> Option<(usize, usize)> {
1309    let merge = |a: Option<(usize, usize)>, b: Option<(usize, usize)>| match (a, b) {
1310        (Some((a0, a1)), Some((b0, b1))) => Some((a0.min(b0), a1.max(b1))),
1311        (x, None) | (None, x) => x,
1312    };
1313    match node {
1314        Node::Group { idx, node } => merge(idx.map(|i| (i, i)), group_range(node)),
1315        Node::Concat(items) | Node::Alt(items) => items.iter().map(group_range).fold(None, merge),
1316        Node::Repeat { node, .. } | Node::Look { node, .. } | Node::Modifiers { node, .. } => {
1317            group_range(node)
1318        }
1319        _ => None,
1320    }
1321}
1322
1323impl Parser {
1324    fn peek(&self) -> Option<char> {
1325        self.chars.get(self.pos).copied()
1326    }
1327    fn peek_at(&self, offset: usize) -> Option<char> {
1328        self.chars.get(self.pos + offset).copied()
1329    }
1330    fn bump(&mut self) -> Option<char> {
1331        let c = self.peek();
1332        if c.is_some() {
1333            self.pos += 1;
1334        }
1335        c
1336    }
1337    fn eat(&mut self, c: char) -> bool {
1338        if self.peek() == Some(c) {
1339            self.pos += 1;
1340            true
1341        } else {
1342            false
1343        }
1344    }
1345    fn starts(&self, s: &str) -> bool {
1346        s.chars().enumerate().all(|(k, ch)| self.peek_at(k) == Some(ch))
1347    }
1348
1349    fn parse_alt(&mut self) -> Node {
1350        let mut branches = vec![self.parse_concat()];
1351        while self.eat('|') {
1352            branches.push(self.parse_concat());
1353        }
1354        if branches.len() == 1 {
1355            branches.pop().unwrap_or(Node::Empty)
1356        } else {
1357            Node::Alt(branches)
1358        }
1359    }
1360
1361    fn parse_concat(&mut self) -> Node {
1362        let mut items = Vec::new();
1363        while let Some(c) = self.peek() {
1364            if c == '|' || c == ')' {
1365                break;
1366            }
1367            let atom = self.parse_atom();
1368            let quantified = self.parse_quantifier(atom);
1369            items.push(quantified);
1370        }
1371        if items.is_empty() {
1372            Node::Empty
1373        } else if items.len() == 1 {
1374            items.pop().unwrap_or(Node::Empty)
1375        } else {
1376            Node::Concat(items)
1377        }
1378    }
1379
1380    fn parse_quantifier(&mut self, atom: Node) -> Node {
1381        let (min, max) = match self.peek() {
1382            Some('*') => {
1383                self.bump();
1384                (0, None)
1385            }
1386            Some('+') => {
1387                self.bump();
1388                (1, None)
1389            }
1390            Some('?') => {
1391                self.bump();
1392                (0, Some(1))
1393            }
1394            Some('{') => {
1395                if let Some((mn, mx)) = self.try_parse_brace() {
1396                    (mn, mx)
1397                } else {
1398                    return atom;
1399                }
1400            }
1401            _ => return atom,
1402        };
1403        let greedy = !self.eat('?');
1404        Node::Repeat {
1405            node: Box::new(atom),
1406            min,
1407            max,
1408            greedy,
1409        }
1410    }
1411
1412    fn try_parse_brace(&mut self) -> Option<(usize, Option<usize>)> {
1413        let save = self.pos;
1414        self.bump(); // {
1415        let mut min_s = String::new();
1416        while let Some(c) = self.peek() {
1417            if c.is_ascii_digit() {
1418                min_s.push(c);
1419                self.bump();
1420            } else {
1421                break;
1422            }
1423        }
1424        if min_s.is_empty() {
1425            self.pos = save;
1426            return None;
1427        }
1428        let min: usize = min_s.parse().unwrap_or(usize::MAX);
1429        let max = if self.eat(',') {
1430            let mut max_s = String::new();
1431            while let Some(c) = self.peek() {
1432                if c.is_ascii_digit() {
1433                    max_s.push(c);
1434                    self.bump();
1435                } else {
1436                    break;
1437                }
1438            }
1439            if max_s.is_empty() {
1440                None
1441            } else {
1442                Some(max_s.parse().unwrap_or(usize::MAX))
1443            }
1444        } else {
1445            Some(min)
1446        };
1447        if !self.eat('}') {
1448            self.pos = save;
1449            return None;
1450        }
1451        Some((min, max))
1452    }
1453
1454    /// `<` の直後から `>` までのグループ名を読む(`\uXXXX` / `\u{...}` とサロゲート対を解釈)。
1455    fn parse_group_name(&mut self) -> String {
1456        let mut name = String::new();
1457        while let Some(c) = self.peek() {
1458            if c == '>' {
1459                self.bump();
1460                break;
1461            }
1462            if c == '\\' && self.peek_at(1) == Some('u') {
1463                self.bump(); // \
1464                self.bump(); // u
1465                if let Some(cp) = self.parse_u_escape(true, true) {
1466                    if let Some(ch) = char::from_u32(cp) {
1467                        name.push(ch);
1468                        continue;
1469                    }
1470                }
1471                name.push('u');
1472            } else {
1473                self.bump();
1474                name.push(c);
1475            }
1476        }
1477        name
1478    }
1479
1480    fn parse_atom(&mut self) -> Node {
1481        match self.peek() {
1482            Some('(') => {
1483                self.bump();
1484                let mut group_name: Option<String> = None;
1485                let idx = if self.peek() == Some('?') {
1486                    self.bump(); // ?
1487                    if self.peek() == Some('<') && !matches!(self.peek_at(1), Some('=') | Some('!'))
1488                    {
1489                        self.bump(); // <
1490                        let name = self.parse_group_name();
1491                        self.ngroups += 1;
1492                        group_name = Some(name);
1493                        Some(self.ngroups)
1494                    } else {
1495                        let look = match (self.peek(), self.peek_at(1)) {
1496                            (Some('='), _) => Some((true, false, 1)),
1497                            (Some('!'), _) => Some((true, true, 1)),
1498                            (Some('<'), Some('=')) => Some((false, false, 2)),
1499                            (Some('<'), Some('!')) => Some((false, true, 2)),
1500                            _ => None,
1501                        };
1502                        if let Some((ahead, negate, n)) = look {
1503                            for _ in 0..n {
1504                                self.bump();
1505                            }
1506                            let inner = self.parse_alt();
1507                            self.eat(')');
1508                            return Node::Look { ahead, negate, node: Box::new(inner) };
1509                        }
1510                        if self.peek() == Some(':') {
1511                            self.bump();
1512                            None
1513                        } else {
1514                            let mut add = (false, false, false);
1515                            let mut rem = (false, false, false);
1516                            let mut neg = false;
1517                            while let Some(c) = self.peek() {
1518                                match c {
1519                                    '-' if !neg => {
1520                                        neg = true;
1521                                        self.bump();
1522                                    }
1523                                    'i' => {
1524                                        if neg { rem.0 = true; } else { add.0 = true; }
1525                                        self.bump();
1526                                    }
1527                                    'm' => {
1528                                        if neg { rem.1 = true; } else { add.1 = true; }
1529                                        self.bump();
1530                                    }
1531                                    's' => {
1532                                        if neg { rem.2 = true; } else { add.2 = true; }
1533                                        self.bump();
1534                                    }
1535                                    ':' => {
1536                                        self.bump();
1537                                        break;
1538                                    }
1539                                    _ => {
1540                                        self.bump();
1541                                        break;
1542                                    }
1543                                }
1544                            }
1545                            let inner = self.parse_alt();
1546                            self.eat(')');
1547                            return Node::Modifiers {
1548                                add,
1549                                rem,
1550                                node: Box::new(inner),
1551                            };
1552                        }
1553                    }
1554                } else {
1555                    self.ngroups += 1;
1556                    Some(self.ngroups)
1557                };
1558                let inner = self.parse_alt();
1559                self.eat(')');
1560                if let (Some(idx), Some(name)) = (idx, group_name) {
1561                    self.group_names.push((name, idx));
1562                }
1563                Node::Group {
1564                    idx,
1565                    node: Box::new(inner),
1566                }
1567            }
1568            Some('[') => {
1569                if self.unicode_sets {
1570                    self.parse_v_class()
1571                } else {
1572                    self.parse_class()
1573                }
1574            }
1575            Some('.') => {
1576                self.bump();
1577                Node::Any
1578            }
1579            Some('^') => {
1580                self.bump();
1581                Node::Start
1582            }
1583            Some('$') => {
1584                self.bump();
1585                Node::End
1586            }
1587            Some('\\') => {
1588                self.bump();
1589                self.parse_escape()
1590            }
1591            Some(c) => {
1592                self.bump();
1593                let u = c as u32;
1594                if !self.unicode && u >= 0x10000 {
1595                    let n = u - 0x10000;
1596                    Node::Concat(vec![
1597                        Node::Char(0xD800 + (n >> 10)),
1598                        Node::Char(0xDC00 + (n & 0x3FF)),
1599                    ])
1600                } else {
1601                    Node::Char(u)
1602                }
1603            }
1604            None => Node::Empty,
1605        }
1606    }
1607
1608    fn parse_escape(&mut self) -> Node {
1609        match self.bump() {
1610            Some('d') => Node::Class(ClassData {
1611                negate: false,
1612                items: vec![ClassItem::Digit],
1613            }),
1614            Some('D') => Node::Class(ClassData {
1615                negate: false,
1616                items: vec![ClassItem::NotDigit],
1617            }),
1618            Some('w') => Node::Class(ClassData {
1619                negate: false,
1620                items: vec![ClassItem::Word],
1621            }),
1622            Some('W') => Node::Class(ClassData {
1623                negate: false,
1624                items: vec![ClassItem::NotWord],
1625            }),
1626            Some('s') => Node::Class(ClassData {
1627                negate: false,
1628                items: vec![ClassItem::Space],
1629            }),
1630            Some('S') => Node::Class(ClassData {
1631                negate: false,
1632                items: vec![ClassItem::NotSpace],
1633            }),
1634            Some('b') => Node::WordBoundary(true),
1635            Some('B') => Node::WordBoundary(false),
1636            Some('n') => Node::Char('\n' as u32),
1637            Some('t') => Node::Char('\t' as u32),
1638            Some('r') => Node::Char('\r' as u32),
1639            Some('f') => Node::Char(0x0C),
1640            Some('v') => Node::Char(0x0B),
1641            Some('0') if !self.peek().is_some_and(|d| d.is_ascii_digit()) => Node::Char(0),
1642            Some('c') => match self.peek() {
1643                Some(l) if l.is_ascii_alphabetic() => {
1644                    self.bump();
1645                    Node::Char(u32::from((l as u8) % 32))
1646                }
1647                _ => Node::Concat(vec![Node::Char('\\' as u32), Node::Char('c' as u32)]),
1648            },
1649            Some('u') => match self.parse_u_escape(false, self.unicode) {
1650                Some(cp) => Node::Char(cp),
1651                None => Node::Char('u' as u32),
1652            },
1653            Some('x') => Node::Char(self.parse_x_escape()),
1654            Some('p') if self.unicode => self.parse_p_escape(false),
1655            Some('P') if self.unicode => self.parse_p_escape(true),
1656            Some('k') if self.peek() == Some('<') => {
1657                let save = self.pos;
1658                self.bump();
1659                let name = self.parse_group_name();
1660                let idxs = self.named_group_indices(&name);
1661                if idxs.is_empty() {
1662                    self.pos = save;
1663                    Node::Char('k' as u32)
1664                } else if idxs.len() == 1 {
1665                    Node::Backref(idxs[0])
1666                } else {
1667                    Node::NamedBackref(idxs)
1668                }
1669            }
1670            Some(c) if c.is_ascii_digit() => {
1671                let start = self.pos - 1;
1672                let mut num = String::new();
1673                num.push(c);
1674                while let Some(d) = self.peek() {
1675                    if d.is_ascii_digit() {
1676                        num.push(d);
1677                        self.bump();
1678                    } else {
1679                        break;
1680                    }
1681                }
1682                let total = self.total_groups();
1683                match num.parse::<usize>() {
1684                    Ok(n) if c != '0' && n <= total => Node::Backref(n),
1685                    _ => {
1686                        self.pos = start + 1;
1687                        if c >= '8' {
1688                            return Node::Char(c as u32);
1689                        }
1690                        let mut v = c as u32 - '0' as u32;
1691                        let max_len = if c <= '3' { 3 } else { 2 };
1692                        let mut len = 1;
1693                        while len < max_len {
1694                            match self.peek() {
1695                                Some(d) if ('0'..='7').contains(&d) => {
1696                                    v = v * 8 + (d as u32 - '0' as u32);
1697                                    self.bump();
1698                                    len += 1;
1699                                }
1700                                _ => break,
1701                            }
1702                        }
1703                        Node::Char(v)
1704                    }
1705                }
1706            }
1707            Some(c) => Node::Char(c as u32),
1708            None => Node::Empty,
1709        }
1710    }
1711
1712    fn total_groups(&mut self) -> usize {
1713        if let Some(n) = self.total {
1714            return n;
1715        }
1716        let c = &self.chars;
1717        let (mut n, mut i, mut in_class) = (0usize, 0usize, 0usize);
1718        while i < c.len() {
1719            match c[i] {
1720                '\\' => i += 1,
1721                '[' if self.unicode_sets => in_class += 1,
1722                '[' if in_class == 0 => in_class = 1,
1723                ']' if in_class > 0 => in_class -= 1,
1724                '(' if in_class == 0
1725                    && (c.get(i + 1) != Some(&'?')
1726                        || (c.get(i + 2) == Some(&'<') && !matches!(c.get(i + 3), Some('=' | '!')))) =>
1727                {
1728                    n += 1;
1729                }
1730                _ => {}
1731            }
1732            i += 1;
1733        }
1734        self.total = Some(n);
1735        n
1736    }
1737
1738    fn named_group_indices(&self, name: &str) -> Vec<usize> {
1739        let c = &self.chars;
1740        let mut idx = 0usize;
1741        let mut in_class = 0usize;
1742        let mut i = 0usize;
1743        let mut out = Vec::new();
1744        while i < c.len() {
1745            match c[i] {
1746                '\\' => i += 1,
1747                '[' if self.unicode_sets => in_class += 1,
1748                '[' if in_class == 0 => in_class = 1,
1749                ']' if in_class > 0 => in_class -= 1,
1750                '(' if in_class == 0 => {
1751                    if c.get(i + 1) != Some(&'?') {
1752                        idx += 1;
1753                    } else if c.get(i + 2) == Some(&'<') && !matches!(c.get(i + 3), Some('=' | '!')) {
1754                        idx += 1;
1755                        let mut p = Parser {
1756                            chars: self.chars.clone(),
1757                            pos: i + 3,
1758                            ngroups: 0,
1759                            group_names: Vec::new(),
1760                            total: None,
1761                            unicode: self.unicode,
1762                            unicode_sets: self.unicode_sets,
1763                        };
1764                        let gname = p.parse_group_name();
1765                        if gname == name {
1766                            out.push(idx);
1767                        }
1768                        i = p.pos.saturating_sub(1);
1769                    }
1770                }
1771                _ => {}
1772            }
1773            i += 1;
1774        }
1775        out
1776    }
1777
1778    fn parse_p_escape(&mut self, negate: bool) -> Node {
1779        if self.peek() == Some('{') {
1780            self.bump();
1781            let mut prop_name = String::new();
1782            while let Some(c) = self.bump() {
1783                if c == '}' {
1784                    break;
1785                }
1786                prop_name.push(c);
1787            }
1788            if !negate && self.unicode_sets {
1789                if let Some(sp) = unicode::parse_string_prop(&prop_name) {
1790                    return Node::VClass(VSet::StrProp(sp));
1791                }
1792            }
1793            if let Some(pk) = unicode::parse_unicode_prop(&prop_name) {
1794                return Node::Class(ClassData {
1795                    negate: false,
1796                    items: vec![ClassItem::UnicodeProp(pk, negate)],
1797                });
1798            }
1799            never_match()
1800        } else {
1801            Node::Char(if negate { 'P' } else { 'p' } as u32)
1802        }
1803    }
1804
1805    fn parse_u_code(&mut self, allow_braced: bool) -> Option<u32> {
1806        let save = self.pos;
1807        if allow_braced && self.peek() == Some('{') {
1808            self.bump();
1809            let mut hex = String::new();
1810            while let Some(c) = self.peek() {
1811                if c == '}' {
1812                    break;
1813                }
1814                hex.push(c);
1815                self.bump();
1816            }
1817            self.bump(); // }
1818            let cp = u32::from_str_radix(&hex, 16).ok().filter(|&cp| cp <= 0x10FFFF);
1819            if cp.is_none() {
1820                self.pos = save;
1821            }
1822            return cp;
1823        }
1824        let mut hex = String::new();
1825        for _ in 0..4 {
1826            match self.peek() {
1827                Some(c) if c.is_ascii_hexdigit() => {
1828                    hex.push(c);
1829                    self.bump();
1830                }
1831                _ => break,
1832            }
1833        }
1834        if hex.len() == 4 {
1835            u32::from_str_radix(&hex, 16).ok()
1836        } else {
1837            self.pos = save;
1838            None
1839        }
1840    }
1841
1842    fn parse_u_escape(&mut self, force_braced: bool, combine_surrogates: bool) -> Option<u32> {
1843        let allow_braced = self.unicode || force_braced;
1844        let hi = self.parse_u_code(allow_braced)?;
1845        if combine_surrogates && (0xD800..0xDC00).contains(&hi) {
1846            let save = self.pos;
1847            if self.eat('\\') && self.eat('u') {
1848                if let Some(lo) = self.parse_u_code(false).filter(|lo| (0xDC00..0xE000).contains(lo)) {
1849                    return Some(0x10000 + ((hi - 0xD800) << 10) + (lo - 0xDC00));
1850                }
1851            }
1852            self.pos = save;
1853        }
1854        Some(hi)
1855    }
1856
1857    fn parse_x_escape(&mut self) -> u32 {
1858        let save = self.pos;
1859        let mut hex = String::new();
1860        for _ in 0..2 {
1861            match self.peek() {
1862                Some(c) if c.is_ascii_hexdigit() => {
1863                    hex.push(c);
1864                    self.bump();
1865                }
1866                _ => break,
1867            }
1868        }
1869        match u32::from_str_radix(&hex, 16) {
1870            Ok(v) if hex.len() == 2 => v,
1871            _ => {
1872                self.pos = save;
1873                'x' as u32
1874            }
1875        }
1876    }
1877
1878    fn peek_is_class_escape(&self) -> bool {
1879        self.peek() == Some('\\')
1880            && match self.peek_at(1) {
1881                Some('d' | 'D' | 'w' | 'W' | 's' | 'S') => true,
1882                Some('p' | 'P') if self.unicode && self.peek_at(2) == Some('{') => true,
1883                _ => false,
1884            }
1885    }
1886
1887    fn parse_class_escape_item(&mut self) -> Option<ClassItem> {
1888        if self.peek() != Some('\\') {
1889            return None;
1890        }
1891        match self.peek_at(1) {
1892            Some('d') => { self.pos += 2; Some(ClassItem::Digit) }
1893            Some('D') => { self.pos += 2; Some(ClassItem::NotDigit) }
1894            Some('w') => { self.pos += 2; Some(ClassItem::Word) }
1895            Some('W') => { self.pos += 2; Some(ClassItem::NotWord) }
1896            Some('s') => { self.pos += 2; Some(ClassItem::Space) }
1897            Some('S') => { self.pos += 2; Some(ClassItem::NotSpace) }
1898            Some(e @ ('p' | 'P')) if self.unicode && self.peek_at(2) == Some('{') => {
1899                self.pos += 2;
1900                if let Node::Class(cd) = self.parse_p_escape(e == 'P') {
1901                    cd.items.into_iter().next()
1902                } else {
1903                    None
1904                }
1905            }
1906            _ => None,
1907        }
1908    }
1909
1910    fn parse_class(&mut self) -> Node {
1911        self.bump(); // [
1912        let negate = self.eat('^');
1913        let mut items = Vec::new();
1914        while let Some(c) = self.peek() {
1915            if c == ']' {
1916                break;
1917            }
1918            if let Some(esc_item) = self.parse_class_escape_item() {
1919                items.push(esc_item);
1920                // Annex B: `[\d-z]` の `-` は範囲演算子ではなく文字 `-` と後続の文字。
1921                if self.peek() == Some('-') && self.peek_at(1).is_some_and(|x| x != ']') {
1922                    self.bump();
1923                    items.push(ClassItem::Ch('-' as u32));
1924                }
1925                continue;
1926            }
1927            let lo = if c == '\\' {
1928                self.bump();
1929                match self.bump() {
1930                    Some(e) => self.class_escape_code(e),
1931                    None => break,
1932                }
1933            } else {
1934                self.bump();
1935                c as u32
1936            };
1937            if self.peek() == Some('-') && self.chars.get(self.pos + 1).is_some_and(|&x| x != ']') {
1938                self.bump(); // -
1939                // Annex B: `[--\d]` のように右辺がクラスエスケープなら範囲ではなく和集合。
1940                if self.peek_is_class_escape() {
1941                    items.push(ClassItem::Ch(lo));
1942                    items.push(ClassItem::Ch('-' as u32));
1943                    if let Some(esc_item) = self.parse_class_escape_item() {
1944                        items.push(esc_item);
1945                    }
1946                    continue;
1947                }
1948                let hi = if self.peek() == Some('\\') {
1949                    self.bump();
1950                    match self.bump() {
1951                        Some(e) => self.class_escape_code(e),
1952                        None => lo,
1953                    }
1954                } else {
1955                    self.bump().map(|c| c as u32).unwrap_or(lo)
1956                };
1957                if lo <= hi {
1958                    items.push(ClassItem::Range(lo, hi));
1959                }
1960            } else if !self.unicode && lo >= 0x10000 {
1961                let n = lo - 0x10000;
1962                items.push(ClassItem::Ch(0xD800 + (n >> 10)));
1963                items.push(ClassItem::Ch(0xDC00 + (n & 0x3FF)));
1964            } else {
1965                items.push(ClassItem::Ch(lo));
1966            }
1967        }
1968        self.eat(']');
1969        Node::Class(ClassData { negate, items })
1970    }
1971
1972    // ---- v フラグ (`unicodeSets`) 文字クラスパーサ ----
1973
1974    fn parse_v_class(&mut self) -> Node {
1975        self.bump(); // [
1976        let neg = self.eat('^');
1977        let expr = self.parse_v_class_body();
1978        self.eat(']');
1979        Node::VClass(if neg { VSet::Neg(Box::new(expr)) } else { expr })
1980    }
1981
1982    fn parse_v_class_body(&mut self) -> VSet {
1983        #[derive(PartialEq, Clone, Copy)]
1984        enum Mode {
1985            Unknown,
1986            Union,
1987            Inter,
1988            Sub,
1989        }
1990        let mut mode = Mode::Unknown;
1991        let mut parts: Vec<VSet> = Vec::new();
1992        while let Some(c) = self.peek() {
1993            if c == ']' {
1994                break;
1995            }
1996            if self.starts("&&") {
1997                mode = Mode::Inter;
1998                self.pos += 2;
1999                let (op, _) = self.parse_v_operand();
2000                parts.push(op);
2001                continue;
2002            }
2003            if self.starts("--") {
2004                mode = Mode::Sub;
2005                self.pos += 2;
2006                let (op, _) = self.parse_v_operand();
2007                parts.push(op);
2008                continue;
2009            }
2010            let (op, single) = self.parse_v_operand();
2011            if let Some(lo) = single {
2012                if self.peek() == Some('-') && self.peek_at(1) != Some('-') && self.peek_at(1) != Some(']') {
2013                    self.bump(); // -
2014                    let (_op2, hi_opt) = self.parse_v_operand();
2015                    if let Some(hi) = hi_opt {
2016                        if lo <= hi {
2017                            parts.push(VSet::Item(ClassItem::Range(lo, hi)));
2018                        }
2019                    } else {
2020                        parts.push(op);
2021                    }
2022                    if mode == Mode::Unknown {
2023                        mode = Mode::Union;
2024                    }
2025                    continue;
2026                }
2027            }
2028            if mode == Mode::Unknown {
2029                mode = Mode::Union;
2030            }
2031            parts.push(op);
2032        }
2033        match mode {
2034            Mode::Inter => VSet::Inter(parts),
2035            Mode::Sub => VSet::Diff(parts),
2036            _ => {
2037                if parts.len() == 1 {
2038                    match parts.pop() {
2039                        Some(only) => only,
2040                        None => VSet::Union(parts),
2041                    }
2042                } else {
2043                    VSet::Union(parts)
2044                }
2045            }
2046        }
2047    }
2048
2049    fn parse_v_operand(&mut self) -> (VSet, Option<u32>) {
2050        let Some(ch) = self.peek() else {
2051            return (VSet::Union(Vec::new()), None);
2052        };
2053        if ch == '[' {
2054            self.bump();
2055            let neg = self.eat('^');
2056            let body = self.parse_v_class_body();
2057            self.eat(']');
2058            let set = if neg { VSet::Neg(Box::new(body)) } else { body };
2059            return (set, None);
2060        }
2061        if ch == '\\' {
2062            match self.peek_at(1) {
2063                Some('q') if self.peek_at(2) == Some('{') => {
2064                    self.pos += 3; // \q{
2065                    let mut alts: Vec<Vec<u32>> = Vec::new();
2066                    let mut cur: Vec<u32> = Vec::new();
2067                    while let Some(c) = self.peek() {
2068                        if c == '}' {
2069                            self.bump();
2070                            alts.push(cur);
2071                            break;
2072                        }
2073                        if c == '|' {
2074                            self.bump();
2075                            alts.push(core::mem::take(&mut cur));
2076                        } else {
2077                            cur.push(self.parse_v_class_char());
2078                        }
2079                    }
2080                    return (VSet::Strings(alts), None);
2081                }
2082                Some(e @ ('p' | 'P')) if self.peek_at(2) == Some('{') => {
2083                    self.pos += 2;
2084                    match self.parse_p_escape(e == 'P') {
2085                        Node::VClass(vs) => return (vs, None),
2086                        Node::Class(cd) => {
2087                            if let Some(it) = cd.items.into_iter().next() {
2088                                return (VSet::Item(it), None);
2089                            }
2090                            return (VSet::Union(Vec::new()), None);
2091                        }
2092                        _ => return (VSet::Union(Vec::new()), None),
2093                    }
2094                }
2095                Some('d') => { self.pos += 2; return (VSet::Item(ClassItem::Digit), None); }
2096                Some('D') => { self.pos += 2; return (VSet::Item(ClassItem::NotDigit), None); }
2097                Some('w') => { self.pos += 2; return (VSet::Item(ClassItem::Word), None); }
2098                Some('W') => { self.pos += 2; return (VSet::Item(ClassItem::NotWord), None); }
2099                Some('s') => { self.pos += 2; return (VSet::Item(ClassItem::Space), None); }
2100                Some('S') => { self.pos += 2; return (VSet::Item(ClassItem::NotSpace), None); }
2101                _ => {}
2102            }
2103        }
2104        let cp = self.parse_v_class_char();
2105        (VSet::Item(ClassItem::Ch(cp)), Some(cp))
2106    }
2107
2108    fn parse_v_class_char(&mut self) -> u32 {
2109        let Some(ch) = self.bump() else {
2110            return 0;
2111        };
2112        if ch == '\\' {
2113            return match self.bump() {
2114                Some(e) => self.class_escape_code(e),
2115                None => '\\' as u32,
2116            };
2117        }
2118        ch as u32
2119    }
2120
2121    /// 文字クラスの中の `\e`(1 文字を表す物)の符号位置。
2122    fn class_escape_code(&mut self, e: char) -> u32 {
2123        match e {
2124            'n' => 0x0A,
2125            't' => 0x09,
2126            'r' => 0x0D,
2127            'f' => 0x0C,
2128            'v' => 0x0B,
2129            'b' => 0x08,
2130            '0' if !self.peek().is_some_and(|d| d.is_ascii_digit()) => 0,
2131            '0'..='7' if !self.unicode => {
2132                let mut v = e as u32 - '0' as u32;
2133                let max_len = if e <= '3' { 3 } else { 2 };
2134                let mut len = 1;
2135                while len < max_len {
2136                    match self.peek() {
2137                        Some(d) if ('0'..='7').contains(&d) => {
2138                            v = v * 8 + (d as u32 - '0' as u32);
2139                            self.bump();
2140                            len += 1;
2141                        }
2142                        _ => break,
2143                    }
2144                }
2145                v
2146            }
2147            'c' => match self.peek() {
2148                Some(l) if l.is_ascii_alphabetic() => {
2149                    self.bump();
2150                    u32::from(l as u8 % 32)
2151                }
2152                _ => u32::from('c'),
2153            },
2154            'u' => self.parse_u_escape(false, self.unicode).unwrap_or(u32::from('u')),
2155            'x' => self.parse_x_escape(),
2156            other => other as u32,
2157        }
2158    }
2159}
2160
2161/// どの文字にも一致しない部分(空の文字クラス)。
2162fn never_match() -> Node {
2163    Node::Class(ClassData { negate: false, items: Vec::new() })
2164}