quickjs/builtins/regexp.rs
1//! `RegExp` and `RegExp.prototype`.
2//!
3//! The engine lives in [`crate::regexp`]; this module is the JavaScript-facing half: the
4//! constructor, the compiled-pattern cache, `lastIndex`, and `exec`.
5//!
6//! `exec` is where most of the observable semantics live. A `g` or `y` pattern advances
7//! `lastIndex`, a failed match resets it to zero, and the returned array carries the
8//! captured groups plus `index`, `input` and (for the `d` flag) `indices`.
9
10use crate::builtins::substitution::{Substitution, get_substitution, template_group_names};
11use crate::builtins::{arg, define_method, install_species_accessor};
12use crate::interp::{Interp, JsResult};
13use crate::object::{JsObject, Property};
14use crate::regexp::{Flags, Regex};
15use crate::value::Value;
16use js_gc::Gc;
17
18/// The compiled pattern an object of `ObjectKind::RegExp` carries.
19///
20/// Boxed through `Rc` because a `RegExp` object is shared by every reference to it and
21/// the pattern is immutable once compiled.
22#[derive(Clone)]
23pub struct RegExpData {
24 /// The compiled pattern, shared between `exec` calls.
25 pub regex: std::rc::Rc<Regex>,
26 /// Pattern source as written, which `.source` reports.
27 pub source: String,
28 /// The flags, in canonical order.
29 pub flags: String,
30}
31
32/// Install `RegExp` and its prototype methods.
33pub fn install(interp: &mut Interp<'_>, object_proto: &Gc<JsObject>) -> Gc<JsObject> {
34 let prototype = interp.new_object(Some(object_proto.clone()));
35 let constructor = interp.new_native_constructor("RegExp", 2, constructor);
36 constructor.define(
37 "prototype",
38 Property::with_attributes(Value::Object(prototype.clone()), false, false),
39 );
40 prototype.define(
41 "constructor",
42 Property::with_attributes(Value::Object(constructor.clone()), true, false),
43 );
44
45 define_method(&prototype, "exec", 1, exec, interp);
46 define_method(&prototype, "test", 1, test, interp);
47 define_method(&prototype, "toString", 0, to_string, interp);
48 for (name, getter) in [
49 (
50 "source",
51 source as fn(&mut Interp<'_>, Value, &[Value]) -> JsResult<Value>,
52 ),
53 ("flags", flags),
54 ("global", global),
55 ("ignoreCase", ignore_case),
56 ("multiline", multiline),
57 ("sticky", sticky),
58 ("unicode", unicode),
59 ("unicodeSets", unicode_sets),
60 ("dotAll", dot_all),
61 ("hasIndices", has_indices),
62 ] {
63 // `get unicodeSets`, not `unicodeSets`: §22.2.6's accessors are named with the
64 // `get ` prefix, which `RegExp/prototype/unicodeSets/name` checks. The prefix is a
65 // property of the *function*, applied here because `new_native` takes the bare name.
66 let getter = interp.new_native(format!("get {name}"), 0, getter);
67 prototype.define(
68 name,
69 Property {
70 getter: Some(Value::Object(getter)),
71 enumerable: false,
72 configurable: true,
73 ..Property::default()
74 },
75 );
76 }
77
78 // `RegExp.escape` is a static: it is on the constructor, not the prototype.
79 define_method(&constructor, "escape", 1, escape, interp);
80 install_species_accessor(&constructor, interp);
81
82 // `Symbol.match` and friends are what `String.prototype.match` looks up; without them
83 // a regexp is not recognised as a pattern by those methods.
84 install_symbol_methods(interp, &prototype, &constructor);
85 interp.realm.regexp_proto = Some(prototype.clone());
86 interp.realm.regexp_ctor = Some(constructor.clone());
87 constructor
88}
89
90fn install_symbol_methods(
91 interp: &mut Interp<'_>,
92 prototype: &Gc<JsObject>,
93 constructor: &Gc<JsObject>,
94) {
95 use crate::interp::WellKnown;
96 for (which, name, func, length) in [
97 (
98 WellKnown::Match,
99 "[Symbol.match]",
100 symbol_match as crate::object::NativeFn,
101 1,
102 ),
103 (WellKnown::Replace, "[Symbol.replace]", symbol_replace, 2),
104 (
105 WellKnown::MatchAll,
106 "[Symbol.matchAll]",
107 symbol_match_all,
108 1,
109 ),
110 (WellKnown::Search, "[Symbol.search]", symbol_search, 1),
111 (WellKnown::Split, "[Symbol.split]", symbol_split, 2),
112 ] {
113 let method = interp.new_native(name, length, func);
114 prototype.define_key(
115 &interp.realm.well_known_key(which),
116 Property::with_attributes(Value::Object(method), true, false),
117 );
118 }
119 let _ = constructor;
120}
121
122/// `RegExp.escape(string)`: escape `string` so it can be used as a literal pattern.
123///
124/// Two things make this more than a backslash loop:
125///
126/// * **The first character is escaped differently.** A leading ASCII letter or digit
127/// becomes `\xNN`, because `"1"` after a `\0` or `\c` would otherwise be read as part
128/// of the preceding escape rather than as a digit.
129/// * **Most characters need no escape at all.** Only the syntax characters, `/`, the
130/// control escapes, a fixed list of other punctuators, whitespace, line terminators and
131/// lone surrogates are touched; everything else — including all non-ASCII letters — is
132/// copied through, because a literal character in a pattern is already literal outside
133/// syntax positions.
134///
135/// Note `\s`'s set is reused for "whitespace or line terminator" (see
136/// [`quickjs_regexp::is_space`]) rather than restated, so the two cannot drift.
137fn escape(interp: &mut Interp<'_>, _this: Value, args: &[Value]) -> JsResult<Value> {
138 let arg = arg(args, 0);
139 // Not `ToString`: the spec is explicit that a non-string is a TypeError rather than
140 // being coerced, so `RegExp.escape(1)` throws instead of returning `"1"`.
141 if !matches!(arg, Value::String(_)) {
142 return Err(interp.type_error("not a string"));
143 }
144 let source = interp.checked_to_wtf8(&arg)?.code_point_values();
145 let mut out: Vec<u32> = Vec::with_capacity(source.len());
146 for (position, cp) in source.iter().enumerate() {
147 // `escaped` is empty exactly at the first code point, since every branch below
148 // emits at least one code unit.
149 let leading = position == 0;
150 encode_for_regexp_escape(*cp, leading, &mut out);
151 }
152 Ok(interp.string_wtf8(points_to_wtf8(&out)))
153}
154
155/// The per-code-point half of `RegExp.escape`: `EncodeForRegExpEscape`, plus the leading
156/// alphanumeric rule that the caller knows about and this does not.
157fn encode_for_regexp_escape(c: u32, leading: bool, out: &mut Vec<u32>) {
158 let backslash = u32::from(b'\\');
159 // A leading ASCII letter or digit is always hex-escaped: it may otherwise be read as
160 // part of a preceding `\0…` or `\c…`.
161 let ascii_alnum = matches!(c, 0x30..=0x39 | 0x41..=0x5A | 0x61..=0x7A);
162 if leading && ascii_alnum {
163 push_hex_escape(c, out);
164 return;
165 }
166 // SyntaxCharacter, plus `/` — the one character a pattern literal would terminate on.
167 if matches!(
168 c,
169 0x2E | 0x2A | 0x2B | 0x3F | 0x5E | 0x24 | 0x7C // . * + ? ^ $ |
170 | 0x28 | 0x29 | 0x5B | 0x5D | 0x7B | 0x7D // ( ) [ ] { }
171 | 0x5C | 0x2F // \ /
172 ) {
173 out.push(backslash);
174 out.push(c);
175 return;
176 }
177 // The five control escapes that have a short spelling.
178 if let Some(letter) = match c {
179 0x09 => Some('t'),
180 0x0A => Some('n'),
181 0x0B => Some('v'),
182 0x0C => Some('f'),
183 0x0D => Some('r'),
184 _ => None,
185 } {
186 out.push(backslash);
187 out.push(u32::from(letter as u8));
188 return;
189 }
190 // `otherPunctuators` from the spec, then whitespace, line terminators and lone
191 // surrogates: all of these become `\xNN` or `\uNNNN`.
192 let other_punctuator = matches!(
193 c,
194 0x2C | 0x2D | 0x3D | 0x3C | 0x3E | 0x23 | 0x26 | 0x21 // , - = < > # & !
195 | 0x25 | 0x3A | 0x3B | 0x40 | 0x7E | 0x27 | 0x60 | 0x22 // % : ; @ ~ ' ` "
196 );
197 if other_punctuator || quickjs_regexp::is_space(c) || (0xD800..=0xDFFF).contains(&c) {
198 if c <= 0xFF {
199 push_hex_escape(c, out);
200 } else {
201 // `\uNNNN`, per code unit. Every code point in this branch is below 0x10000
202 // (the spaces, the line separators, the surrogates), so one unit is enough;
203 // anything astral falls through to the literal case below.
204 out.push(backslash);
205 out.push(u32::from(b'u'));
206 for shift in [12, 8, 4, 0] {
207 out.push(u32::from(hex_digit((c >> shift) & 0xF)));
208 }
209 }
210 return;
211 }
212 // Everything else is already literal in a pattern, so it is copied through.
213 out.push(c);
214}
215
216/// `\xNN` for a code point below 0x100.
217fn push_hex_escape(c: u32, out: &mut Vec<u32>) {
218 out.push(u32::from(b'\\'));
219 out.push(u32::from(b'x'));
220 out.push(u32::from(hex_digit((c >> 4) & 0xF)));
221 out.push(u32::from(hex_digit(c & 0xF)));
222}
223
224/// Lowercase hex, which is the case both `\x` and `\u` escapes are expected in.
225fn hex_digit(nibble: u32) -> u8 {
226 match nibble {
227 0..=9 => b'0' + nibble as u8,
228 _ => b'a' + (nibble as u8 - 10),
229 }
230}
231
232/// `new RegExp(pattern, flags)`.
233///
234/// §22.2.3.1 steps 2–3 are `IsRegExp(pattern)` and, when it answers true, `Get(pattern,
235/// "source")` — **not** a read of the internal slot. That difference is observable: a plain
236/// object whose `@@match` getter throws makes `new RegExp(obj, "")` throw, which is what
237/// test262 `Symbol.matchAll/isregexp-this-throws` runs into on its way through the species
238/// constructor. Reading `object.regexp()` made the constructor silently treat such an object
239/// as a string pattern.
240fn constructor(interp: &mut Interp<'_>, _this: Value, args: &[Value]) -> JsResult<Value> {
241 let pattern = arg(args, 0);
242 let flags = arg(args, 1);
243 let (source, flags) = if crate::builtins::string::is_regexp(interp, &pattern)? {
244 let Value::Object(object) = &pattern else {
245 return Err(interp.type_error("a regexp is not an object"));
246 };
247 let source = interp
248 .get_property(object, "source")?
249 .unwrap_or(Value::Undefined);
250 let source = interp.to_js_string(&source)?;
251 let flags = if matches!(flags, Value::Undefined) {
252 let flags = interp
253 .get_property(object, "flags")?
254 .unwrap_or(Value::Undefined);
255 interp.checked_to_string(&flags)?
256 } else {
257 interp.checked_to_string(&flags)?
258 };
259 (source, flags)
260 } else {
261 // `RegExpCreate(undefined, flags)`: the *pattern* is empty, the flags are not.
262 // Dropping them made `new RegExp(x, "g")` a non-global regexp, so
263 // `"asdf".replace(new RegExp(undefined, "g"), "1")` replaced once rather than five
264 // times — test262's `replace/S15.5.4.11_A1_T17`.
265 let source = match &pattern {
266 Value::Undefined => String::new(),
267 other => interp.to_js_string(other)?,
268 };
269 let flags = if matches!(flags, Value::Undefined) {
270 String::new()
271 } else {
272 interp.checked_to_string(&flags)?
273 };
274 (source, flags)
275 };
276 let object = allocate(interp)?;
277 Ok(Value::Object(initialise(interp, object, &source, &flags)?))
278}
279
280/// `RegExp.prototype.exec(string)`.
281fn exec(interp: &mut Interp<'_>, this: Value, args: &[Value]) -> JsResult<Value> {
282 let Some(object) = this.as_object() else {
283 return Err(interp.type_error("RegExp.prototype.exec called on a non-object"));
284 };
285 let text = interp.checked_to_wtf8(&arg(args, 0))?;
286 exec_on(interp, object, &text)
287}
288
289/// The shared implementation of `exec`, used by the `String` methods as well.
290pub fn exec_on(
291 interp: &mut Interp<'_>,
292 object: &Gc<JsObject>,
293 text: &crate::value::Wtf8,
294) -> JsResult<Value> {
295 let Some(data) = object.regexp() else {
296 return Err(interp.type_error("method called on a non-RegExp"));
297 };
298 let sticky_or_global = data.regex.flags.global || data.regex.flags.sticky;
299 let start = if sticky_or_global {
300 // §22.2.6.2 step 4.b: `ToLength(Get(R, "lastIndex"))`. `ToLength` is **not** a
301 // range check — it clamps: `NaN` (so `undefined`, `null`, a throwing `valueOf` that
302 // answers `NaN`) becomes `0`, a negative value becomes `0`, and a fraction is
303 // truncated. Only `+Infinity` survives as "past the end", which the length check
304 // below turns into a `null` result.
305 let index = interp.get_property(object, "lastIndex")?;
306 let index = interp.to_js_number(&index.unwrap_or(Value::Int(0)))?;
307 let index = if index.is_nan() || index < 0.0 {
308 0.0
309 } else if index.is_infinite() {
310 // Anything at or past `2^53` is past the end of any string.
311 f64::INFINITY
312 } else {
313 index.trunc()
314 };
315 if !index.is_finite() {
316 interp.set_property(object, "lastIndex", Value::Int(0))?;
317 return Ok(Value::Null);
318 }
319 index as usize
320 } else {
321 0
322 };
323 let input = MatchInput::new(&data.regex, text);
324 // A `lastIndex` inside a surrogate pair has no character of its own; it belongs to the
325 // character that contains it, which is the same as rounding down to a unit boundary —
326 // what the reference does, and what makes `/(?:)/gu` with `lastIndex = 1` on `"🐱"`
327 // report `index === 0`.
328 if start > input.units_len() {
329 if sticky_or_global {
330 interp.set_property(object, "lastIndex", Value::Int(0))?;
331 }
332 return Ok(Value::Null);
333 }
334 let start = input.position(start);
335 let found = data.regex.exec_at(&input.units, start);
336 let Some(found) = found else {
337 if sticky_or_global {
338 interp.set_property(object, "lastIndex", Value::Int(0))?;
339 }
340 return Ok(Value::Null);
341 };
342 // `lastIndex` moves to the end of the match, in code units — not characters, which is
343 // why an astral match under `u` advances by two.
344 if sticky_or_global {
345 let end = input.offset(found.end);
346 interp.set_property(object, "lastIndex", Value::Int(end as i32))?;
347 }
348 // The result array: the whole match, then one element per group. A group that did not
349 // participate is `undefined`, not a hole.
350 let mut elements: Vec<Value> = Vec::with_capacity(found.captures.len());
351 for capture in &found.captures {
352 elements.push(match capture {
353 Some((start, end)) => interp.string_wtf8(input.slice(*start, *end)),
354 None => Value::Undefined,
355 });
356 }
357 let array = interp.new_array(elements);
358 let index = input.offset(found.start);
359 let input_value = interp.string_wtf8(text.clone());
360 // `CreateDataPropertyOrThrow`, not `Set`: §22.2.7.2 step 18 defines these, so a
361 // `groups`/`index` accessor installed on `Array.prototype` is never consulted — which is
362 // exactly what `named-groups/groups-object` counts.
363 interp.create_named_data_property_or_throw(&array, "index", Value::Int(index as i32))?;
364 interp.create_named_data_property_or_throw(&array, "input", input_value.clone())?;
365 // `m.groups`: a null-prototype object mapping each *named* group to its capture, or
366 // `undefined` when the pattern has no named groups at all — which is what the spec
367 // says, and what `m.groups === undefined` tests check.
368 //
369 // The object has a `null` prototype (`Object.create(null)`), so `m.groups.toString`
370 // is `undefined` and a group named `toString` does not collide with `Object.prototype`.
371 let groups = if data.regex.names.is_empty() {
372 Value::Undefined
373 } else {
374 let groups = interp.new_object(None);
375 for (name, index) in &data.regex.names {
376 let value = match found.captures.get(*index).copied().flatten() {
377 Some((start, end)) => interp.string_wtf8(input.slice(start, end)),
378 None => Value::Undefined,
379 };
380 interp.create_named_data_property_or_throw(&groups, name, value)?;
381 }
382 Value::Object(groups)
383 };
384 interp.create_named_data_property_or_throw(&array, "groups", groups)?;
385 if data.regex.flags.has_indices {
386 let mut pairs = Vec::with_capacity(found.captures.len());
387 for capture in &found.captures {
388 pairs.push(match capture {
389 Some((start, end)) => {
390 let (start, end) = (input.offset(*start), input.offset(*end));
391 let pair =
392 interp.new_array(vec![Value::Int(start as i32), Value::Int(end as i32)]);
393 Value::Object(pair)
394 }
395 None => Value::Undefined,
396 });
397 }
398 let indices = interp.new_array(pairs);
399 // §22.2.7.2 steps 19–23: when the pattern has names, `indices` carries its own
400 // `groups` object with the same shape as the match's — null prototype, each name
401 // mapped to `[start, end]` (or `undefined` for a group that did not participate).
402 // The property is defined **always**, with `undefined` when the pattern has no
403 // names (`indices-groups-object-undefined` reads the descriptor back).
404 let groups_value = if data.regex.names.is_empty() {
405 Value::Undefined
406 } else {
407 let groups_indices = interp.new_object(None);
408 for (name, index) in &data.regex.names {
409 let value = match found.captures.get(*index).copied().flatten() {
410 Some((start, end)) => {
411 let (start, end) = (input.offset(start), input.offset(end));
412 let pair = interp
413 .new_array(vec![Value::Int(start as i32), Value::Int(end as i32)]);
414 Value::Object(pair)
415 }
416 None => Value::Undefined,
417 };
418 interp.create_named_data_property_or_throw(&groups_indices, name, value)?;
419 }
420 Value::Object(groups_indices)
421 };
422 interp.create_named_data_property_or_throw(&indices, "groups", groups_value)?;
423 // `CreateDataPropertyOrThrow`, like `index`/`input`/`groups` above.
424 interp.create_named_data_property_or_throw(&array, "indices", Value::Object(indices))?;
425 }
426 Ok(Value::Object(array))
427}
428
429/// The matcher's view of a string, and the bridge back to the code units a script sees.
430///
431/// Which unit the matcher consumes is decided by the pattern, not by the caller
432/// ([`quickjs_regexp::Regex::per_code_unit`]):
433///
434/// * **No `u`/`v`.** A pattern is a sequence of UTF-16 code units, so `.` matches one unit,
435/// a quantifier binds to one unit, and `[😀]` is a two-unit class. `units` is therefore the
436/// string's code units, every offset the matcher reports is already a code-unit offset —
437/// the unit `lastIndex`, `index`, `.length` and `d`'s pairs are expressed in — and
438/// `unit_start` is the identity.
439/// * **`u`/`v`.** A pattern is a sequence of code points, so `units` is the code points and
440/// `unit_start` maps an offset back to code units.
441///
442/// Having one type for both is what keeps the four call sites (`exec`, `[Symbol.match]`,
443/// `[Symbol.split]`, `[Symbol.replace]`) from each carrying their own copy of the mapping —
444/// they had one, and `[Symbol.split]` was missing it entirely.
445struct MatchInput {
446 /// What the matcher consumes: code units, or code points.
447 units: Vec<u32>,
448 /// `unit_start[i]` is the code-unit offset of matcher position `i`, with one extra
449 /// entry for the end.
450 unit_start: Vec<usize>,
451}
452
453impl MatchInput {
454 fn new(regex: &quickjs_regexp::Regex, text: &crate::value::Wtf8) -> Self {
455 if regex.per_code_unit() {
456 let units: Vec<u32> = text.to_units().into_iter().map(u32::from).collect();
457 let unit_start = (0..=units.len()).collect();
458 Self { units, unit_start }
459 } else {
460 let units = text.code_point_values();
461 let mut unit_start = Vec::with_capacity(units.len() + 1);
462 let mut count = 0;
463 for point in &units {
464 unit_start.push(count);
465 count += if *point > 0xFFFF { 2 } else { 1 };
466 }
467 unit_start.push(count);
468 Self { units, unit_start }
469 }
470 }
471
472 /// How many positions the matcher can be at — code units, for both kinds of pattern,
473 /// since that is what `lastIndex` is compared against.
474 fn units_len(&self) -> usize {
475 self.unit_start[self.unit_start.len() - 1]
476 }
477
478 /// The matcher position a code-unit offset starts at, rounded down to a boundary.
479 ///
480 /// The rounding is what makes a `lastIndex` in the middle of a surrogate pair land on
481 /// the character that contains it instead of between two.
482 fn position(&self, offset: usize) -> usize {
483 self.unit_start
484 .partition_point(|start| *start <= offset)
485 .saturating_sub(1)
486 }
487
488 /// The code-unit offset of a matcher position.
489 fn offset(&self, position: usize) -> usize {
490 self.unit_start[position.min(self.unit_start.len() - 1)]
491 }
492
493 /// The text between two matcher positions.
494 ///
495 /// Built through UTF-16 so that a lone surrogate survives: collecting code points into a
496 /// `String` would turn one into U+FFFD, and then `exec` would report different text than
497 /// the input it was given.
498 fn slice(&self, start: usize, end: usize) -> crate::value::Wtf8 {
499 points_to_wtf8(self.units.get(start..end).unwrap_or_default())
500 }
501}
502
503/// Code points (or code units) to WTF-8, keeping a lone surrogate instead of replacing it.
504fn points_to_wtf8(points: &[u32]) -> crate::value::Wtf8 {
505 let mut units = Vec::with_capacity(points.len());
506 for point in points {
507 if *point > 0xFFFF {
508 let value = point - 0x10000;
509 units.push(0xD800 + (value >> 10) as u16);
510 units.push(0xDC00 + (value & 0x3FF) as u16);
511 } else {
512 units.push(*point as u16);
513 }
514 }
515 crate::value::Wtf8::from_units(&units)
516}
517
518/// `RegExp.prototype.test(string)`.
519fn test(interp: &mut Interp<'_>, this: Value, args: &[Value]) -> JsResult<Value> {
520 let result = exec(interp, this, args)?;
521 Ok(Value::Bool(!matches!(result, Value::Null)))
522}
523
524fn to_string(interp: &mut Interp<'_>, this: Value, _args: &[Value]) -> JsResult<Value> {
525 let Some(object) = this.as_object() else {
526 return Err(interp.type_error("RegExp.prototype.toString called on a non-object"));
527 };
528 let Some(data) = object.regexp() else {
529 return Err(interp.type_error("RegExp.prototype.toString called on a non-RegExp"));
530 };
531 let source = if data.source.is_empty() {
532 "(?:)".to_string()
533 } else {
534 data.source.clone()
535 };
536 Ok(interp.string(format!("/{source}/{}", data.flags)))
537}
538
539fn source(interp: &mut Interp<'_>, this: Value, _args: &[Value]) -> JsResult<Value> {
540 // §22.2.6.13: `RegExp.prototype` has no pattern, and the spec has it answer `"(?:)"`
541 // rather than throw — which is also what keeps `/` + source + `/` re-parseable.
542 if is_regexp_prototype(interp, &this) {
543 return Ok(interp.string("(?:)"));
544 }
545 let data = data_of(interp, &this)?;
546 // An empty pattern reports `(?:)` so that `/` + source + `/` parses again.
547 if data.source.is_empty() {
548 return Ok(interp.string("(?:)"));
549 }
550 // Section 22.2.6.13 `EscapeRegExpPattern`: exactly three characters would break the
551 // `/source/flags` round trip, so they are escaped and nothing else is. A slash becomes
552 // a backslash followed by a slash; a line feed and a carriage return each become a
553 // backslash followed by the letter. Everything else is reported verbatim, non-ASCII
554 // included — a surrogate pair survives as the pair, which is what `source/value-u`
555 // re-parses.
556 let mut text = String::with_capacity(data.source.len());
557 for c in data.source.chars() {
558 match c {
559 '/' => text.push_str("\\/"),
560 '\n' => text.push_str("\\n"),
561 '\r' => text.push_str("\\r"),
562 _ => text.push(c),
563 }
564 }
565 let text = text;
566 Ok(interp.string(&text))
567}
568
569/// `RegExp.prototype.flags` — §22.2.4.8.
570///
571/// Every flag is `Get(R, name)`, one observable property read each, **not** a peek at the
572/// internal slots. That is what makes `get-global-err` throw (the `global` getter is user
573/// code) and what makes `builtin-success-g-set-lastindex` see `global: false` on a regexp
574/// that *is* global — and, because `@@match` derives `global` from this string, what makes
575/// it behave like the reference instead of like the slot.
576///
577/// The order below is the spec's canonical order (`dgimsuvy`), so the answer reads the same
578/// as `RegExp.prototype.toString` builds it.
579fn flags(interp: &mut Interp<'_>, this: Value, _args: &[Value]) -> JsResult<Value> {
580 let Some(object) = this.as_object().cloned() else {
581 return Err(interp.type_error("flags called on a non-object"));
582 };
583 let mut out = String::with_capacity(8);
584 for (name, letter) in [
585 ("hasIndices", 'd'),
586 ("global", 'g'),
587 ("ignoreCase", 'i'),
588 ("multiline", 'm'),
589 ("dotAll", 's'),
590 ("unicode", 'u'),
591 ("unicodeSets", 'v'),
592 ("sticky", 'y'),
593 ] {
594 let value = interp
595 .get_property(&object, name)?
596 .unwrap_or(Value::Undefined);
597 if value.to_boolean() {
598 out.push(letter);
599 }
600 }
601 Ok(interp.string(out))
602}
603
604fn data_of(interp: &mut Interp<'_>, this: &Value) -> JsResult<RegExpData> {
605 match this.as_object().and_then(|object| object.regexp()) {
606 Some(data) => Ok(data.clone()),
607 None => Err(interp.type_error("method called on a non-RegExp")),
608 }
609}
610
611/// Every `RegExp.prototype` accessor starts here (§22.2.6.4's preamble).
612///
613/// `RegExp.prototype` is deliberately **not** a `RegExp`: it has no `[[OriginalSource]]`
614/// and no `[[OriginalFlags]]`, and the spec says so explicitly so that the getters answer
615/// the "no pattern" values (`undefined` for a flag, `"(?:)"` for `source`, `""` for
616/// `flags`) instead of throwing. Anything else without the internal slot is a `TypeError`.
617fn is_regexp_prototype(interp: &Interp<'_>, this: &Value) -> bool {
618 let Some(object) = this.as_object() else {
619 return false;
620 };
621 let Some(proto) = interp.realm.regexp_proto.as_ref() else {
622 return false;
623 };
624 object.ptr_eq(proto)
625}
626
627/// One of the boolean flag accessors.
628fn flag_getter(interp: &mut Interp<'_>, this: Value, pick: fn(&Flags) -> bool) -> JsResult<Value> {
629 if is_regexp_prototype(interp, &this) {
630 return Ok(Value::Undefined);
631 }
632 let data = data_of(interp, &this)?;
633 Ok(Value::Bool(pick(&data.regex.flags)))
634}
635
636fn global(interp: &mut Interp<'_>, this: Value, _args: &[Value]) -> JsResult<Value> {
637 flag_getter(interp, this, |flags| flags.global)
638}
639fn ignore_case(interp: &mut Interp<'_>, this: Value, _args: &[Value]) -> JsResult<Value> {
640 flag_getter(interp, this, |flags| flags.ignore_case)
641}
642fn multiline(interp: &mut Interp<'_>, this: Value, _args: &[Value]) -> JsResult<Value> {
643 flag_getter(interp, this, |flags| flags.multiline)
644}
645fn sticky(interp: &mut Interp<'_>, this: Value, _args: &[Value]) -> JsResult<Value> {
646 flag_getter(interp, this, |flags| flags.sticky)
647}
648fn unicode(interp: &mut Interp<'_>, this: Value, _args: &[Value]) -> JsResult<Value> {
649 flag_getter(interp, this, |flags| flags.unicode)
650}
651fn unicode_sets(interp: &mut Interp<'_>, this: Value, _args: &[Value]) -> JsResult<Value> {
652 flag_getter(interp, this, |flags| flags.unicode_sets)
653}
654fn dot_all(interp: &mut Interp<'_>, this: Value, _args: &[Value]) -> JsResult<Value> {
655 flag_getter(interp, this, |flags| flags.dot_all)
656}
657fn has_indices(interp: &mut Interp<'_>, this: Value, _args: &[Value]) -> JsResult<Value> {
658 flag_getter(interp, this, |flags| flags.has_indices)
659}
660
661// -- the Symbol methods ------------------------------------------------------
662//
663// These are what `String.prototype.match` and friends dispatch to. Each one re-reads the
664// pattern's flags through the object's own properties, as the spec does, so a subclass
665// that overrides `lastIndex` keeps working.
666
667/// `String.prototype.match`'s hook — §22.2.7.2.
668///
669/// The global branch collects `ToString(result[0])`, **not** the result objects: `"aa".match(/a/g)`
670/// is `["a","a"]`, an array of strings. It used to push the whole `exec` array, so every
671/// global match came back as a nested array — visible to any `===` comparison against a
672/// string, which is most of `S15.5.4.10_A2_*`.
673fn symbol_match(interp: &mut Interp<'_>, this: Value, args: &[Value]) -> JsResult<Value> {
674 let Some(object) = this.as_object().cloned() else {
675 return Err(interp.type_error("Symbol.match called on a non-object"));
676 };
677 let text = interp.checked_to_wtf8(&arg(args, 0))?;
678 let text_value = interp.string_wtf8(text.clone());
679 // §22.2.7.2 step 3 reads `flags` **before** it decides anything, and reads it once:
680 // `global` and `unicode` are parsed out of that string rather than read as their own
681 // properties. Reading `global`/`unicode` directly made `flags-tostring-error` and
682 // `get-flags-err` unreachable — a regexp whose `flags` getter throws was silently
683 // treated as non-global instead of throwing, and a subclass that overrides `flags`
684 // was ignored entirely.
685 let flags = interp
686 .get_property(&object, "flags")?
687 .unwrap_or(Value::Undefined);
688 let flags = interp.checked_to_string(&flags)?;
689 let is_global = flags.contains('g');
690 let full_unicode = flags.contains('u') || flags.contains('v');
691 if !is_global {
692 return regexp_exec(interp, &Value::Object(object), &text_value);
693 }
694 interp.set_property(&object, "lastIndex", Value::Int(0))?;
695 let units = text.to_units();
696 let mut results = Vec::new();
697 loop {
698 let result = regexp_exec(interp, &Value::Object(object.clone()), &text_value)?;
699 let Value::Object(hit) = result else {
700 // `null` ends the walk; an empty `A` means the whole match failed.
701 break;
702 };
703 let matched = interp.get_property(&hit, "0")?.unwrap_or(Value::Undefined);
704 // `ToString(result[0])`, keeping the code units: a match can *be* half a surrogate
705 // pair (`. ` without `u`), and the lossy `String` path turns that half into U+FFFD —
706 // `"𠮷".match(/./g)` answered two replacement characters instead of the two halves.
707 let matched = interp.checked_to_wtf8(&matched)?;
708 let empty = matched.is_empty();
709 results.push(interp.string_wtf8(matched));
710 if empty {
711 // An empty match leaves `lastIndex` where it was, so it is advanced by one
712 // position — a code point rather than a unit under `u`.
713 let next = interp
714 .get_property(&object, "lastIndex")?
715 .unwrap_or(Value::Int(0));
716 let next = interp.to_js_number(&next)?;
717 let next = advance_string_index(&units, next, full_unicode);
718 interp.set_property(&object, "lastIndex", Value::Float(next))?;
719 }
720 }
721 if results.is_empty() {
722 return Ok(Value::Null);
723 }
724 Ok(Value::Object(interp.new_array(results)))
725}
726
727/// §22.2.7.3 `RegExp.prototype [ @@matchAll ] ( string )`.
728///
729/// Two things here are easy to get wrong and are both tested by test262:
730///
731/// * **`lastIndex` is read once, at creation, and shows up as a property *copy*.** The
732/// species constructor is handed `(R, flags)` and would therefore carry `R`'s
733/// `lastIndex` over, so the value is read here first, coerced with `ToLength`, and set on
734/// the *clone* — `this-lastindex-cached.js` asserts that reassigning `R.lastIndex`
735/// afterwards changes nothing.
736/// * **`Symbol.match` is consulted through `IsRegExp`, not through the internal slot.**
737/// `isregexp-called-once.js` installs a counting getter on `RegExp.prototype[@@match]`,
738/// so the pattern's regexp-ness has to be probed exactly once.
739///
740/// Returning `string.matchAll(re)` for a string pattern works because this method exists:
741/// the string method is specified to build a `RegExp` and then call *this*. The previous
742/// error message ("matchAll needs a global RegExp") pointed the blame at the caller's
743/// regexp, which was never the problem.
744fn symbol_match_all(interp: &mut Interp<'_>, this: Value, args: &[Value]) -> JsResult<Value> {
745 let Some(object) = this.as_object().cloned() else {
746 return Err(interp.type_error("Symbol.matchAll called on a non-object"));
747 };
748 let text = interp.checked_to_wtf8(&arg(args, 0))?;
749 // A missing `%RegExp%` means the realm is half-built; `undefined` here would turn that
750 // into a confusing "not a constructor" instead of the real problem.
751 let default_constructor = match interp.realm.regexp_ctor.clone() {
752 Some(constructor) => Value::Object(constructor),
753 None => return Err(interp.type_error("the realm has no RegExp constructor")),
754 };
755 let constructor = interp.species_constructor(&object, default_constructor.clone())?;
756 let flags = interp
757 .get_property(&object, "flags")?
758 .unwrap_or(Value::Undefined);
759 let flags = interp.checked_to_string(&flags)?;
760 let matcher = interp.construct(
761 constructor,
762 default_constructor,
763 vec![Value::Object(object.clone()), interp.string(flags.clone())],
764 )?;
765 let Some(matcher) = matcher.as_object().cloned() else {
766 return Err(interp.type_error("species constructor did not answer an object"));
767 };
768 // `IsRegExp` is **not** re-read here. `Construct(C, «R, flags»)` above already ran it
769 // (the `RegExp` constructor's step 2) and that is the read `isregexp-called-once` counts;
770 // doing it again here made the `@@match` getter fire twice. For the same reason a plain
771 // object whose getter throws throws from the constructor — `isregexp-this-throws` passes
772 // without a second probe. What is needed locally is only the internal-slot test, to
773 // decide whether `lastIndex` belongs on the clone.
774 let is_regexp = object.regexp().is_some();
775 if is_regexp {
776 // §22.2.7.3 MatchAllIterator steps 2.e–2.g. `ToLength` of a `lastIndex` that is an
777 // object runs its `valueOf`, which is what `this-lastindex-cached.js` relies on.
778 let cached = interp
779 .get_property(&object, "lastIndex")?
780 .unwrap_or(Value::Undefined);
781 let cached = interp.to_js_number(&cached)?;
782 let cached = to_length(cached);
783 interp.set_property(&matcher, "lastIndex", Value::Float(cached))?;
784 }
785 // The two flags are read off the **coerced flag string**, not off the clone. A species
786 // constructor that returns a regexp with a throwing `global` getter therefore never
787 // runs it — `species-regexp-get-global-throws.js` asserts exactly that.
788 let global = flags.contains('g');
789 let full_unicode = flags.contains('u') || flags.contains('v');
790 Ok(new_regexp_string_iterator(
791 interp,
792 matcher,
793 text,
794 global,
795 full_unicode,
796 ))
797}
798
799/// `%RegExpStringIteratorPrototype%`, created on first use.
800///
801/// It is installed lazily rather than at bootstrap because `RegExp` is installed before
802/// `Iterator.prototype` exists in some embedders, and because the prototype needs the
803/// realm's `%Object.prototype%` only.
804fn regexp_string_iterator_proto(interp: &mut Interp<'_>) -> Gc<JsObject> {
805 if let Some(proto) = interp.realm.iterator_protos.get(REGEXP_STRING_ITERATOR_TAG) {
806 return proto.clone();
807 }
808 interp.new_iterator_prototype(REGEXP_STRING_ITERATOR_TAG, regexp_string_iterator_next)
809}
810
811const REGEXP_STRING_ITERATOR_TAG: &str = "RegExp String Iterator";
812
813/// §22.2.9.1 CreateRegExpStringIterator — the object behind `[@@matchAll]`.
814///
815/// The state lives under non-enumerable "_"-prefixed properties, the same shape the array
816/// iterators use. Two of the four are internal slots and two are the flags that decide how
817/// `next` advances, so `Object.keys` on the iterator stays empty either way.
818fn new_regexp_string_iterator(
819 interp: &mut Interp<'_>,
820 matcher: Gc<JsObject>,
821 text: crate::value::Wtf8,
822 global: bool,
823 full_unicode: bool,
824) -> Value {
825 let proto = regexp_string_iterator_proto(interp);
826 let object = interp.new_object(Some(proto));
827 // Non-enumerable, so `Object.keys` on the iterator stays `[]` as the reference's does.
828 // They are ordinary properties rather than true internal slots, which is the same trade
829 // the array iterators make; `next` re-checks `_iterating` is *own*, so an object that
830 // merely inherits from an iterator (`Object.create(iterator)`) is still a `TypeError`.
831 let hidden = |value: Value| Property {
832 value: Some(value),
833 writable: true,
834 enumerable: false,
835 configurable: true,
836 ..Property::default()
837 };
838 object.define("_iterating", hidden(Value::Bool(true)));
839 object.define("_matcher", hidden(Value::Object(matcher)));
840 object.define("_string", hidden(interp.string_wtf8(text)));
841 object.define("_global", hidden(Value::Bool(global)));
842 object.define("_fullUnicode", hidden(Value::Bool(full_unicode)));
843 Value::Object(object)
844}
845
846/// §22.2.9.2.1 `%RegExpStringIteratorPrototype%.next()`.
847///
848/// Step order matters: the *matcher's* `exec` is looked up **each time** rather than once at
849/// creation, so replacing `RegExp.prototype.exec` between two `next` calls is observed.
850fn regexp_string_iterator_next(
851 interp: &mut Interp<'_>,
852 this: Value,
853 _args: &[Value],
854) -> JsResult<Value> {
855 let Some(iterator) = this.as_object().cloned() else {
856 return Err(interp.type_error("next called on a non-object"));
857 };
858 // §22.2.9.2.1 step 3: the slots have to be the object's *own*. A prototype-inherited
859 // `_iterating` would let `Object.create(iterator).next()` walk the original's state,
860 // which is exactly what `next-missing-internal-slots.js` forbids.
861 let iterating = match iterator.own_property("_iterating") {
862 Some(property) => property.value.unwrap_or(Value::Undefined),
863 None => {
864 return Err(
865 interp.type_error("next called on an object that is not a RegExp String Iterator")
866 );
867 }
868 };
869 if !iterating.to_boolean() {
870 return Ok(iterator_result(interp, Value::Undefined, true));
871 }
872 let matcher = interp
873 .get_property(&iterator, "_matcher")?
874 .unwrap_or(Value::Undefined);
875 let text = interp
876 .get_property(&iterator, "_string")?
877 .unwrap_or(Value::Undefined);
878 let global = interp
879 .get_property(&iterator, "_global")?
880 .unwrap_or(Value::Undefined)
881 .to_boolean();
882 let full_unicode = interp
883 .get_property(&iterator, "_fullUnicode")?
884 .unwrap_or(Value::Undefined)
885 .to_boolean();
886 let match_value = regexp_exec(interp, &matcher, &text)?;
887 if matches!(match_value, Value::Null) {
888 iterator.define_data("_iterating", Value::Bool(false));
889 return Ok(iterator_result(interp, Value::Undefined, true));
890 }
891 if !global {
892 iterator.define_data("_iterating", Value::Bool(false));
893 return Ok(iterator_result(interp, match_value, false));
894 }
895 // "Global" means: match again from the advanced `lastIndex`. An empty match would leave
896 // it where it is, so it is pushed forward by one — and the units it moves are code
897 // points under `u`, which is what `u-advance-after-empty.js` checks on an astral pair.
898 let empty = {
899 let Value::Object(ref hit) = match_value else {
900 return Err(interp.type_error("exec did not answer an array"));
901 };
902 let first = interp.get_property(hit, "0")?.unwrap_or(Value::Undefined);
903 interp.to_js_string(&first)?.is_empty()
904 };
905 if empty {
906 let matcher_object = match matcher.as_object() {
907 Some(object) => object.clone(),
908 None => return Err(interp.type_error("exec did not answer an array")),
909 };
910 let index = interp
911 .get_property(&matcher_object, "lastIndex")?
912 .unwrap_or(Value::Int(0));
913 let index = interp.to_js_number(&index)?;
914 let units = text
915 .as_wtf8()
916 .map(|text| text.to_units())
917 .unwrap_or_default();
918 let next = advance_string_index(&units, index, full_unicode);
919 interp.set_property(&matcher_object, "lastIndex", Value::Float(next))?;
920 }
921 Ok(iterator_result(interp, match_value, false))
922}
923
924/// §7.1.20 `ToLength`, as a number rather than a `usize`.
925///
926/// Kept local rather than reusing `array`'s, which clamps to `MAX_SAFE_INTEGER` as an index
927/// type: `lastIndex` is stored back into the regexp, so the exact double has to survive.
928fn to_length(value: f64) -> f64 {
929 if value.is_nan() || value <= 0.0 {
930 return 0.0;
931 }
932 value.trunc().min(9_007_199_254_740_991.0)
933}
934
935/// §22.2.9.2.1 `AdvanceStringIndex(S, index, unicode)`.
936///
937/// The stride is one *unit* unless `fullUnicode`, in which case an index that lands on the
938/// lead half of a surrogate pair skips both halves. `index + 1` is returned unchanged past
939/// the end, so the caller's next `exec` fails and the iteration stops.
940fn advance_string_index(units: &[u16], index: f64, unicode: bool) -> f64 {
941 if !unicode || !index.is_finite() || index < 0.0 {
942 return index + 1.0;
943 }
944 let start = index as usize;
945 let Some(&lead) = units.get(start) else {
946 return index + 1.0;
947 };
948 if !(0xD800..=0xDBFF).contains(&lead) {
949 return index + 1.0;
950 }
951 match units.get(start + 1) {
952 Some(&trail) if (0xDC00..=0xDFFF).contains(&trail) => index + 2.0,
953 _ => index + 1.0,
954 }
955}
956
957/// §7.4.14 `RegExpExec(R, S)` — the *generic* one, which is what every `@@` method uses.
958///
959/// A pattern whose `exec` is callable gets to answer for itself (that is how a subclass or a
960/// duck-typed matcher participates), and only an `undefined` answer falls back to the
961/// builtin. Requiring the result to be an object or `null` is a real check, not a formality:
962/// `exec-return-type-invalid.js` asserts the `TypeError`.
963pub(crate) fn regexp_exec(
964 interp: &mut Interp<'_>,
965 matcher: &Value,
966 text: &Value,
967) -> JsResult<Value> {
968 let exec_fn = match matcher.as_object() {
969 Some(object) => interp.get_property(object, "exec")?,
970 None => None,
971 };
972 if let Some(exec_fn) = exec_fn
973 && matches!(&exec_fn, Value::Object(function) if function.is_callable())
974 {
975 let result = interp.call_value(exec_fn, matcher.clone(), vec![text.clone()])?;
976 return match result {
977 Value::Object(_) | Value::Null => Ok(result),
978 _ => Err(interp.type_error("exec must answer an object or null")),
979 };
980 }
981 let Some(object) = matcher.as_object().cloned() else {
982 return Err(interp.type_error("method called on a non-RegExp"));
983 };
984 let text = interp.checked_to_wtf8(text)?;
985 exec_on(interp, &object, &text)
986}
987
988/// An `{value, done}` iterator result, created with the realm's `%Object.prototype%`.
989fn iterator_result(interp: &mut Interp<'_>, value: Value, done: bool) -> Value {
990 let proto = interp.realm.object_proto.clone();
991 let result = interp.new_object(Some(proto));
992 result.define_data("value", value);
993 result.define_data("done", Value::Bool(done));
994 Value::Object(result)
995}
996
997/// `String.prototype.search`'s hook: the index of the first match, or -1.
998///
999/// §22.2.6.13. Step 5 delegates to `RegExpExec`, not to the compiled matcher — the same
1000/// correction `@@replace` (§4.40) and `@@split` (§4.41) needed, and this was the last member
1001/// of the family still scanning directly. The visible consequence is that a receiver which
1002/// is not a `RegExp` must still work, because `RegExpExec` only insists on an `exec`:
1003///
1004/// ```js
1005/// RegExp.prototype[Symbol.search].call({exec: () => ({index: 2})}, "abc") // 2
1006/// ```
1007///
1008/// It failed 5 of the 23 cases in `RegExp/prototype/Symbol.search`, and the error was
1009/// `method called on a non-RegExp` — blaming the caller for using the hook the spec says to.
1010///
1011/// **`lastIndex` is read, not just written.** The obvious implementation resets it with one
1012/// `Set`; the spec reads it first and only writes when it is not already `0`, which is
1013/// observable through a getter/setter pair, and `lastindex-no-restore` counts both:
1014///
1015/// * `lastIndexReads == 2` — once here, once inside `exec`'s own `[[Get]]`;
1016/// * `lastIndexWrites == 0` when it started at `0`, `== 1` when it did not.
1017///
1018/// Getting this wrong is invisible without an accessor, which is exactly why the test uses
1019/// one. A poisoned getter must also propagate (`get-lastindex-err`).
1020fn symbol_search(interp: &mut Interp<'_>, this: Value, args: &[Value]) -> JsResult<Value> {
1021 let Some(object) = this.as_object().cloned() else {
1022 return Err(interp.type_error("Symbol.search called on a non-object"));
1023 };
1024 let text = arg(args, 0);
1025 // §22.2.6.13 steps 4–8, in order. Every one of them is observable, and
1026 // `lastindex-no-restore` counts the reads and writes through a getter/setter pair:
1027 //
1028 // 4. previousLastIndex = Get(rx, "lastIndex") // read 1
1029 // 5. if previousLastIndex is not 0: Set(rx, 0)
1030 // 6. result = RegExpExec(rx, S) // may read again
1031 // 7. currentLastIndex = Get(rx, "lastIndex") // read 2
1032 // 8. if currentLastIndex is not previousLastIndex: Set(rx, previousLastIndex)
1033 //
1034 // So a `lastIndex` of 0 is *never written*, one of 420 is written twice when `exec`
1035 // leaves it alone — and the restore in step 8 is what makes `search` non-destructive.
1036 // Resetting up front and not restoring (the obvious reading) gets every one of those
1037 // wrong, and looks correct until an accessor is watching.
1038 let previous = interp.get_property(&object, "lastIndex")?;
1039 let previous_is_zero = matches!(previous, Some(Value::Int(0)) | None);
1040 if !previous_is_zero {
1041 interp.set_property(&object, "lastIndex", Value::Int(0))?;
1042 }
1043 let result = regexp_exec(interp, &this, &text)?;
1044 let current = interp.get_property(&object, "lastIndex")?;
1045 let unchanged = match (¤t, &previous) {
1046 (Some(a), Some(b)) => a.same_value(b),
1047 (None, None) => true,
1048 _ => false,
1049 };
1050 if !unchanged {
1051 let restore = previous.clone().unwrap_or(Value::Undefined);
1052 interp.set_property(&object, "lastIndex", restore)?;
1053 }
1054 let Value::Object(array) = result else {
1055 // `null` means "no match"; a broken `exec` already threw inside `regexp_exec`.
1056 return Ok(Value::Int(-1));
1057 };
1058 Ok(interp
1059 .get_property(&array, "index")?
1060 .unwrap_or(Value::Int(-1)))
1061}
1062
1063/// `String.prototype.split`'s hook.
1064///
1065/// §22.2.6.14. This is the last of the `Symbol.*` family to stop scanning with the compiled
1066/// matcher directly, and it matters for the same reason `@@replace` did: a subclass or a
1067/// duck-typed object has to be able to answer for itself.
1068///
1069/// ```js
1070/// var r = /a/; r.exec = () => null; "abc".split(r) // ["abc"], and exec ran
1071/// ```
1072///
1073/// Three details are easy to get wrong and each one has cases behind it:
1074///
1075/// * **`flags` gets a `y` appended** unless it already has one (step 8). The clone is
1076/// sticky so that `exec` anchors at `lastIndex`; without it a pattern without `g` would
1077/// match from anywhere and the bookkeeping below silently produces the wrong pieces.
1078/// * **`limit` is `ToUint32`, not a clamp.** `split(re, -1)` keeps everything because
1079/// `ToUint32(-1)` is 4294967295, while `split(re, 2**32)` is the empty array. The
1080/// previous code treated negatives as zero, which was wrong for exactly those inputs.
1081/// * **the scan resumes at `p`, not at the end of the match.** Only `p` moves; getting past
1082/// a zero-width match has to go through `AdvanceStringIndex`, which is the `e == p` branch.
1083fn symbol_split(interp: &mut Interp<'_>, this: Value, args: &[Value]) -> JsResult<Value> {
1084 let Some(object) = this.as_object().cloned() else {
1085 return Err(interp.type_error("Symbol.split called on a non-object"));
1086 };
1087 // 4. `ToString(string)` comes before anything else is read off the regexp.
1088 let text = interp.checked_to_wtf8(&arg(args, 0))?;
1089 let units = text.to_units();
1090 // 5. `SpeciesConstructor(rx, %RegExp%)`.
1091 let default_constructor = match interp.realm.regexp_ctor.clone() {
1092 Some(constructor) => Value::Object(constructor),
1093 None => return Err(interp.type_error("the realm has no RegExp constructor")),
1094 };
1095 let constructor = interp.species_constructor(&object, default_constructor.clone())?;
1096 // 6-7. `flags` is `ToString(Get(rx, "flags"))` — the property, not the pattern's slots.
1097 let flags = interp
1098 .get_property(&object, "flags")?
1099 .unwrap_or(Value::Undefined);
1100 let flags = interp.checked_to_string(&flags)?;
1101 // 8. `unicodeMatching` is decided from the `flags` *string*, and `y` is appended when
1102 // absent so that `exec` anchors at `lastIndex`.
1103 let unicode_matching = flags.contains('u') || flags.contains('v');
1104 let sticky_flags = if flags.contains('y') {
1105 flags.clone()
1106 } else {
1107 format!("{flags}y")
1108 };
1109 // 9. `Construct(C, «rx, flags»)`. **`newTarget` is `C`, not `%RegExp%`**: passing the
1110 // default here made the clone a plain `RegExp` even when `C` was a subclass, so a
1111 // subclass's `exec` on its prototype was never reached — `@@split` then scanned with the
1112 // builtin matcher and quietly produced the right pieces for the wrong reason. Every
1113 // clone-routing probe (`split:exec-is-taken-from-...`) was blind to it until `exec` was
1114 // observed at the prototype rather than on the receiver.
1115 let splitter = interp.construct(
1116 constructor.clone(),
1117 constructor,
1118 vec![Value::Object(object), interp.string(sticky_flags)],
1119 )?;
1120 // `SpeciesCreate` answering a primitive would be a `TypeError` further down (the clone
1121 // has to carry a `lastIndex`); failing here names the real cause.
1122 let Some(splitter_object) = splitter.as_object().cloned() else {
1123 return Err(interp.type_error("species constructor did not answer an object"));
1124 };
1125 // 11-12. `lim` is `ToUint32(limit)`; a zero limit is the empty array *before* any match.
1126 let limit = match arg(args, 1) {
1127 Value::Undefined => u32::MAX,
1128 other => Value::Float(interp.to_js_number(&other)?).to_uint32(),
1129 };
1130 let mut parts: Vec<Value> = Vec::new();
1131 if limit == 0 {
1132 return Ok(Value::Object(interp.new_array(parts)));
1133 }
1134 let size = units.len();
1135 // 13. An empty subject still asks `exec` once — `"".split(/x/)` is `[""]`, but
1136 // `"".split(/(?:)/)` is `[]` because that match *succeeds*, so the algorithm returns
1137 // the (still empty) array instead of falling through to the tail.
1138 if size == 0 {
1139 let subject = interp.string_wtf8(text.clone());
1140 let result = regexp_exec(interp, &splitter, &subject)?;
1141 if matches!(result, Value::Null) {
1142 parts.push(interp.string_wtf8(text));
1143 }
1144 return Ok(Value::Object(interp.new_array(parts)));
1145 }
1146 let mut last = 0usize;
1147 let mut scan = 0usize;
1148 // 14. `scan` is `q`, the search position; `last` is `p`, the end of the previous match.
1149 while scan < size {
1150 // 14.a. `lastIndex` is written before every `exec`, through the property system so
1151 // that a clone with a setter (or a subclass) observes the write.
1152 interp.set_property(&splitter_object, "lastIndex", Value::Int(scan as i32))?;
1153 let subject = interp.string_wtf8(text.clone());
1154 let result = regexp_exec(interp, &splitter, &subject)?;
1155 let Value::Object(hit) = &result else {
1156 // 14.b. No match here: step the search position and try again.
1157 scan = advance_string_index(&units, scan as f64, unicode_matching) as usize;
1158 continue;
1159 };
1160 // 14.c. `e` is `ToLength(Get(splitter, "lastIndex"))`, clamped to the subject.
1161 let end = interp
1162 .get_property(&splitter_object, "lastIndex")?
1163 .unwrap_or(Value::Undefined);
1164 let end = to_length(interp.to_js_number(&end)?);
1165 let end = if end > size as f64 {
1166 size
1167 } else {
1168 end as usize
1169 };
1170 if end == last {
1171 // 14.c.iii. A zero-width match at `p` cannot split anything; stepping is what
1172 // keeps the loop finite.
1173 scan = advance_string_index(&units, scan as f64, unicode_matching) as usize;
1174 continue;
1175 }
1176 // 14.c.iv-v. Accept the piece before the match, then every capture group as-is (a
1177 // group that did not participate stays `undefined`).
1178 parts.push(interp.string_wtf8(crate::value::Wtf8::from_units(&units[last..scan])));
1179 if parts.len() as u32 == limit {
1180 return Ok(Value::Object(interp.new_array(parts)));
1181 }
1182 last = end;
1183 // 14.c.vi is `LengthOfArrayLike(z)` — the `length` *property*, so a hand-made `exec`
1184 // result is honoured exactly like the builtin array.
1185 let length = interp
1186 .get_property(hit, "length")?
1187 .unwrap_or(Value::Undefined);
1188 let length = to_length(interp.to_js_number(&length)?) as usize;
1189 for i in 1..length {
1190 let capture = interp
1191 .get_property(hit, &i.to_string())?
1192 .unwrap_or(Value::Undefined);
1193 parts.push(capture);
1194 if parts.len() as u32 == limit {
1195 return Ok(Value::Object(interp.new_array(parts)));
1196 }
1197 }
1198 // 14.c.vii. The search resumes at `p`, **not** at the end of the match.
1199 scan = last;
1200 }
1201 // 15. The tail, clamped in case `lastIndex` ran past the end of the subject.
1202 let last = last.min(size);
1203 parts.push(interp.string_wtf8(crate::value::Wtf8::from_units(&units[last..])));
1204 Ok(Value::Object(interp.new_array(parts)))
1205}
1206
1207/// `RegExp.prototype[Symbol.replace]` — §22.2.6.11, the half `String.prototype.replace` and
1208/// `replaceAll` delegate to.
1209///
1210/// **Every match comes from `RegExpExec(R, S)`**, never from the internal matcher. That is
1211/// what lets a subclass or a duck-typed object answer for itself:
1212///
1213/// ```js
1214/// var r = /a/; r.exec = () => null; "abc".replace(r, "X") // "abc", and exec ran once
1215/// ```
1216///
1217/// This function used to scan with the compiled matcher directly, so the observable
1218/// contract was wrong in three ways at once — `exec` was never called, `lastIndex` was
1219/// never written back, and `unicode`/`global` were read off the pattern's flags instead of
1220/// off the properties. Forty of the seventy `Symbol.replace` test262 cases failed on
1221/// exactly those three.
1222///
1223/// The step order is load-bearing and matches the spec literally, because the cases assert
1224/// it: `ToString(string)` (3), `IsCallable`+`ToString` of the replacement (5–7, so a bad
1225/// replacement throws *before* any property of the regexp is touched), `flags` (9),
1226/// `global` (10), and only then `unicode` (11.c) — which is read **only** in the global
1227/// branch, so a non-global regexp with a throwing `unicode` getter does not throw.
1228fn symbol_replace(interp: &mut Interp<'_>, this: Value, args: &[Value]) -> JsResult<Value> {
1229 let Some(object) = this.as_object().cloned() else {
1230 return Err(interp.type_error("Symbol.replace called on a non-object"));
1231 };
1232 let matcher = Value::Object(object.clone());
1233 // 3. `ToString(string)`.
1234 let text = interp.checked_to_wtf8(&arg(args, 0))?;
1235 let units = text.to_units();
1236 // 5–7. A functional replacement is used as-is; anything else is coerced *now*, before the
1237 // regexp's own properties are read.
1238 let replacement = arg(args, 1);
1239 let functional = matches!(&replacement, Value::Object(o) if o.is_callable());
1240 let template = if functional {
1241 None
1242 } else {
1243 Some(interp.checked_to_wtf8(&replacement)?)
1244 };
1245 // 9. `ToString(Get(rx, "flags"))`. Read even when the value is later unused, because the
1246 // getter's side effects (and its throw) are observable.
1247 let flags = interp
1248 .get_property(&object, "flags")?
1249 .unwrap_or(Value::Undefined);
1250 let flags = interp.checked_to_string(&flags)?;
1251 // 10. `global` comes from the property, not `flags`. A regexp whose `global` was
1252 // redefined must follow the property — `coerce-global.js` walks `undefined`, `null`, `0`,
1253 // `""` and `NaN`, all of which are falsy but are not the same as "no `g` flag".
1254 let global = interp
1255 .get_property(&object, "global")?
1256 .unwrap_or(Value::Undefined)
1257 .to_boolean();
1258 // 11.a–11.d. `lastIndex` is zeroed before the loop, and `fullUnicode` is read from
1259 // `unicode` — only on this path. `v` counts as unicode for `AdvanceStringIndex`.
1260 let mut full_unicode = false;
1261 if global {
1262 let unicode = interp
1263 .get_property(&object, "unicode")?
1264 .unwrap_or(Value::Undefined)
1265 .to_boolean();
1266 let unicode_sets = if unicode {
1267 false
1268 } else {
1269 // §22.2.6.11 step 11.c reads `unicodeSets` only when `unicode` is false, and only
1270 // when the pattern has the `v` flag; `flags` already tells us that.
1271 flags.contains('v')
1272 };
1273 full_unicode = unicode || unicode_sets;
1274 interp.set_property(&object, "lastIndex", Value::Int(0))?;
1275 }
1276 // 12–13. Collect the matches.
1277 //
1278 // Each entry is the `RegExpExec` result as a *value* plus the pieces taken out of it, so
1279 // an `exec` that answers a plain object with a hand-made `index` is honoured exactly like
1280 // the builtin's array.
1281 struct Hit {
1282 result: Value,
1283 /// `ToString(result[0])`, in code units.
1284 matched: Vec<u16>,
1285 /// `ToIntegerOrInfinity(result.index)`, clamped into the string.
1286 position: usize,
1287 /// The capture values as `RegExpExec` reported them, still uncoerced.
1288 captures: Vec<Value>,
1289 }
1290 let mut hits: Vec<Hit> = Vec::new();
1291 loop {
1292 let subject = interp.string_wtf8(text.clone());
1293 let result = regexp_exec(interp, &matcher, &subject)?;
1294 let Value::Object(hit) = &result else {
1295 break;
1296 };
1297 let zero = interp.get_property(hit, "0")?.unwrap_or(Value::Undefined);
1298 let matched = interp.checked_to_wtf8(&zero)?.to_units();
1299 let index = interp
1300 .get_property(hit, "index")?
1301 .unwrap_or(Value::Undefined);
1302 let index = interp.to_js_number(&index)?;
1303 // A `lastIndex`/`index` past the end has no characters before it, but the text still
1304 // appends to the end rather than panicking — the spec's `ToLength` clamps it.
1305 let position = to_length(index) as usize;
1306 // §22.2.6.11 step 14.b.i is `LengthOfArrayLike(result)`, which reads the `length`
1307 // **property** — not the internal array length. A hand-made `exec` result is a plain
1308 // object, so `array_length()` answered `None` and every group vanished; a group whose
1309 // `toString` throws then never threw.
1310 let length = interp
1311 .get_property(hit, "length")?
1312 .unwrap_or(Value::Undefined);
1313 let length = to_length(interp.to_js_number(&length)?) as usize;
1314 let mut captures = Vec::with_capacity(length.saturating_sub(1));
1315 for i in 1..length {
1316 captures.push(
1317 interp
1318 .get_property(hit, &i.to_string())?
1319 .unwrap_or(Value::Undefined),
1320 );
1321 }
1322 hits.push(Hit {
1323 result,
1324 matched,
1325 position: position.min(units.len()),
1326 captures,
1327 });
1328 if !global {
1329 break;
1330 }
1331 // `matched` is empty exactly when `result[0]` is the empty string; then `lastIndex`
1332 // has to advance or the loop cannot end.
1333 if !hits.last().is_some_and(|h| h.matched.is_empty()) {
1334 continue;
1335 }
1336 let this_index = interp
1337 .get_property(&object, "lastIndex")?
1338 .unwrap_or(Value::Int(0));
1339 let this_index = interp.to_js_number(&this_index)?;
1340 let next = advance_string_index(&units, to_length(this_index), full_unicode);
1341 interp.set_property(&object, "lastIndex", Value::Float(next))?;
1342 }
1343 if hits.is_empty() {
1344 return Ok(interp.string_wtf8(text));
1345 }
1346 // 14. Assemble.
1347 let mut out: Vec<u16> = Vec::new();
1348 let mut next_source_position = 0usize;
1349 for hit in &hits {
1350 let start = next_source_position.max(hit.position);
1351 if start > units.len() {
1352 break;
1353 }
1354 out.extend_from_slice(&units[next_source_position..start]);
1355 let substituted = substitute_generic(
1356 interp,
1357 &replacement,
1358 template.as_ref(),
1359 &hit.result,
1360 &hit.matched,
1361 &hit.captures,
1362 &units,
1363 start,
1364 )?;
1365 out.extend_from_slice(&substituted);
1366 next_source_position = start + hit.matched.len();
1367 }
1368 if next_source_position < units.len() {
1369 out.extend_from_slice(&units[next_source_position..]);
1370 }
1371 Ok(interp.string_wtf8(crate::value::Wtf8::from_units(&out)))
1372}
1373
1374/// Expand one match of `RegExp.prototype[@@replace]`.
1375///
1376/// Every capture is a **value** out of the `RegExpExec` result, `ToString`-ed here, rather
1377/// than a slice this function takes itself — an `exec` that returns `{ 0: ..., 1: { toString
1378/// throws } }` is observable, and `result-coerce-capture-err.js` asserts the throw.
1379#[allow(clippy::too_many_arguments)]
1380fn substitute_generic(
1381 interp: &mut Interp<'_>,
1382 replacement: &Value,
1383 template: Option<&crate::value::Wtf8>,
1384 result: &Value,
1385 matched: &[u16],
1386 captures: &[Value],
1387 units: &[u16],
1388 position: usize,
1389) -> JsResult<Vec<u16>> {
1390 // 14.c. A callable replacement gets the match, every group, the position and the string.
1391 if let Value::Object(function) = replacement
1392 && function.is_callable()
1393 {
1394 let mut args: Vec<Value> =
1395 vec![interp.string_wtf8(crate::value::Wtf8::from_units(matched))];
1396 args.extend(captures.iter().cloned());
1397 args.push(Value::Int(position as i32));
1398 args.push(interp.string_wtf8(crate::value::Wtf8::from_units(units)));
1399 // 14.c.viii: the **groups** object is the last argument — and only when
1400 // `Get(result, "groups")` is not `undefined`. A pattern with no names has no
1401 // `groups` property at all, so the callback gets 5 arguments rather than 6
1402 // (`Symbol.replace/fn-invoke-args` counts them).
1403 let groups = match result.as_object() {
1404 Some(hit) => interp
1405 .get_property(hit, "groups")?
1406 .unwrap_or(Value::Undefined),
1407 None => Value::Undefined,
1408 };
1409 if !matches!(groups, Value::Undefined) {
1410 args.push(groups);
1411 }
1412 // 14.c.ix: the *result* of the call is `ToString`-ed, keeping any unpaired surrogate
1413 // it produced.
1414 let outcome = interp.call_value(Value::Object(function.clone()), Value::Undefined, args)?;
1415 return Ok(interp.checked_to_wtf8(&outcome)?.to_units());
1416 }
1417 let Some(template) = template else {
1418 // A non-callable replacement was coerced by the caller; reaching here would mean the
1419 // two decisions disagreed.
1420 return Err(interp.type_error("replacement was neither callable nor coerced"));
1421 };
1422 // 14.d.ii: `namedCaptures` is `Get(result, "groups")`, and `undefined` means "no named
1423 // groups at all", which is what makes `$<y>` literal rather than empty.
1424 let named_captures = match result.as_object() {
1425 Some(hit) => interp
1426 .get_property(hit, "groups")?
1427 .unwrap_or(Value::Undefined),
1428 None => Value::Undefined,
1429 };
1430 // §22.1.3.19.1 steps 2–3: `namedCaptures` is `Get(result, "groups")`, and when it is not
1431 // `undefined` it is **`ToObject`-ed right away** — so `groups: null` is a `TypeError`
1432 // before the template is even looked at (`Symbol.replace/result-coerce-groups-err`), and
1433 // `groups: "123"` works through the wrapper (`…/result-coerce-groups` looks up `length`
1434 // on it).
1435 let named_captures = match named_captures {
1436 Value::Undefined => Value::Undefined,
1437 other => Value::Object(interp.object_from(&other)?),
1438 };
1439 let mut named: Vec<(String, Vec<u16>)> = Vec::new();
1440 let has_names = !matches!(named_captures, Value::Undefined);
1441 if let Value::Object(groups) = &named_captures {
1442 // The names are taken from the **template**, not from the groups object's own keys:
1443 // step 2.c.iii is `Get(namedCaptures, groupName)` for whatever `$<…>` says, so a
1444 // name the object inherits resolves too
1445 // (`named-groups/groups-object-subclass` puts `b` on the prototype).
1446 for name in template_group_names(template) {
1447 let value = interp
1448 .get_property(groups, &name)?
1449 .unwrap_or(Value::Undefined);
1450 // An **undefined** capture is the *empty* string, not `"undefined"`. That is the
1451 // opposite rule from `$n`, and both are the reference's.
1452 let units = match value {
1453 Value::Undefined => Vec::new(),
1454 other => interp.checked_to_wtf8(&other)?.to_units(),
1455 };
1456 named.push((name, units));
1457 }
1458 }
1459 let mut owned: Vec<Option<Vec<u16>>> = Vec::with_capacity(captures.len() + 1);
1460 owned.push(Some(matched.to_vec()));
1461 for capture in captures {
1462 owned.push(match capture {
1463 Value::Undefined => None,
1464 other => Some(interp.checked_to_wtf8(other)?.to_units()),
1465 });
1466 }
1467 let mut out: Vec<u16> = Vec::new();
1468 get_substitution(
1469 &mut out,
1470 template,
1471 &Substitution {
1472 input: units,
1473 position,
1474 match_len: matched.len(),
1475 captures: &owned,
1476 names: has_names.then_some(named.as_slice()),
1477 },
1478 );
1479 Ok(out)
1480}
1481
1482/// Build a `RegExp` object for `source`/`flags`, reusing an existing one when the same
1483/// pattern was compiled before.
1484pub fn new_regexp(interp: &mut Interp<'_>, source: &str, flags: &str) -> JsResult<Gc<JsObject>> {
1485 let prototype = default_prototype(interp);
1486 let object = interp.new_object(Some(prototype));
1487 initialise(interp, object, source, flags)
1488}
1489
1490/// The realm's `%RegExp.prototype%`.
1491fn default_prototype(interp: &Interp<'_>) -> Gc<JsObject> {
1492 interp
1493 .realm
1494 .regexp_proto
1495 .clone()
1496 .unwrap_or_else(|| interp.realm.object_proto.clone())
1497}
1498
1499/// `RegExpAlloc(new.target)` — the empty object `new RegExp` fills in.
1500///
1501/// The prototype comes from `new.target` through `OrdinaryCreateFromConstructor`, which is
1502/// what makes `class RE extends RegExp` an instance of `RE`: the derived constructor's
1503/// `super()` runs this same native, and a fixed `%RegExp.prototype%` here produced a plain
1504/// `RegExp`, so a subclass's override of `@@replace` was never reached.
1505fn allocate(interp: &mut Interp<'_>) -> JsResult<Gc<JsObject>> {
1506 let fallback = default_prototype(interp);
1507 interp.new_ctor_instance(fallback)
1508}
1509
1510/// `RegExpInitialize(object, source, flags)`: compile the pattern and install the matcher.
1511fn initialise(
1512 interp: &mut Interp<'_>,
1513 object: Gc<JsObject>,
1514 source: &str,
1515 flags: &str,
1516) -> JsResult<Gc<JsObject>> {
1517 let Some(parsed) = Flags::parse(flags) else {
1518 return Err(invalid_pattern(interp, String::new(), "flags"));
1519 };
1520 let regex = match Regex::compile(source, parsed) {
1521 Ok(regex) => regex,
1522 Err(error) => {
1523 // The reference reports the engine's own message, not a generic one.
1524 return Err(invalid_pattern(interp, error.message, ""));
1525 }
1526 };
1527 object.set_regexp(RegExpData {
1528 regex: std::rc::Rc::new(regex),
1529 source: source.to_string(),
1530 flags: parsed.as_flag_string(),
1531 });
1532 // §22.2.5 step 12: `{[[Writable]]: true, [[Enumerable]]: false, [[Configurable]]: false}`.
1533 // `with_attributes` ties `configurable` to `writable`, so it made `lastIndex` both
1534 // writable *and* configurable — and a configurable property can be deleted, which is
1535 // how `delete regExpProxy.lastIndex` and `getOwnPropertyDescriptor` both caught it.
1536 object.define(
1537 "lastIndex",
1538 Property {
1539 value: Some(Value::Int(0)),
1540 writable: true,
1541 enumerable: false,
1542 configurable: false,
1543 ..Property::default()
1544 },
1545 );
1546 Ok(object)
1547}
1548
1549/// The `SyntaxError` a malformed pattern raises.
1550///
1551/// The two forms the reference uses: a bad flag string reports `invalid regular expression
1552/// flags`, and a bad pattern reports the engine's own message.
1553fn invalid_pattern(interp: &Interp<'_>, message: String, flags: &str) -> crate::interp::Signal {
1554 let text = if flags.is_empty() {
1555 message
1556 } else {
1557 "invalid regular expression flags".to_string()
1558 };
1559 crate::interp::Signal::Throw(interp.make_error("SyntaxError", &text))
1560}
1561
1562/// Whether `value` is a `RegExp` object.
1563pub fn is_regexp(object: &Gc<JsObject>) -> bool {
1564 object.regexp().is_some()
1565}