Skip to main content

atmos/os_lib/ecma/builtins/
regexp_proto.rs

1// RegExp のプロトコル(ECMA-262 §22.2.6・§22.2.4・§22.2.9・§22.1.3)。
2// 【2026-11-20 TODO S1 (5) Wave F】従来は `exec` を差し替えても・`lastIndex` を取りなおしても・`flags`/`source` の
3// ゲッターを定義しても `RegExp.prototype[Symbol.match/replace/search/split/matchAll]` が内部の組込み
4// 実装だけを見ていた。ここは仕様どおりの経路(RegExpExec → 利用者の `exec`、`lastIndex` の ToLength と Set、
5// `flags` ゲッター、Symbol.species、GetSubstitution)を実装する。素の組込み RegExp(`pristine`)は
6// 従来の高速な経路(regexp.rs の `regex_replace`/`regex_split` など)へ回す。
7use super::*;
8
9use super::super::regex::{self, RegExpData};
10
11const SYM_MATCH: &str = "Symbol(Symbol.match)";
12const SYM_MATCH_ALL: &str = "Symbol(Symbol.matchAll)";
13const SYM_REPLACE: &str = "Symbol(Symbol.replace)";
14const SYM_SEARCH: &str = "Symbol(Symbol.search)";
15const SYM_SPLIT: &str = "Symbol(Symbol.split)";
16const SYM_SPECIES: &str = "Symbol(Symbol.species)";
17const SYM_TAG: &str = "Symbol(Symbol.toStringTag)";
18const SYM_ITER: &str = "Symbol(Symbol.iterator)";
19
20type ReData = PromiseRc<PromiseRefCell<RegExpData>>;
21
22fn native_is(v: &Value, f: NativeFn) -> bool {
23    match v {
24        Value::Object(o) => matches!(&o.borrow().kind, ObjKind::Native { func, .. } if (*func as usize) == (f as usize)),
25        _ => false,
26    }
27}
28
29/// `RegExp.prototype`(この実行環境の)。
30pub(crate) fn regexp_proto_obj(it: &Interp) -> Option<ObjRef> {
31    global_ctor_proto(it, "RegExp")
32}
33
34/// 内部スロット([[RegExpMatcher]])を持つ RegExp オブジェクトか(Proxy は持たない)。
35fn own_regexp(v: &Value) -> Option<ReData> {
36    if let Value::Object(o) = v {
37        if let ObjKind::RegExpObj(r) = &o.borrow().kind {
38            return Some(r.clone());
39        }
40    }
41    None
42}
43
44/// プロトタイプ(`exec` と各フラグのゲッター)が組込みのままか。
45fn proto_pristine(it: &Interp) -> bool {
46    let Some(p) = regexp_proto_obj(it) else { return false };
47    let pb = p.borrow();
48    match pb.props.get("exec") {
49        Some(v) if native_is(v, re_exec) => {}
50        _ => return false,
51    }
52    const GETTERS: [(&str, NativeFn); 9] = [
53        ("flags", get_flags),
54        ("global", get_global),
55        ("ignoreCase", get_ignore_case),
56        ("multiline", get_multiline),
57        ("dotAll", get_dot_all),
58        ("unicode", get_unicode),
59        ("unicodeSets", get_unicode_sets),
60        ("sticky", get_sticky),
61        ("hasIndices", get_has_indices),
62    ];
63    for (k, f) in GETTERS {
64        match pb.get_accessor(k).and_then(|a| a.get.as_ref()) {
65            Some(g) if native_is(g, f) => {}
66            _ => return false,
67        }
68    }
69    true
70}
71
72/// 利用者が何も差し替えていない、素の組込み RegExp なら内部データを返す(高速な経路の条件)。
73fn pristine(it: &Interp, v: &Value) -> Option<ReData> {
74    let Value::Object(o) = v else { return None };
75    let r = {
76        let b = o.borrow();
77        let ObjKind::RegExpObj(r) = &b.kind else { return None };
78        if b.has_any_accessor() || b.is_frozen() || b.is_sealed() || b.is_non_extensible() {
79            return None;
80        }
81        match b.proto.as_ref() {
82            None => {}
83            Some(x) => {
84                let p = regexp_proto_obj(it)?;
85                if !Rc::ptr_eq(x, &p) {
86                    return None;
87                }
88            }
89        }
90        match b.props.get("lastIndex") {
91            Some(Value::Number(n)) if *n >= 0.0 && *n < 9.0e15 && libm::floor(*n) == *n => {}
92            _ => return None,
93        }
94        if b.get_attr("lastIndex").is_some() {
95            return None;
96        }
97        if b.props.len() > 1 {
98            for k in [
99                "exec", "flags", "global", "ignoreCase", "multiline", "dotAll", "unicode", "unicodeSets", "sticky",
100                "hasIndices", "constructor",
101            ] {
102                if b.props.contains_key(k) {
103                    return None;
104                }
105            }
106        }
107        r.clone()
108    };
109    if proto_pristine(it) {
110        Some(r)
111    } else {
112        None
113    }
114}
115
116fn to_length(it: &mut Interp, v: &Value) -> Result<f64, Value> {
117    let n = it.num_of(v)?;
118    Ok(if n.is_nan() || n <= 0.0 {
119        0.0
120    } else {
121        libm::floor(n.min(9_007_199_254_740_991.0))
122    })
123}
124
125fn get_last_index(it: &mut Interp, rx: &Value) -> Result<f64, Value> {
126    let v = it.get_property(rx, "lastIndex")?;
127    to_length(it, &v)
128}
129
130/// `Set(rx, "lastIndex", n, true)`。書き込めなければ TypeError。
131fn set_last_index_val(it: &mut Interp, rx: &Value, v: Value) -> Result<(), Value> {
132    if let (Value::Object(o), Value::Number(_)) = (rx, &v) {
133        let mut b = o.borrow_mut();
134        if matches!(b.kind, ObjKind::RegExpObj(_))
135            && !b.is_frozen()
136            && !b.has_any_accessor()
137            && b.get_attr("lastIndex").is_none()
138            && b.props.contains_key("lastIndex")
139        {
140            b.props.insert("lastIndex".into(), v);
141            return Ok(());
142        }
143    }
144    if it.set_property_inner(rx, "lastIndex", None, v)? {
145        Ok(())
146    } else {
147        Err(it.type_error("Cannot assign to read only property 'lastIndex' of object"))
148    }
149}
150
151pub(crate) fn set_last_index(it: &mut Interp, rx: &Value, n: f64) -> Result<(), Value> {
152    set_last_index_val(it, rx, Value::Number(n))
153}
154
155fn require_object(it: &Interp, v: &Value, what: &str) -> Result<(), Value> {
156    if matches!(v, Value::Object(_)) {
157        Ok(())
158    } else {
159        Err(it.type_error(alloc::format!("{} called on a non-object", what)))
160    }
161}
162
163fn require_coercible(it: &Interp, v: &Value, what: &str) -> Result<(), Value> {
164    if matches!(v, Value::Undefined | Value::Null) {
165        Err(it.type_error(alloc::format!("{} called on null or undefined", what)))
166    } else {
167        Ok(())
168    }
169}
170
171fn advance_string_index(u: &[u16], idx: f64, unicode: bool) -> f64 {
172    if !unicode || idx + 1.0 >= u.len() as f64 {
173        return idx + 1.0;
174    }
175    let i = idx as usize;
176    let first = u[i];
177    if !(0xD800..=0xDBFF).contains(&first) {
178        return idx + 1.0;
179    }
180    if (0xDC00..=0xDFFF).contains(&u[i + 1]) {
181        idx + 2.0
182    } else {
183        idx + 1.0
184    }
185}
186
187// ============ RegExpBuiltinExec / RegExpExec ============
188
189/// RegExpBuiltinExec(§22.2.7.2)。`rx` は [[RegExpMatcher]] を持つこと。
190fn builtin_exec(it: &mut Interp, rx: &Value, r: &ReData, s: &str) -> Result<Value, Value> {
191    let last_index = get_last_index(it, rx)?;
192    let (global, sticky, has_indices) = {
193        let d = r.borrow();
194        (d.re.global, d.re.sticky, d.re.has_indices)
195    };
196    let uses = global || sticky;
197    let li = if uses { last_index } else { 0.0 };
198    let chars: Vec<char> = s.chars().collect();
199    let len16: usize = chars.iter().map(|c| c.len_utf16()).sum();
200    if li > len16 as f64 {
201        if uses {
202            set_last_index(it, rx, 0.0)?;
203        }
204        return Ok(Value::Null);
205    }
206    let start = utf16_pos_to_char(&chars, li as usize);
207    let found = if sticky {
208        r.borrow().re.find_exact_at(&chars, start)
209    } else {
210        r.borrow().re.find_at(&chars, start)
211    };
212    match found {
213        Some(m) => {
214            update_legacy_regexp_statics(it, rx, &m, &chars, s);
215            if uses {
216                set_last_index(it, rx, char_pos_to_utf16(&chars, m.end) as f64)?;
217            }
218            let group_names = r.borrow().re.group_names.clone();
219            Ok(match_to_array_impl(&m, &chars, s, has_indices, &group_names))
220        }
221        None => {
222            if uses {
223                set_last_index(it, rx, 0.0)?;
224            }
225            Ok(Value::Null)
226        }
227    }
228}
229
230/// RegExpExec(§22.2.7.1)。利用者の `exec` があればそれを呼ぶ。
231fn regexp_exec(it: &mut Interp, rx: &Value, s: &str) -> Result<Value, Value> {
232    let exec = it.get_property(rx, "exec")?;
233    if callable_or_none(exec.clone()).is_some() {
234        if native_is(&exec, re_exec) {
235            if let Some(r) = own_regexp(rx) {
236                return builtin_exec(it, rx, &r, s);
237            }
238        }
239        let res = it.call_value(&exec, rx.clone(), &[Value::str(String::from(s))])?;
240        if !matches!(res, Value::Object(_) | Value::Null) {
241            return Err(it.type_error("object or null expected from RegExp exec result"));
242        }
243        return Ok(res);
244    }
245    match own_regexp(rx) {
246        Some(r) => builtin_exec(it, rx, &r, s),
247        None => Err(it.type_error("RegExp.prototype.exec called on incompatible receiver")),
248    }
249}
250
251pub(crate) fn re_exec(it: &mut Interp, this: Value, a: &[Value]) -> Result<Value, Value> {
252    let r = match own_regexp(&this) {
253        Some(r) => r,
254        None => return Err(it.type_error("RegExp.prototype.exec requires that 'this' be a RegExp object")),
255    };
256    let s = it.to_string_value(arg(a, 0))?;
257    builtin_exec(it, &this, &r, &s)
258}
259
260pub(crate) fn re_test(it: &mut Interp, this: Value, a: &[Value]) -> Result<Value, Value> {
261    require_object(it, &this, "RegExp.prototype.test")?;
262    let s = it.to_string_value(arg(a, 0))?;
263    if let Some(r) = pristine(it, &this) {
264        let (global, sticky) = {
265            let d = r.borrow();
266            (d.re.global, d.re.sticky)
267        };
268        if !global && !sticky {
269            let chars: Vec<char> = s.chars().collect();
270            return Ok(Value::Bool(match r.borrow().re.find_at(&chars, 0) {
271                Some(m) => {
272                    update_legacy_regexp_statics(it, &this, &m, &chars, &s);
273                    true
274                }
275                None => false,
276            }));
277        }
278    }
279    Ok(Value::Bool(!matches!(regexp_exec(it, &this, &s)?, Value::Null)))
280}
281
282pub(crate) fn re_to_string(it: &mut Interp, this: Value, _a: &[Value]) -> Result<Value, Value> {
283    require_object(it, &this, "RegExp.prototype.toString")?;
284    let src = it.get_property(&this, "source")?;
285    let src = it.to_string_value(src)?;
286    let flags = it.get_property(&this, "flags")?;
287    let flags = it.to_string_value(flags)?;
288    Ok(Value::str(alloc::format!("/{}/{}", src, flags)))
289}
290
291// ============ アクセサ(flags・個々のフラグ・source) ============
292
293fn flag_getter(it: &mut Interp, this: &Value, name: &str, pick: fn(&RegExpData) -> bool) -> Result<Value, Value> {
294    match own_regexp(this) {
295        Some(r) => Ok(Value::Bool(pick(&r.borrow()))),
296        None => {
297            if let (Value::Object(o), Some(p)) = (this, regexp_proto_obj(it)) {
298                if Rc::ptr_eq(o, &p) {
299                    return Ok(Value::Undefined);
300                }
301            }
302            Err(it.type_error(alloc::format!("RegExp.prototype.{} getter called on non-RegExp object", name)))
303        }
304    }
305}
306
307fn get_global(it: &mut Interp, t: Value, _a: &[Value]) -> Result<Value, Value> {
308    flag_getter(it, &t, "global", |d| d.re.global)
309}
310fn get_ignore_case(it: &mut Interp, t: Value, _a: &[Value]) -> Result<Value, Value> {
311    flag_getter(it, &t, "ignoreCase", |d| d.re.ignorecase)
312}
313fn get_multiline(it: &mut Interp, t: Value, _a: &[Value]) -> Result<Value, Value> {
314    flag_getter(it, &t, "multiline", |d| d.re.multiline)
315}
316fn get_dot_all(it: &mut Interp, t: Value, _a: &[Value]) -> Result<Value, Value> {
317    flag_getter(it, &t, "dotAll", |d| d.re.dotall)
318}
319fn get_sticky(it: &mut Interp, t: Value, _a: &[Value]) -> Result<Value, Value> {
320    flag_getter(it, &t, "sticky", |d| d.re.sticky)
321}
322fn get_has_indices(it: &mut Interp, t: Value, _a: &[Value]) -> Result<Value, Value> {
323    flag_getter(it, &t, "hasIndices", |d| d.re.has_indices)
324}
325fn get_unicode(it: &mut Interp, t: Value, _a: &[Value]) -> Result<Value, Value> {
326    flag_getter(it, &t, "unicode", |d| d.re.flags.contains('u'))
327}
328fn get_unicode_sets(it: &mut Interp, t: Value, _a: &[Value]) -> Result<Value, Value> {
329    flag_getter(it, &t, "unicodeSets", |d| d.re.flags.contains('v'))
330}
331
332fn get_flags(it: &mut Interp, this: Value, _a: &[Value]) -> Result<Value, Value> {
333    require_object(it, &this, "RegExp.prototype.flags getter")?;
334    let mut out = String::new();
335    for (name, ch) in [
336        ("hasIndices", 'd'),
337        ("global", 'g'),
338        ("ignoreCase", 'i'),
339        ("multiline", 'm'),
340        ("dotAll", 's'),
341        ("unicode", 'u'),
342        ("unicodeSets", 'v'),
343        ("sticky", 'y'),
344    ] {
345        if it.get_property(&this, name)?.truthy() {
346            out.push(ch);
347        }
348    }
349    Ok(Value::str(out))
350}
351
352/// EscapeRegExpPattern: `/`・改行を `source` に出すときのエスケープ。
353fn escape_source(src: &str) -> String {
354    if src.is_empty() {
355        return String::from("(?:)");
356    }
357    let mut out = String::with_capacity(src.len());
358    let mut in_class = false;
359    let mut esc = false;
360    for c in src.chars() {
361        if esc {
362            esc = false;
363            match c {
364                '\n' => out.push('n'),
365                '\r' => out.push('r'),
366                '\u{2028}' => out.push_str("u2028"),
367                '\u{2029}' => out.push_str("u2029"),
368                _ => out.push(c),
369            }
370            continue;
371        }
372        match c {
373            '\\' => {
374                esc = true;
375                out.push(c);
376            }
377            '[' => {
378                in_class = true;
379                out.push(c);
380            }
381            ']' => {
382                in_class = false;
383                out.push(c);
384            }
385            '/' if !in_class => out.push_str("\\/"),
386            '\n' => out.push_str("\\n"),
387            '\r' => out.push_str("\\r"),
388            '\u{2028}' => out.push_str("\\u2028"),
389            '\u{2029}' => out.push_str("\\u2029"),
390            _ => out.push(c),
391        }
392    }
393    out
394}
395
396fn get_source(it: &mut Interp, this: Value, _a: &[Value]) -> Result<Value, Value> {
397    require_object(it, &this, "RegExp.prototype.source getter")?;
398    match own_regexp(&this) {
399        Some(r) => Ok(Value::str(escape_source(&r.borrow().re.source))),
400        None => {
401            if let (Value::Object(o), Some(p)) = (&this, regexp_proto_obj(it)) {
402                if Rc::ptr_eq(o, &p) {
403                    return Ok(Value::str("(?:)"));
404                }
405            }
406            Err(it.type_error("RegExp.prototype.source getter called on non-RegExp object"))
407        }
408    }
409}
410
411/// `RegExp.prototype` へアクセサ・メソッドを並べる(`install` から)。
412pub(crate) fn install_regexp_proto(pb: &mut Obj) {
413    let hidden = PropertyAttributes { writable: true, configurable: true, enumerable: false };
414    let getters: [(&str, &str, NativeFn); 10] = [
415        ("flags", "get flags", get_flags),
416        ("global", "get global", get_global),
417        ("ignoreCase", "get ignoreCase", get_ignore_case),
418        ("multiline", "get multiline", get_multiline),
419        ("dotAll", "get dotAll", get_dot_all),
420        ("unicode", "get unicode", get_unicode),
421        ("unicodeSets", "get unicodeSets", get_unicode_sets),
422        ("sticky", "get sticky", get_sticky),
423        ("hasIndices", "get hasIndices", get_has_indices),
424        ("source", "get source", get_source),
425    ];
426    for (key, name, f) in getters {
427        pb.insert_accessor(key, Accessor { get: Some(nv(name, f)), set: None });
428        pb.insert_attr(key, PropertyAttributes { writable: false, configurable: true, enumerable: false });
429    }
430    let methods: [(&str, &str, NativeFn); 9] = [
431        ("test", "test", re_test),
432        ("exec", "exec", re_exec),
433        ("toString", "toString", re_to_string),
434        ("compile", "compile", re_compile),
435        (SYM_MATCH, SYM_MATCH, re_symbol_match),
436        (SYM_REPLACE, SYM_REPLACE, re_symbol_replace),
437        (SYM_SEARCH, SYM_SEARCH, re_symbol_search),
438        (SYM_SPLIT, SYM_SPLIT, re_symbol_split),
439        (SYM_MATCH_ALL, SYM_MATCH_ALL, re_symbol_match_all),
440    ];
441    for (key, name, f) in methods {
442        pb.props.insert(key.into(), nv(name, f));
443        pb.insert_attr(key, hidden);
444    }
445}
446
447// ============ コンストラクタ ============
448
449/// IsRegExp(§7.2.8)。
450pub(crate) fn is_regexp(it: &mut Interp, v: &Value) -> Result<bool, Value> {
451    if !matches!(v, Value::Object(_)) {
452        return Ok(false);
453    }
454    let m = it.get_property(v, SYM_MATCH)?;
455    if !matches!(m, Value::Undefined) {
456        return Ok(m.truthy());
457    }
458    Ok(own_regexp(v).is_some())
459}
460
461/// パターンとフラグの文字列(`undefined` は空)から正規表現を作る(RegExpInitialize の前半)。
462fn regexp_parse(it: &mut Interp, p: &Value, f: &Value) -> Result<regex::Regex, Value> {
463    let pattern = if matches!(p, Value::Undefined) { String::new() } else { it.to_string_value(p.clone())? };
464    let flags = if matches!(f, Value::Undefined) { String::new() } else { it.to_string_value(f.clone())? };
465    if let Some(msg) = regexp_syntax_error(&pattern, &flags) {
466        return Err(it.syntax_error(msg));
467    }
468    Ok(regex::Regex::new(&pattern, &flags))
469}
470
471fn regexp_initialize(it: &mut Interp, p: &Value, f: &Value) -> Result<ObjRef, Value> {
472    let re = regexp_parse(it, p, f)?;
473    Ok(Obj::regexp(RegExpData { re, last_index: 0 }))
474}
475
476/// RegExpCreate(P, F)(§22.2.3.1)。
477pub(crate) fn regexp_create(it: &mut Interp, p: Value, f: Value) -> Result<Value, Value> {
478    Ok(Value::Object(regexp_initialize(it, &p, &f)?))
479}
480
481pub(crate) fn regexp_ctor(it: &mut Interp, this_v: Value, a: &[Value]) -> Result<Value, Value> {
482    let pattern = arg(a, 0);
483    let flags = arg(a, 1);
484    let regexp_fn = super::super::interp::scope_get(&it.global, "RegExp").unwrap_or(Value::Undefined);
485    let nt = it.take_pending_new_target();
486    let pattern_is_regexp = is_regexp(it, &pattern)?;
487    let new_target = match &nt {
488        Some(n) => n.clone(),
489        None => {
490            if pattern_is_regexp && matches!(flags, Value::Undefined) {
491                let pc = it.get_property(&pattern, "constructor")?;
492                if same_value_obj(&pc, &regexp_fn) {
493                    return Ok(pattern);
494                }
495            }
496            regexp_fn.clone()
497        }
498    };
499    let (p, f) = if let Some(r) = own_regexp(&pattern) {
500        let d = r.borrow();
501        let f = if matches!(flags, Value::Undefined) { Value::str(d.re.flags.clone()) } else { flags.clone() };
502        (Value::str(d.re.source.clone()), f)
503    } else if pattern_is_regexp {
504        let p = it.get_property(&pattern, "source")?;
505        let f = if matches!(flags, Value::Undefined) { it.get_property(&pattern, "flags")? } else { flags.clone() };
506        (p, f)
507    } else {
508        (pattern.clone(), flags.clone())
509    };
510    // `new` で呼ばれ、`this` が構築中の素のオブジェクト(`new RegExp`・派生クラスの `super(...)`)なら、
511    // その場で RegExp に変える(派生クラスのインスタンスが RegExp の実体を持てる)。
512    if nt.is_some() {
513        if let Value::Object(t) = &this_v {
514            let fresh = {
515                let b = t.borrow();
516                matches!(b.kind, ObjKind::Plain) && b.props.is_empty() && !b.has_any_accessor()
517            };
518            if fresh {
519                let re = regexp_parse(it, &p, &f)?;
520                let mut b = t.borrow_mut();
521                b.kind = ObjKind::RegExpObj(PromiseRc::new(PromiseRefCell::new(RegExpData { re, last_index: 0 })));
522                b.props.insert("lastIndex".into(), Value::Number(0.0));
523                return Ok(this_v.clone());
524            }
525        }
526    }
527    // RegExpAlloc: `new_target.prototype` を先に読む(ToString より前)。
528    let mut proto_override = None;
529    if !same_value_obj(&new_target, &regexp_fn) {
530        if let Value::Object(po) = it.get_property(&new_target, "prototype")? {
531            proto_override = Some(po);
532        }
533    }
534    let o = regexp_initialize(it, &p, &f)?;
535    if let Some(po) = proto_override {
536        o.borrow_mut().proto = Some(po);
537    }
538    Ok(Value::Object(o))
539}
540
541fn same_value_obj(a: &Value, b: &Value) -> bool {
542    matches!((a, b), (Value::Object(x), Value::Object(y)) if Rc::ptr_eq(x, y))
543}
544
545/// `RegExp.prototype.compile(pattern, flags)`(Annex B.2.4)。
546pub(crate) fn re_compile(it: &mut Interp, this: Value, a: &[Value]) -> Result<Value, Value> {
547    let Some(r) = own_regexp(&this) else {
548        return Err(it.type_error("RegExp.prototype.compile requires that 'this' be a RegExp object"));
549    };
550    let pattern = arg(a, 0);
551    let flags = arg(a, 1);
552    let (p, f) = if let Some(src) = own_regexp(&pattern) {
553        if !matches!(flags, Value::Undefined) {
554            return Err(it.type_error("flags must be undefined when pattern is a RegExp"));
555        }
556        let d = src.borrow();
557        (Value::str(d.re.source.clone()), Value::str(d.re.flags.clone()))
558    } else {
559        (pattern, flags)
560    };
561    let re = regexp_parse(it, &p, &f)?;
562    r.borrow_mut().re = re;
563    set_last_index(it, &this, 0.0)?;
564    Ok(this)
565}
566
567// ============ GetSubstitution ============
568
569/// GetSubstitution(§22.1.3.19.1)。位置は UTF-16 単位。
570fn get_substitution(
571    it: &mut Interp,
572    matched: &str,
573    s16: &[u16],
574    position: usize,
575    captures: &[Value],
576    named: &Value,
577    template: &str,
578) -> Result<String, Value> {
579    let t: Vec<char> = template.chars().collect();
580    let m = captures.len();
581    let match_len16 = matched.encode_utf16().count();
582    let mut out = String::new();
583    let mut i = 0;
584    while i < t.len() {
585        let c = t[i];
586        if c != '$' || i + 1 >= t.len() {
587            out.push(c);
588            i += 1;
589            continue;
590        }
591        let n = t[i + 1];
592        match n {
593            '$' => {
594                out.push('$');
595                i += 2;
596            }
597            '&' => {
598                out.push_str(matched);
599                i += 2;
600            }
601            '`' => {
602                out.push_str(&String::from_utf16_lossy(&s16[..position.min(s16.len())]));
603                i += 2;
604            }
605            '\'' => {
606                let tail = (position + match_len16).min(s16.len());
607                out.push_str(&String::from_utf16_lossy(&s16[tail..]));
608                i += 2;
609            }
610            '0'..='9' => {
611                let d1 = n as usize - '0' as usize;
612                let two = t.get(i + 2).filter(|c| c.is_ascii_digit()).map(|c| d1 * 10 + (*c as usize - '0' as usize));
613                let (idx, used) = match two {
614                    Some(v) if v >= 1 && v <= m => (v, 2),
615                    _ => (d1, 1),
616                };
617                if idx >= 1 && idx <= m {
618                    match &captures[idx - 1] {
619                        Value::Undefined => {}
620                        v => out.push_str(&v.to_js_string()),
621                    }
622                    i += 1 + used;
623                } else {
624                    out.push('$');
625                    i += 1;
626                }
627            }
628            '<' => {
629                if matches!(named, Value::Undefined) {
630                    out.push_str("$<");
631                    i += 2;
632                } else {
633                    match t[i + 2..].iter().position(|c| *c == '>') {
634                        None => {
635                            out.push_str("$<");
636                            i += 2;
637                        }
638                        Some(rel) => {
639                            let name: String = t[i + 2..i + 2 + rel].iter().collect();
640                            let cap = it.get_property(named, &name)?;
641                            if !matches!(cap, Value::Undefined) {
642                                out.push_str(&it.to_string_value(cap)?);
643                            }
644                            i += 2 + rel + 1;
645                        }
646                    }
647                }
648            }
649            _ => {
650                out.push('$');
651                i += 1;
652            }
653        }
654    }
655    Ok(out)
656}
657
658// ============ Symbol.match ============
659
660/// 素の組込み RegExp(`g`・非 sticky)の `match`。結果は一致した文字列の配列(無ければ null)。
661fn native_match_global(r: &ReData, s: &str) -> Value {
662    let chars: Vec<char> = s.chars().collect();
663    let mut items = Vec::new();
664    let mut pos = 0;
665    while let Some(m) = r.borrow().re.find_at(&chars, pos) {
666        items.push(Value::str(chars[m.start..m.end].iter().collect::<String>()));
667        pos = if m.end > m.start { m.end } else { m.end + 1 };
668        if pos > chars.len() {
669            break;
670        }
671    }
672    if items.is_empty() {
673        Value::Null
674    } else {
675        Value::Object(Obj::array(items))
676    }
677}
678
679pub(crate) fn re_symbol_match(it: &mut Interp, this: Value, a: &[Value]) -> Result<Value, Value> {
680    require_object(it, &this, "RegExp.prototype[Symbol.match]")?;
681    let s = it.to_string_value(arg(a, 0))?;
682    if let Some(r) = pristine(it, &this) {
683        let (global, sticky) = {
684            let d = r.borrow();
685            (d.re.global, d.re.sticky)
686        };
687        if global && !sticky {
688            set_last_index(it, &this, 0.0)?;
689            return Ok(native_match_global(&r, &s));
690        }
691        if !global && !sticky {
692            return builtin_exec(it, &this, &r, &s);
693        }
694    }
695    let flags = it.get_property(&this, "flags")?;
696    let flags = it.to_string_value(flags)?;
697    if !flags.contains('g') {
698        return regexp_exec(it, &this, &s);
699    }
700    let full_unicode = flags.contains('u') || flags.contains('v');
701    set_last_index(it, &this, 0.0)?;
702    let s16: Vec<u16> = s.encode_utf16().collect();
703    let mut items = Vec::new();
704    loop {
705        let result = regexp_exec(it, &this, &s)?;
706        if matches!(result, Value::Null) {
707            return Ok(if items.is_empty() { Value::Null } else { Value::Object(Obj::array(items)) });
708        }
709        let m = it.get_property(&result, "0")?;
710        let m = it.to_string_value(m)?;
711        let empty = m.is_empty();
712        items.push(Value::str(m));
713        if empty {
714            let this_index = get_last_index(it, &this)?;
715            set_last_index(it, &this, advance_string_index(&s16, this_index, full_unicode))?;
716        }
717    }
718}
719
720// ============ Symbol.search ============
721
722fn same_value(a: &Value, b: &Value) -> bool {
723    match (a, b) {
724        (Value::Number(x), Value::Number(y)) => (x.is_nan() && y.is_nan()) || (x == y && x.is_sign_negative() == y.is_sign_negative()),
725        (Value::Object(x), Value::Object(y)) => Rc::ptr_eq(x, y),
726        (Value::Undefined, Value::Undefined) | (Value::Null, Value::Null) => true,
727        (Value::Bool(x), Value::Bool(y)) => x == y,
728        (Value::Str(x), Value::Str(y)) => x == y,
729        _ => false,
730    }
731}
732
733pub(crate) fn re_symbol_search(it: &mut Interp, this: Value, a: &[Value]) -> Result<Value, Value> {
734    require_object(it, &this, "RegExp.prototype[Symbol.search]")?;
735    let s = it.to_string_value(arg(a, 0))?;
736    if let Some(r) = pristine(it, &this) {
737        if !r.borrow().re.sticky {
738            let chars: Vec<char> = s.chars().collect();
739            let found = r.borrow().re.find_at(&chars, 0);
740            return Ok(match found {
741                Some(m) => Value::Number(char_pos_to_utf16(&chars, m.start) as f64),
742                None => Value::Number(-1.0),
743            });
744        }
745    }
746    let previous = it.get_property(&this, "lastIndex")?;
747    if !same_value(&previous, &Value::Number(0.0)) {
748        set_last_index(it, &this, 0.0)?;
749    }
750    let result = regexp_exec(it, &this, &s)?;
751    let current = it.get_property(&this, "lastIndex")?;
752    if !same_value(&current, &previous) {
753        set_last_index_val(it, &this, previous)?;
754    }
755    if matches!(result, Value::Null) {
756        return Ok(Value::Number(-1.0));
757    }
758    it.get_property(&result, "index")
759}
760
761// ============ Symbol.replace ============
762
763pub(crate) fn re_symbol_replace(it: &mut Interp, this: Value, a: &[Value]) -> Result<Value, Value> {
764    require_object(it, &this, "RegExp.prototype[Symbol.replace]")?;
765    let s = it.to_string_value(arg(a, 0))?;
766    let mut replace_value = arg(a, 1);
767    let functional = callable_or_none(replace_value.clone()).is_some();
768    if !functional {
769        replace_value = Value::str(it.to_string_value(replace_value)?);
770    }
771    if let Some(r) = pristine(it, &this) {
772        let (global, sticky) = {
773            let d = r.borrow();
774            (d.re.global, d.re.sticky)
775        };
776        if !sticky {
777            if global {
778                set_last_index(it, &this, 0.0)?;
779            }
780            return Ok(Value::str(regex_replace(it, &s, &r, replace_value, global)?));
781        }
782    }
783    let flags = it.get_property(&this, "flags")?;
784    let flags = it.to_string_value(flags)?;
785    let global = flags.contains('g');
786    let mut full_unicode = false;
787    let s16: Vec<u16> = s.encode_utf16().collect();
788    if global {
789        full_unicode = flags.contains('u') || flags.contains('v');
790        set_last_index(it, &this, 0.0)?;
791    }
792    let mut results: Vec<Value> = Vec::new();
793    loop {
794        let result = regexp_exec(it, &this, &s)?;
795        if matches!(result, Value::Null) {
796            break;
797        }
798        results.push(result.clone());
799        if !global {
800            break;
801        }
802        let m = it.get_property(&result, "0")?;
803        let m = it.to_string_value(m)?;
804        if m.is_empty() {
805            let this_index = get_last_index(it, &this)?;
806            set_last_index(it, &this, advance_string_index(&s16, this_index, full_unicode))?;
807        }
808    }
809    let mut acc = String::new();
810    let mut next_pos = 0usize;
811    for result in results {
812        let len_v = it.get_property(&result, "length")?;
813        let result_len = to_length(it, &len_v)?;
814        let n_captures = if result_len > 1.0 { (result_len - 1.0) as usize } else { 0 };
815        let m0 = it.get_property(&result, "0")?;
816        let matched = it.to_string_value(m0)?;
817        let match_len = matched.encode_utf16().count();
818        let idx_v = it.get_property(&result, "index")?;
819        let pos_n = it.num_of(&idx_v)?;
820        let pos_i = if pos_n.is_nan() { 0.0 } else { libm::trunc(pos_n) };
821        let position = pos_i.max(0.0).min(s16.len() as f64) as usize;
822        let mut captures: Vec<Value> = Vec::new();
823        for n in 1..=n_captures {
824            let c = it.get_property(&result, &n.to_string())?;
825            captures.push(if matches!(c, Value::Undefined) { c } else { Value::str(it.to_string_value(c)?) });
826        }
827        let named = it.get_property(&result, "groups")?;
828        let replacement = if functional {
829            let mut args: Vec<Value> = Vec::new();
830            args.push(Value::str(matched.clone()));
831            args.extend(captures.iter().cloned());
832            args.push(Value::Number(position as f64));
833            args.push(Value::str(s.clone()));
834            if !matches!(named, Value::Undefined) {
835                args.push(named.clone());
836            }
837            let rv = it.call_value(&replace_value, Value::Undefined, &args)?;
838            it.to_string_value(rv)?
839        } else {
840            let named_obj = if matches!(named, Value::Undefined) {
841                named
842            } else if matches!(named, Value::Null) {
843                return Err(it.type_error("Cannot convert undefined or null to object"));
844            } else {
845                named
846            };
847            let tpl = replace_value.to_js_string();
848            get_substitution(it, &matched, &s16, position, &captures, &named_obj, &tpl)?
849        };
850        if position >= next_pos {
851            acc.push_str(&String::from_utf16_lossy(&s16[next_pos..position]));
852            acc.push_str(&replacement);
853            next_pos = position + match_len;
854        }
855    }
856    if next_pos < s16.len() {
857        acc.push_str(&String::from_utf16_lossy(&s16[next_pos..]));
858    }
859    Ok(Value::str(acc))
860}
861
862// ============ Symbol.split ============
863
864fn species_constructor(it: &mut Interp, o: &Value, default: &Value) -> Result<Value, Value> {
865    let c = it.get_property(o, "constructor")?;
866    if matches!(c, Value::Undefined) {
867        return Ok(default.clone());
868    }
869    if !matches!(c, Value::Object(_)) {
870        return Err(it.type_error("object.constructor is not an object"));
871    }
872    let sp = it.get_property(&c, SYM_SPECIES)?;
873    if matches!(sp, Value::Undefined | Value::Null) {
874        return Ok(default.clone());
875    }
876    if super::super::interp::calls::is_constructor(&sp) {
877        return Ok(sp);
878    }
879    Err(it.type_error("object.constructor[Symbol.species] is not a constructor"))
880}
881
882pub(crate) fn to_uint32(n: f64) -> f64 {
883    if !n.is_finite() {
884        return 0.0;
885    }
886    let t = libm::trunc(n);
887    let m = 4294967296.0;
888    let r = t - libm::floor(t / m) * m;
889    if r < 0.0 {
890        r + m
891    } else {
892        r
893    }
894}
895
896pub(crate) fn re_symbol_split(it: &mut Interp, this: Value, a: &[Value]) -> Result<Value, Value> {
897    require_object(it, &this, "RegExp.prototype[Symbol.split]")?;
898    let s = it.to_string_value(arg(a, 0))?;
899    let regexp_fn = super::super::interp::scope_get(&it.global, "RegExp").unwrap_or(Value::Undefined);
900    let c = species_constructor(it, &this, &regexp_fn)?;
901    let flags = it.get_property(&this, "flags")?;
902    let flags = it.to_string_value(flags)?;
903    let unicode = flags.contains('u') || flags.contains('v');
904    let new_flags = if flags.contains('y') { flags.clone() } else { alloc::format!("{}y", flags) };
905    // 素の組込み RegExp で、種別(constructor)も組込みのままなら、従来の高速な分割へ。
906    // (`limit` がオブジェクトなら、その変換が正規表現を書き換え得るので、仕様どおり先に splitter を作る遅い経路へ。)
907    if same_value_obj(&c, &regexp_fn) && !matches!(arg(a, 1), Value::Object(_)) {
908        if let Some(r) = pristine(it, &this) {
909            let lim = match arg(a, 1) {
910                Value::Undefined => 4294967295.0,
911                v => to_uint32(it.num_of(&v)?),
912            };
913            let limit = if lim >= usize::MAX as f64 { usize::MAX } else { lim as usize };
914            let items = regex_split(&r.borrow().re, &s, limit);
915            return Ok(Value::Object(Obj::array(items)));
916        }
917    }
918    let splitter = it.construct_value(&c, &[this.clone(), Value::str(new_flags)])?;
919    let lim = match arg(a, 1) {
920        Value::Undefined => 4294967295.0,
921        v => to_uint32(it.num_of(&v)?),
922    };
923    let mut out: Vec<Value> = Vec::new();
924    if lim == 0.0 {
925        return Ok(Value::Object(Obj::array(out)));
926    }
927    let s16: Vec<u16> = s.encode_utf16().collect();
928    let size = s16.len();
929    if size == 0 {
930        let z = regexp_exec(it, &splitter, &s)?;
931        if !matches!(z, Value::Null) {
932            return Ok(Value::Object(Obj::array(out)));
933        }
934        out.push(Value::str(s));
935        return Ok(Value::Object(Obj::array(out)));
936    }
937    let mut p = 0usize;
938    let mut q = 0f64;
939    while q < size as f64 {
940        set_last_index(it, &splitter, q)?;
941        let z = regexp_exec(it, &splitter, &s)?;
942        if matches!(z, Value::Null) {
943            q = advance_string_index(&s16, q, unicode);
944            continue;
945        }
946        let e = get_last_index(it, &splitter)?.min(size as f64) as usize;
947        if e == p {
948            q = advance_string_index(&s16, q, unicode);
949            continue;
950        }
951        out.push(Value::str(String::from_utf16_lossy(&s16[p..q as usize])));
952        if out.len() as f64 == lim {
953            return Ok(Value::Object(Obj::array(out)));
954        }
955        p = e;
956        let len_v = it.get_property(&z, "length")?;
957        let zl = to_length(it, &len_v)?;
958        let ncap = if zl > 1.0 { (zl - 1.0) as usize } else { 0 };
959        for i in 1..=ncap {
960            out.push(it.get_property(&z, &i.to_string())?);
961            if out.len() as f64 == lim {
962                return Ok(Value::Object(Obj::array(out)));
963            }
964        }
965        q = p as f64;
966    }
967    out.push(Value::str(String::from_utf16_lossy(&s16[p.min(size)..])));
968    Ok(Value::Object(Obj::array(out)))
969}
970
971// ============ Symbol.matchAll と %RegExpStringIteratorPrototype% ============
972
973fn iterator_proto(it: &Interp) -> Option<ObjRef> {
974    global_ctor_proto(it, "Iterator")
975}
976
977fn rsi_proto(it: &Interp) -> Option<ObjRef> {
978    let ip = iterator_proto(it)?;
979    if let Some(Value::Object(h)) = ip.borrow().props.get("_rsp").cloned() {
980        return Some(h);
981    }
982    let h = Obj::plain();
983    {
984        let mut b = h.borrow_mut();
985        b.proto = Some(ip.clone());
986        b.props.insert("next".into(), nv("next", rsi_next));
987        b.insert_attr("next", PropertyAttributes { writable: true, configurable: true, enumerable: false });
988        b.props.insert(SYM_TAG.into(), Value::str("RegExp String Iterator"));
989        b.insert_attr(SYM_TAG, PropertyAttributes { writable: false, configurable: true, enumerable: false });
990    }
991    ip.borrow_mut().props.insert("_rsp".into(), Value::Object(h.clone()));
992    Some(h)
993}
994
995fn rsi_state(o: &ObjRef, k: &str) -> Value {
996    o.borrow().props.get(k).cloned().unwrap_or(Value::Undefined)
997}
998
999fn rsi_next(it: &mut Interp, this: Value, _a: &[Value]) -> Result<Value, Value> {
1000    let o = match &this {
1001        Value::Object(o) if o.borrow().props.contains_key("_rsx") && o.borrow().props.contains_key("_rss") => o.clone(),
1002        _ => return Err(it.type_error("%RegExpStringIterator%.next called on incompatible receiver")),
1003    };
1004    if matches!(rsi_state(&o, "_rsd"), Value::Bool(true)) {
1005        return Ok(iter_result(Value::Undefined, true));
1006    }
1007    let rx = rsi_state(&o, "_rsx");
1008    let s = rsi_state(&o, "_rss").to_js_string();
1009    let global = rsi_state(&o, "_rsg").truthy();
1010    let unicode = rsi_state(&o, "_rsu").truthy();
1011    let m = match regexp_exec(it, &rx, &s) {
1012        Ok(m) => m,
1013        Err(e) => {
1014            o.borrow_mut().props.insert("_rsd".into(), Value::Bool(true));
1015            return Err(e);
1016        }
1017    };
1018    if matches!(m, Value::Null) {
1019        o.borrow_mut().props.insert("_rsd".into(), Value::Bool(true));
1020        return Ok(iter_result(Value::Undefined, true));
1021    }
1022    if !global {
1023        o.borrow_mut().props.insert("_rsd".into(), Value::Bool(true));
1024        return Ok(iter_result(m, false));
1025    }
1026    let r = (|| -> Result<(), Value> {
1027        let m0 = it.get_property(&m, "0")?;
1028        let ms = it.to_string_value(m0)?;
1029        if ms.is_empty() {
1030            let this_index = get_last_index(it, &rx)?;
1031            let s16: Vec<u16> = s.encode_utf16().collect();
1032            set_last_index(it, &rx, advance_string_index(&s16, this_index, unicode))?;
1033        }
1034        Ok(())
1035    })();
1036    if let Err(e) = r {
1037        o.borrow_mut().props.insert("_rsd".into(), Value::Bool(true));
1038        return Err(e);
1039    }
1040    Ok(iter_result(m, false))
1041}
1042
1043pub(crate) fn re_symbol_match_all(it: &mut Interp, this: Value, a: &[Value]) -> Result<Value, Value> {
1044    require_object(it, &this, "RegExp.prototype[Symbol.matchAll]")?;
1045    let s = it.to_string_value(arg(a, 0))?;
1046    let regexp_fn = super::super::interp::scope_get(&it.global, "RegExp").unwrap_or(Value::Undefined);
1047    let c = species_constructor(it, &this, &regexp_fn)?;
1048    let flags = it.get_property(&this, "flags")?;
1049    let flags = it.to_string_value(flags)?;
1050    let matcher = it.construct_value(&c, &[this.clone(), Value::str(flags.clone())])?;
1051    let last_index = get_last_index(it, &this)?;
1052    set_last_index(it, &matcher, last_index)?;
1053    let o = Obj::plain();
1054    {
1055        let mut b = o.borrow_mut();
1056        b.proto = rsi_proto(it);
1057        b.props.insert("_rsx".into(), matcher);
1058        b.props.insert("_rss".into(), Value::str(s));
1059        b.props.insert("_rsg".into(), Value::Bool(flags.contains('g')));
1060        b.props.insert("_rsu".into(), Value::Bool(flags.contains('u') || flags.contains('v')));
1061        b.props.insert("_rsd".into(), Value::Bool(false));
1062    }
1063    let _ = SYM_ITER;
1064    Ok(Value::Object(o))
1065}
1066
1067// ============ String.prototype.match / matchAll / search / replace / replaceAll / split の入口 ============
1068
1069/// GetMethod(v, key)(`undefined`/`null` は None、関数でなければ TypeError)。
1070fn get_method(it: &mut Interp, v: &Value, key: &str) -> Result<Option<Value>, Value> {
1071    let m = it.get_property(v, key)?;
1072    if matches!(m, Value::Undefined | Value::Null) {
1073        return Ok(None);
1074    }
1075    if callable_or_none(m.clone()).is_none() {
1076        return Err(it.type_error(alloc::format!("{} is not a function", key)));
1077    }
1078    Ok(Some(m))
1079}
1080
1081pub(crate) fn str_match(it: &mut Interp, t: Value, a: &[Value]) -> Result<Value, Value> {
1082    require_coercible(it, &t, "String.prototype.match")?;
1083    let rx = arg(a, 0);
1084    if let Value::Object(_) = &rx {
1085        if let Some(m) = get_method(it, &rx, SYM_MATCH)? {
1086            return it.call_value(&m, rx.clone(), &[t]);
1087        }
1088    }
1089    let s = Value::str(it.to_string_value(t)?);
1090    let rxo = regexp_create(it, rx, Value::Undefined)?;
1091    let m = it.get_property(&rxo, SYM_MATCH)?;
1092    it.call_value(&m, rxo, &[s])
1093}
1094
1095pub(crate) fn str_match_all(it: &mut Interp, t: Value, a: &[Value]) -> Result<Value, Value> {
1096    require_coercible(it, &t, "String.prototype.matchAll")?;
1097    let rx = arg(a, 0);
1098    if !matches!(rx, Value::Undefined | Value::Null) {
1099        if is_regexp(it, &rx)? {
1100            let flags = it.get_property(&rx, "flags")?;
1101            require_coercible(it, &flags, "RegExp flags")?;
1102            let flags = it.to_string_value(flags)?;
1103            if !flags.contains('g') {
1104                return Err(it.type_error("String.prototype.matchAll called with a non-global RegExp argument"));
1105            }
1106        }
1107        if let Value::Object(_) = &rx {
1108            if let Some(m) = get_method(it, &rx, SYM_MATCH_ALL)? {
1109                return it.call_value(&m, rx.clone(), &[t]);
1110            }
1111        }
1112    }
1113    let s = Value::str(it.to_string_value(t)?);
1114    let rxo = regexp_create(it, rx, Value::str("g"))?;
1115    let m = it.get_property(&rxo, SYM_MATCH_ALL)?;
1116    it.call_value(&m, rxo, &[s])
1117}
1118
1119pub(crate) fn str_search(it: &mut Interp, t: Value, a: &[Value]) -> Result<Value, Value> {
1120    require_coercible(it, &t, "String.prototype.search")?;
1121    let rx = arg(a, 0);
1122    if let Value::Object(_) = &rx {
1123        if let Some(m) = get_method(it, &rx, SYM_SEARCH)? {
1124            return it.call_value(&m, rx.clone(), &[t]);
1125        }
1126    }
1127    let s = Value::str(it.to_string_value(t)?);
1128    let rxo = regexp_create(it, rx, Value::Undefined)?;
1129    let m = it.get_property(&rxo, SYM_SEARCH)?;
1130    it.call_value(&m, rxo, &[s])
1131}
1132
1133/// `replace`・`replaceAll`・`split` が最初に試す `[Symbol.xxx]` への委譲(引数がオブジェクトのときだけ)。
1134pub(crate) fn dispatch_symbol(it: &mut Interp, t: &Value, rx: &Value, key: &str, extra: Value) -> Result<Option<Value>, Value> {
1135    if let Value::Object(_) = rx {
1136        if let Some(m) = get_method(it, rx, key)? {
1137            return Ok(Some(it.call_value(&m, rx.clone(), &[t.clone(), extra])?));
1138        }
1139    }
1140    Ok(None)
1141}
1142
1143/// `replaceAll` の前段(`g` のない RegExp 風の引数は TypeError)。
1144pub(crate) fn replace_all_precheck(it: &mut Interp, rx: &Value) -> Result<(), Value> {
1145    if !matches!(rx, Value::Undefined | Value::Null) && is_regexp(it, rx)? {
1146        let flags = it.get_property(rx, "flags")?;
1147        require_coercible(it, &flags, "RegExp flags")?;
1148        let flags = it.to_string_value(flags)?;
1149        if !flags.contains('g') {
1150            return Err(it.type_error("String.prototype.replaceAll called with a non-global RegExp argument"));
1151        }
1152    }
1153    Ok(())
1154}
1155
1156pub(crate) fn symbol_replace_key() -> &'static str {
1157    SYM_REPLACE
1158}
1159pub(crate) fn symbol_split_key() -> &'static str {
1160    SYM_SPLIT
1161}
1162
1163/// 文字列の検索値での `replace`(先頭の一致だけ)・`replaceAll`(全部)。ToString(replaceValue) は検索より前(仕様の順序)。
1164pub(crate) fn replace_string_pattern(
1165    it: &mut Interp,
1166    s: &str,
1167    search: &str,
1168    repl: Value,
1169    all: bool,
1170) -> Result<String, Value> {
1171    let functional = callable_or_none(repl.clone()).is_some();
1172    let tpl = if functional {
1173        String::new()
1174    } else {
1175        super::props_methods::to_str_strict(it, repl.clone())?
1176    };
1177    // 一致の位置(バイト)。空の検索値は文字の境界ごと(replaceAll)・先頭(replace)。
1178    let positions: Vec<usize> = if search.is_empty() {
1179        if all {
1180            s.char_indices().map(|(i, _)| i).chain(core::iter::once(s.len())).collect()
1181        } else {
1182            alloc::vec![0]
1183        }
1184    } else if all {
1185        s.match_indices(search).map(|(i, _)| i).collect()
1186    } else {
1187        s.find(search).into_iter().collect()
1188    };
1189    if positions.is_empty() {
1190        return Ok(String::from(s));
1191    }
1192    let needs_sub = !functional && tpl.contains('$');
1193    let s16: Vec<u16> = if needs_sub { s.encode_utf16().collect() } else { Vec::new() };
1194    let mut out = String::with_capacity(s.len());
1195    let mut last_byte = 0usize;
1196    let mut upos = 0usize; // `last_byte` に対応する UTF-16 の位置
1197    for pos in positions {
1198        let seg = s.get(last_byte..pos).unwrap_or("");
1199        out.push_str(seg);
1200        upos += seg.encode_utf16().count();
1201        let rep = if functional {
1202            let rv = it.call_value(
1203                &repl,
1204                Value::Undefined,
1205                &[Value::str(String::from(search)), Value::Number(upos as f64), Value::str(String::from(s))],
1206            )?;
1207            super::props_methods::to_str_strict(it, rv)?
1208        } else if needs_sub {
1209            get_substitution(it, search, &s16, upos, &[], &Value::Undefined, &tpl)?
1210        } else {
1211            tpl.clone()
1212        };
1213        out.push_str(&rep);
1214        last_byte = pos + search.len();
1215        upos += search.encode_utf16().count();
1216    }
1217    out.push_str(s.get(last_byte.min(s.len())..).unwrap_or(""));
1218    Ok(out)
1219}
1220
1221// ============ Annex B RegExp legacy static accessors ============
1222
1223fn require_regexp_ctor(it: &mut Interp, this: &Value) -> Result<ObjRef, Value> {
1224    if let (Value::Object(o), Some(Value::Object(rc))) = (this, it.global.borrow().vars.get("RegExp")) {
1225        if Rc::ptr_eq(o, rc) {
1226            return Ok(rc.clone());
1227        }
1228    }
1229    Err(it.type_error("RegExp legacy static accessor called on incompatible receiver"))
1230}
1231
1232fn legacy_re_get(it: &mut Interp, this: Value, slot: &str) -> Result<Value, Value> {
1233    let rc = require_regexp_ctor(it, &this)?;
1234    let v = rc
1235        .borrow()
1236        .props
1237        .get(slot)
1238        .cloned()
1239        .unwrap_or_else(|| Value::str(""));
1240    Ok(v)
1241}
1242
1243fn legacy_re_input_get(it: &mut Interp, this: Value, _a: &[Value]) -> Result<Value, Value> {
1244    legacy_re_get(it, this, "_re_input")
1245}
1246fn legacy_re_input_set(it: &mut Interp, this: Value, a: &[Value]) -> Result<Value, Value> {
1247    let rc = require_regexp_ctor(it, &this)?;
1248    let s = it.to_string_value(arg(a, 0))?;
1249    rc.borrow_mut().props.insert("_re_input".into(), Value::str(s));
1250    Ok(Value::Undefined)
1251}
1252fn legacy_re_last_match_get(it: &mut Interp, this: Value, _a: &[Value]) -> Result<Value, Value> {
1253    legacy_re_get(it, this, "_re_last_match")
1254}
1255fn legacy_re_last_paren_get(it: &mut Interp, this: Value, _a: &[Value]) -> Result<Value, Value> {
1256    legacy_re_get(it, this, "_re_last_paren")
1257}
1258fn legacy_re_left_get(it: &mut Interp, this: Value, _a: &[Value]) -> Result<Value, Value> {
1259    legacy_re_get(it, this, "_re_left")
1260}
1261fn legacy_re_right_get(it: &mut Interp, this: Value, _a: &[Value]) -> Result<Value, Value> {
1262    legacy_re_get(it, this, "_re_right")
1263}
1264fn legacy_re_p1_get(it: &mut Interp, this: Value, _a: &[Value]) -> Result<Value, Value> { legacy_re_get(it, this, "_re_p1") }
1265fn legacy_re_p2_get(it: &mut Interp, this: Value, _a: &[Value]) -> Result<Value, Value> { legacy_re_get(it, this, "_re_p2") }
1266fn legacy_re_p3_get(it: &mut Interp, this: Value, _a: &[Value]) -> Result<Value, Value> { legacy_re_get(it, this, "_re_p3") }
1267fn legacy_re_p4_get(it: &mut Interp, this: Value, _a: &[Value]) -> Result<Value, Value> { legacy_re_get(it, this, "_re_p4") }
1268fn legacy_re_p5_get(it: &mut Interp, this: Value, _a: &[Value]) -> Result<Value, Value> { legacy_re_get(it, this, "_re_p5") }
1269fn legacy_re_p6_get(it: &mut Interp, this: Value, _a: &[Value]) -> Result<Value, Value> { legacy_re_get(it, this, "_re_p6") }
1270fn legacy_re_p7_get(it: &mut Interp, this: Value, _a: &[Value]) -> Result<Value, Value> { legacy_re_get(it, this, "_re_p7") }
1271fn legacy_re_p8_get(it: &mut Interp, this: Value, _a: &[Value]) -> Result<Value, Value> { legacy_re_get(it, this, "_re_p8") }
1272fn legacy_re_p9_get(it: &mut Interp, this: Value, _a: &[Value]) -> Result<Value, Value> { legacy_re_get(it, this, "_re_p9") }
1273
1274pub(crate) fn update_legacy_regexp_statics(
1275    it: &mut Interp,
1276    rx: &Value,
1277    m: &regex::Match,
1278    chars: &[char],
1279    input: &str,
1280) {
1281    let is_builtin_rx = if let (Value::Object(ro), Some(rp)) = (rx, regexp_proto_obj(it)) {
1282        ro.borrow().proto.as_ref().is_none_or(|p| Rc::ptr_eq(p, &rp))
1283    } else {
1284        false
1285    };
1286    if !is_builtin_rx {
1287        return;
1288    }
1289    let Some(Value::Object(rc)) = it.global.borrow().vars.get("RegExp").cloned() else {
1290        return;
1291    };
1292    let slice_chars = |s: usize, e: usize| -> String {
1293        chars.get(s..e).map(|sl| sl.iter().collect()).unwrap_or_default()
1294    };
1295    let last_match = m
1296        .captures
1297        .first()
1298        .and_then(|c| c.map(|(s, e)| slice_chars(s, e)))
1299        .unwrap_or_default();
1300    let left = slice_chars(0, m.start);
1301    let right = slice_chars(m.end, chars.len());
1302    let last_paren = if m.captures.len() > 1 {
1303        m.captures
1304            .last()
1305            .and_then(|c| c.map(|(s, e)| slice_chars(s, e)))
1306            .unwrap_or_default()
1307    } else {
1308        String::new()
1309    };
1310    let mut rb = rc.borrow_mut();
1311    rb.props.insert("_re_input".into(), Value::str(String::from(input)));
1312    rb.props.insert("_re_last_match".into(), Value::str(last_match));
1313    rb.props.insert("_re_last_paren".into(), Value::str(last_paren));
1314    rb.props.insert("_re_left".into(), Value::str(left));
1315    rb.props.insert("_re_right".into(), Value::str(right));
1316    const SLOTS: [&str; 9] = [
1317        "_re_p1", "_re_p2", "_re_p3", "_re_p4", "_re_p5", "_re_p6", "_re_p7", "_re_p8", "_re_p9",
1318    ];
1319    for (idx, slot) in SLOTS.iter().enumerate() {
1320        let cap_s = m
1321            .captures
1322            .get(idx + 1)
1323            .and_then(|c| c.map(|(s, e)| slice_chars(s, e)))
1324            .unwrap_or_default();
1325        rb.props.insert((*slot).into(), Value::str(cap_s));
1326    }
1327}
1328
1329pub(crate) fn install_regexp_legacy_accessors(rc: &ObjRef) {
1330    let attr = PropertyAttributes { writable: false, enumerable: false, configurable: true };
1331    let mut rb = rc.borrow_mut();
1332    let input_acc = Accessor {
1333        get: Some(nv("get input", legacy_re_input_get)),
1334        set: Some(nv("set input", legacy_re_input_set)),
1335    };
1336    for name in ["input", "$_"] {
1337        rb.insert_accessor(name, input_acc.clone());
1338        rb.insert_attr(name, attr);
1339    }
1340    let ro_accs: [(&str, NativeFn); 17] = [
1341        ("lastMatch", legacy_re_last_match_get),
1342        ("$&", legacy_re_last_match_get),
1343        ("lastParen", legacy_re_last_paren_get),
1344        ("$+", legacy_re_last_paren_get),
1345        ("leftContext", legacy_re_left_get),
1346        ("$`", legacy_re_left_get),
1347        ("rightContext", legacy_re_right_get),
1348        ("$'", legacy_re_right_get),
1349        ("$1", legacy_re_p1_get),
1350        ("$2", legacy_re_p2_get),
1351        ("$3", legacy_re_p3_get),
1352        ("$4", legacy_re_p4_get),
1353        ("$5", legacy_re_p5_get),
1354        ("$6", legacy_re_p6_get),
1355        ("$7", legacy_re_p7_get),
1356        ("$8", legacy_re_p8_get),
1357        ("$9", legacy_re_p9_get),
1358    ];
1359    for (name, f) in ro_accs {
1360        rb.insert_accessor(name, Accessor { get: Some(nv(name, f)), set: None });
1361        rb.insert_attr(name, attr);
1362    }
1363}