Skip to main content

atmos/os_lib/ecma/builtins/
regexp.rs

1// 分割: builtins.rs より機械的に移動(2026-07-16 リファクタ フェーズ2)。
2// ロジック不変。可視性のみ pub(crate) へ昇格し、親が pub(crate) use で再エクスポート。
3use super::*;
4
5// ============ RegExp ============
6
7use super::super::regex::{self, RegExpData};
8
9pub(crate) fn as_regexp(v: &Value) -> Option<PromiseRc<PromiseRefCell<RegExpData>>> {
10    if let Value::Object(o) = v {
11        let o = unwrap_proxy_target(o);
12        let b = o.borrow();
13        if let ObjKind::RegExpObj(r) = &b.kind {
14            return Some(r.clone());
15        }
16    }
17    None
18}
19
20/// `new RegExp` に渡されたパターン・フラグの構文の誤り(SyntaxError の文言)。2026-11-16 以前は
21/// 誤りでも黙って正規表現を作っていた(`new RegExp("(")`・`new RegExp("a", "gg")`)。
22/// 見るのは、フラグ(知らない文字・重複・`u` と `v` の併用)、括弧の対応、閉じていない `[`、末尾の `\`、
23/// 名前つきの捕捉の名前の重複だけ(量指定子の誤りなどは見ない)。
24pub(crate) fn regexp_syntax_error(pattern: &str, flags: &str) -> Option<String> {
25    let mut seen = String::new();
26    for c in flags.chars() {
27        if !"dgimsuvy".contains(c) || seen.contains(c) {
28            return Some(alloc::format!("Invalid flags supplied to RegExp constructor '{}'", flags));
29        }
30        seen.push(c);
31    }
32    if seen.contains('u') && seen.contains('v') {
33        return Some(alloc::format!("Invalid flags supplied to RegExp constructor '{}'", flags));
34    }
35    super::super::regex_syntax::pattern_error(pattern, flags)
36}
37
38/// `RegExp.escape(str)`(ES2025 §22.2.5.1)。
39pub(crate) fn regexp_escape_static(it: &mut Interp, _t: Value, a: &[Value]) -> Result<Value, Value> {
40    let v = arg(a, 0);
41    if v.type_of() == "symbol" {
42        return Err(it.type_error("RegExp.escape requires a string"));
43    }
44    let Value::Str(s) = v else {
45        return Err(it.type_error("RegExp.escape requires a string"));
46    };
47    let mut out = String::new();
48    for (idx, c) in s.chars().enumerate() {
49        if idx == 0 && c.is_ascii_alphanumeric() {
50            out.push_str(&alloc::format!("\\x{:02x}", c as u32));
51            continue;
52        }
53        match c {
54            '^' | '$' | '\\' | '.' | '*' | '+' | '?' | '(' | ')' | '[' | ']' | '{' | '}' | '|'
55            | '/' => {
56                out.push('\\');
57                out.push(c);
58            }
59            '\t' => out.push_str("\\t"),
60            '\n' => out.push_str("\\n"),
61            '\u{000B}' => out.push_str("\\v"),
62            '\u{000C}' => out.push_str("\\f"),
63            '\r' => out.push_str("\\r"),
64            ',' | '-' | '=' | '<' | '>' | '#' | '&' | '!' | '%' | ':' | ';' | '@' | '~'
65            | '\'' | '"' | ' ' => {
66                out.push_str(&alloc::format!("\\x{:02x}", c as u32));
67            }
68            '\u{00A0}' => out.push_str("\\xa0"),
69            '\u{1680}' | '\u{2000}'..='\u{200A}' | '\u{2028}' | '\u{2029}' | '\u{202F}'
70            | '\u{205F}' | '\u{3000}' | '\u{FEFF}' => {
71                out.push_str(&alloc::format!("\\u{:04x}", c as u32));
72            }
73            _ => out.push(c),
74        }
75    }
76    Ok(Value::str(out))
77}
78
79/// マッチ結果を JS 配列(index/input プロパティ付き)に変換。
80pub(crate) fn match_to_array(
81    m: &regex::Match,
82    chars: &[char],
83    input: &str,
84    group_names: &[(String, usize)],
85) -> Value {
86    match_to_array_impl(m, chars, input, false, group_names)
87}
88
89/// 名前付きキャプチャグループ(ES2018)の `groups` オブジェクトを組み立てる。
90/// `values` は各グループ番号 `idx`(0 は全体一致なので使わない)に対応する値。
91pub(crate) fn build_named_groups(group_names: &[(String, usize)], values: &[Value]) -> Value {
92    if group_names.is_empty() {
93        return Value::Undefined;
94    }
95    let g = Obj::plain();
96    g.borrow_mut().set_null_proto(true);
97    for (name, idx) in group_names {
98        let v = values.get(*idx).cloned().unwrap_or(Value::Undefined);
99        let mut gb = g.borrow_mut();
100        if !gb.props.contains_key(name.as_str()) || !matches!(v, Value::Undefined) {
101            gb.props.insert(name.clone().into(), v);
102        }
103    }
104    Value::Object(g)
105}
106
107#[inline]
108pub(crate) fn char_pos_to_utf16(chars: &[char], char_pos: usize) -> usize {
109    chars.iter().take(char_pos).map(|c| c.len_utf16()).sum()
110}
111
112#[inline]
113pub(crate) fn utf16_pos_to_char(chars: &[char], utf16_pos: usize) -> usize {
114    let mut u16 = 0;
115    for (i, c) in chars.iter().enumerate() {
116        if u16 >= utf16_pos {
117            return i;
118        }
119        u16 += c.len_utf16();
120    }
121    chars.len()
122}
123
124pub(crate) fn match_to_array_impl(
125    m: &regex::Match,
126    chars: &[char],
127    input: &str,
128    has_indices: bool,
129    group_names: &[(String, usize)],
130) -> Value {
131    let mut items = Vec::new();
132    for cap in &m.captures {
133        match cap {
134            Some((s, e)) => items.push(Value::str(chars[*s..*e].iter().collect::<String>())),
135            None => items.push(Value::Undefined),
136        }
137    }
138    // `groups`(名前付きキャプチャグループ、ES2018)。以前は正規表現エンジン自体が
139    // `(?<name>...)` を解析せず非キャプチャにフォールバックしていたため、この
140    // プロパティは常に `undefined` だった。
141    let groups_val = build_named_groups(group_names, &items);
142    let arr = Obj::array(items);
143    arr.borrow_mut()
144        .props
145        .insert("index".into(), Value::Number(chars[..m.start].iter().map(|c| c.len_utf16()).sum::<usize>() as f64));
146    arr.borrow_mut()
147        .props
148        .insert("input".into(), Value::str(String::from(input)));
149    arr.borrow_mut().props.insert("groups".into(), groups_val);
150    if has_indices {
151        // `d`(hasIndices)フラグ: 各キャプチャの [start,end) 文字インデックスを持つ
152        // `indices` 配列(unmatched なグループは undefined)。
153        let indices_items: Vec<Value> = m
154            .captures
155            .iter()
156            .map(|cap| match cap {
157                Some((s, e)) => {
158                    Value::Object(Obj::array(alloc::vec![
159                        Value::Number(char_pos_to_utf16(chars, *s) as f64),
160                        Value::Number(char_pos_to_utf16(chars, *e) as f64)
161                    ]))
162                }
163                None => Value::Undefined,
164            })
165            .collect();
166        let indices_groups = build_named_groups(group_names, &indices_items);
167        let indices_arr = Obj::array(indices_items);
168        indices_arr.borrow_mut().props.insert("groups".into(), indices_groups);
169        arr.borrow_mut()
170            .props
171            .insert("indices".into(), Value::Object(indices_arr));
172    }
173    Value::Object(arr)
174}
175
176/// `$&`/`$1`..`$99`/`$$`/`` $` ``/`$'`/`$<name>` 展開。以前は `$&`/`$1`-`$9`/`$$` のみで、
177/// `` $` ``(一致より前の部分)・`$'`(一致より後ろの部分)・`$<name>`(名前付きキャプチャ
178/// グループ、ES2018。名前付きグループ実装と同時にここも配線)・2桁のグループ番号
179/// (`$10` 以降)が非対応だった。
180pub(crate) fn expand_dollar(
181    tpl: &str,
182    m: &regex::Match,
183    chars: &[char],
184    group_names: &[(String, usize)],
185) -> String {
186    let t: Vec<char> = tpl.chars().collect();
187    let mut out = String::new();
188    let mut i = 0;
189    while i < t.len() {
190        if t[i] == '$' && i + 1 < t.len() {
191            let n = t[i + 1];
192            if n == '$' {
193                out.push('$');
194                i += 2;
195                continue;
196            }
197            if n == '&' {
198                out.push_str(&chars[m.start..m.end].iter().collect::<String>());
199                i += 2;
200                continue;
201            }
202            if n == '`' {
203                out.push_str(&chars[..m.start].iter().collect::<String>());
204                i += 2;
205                continue;
206            }
207            if n == '\'' {
208                out.push_str(&chars[m.end..].iter().collect::<String>());
209                i += 2;
210                continue;
211            }
212            if n == '<' && !group_names.is_empty() {
213                if let Some(close) = t[i + 2..].iter().position(|&c| c == '>') {
214                    let name: String = t[i + 2..i + 2 + close].iter().collect();
215                    if let Some((_, gi)) = group_names.iter().find(|(gn, _)| *gn == name) {
216                        if let Some(Some((s, e))) = m.captures.get(*gi) {
217                            out.push_str(&chars[*s..*e].iter().collect::<String>());
218                        }
219                    }
220                    i += 2 + close + 1;
221                    continue;
222                }
223            }
224            if n.is_ascii_digit() {
225                // 2桁優先(`$10` は `$1` ではなくグループ10。存在しなければ1桁として扱う)。
226                let two_digit = if i + 2 < t.len() && t[i + 2].is_ascii_digit() {
227                    let gi2: usize = format!("{}{}", n, t[i + 2]).parse().unwrap_or(0);
228                    if gi2 > 0 && m.captures.get(gi2).is_some() {
229                        Some((gi2, 3))
230                    } else {
231                        None
232                    }
233                } else {
234                    None
235                };
236                let (gi, adv) = two_digit.unwrap_or((n.to_digit(10).unwrap_or(0) as usize, 2));
237                // 【2026-11-17】無い番号(`$0`・捕捉の数を超える `$4`)は仕様どおり `$4` の文字のまま残す。
238                // 以前は空文字にしていた(`"abc".replace(/(a)(b)?(z)?/, "[$4]")` が "[]c")。
239                if gi > 0 && gi < m.captures.len() {
240                    if let Some(Some((s, e))) = m.captures.get(gi) {
241                        out.push_str(&chars[*s..*e].iter().collect::<String>());
242                    }
243                    i += adv;
244                    continue;
245                }
246            }
247        }
248        out.push(t[i]);
249        i += 1;
250    }
251    out
252}
253
254/// RegExp 置換(関数リプレーサ対応・g で全置換)。
255pub(crate) fn regex_replace(
256    it: &mut Interp,
257    s: &str,
258    r: &PromiseRc<PromiseRefCell<RegExpData>>,
259    repl: Value,
260    global: bool,
261) -> Result<String, Value> {
262    let chars: Vec<char> = s.chars().collect();
263    let replacer_fn = callable_or_none(repl.clone());
264    let group_names = r.borrow().re.group_names.clone();
265    // 【2026-11-17】`g` の置換は仕様どおり lastIndex を 0 に戻す(最後の exec の失敗で 0 になる)。以前は前の値が残っていた。
266    if global {
267        r.borrow_mut().last_index = 0;
268    }
269    let mut out = String::new();
270    let mut pos = 0usize;
271    loop {
272        let found = r.borrow().re.find_at(&chars, pos);
273        let m = match found {
274            Some(m) => m,
275            None => break,
276        };
277        out.push_str(&chars[pos..m.start].iter().collect::<String>());
278        let rep = if let Some(f) = &replacer_fn {
279            let mut args: Vec<Value> = Vec::new();
280            for cap in &m.captures {
281                match cap {
282                    Some((cs, ce)) => {
283                        args.push(Value::str(chars[*cs..*ce].iter().collect::<String>()))
284                    }
285                    None => args.push(Value::Undefined),
286                }
287            }
288            args.push(Value::Number(chars[..m.start].iter().map(|c| c.len_utf16()).sum::<usize>() as f64));
289            args.push(Value::str(String::from(s)));
290            // 名前付きキャプチャグループがあれば、仕様どおり最後の引数として
291            // `groups` オブジェクトを渡す(以前は名前付きグループ自体が未実装だった)。
292            if !group_names.is_empty() {
293                args.push(build_named_groups(&group_names, &args[..m.captures.len()]));
294            }
295            let rv = it.call_value(f, Value::Undefined, &args)?;
296            it.to_string_value(rv)?
297        } else {
298            expand_dollar(&repl.to_js_string(), &m, &chars, &group_names)
299        };
300        out.push_str(&rep);
301        // 前進(ゼロ幅一致は 1 文字進めて取りこぼし防止)。
302        if m.end > m.start {
303            pos = m.end;
304        } else {
305            if m.start < chars.len() {
306                out.push(chars[m.start]);
307            }
308            pos = m.start + 1;
309        }
310        if !global || pos > chars.len() {
311            break;
312        }
313    }
314    out.push_str(&chars[pos.min(chars.len())..].iter().collect::<String>());
315    Ok(out)
316}
317
318/// 正規表現で文字列を分ける(仕様の RegExp.prototype[@@split] の手順)。各位置で「そこから始まる一致」を試し、
319/// 一致の終わりが前の区切りの終わりと同じ(空の一致)なら 1 文字進む。区切りの捕捉はその位置に挿入する。
320///
321/// 【2026-11-13】以前は一番近い一致を探して空の一致を飛ばしていた。`"tab".split(/,?/)` が ["tab"]
322/// (正しくは ["t","a","b"])、`"".split(/,?/)` が [""](正しくは [])になっていた。
323pub(crate) fn regex_split(re: &regex::Regex, s: &str, limit: usize) -> Vec<Value> {
324    let chars: Vec<char> = s.chars().collect();
325    let size = chars.len();
326    let mut items = Vec::new();
327    if limit == 0 {
328        return items;
329    }
330    if size == 0 {
331        if re.find_exact_at(&chars, 0).is_none() {
332            items.push(Value::str(String::new()));
333        }
334        return items;
335    }
336    let mut p = 0usize;
337    let mut q = 0usize;
338    'outer: while q < size {
339        let Some(m) = re.find_exact_at(&chars, q) else {
340            q += 1;
341            continue;
342        };
343        let e = m.end.min(size);
344        if e == p {
345            q += 1;
346            continue;
347        }
348        items.push(Value::str(chars[p..q].iter().collect::<String>()));
349        if items.len() >= limit {
350            break 'outer;
351        }
352        for cap in m.captures.iter().skip(1) {
353            items.push(match cap {
354                Some((cs, ce)) => Value::str(chars[*cs..*ce].iter().collect::<String>()),
355                None => Value::Undefined,
356            });
357            if items.len() >= limit {
358                break 'outer;
359            }
360        }
361        p = e;
362        q = p;
363    }
364    if items.len() < limit {
365        items.push(Value::str(chars[p..].iter().collect::<String>()));
366    }
367    items.truncate(limit);
368    items
369}
370