1use crate::builtins::substitution::{Substitution, get_substitution};
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#[derive(Clone)]
23pub struct RegExpData {
24 pub regex: std::rc::Rc<Regex>,
26 pub source: String,
28 pub flags: String,
30}
31
32pub 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 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 define_method(&constructor, "escape", 1, escape, interp);
80 install_species_accessor(&constructor, interp);
81
82 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
122fn escape(interp: &mut Interp<'_>, _this: Value, args: &[Value]) -> JsResult<Value> {
138 let arg = arg(args, 0);
139 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 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
155fn encode_for_regexp_escape(c: u32, leading: bool, out: &mut Vec<u32>) {
158 let backslash = u32::from(b'\\');
159 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 if matches!(
168 c,
169 0x2E | 0x2A | 0x2B | 0x3F | 0x5E | 0x24 | 0x7C | 0x28 | 0x29 | 0x5B | 0x5D | 0x7B | 0x7D | 0x5C | 0x2F ) {
173 out.push(backslash);
174 out.push(c);
175 return;
176 }
177 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 let other_punctuator = matches!(
193 c,
194 0x2C | 0x2D | 0x3D | 0x3C | 0x3E | 0x23 | 0x26 | 0x21 | 0x25 | 0x3A | 0x3B | 0x40 | 0x7E | 0x27 | 0x60 | 0x22 );
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 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 out.push(c);
214}
215
216fn 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
224fn 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
232fn 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 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
280fn 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
289pub 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 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 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 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 if sticky_or_global {
345 let end = input.offset(found.end);
346 interp.set_property(object, "lastIndex", Value::Int(end as i32))?;
347 }
348 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 interp.set_property(&array, "index", Value::Int(index as i32))?;
361 interp.set_property(&array, "input", input_value.clone())?;
362 let groups = if data.regex.names.is_empty() {
369 Value::Undefined
370 } else {
371 let groups = interp.new_object(None);
372 for (name, index) in &data.regex.names {
373 let value = match found.captures.get(*index).copied().flatten() {
374 Some((start, end)) => interp.string_wtf8(input.slice(start, end)),
375 None => Value::Undefined,
376 };
377 interp.set_property(&groups, name, value)?;
378 }
379 Value::Object(groups)
380 };
381 interp.set_property(&array, "groups", groups)?;
382 if data.regex.flags.has_indices {
383 let mut pairs = Vec::with_capacity(found.captures.len());
384 for capture in &found.captures {
385 pairs.push(match capture {
386 Some((start, end)) => {
387 let (start, end) = (input.offset(*start), input.offset(*end));
388 let pair =
389 interp.new_array(vec![Value::Int(start as i32), Value::Int(end as i32)]);
390 Value::Object(pair)
391 }
392 None => Value::Undefined,
393 });
394 }
395 let indices = interp.new_array(pairs);
396 interp.set_property(&array, "indices", Value::Object(indices))?;
397 }
398 Ok(Value::Object(array))
399}
400
401struct MatchInput {
418 units: Vec<u32>,
420 unit_start: Vec<usize>,
423}
424
425impl MatchInput {
426 fn new(regex: &quickjs_regexp::Regex, text: &crate::value::Wtf8) -> Self {
427 if regex.per_code_unit() {
428 let units: Vec<u32> = text.to_units().into_iter().map(u32::from).collect();
429 let unit_start = (0..=units.len()).collect();
430 Self { units, unit_start }
431 } else {
432 let units = text.code_point_values();
433 let mut unit_start = Vec::with_capacity(units.len() + 1);
434 let mut count = 0;
435 for point in &units {
436 unit_start.push(count);
437 count += if *point > 0xFFFF { 2 } else { 1 };
438 }
439 unit_start.push(count);
440 Self { units, unit_start }
441 }
442 }
443
444 fn units_len(&self) -> usize {
447 self.unit_start[self.unit_start.len() - 1]
448 }
449
450 fn position(&self, offset: usize) -> usize {
455 self.unit_start
456 .partition_point(|start| *start <= offset)
457 .saturating_sub(1)
458 }
459
460 fn offset(&self, position: usize) -> usize {
462 self.unit_start[position.min(self.unit_start.len() - 1)]
463 }
464
465 fn slice(&self, start: usize, end: usize) -> crate::value::Wtf8 {
471 points_to_wtf8(self.units.get(start..end).unwrap_or_default())
472 }
473}
474
475fn points_to_wtf8(points: &[u32]) -> crate::value::Wtf8 {
477 let mut units = Vec::with_capacity(points.len());
478 for point in points {
479 if *point > 0xFFFF {
480 let value = point - 0x10000;
481 units.push(0xD800 + (value >> 10) as u16);
482 units.push(0xDC00 + (value & 0x3FF) as u16);
483 } else {
484 units.push(*point as u16);
485 }
486 }
487 crate::value::Wtf8::from_units(&units)
488}
489
490fn test(interp: &mut Interp<'_>, this: Value, args: &[Value]) -> JsResult<Value> {
492 let result = exec(interp, this, args)?;
493 Ok(Value::Bool(!matches!(result, Value::Null)))
494}
495
496fn to_string(interp: &mut Interp<'_>, this: Value, _args: &[Value]) -> JsResult<Value> {
497 let Some(object) = this.as_object() else {
498 return Err(interp.type_error("RegExp.prototype.toString called on a non-object"));
499 };
500 let Some(data) = object.regexp() else {
501 return Err(interp.type_error("RegExp.prototype.toString called on a non-RegExp"));
502 };
503 let source = if data.source.is_empty() {
504 "(?:)".to_string()
505 } else {
506 data.source.clone()
507 };
508 Ok(interp.string(format!("/{source}/{}", data.flags)))
509}
510
511fn source(interp: &mut Interp<'_>, this: Value, _args: &[Value]) -> JsResult<Value> {
512 if is_regexp_prototype(interp, &this) {
515 return Ok(interp.string("(?:)"));
516 }
517 let data = data_of(interp, &this)?;
518 if data.source.is_empty() {
520 return Ok(interp.string("(?:)"));
521 }
522 let mut text = String::with_capacity(data.source.len());
529 for c in data.source.chars() {
530 match c {
531 '/' => text.push_str("\\/"),
532 '\n' => text.push_str("\\n"),
533 '\r' => text.push_str("\\r"),
534 _ => text.push(c),
535 }
536 }
537 let text = text;
538 Ok(interp.string(&text))
539}
540
541fn flags(interp: &mut Interp<'_>, this: Value, _args: &[Value]) -> JsResult<Value> {
552 let Some(object) = this.as_object().cloned() else {
553 return Err(interp.type_error("flags called on a non-object"));
554 };
555 let mut out = String::with_capacity(8);
556 for (name, letter) in [
557 ("hasIndices", 'd'),
558 ("global", 'g'),
559 ("ignoreCase", 'i'),
560 ("multiline", 'm'),
561 ("dotAll", 's'),
562 ("unicode", 'u'),
563 ("unicodeSets", 'v'),
564 ("sticky", 'y'),
565 ] {
566 let value = interp
567 .get_property(&object, name)?
568 .unwrap_or(Value::Undefined);
569 if value.to_boolean() {
570 out.push(letter);
571 }
572 }
573 Ok(interp.string(out))
574}
575
576fn data_of(interp: &mut Interp<'_>, this: &Value) -> JsResult<RegExpData> {
577 match this.as_object().and_then(|object| object.regexp()) {
578 Some(data) => Ok(data.clone()),
579 None => Err(interp.type_error("method called on a non-RegExp")),
580 }
581}
582
583fn is_regexp_prototype(interp: &Interp<'_>, this: &Value) -> bool {
590 let Some(object) = this.as_object() else {
591 return false;
592 };
593 let Some(proto) = interp.realm.regexp_proto.as_ref() else {
594 return false;
595 };
596 object.ptr_eq(proto)
597}
598
599fn flag_getter(interp: &mut Interp<'_>, this: Value, pick: fn(&Flags) -> bool) -> JsResult<Value> {
601 if is_regexp_prototype(interp, &this) {
602 return Ok(Value::Undefined);
603 }
604 let data = data_of(interp, &this)?;
605 Ok(Value::Bool(pick(&data.regex.flags)))
606}
607
608fn global(interp: &mut Interp<'_>, this: Value, _args: &[Value]) -> JsResult<Value> {
609 flag_getter(interp, this, |flags| flags.global)
610}
611fn ignore_case(interp: &mut Interp<'_>, this: Value, _args: &[Value]) -> JsResult<Value> {
612 flag_getter(interp, this, |flags| flags.ignore_case)
613}
614fn multiline(interp: &mut Interp<'_>, this: Value, _args: &[Value]) -> JsResult<Value> {
615 flag_getter(interp, this, |flags| flags.multiline)
616}
617fn sticky(interp: &mut Interp<'_>, this: Value, _args: &[Value]) -> JsResult<Value> {
618 flag_getter(interp, this, |flags| flags.sticky)
619}
620fn unicode(interp: &mut Interp<'_>, this: Value, _args: &[Value]) -> JsResult<Value> {
621 flag_getter(interp, this, |flags| flags.unicode)
622}
623fn unicode_sets(interp: &mut Interp<'_>, this: Value, _args: &[Value]) -> JsResult<Value> {
624 flag_getter(interp, this, |flags| flags.unicode_sets)
625}
626fn dot_all(interp: &mut Interp<'_>, this: Value, _args: &[Value]) -> JsResult<Value> {
627 flag_getter(interp, this, |flags| flags.dot_all)
628}
629fn has_indices(interp: &mut Interp<'_>, this: Value, _args: &[Value]) -> JsResult<Value> {
630 flag_getter(interp, this, |flags| flags.has_indices)
631}
632
633fn symbol_match(interp: &mut Interp<'_>, this: Value, args: &[Value]) -> JsResult<Value> {
646 let Some(object) = this.as_object().cloned() else {
647 return Err(interp.type_error("Symbol.match called on a non-object"));
648 };
649 let text = interp.checked_to_wtf8(&arg(args, 0))?;
650 let text_value = interp.string_wtf8(text.clone());
651 let flags = interp
658 .get_property(&object, "flags")?
659 .unwrap_or(Value::Undefined);
660 let flags = interp.checked_to_string(&flags)?;
661 let is_global = flags.contains('g');
662 let full_unicode = flags.contains('u') || flags.contains('v');
663 if !is_global {
664 return regexp_exec(interp, &Value::Object(object), &text_value);
665 }
666 interp.set_property(&object, "lastIndex", Value::Int(0))?;
667 let units = text.to_units();
668 let mut results = Vec::new();
669 loop {
670 let result = regexp_exec(interp, &Value::Object(object.clone()), &text_value)?;
671 let Value::Object(hit) = result else {
672 break;
674 };
675 let matched = interp.get_property(&hit, "0")?.unwrap_or(Value::Undefined);
676 let matched = interp.checked_to_wtf8(&matched)?;
680 let empty = matched.is_empty();
681 results.push(interp.string_wtf8(matched));
682 if empty {
683 let next = interp
686 .get_property(&object, "lastIndex")?
687 .unwrap_or(Value::Int(0));
688 let next = interp.to_js_number(&next)?;
689 let next = advance_string_index(&units, next, full_unicode);
690 interp.set_property(&object, "lastIndex", Value::Float(next))?;
691 }
692 }
693 if results.is_empty() {
694 return Ok(Value::Null);
695 }
696 Ok(Value::Object(interp.new_array(results)))
697}
698
699fn symbol_match_all(interp: &mut Interp<'_>, this: Value, args: &[Value]) -> JsResult<Value> {
717 let Some(object) = this.as_object().cloned() else {
718 return Err(interp.type_error("Symbol.matchAll called on a non-object"));
719 };
720 let text = interp.checked_to_wtf8(&arg(args, 0))?;
721 let default_constructor = match interp.realm.regexp_ctor.clone() {
724 Some(constructor) => Value::Object(constructor),
725 None => return Err(interp.type_error("the realm has no RegExp constructor")),
726 };
727 let constructor = interp.species_constructor(&object, default_constructor.clone())?;
728 let flags = interp
729 .get_property(&object, "flags")?
730 .unwrap_or(Value::Undefined);
731 let flags = interp.checked_to_string(&flags)?;
732 let matcher = interp.construct(
733 constructor,
734 default_constructor,
735 vec![Value::Object(object.clone()), interp.string(flags.clone())],
736 )?;
737 let Some(matcher) = matcher.as_object().cloned() else {
738 return Err(interp.type_error("species constructor did not answer an object"));
739 };
740 let is_regexp = object.regexp().is_some();
747 if is_regexp {
748 let cached = interp
751 .get_property(&object, "lastIndex")?
752 .unwrap_or(Value::Undefined);
753 let cached = interp.to_js_number(&cached)?;
754 let cached = to_length(cached);
755 interp.set_property(&matcher, "lastIndex", Value::Float(cached))?;
756 }
757 let global = flags.contains('g');
761 let full_unicode = flags.contains('u') || flags.contains('v');
762 Ok(new_regexp_string_iterator(
763 interp,
764 matcher,
765 text,
766 global,
767 full_unicode,
768 ))
769}
770
771fn regexp_string_iterator_proto(interp: &mut Interp<'_>) -> Gc<JsObject> {
777 if let Some(proto) = interp.realm.iterator_protos.get(REGEXP_STRING_ITERATOR_TAG) {
778 return proto.clone();
779 }
780 interp.new_iterator_prototype(REGEXP_STRING_ITERATOR_TAG, regexp_string_iterator_next)
781}
782
783const REGEXP_STRING_ITERATOR_TAG: &str = "RegExp String Iterator";
784
785fn new_regexp_string_iterator(
791 interp: &mut Interp<'_>,
792 matcher: Gc<JsObject>,
793 text: crate::value::Wtf8,
794 global: bool,
795 full_unicode: bool,
796) -> Value {
797 let proto = regexp_string_iterator_proto(interp);
798 let object = interp.new_object(Some(proto));
799 let hidden = |value: Value| Property {
804 value: Some(value),
805 writable: true,
806 enumerable: false,
807 configurable: true,
808 ..Property::default()
809 };
810 object.define("_iterating", hidden(Value::Bool(true)));
811 object.define("_matcher", hidden(Value::Object(matcher)));
812 object.define("_string", hidden(interp.string_wtf8(text)));
813 object.define("_global", hidden(Value::Bool(global)));
814 object.define("_fullUnicode", hidden(Value::Bool(full_unicode)));
815 Value::Object(object)
816}
817
818fn regexp_string_iterator_next(
823 interp: &mut Interp<'_>,
824 this: Value,
825 _args: &[Value],
826) -> JsResult<Value> {
827 let Some(iterator) = this.as_object().cloned() else {
828 return Err(interp.type_error("next called on a non-object"));
829 };
830 let iterating = match iterator.own_property("_iterating") {
834 Some(property) => property.value.unwrap_or(Value::Undefined),
835 None => {
836 return Err(
837 interp.type_error("next called on an object that is not a RegExp String Iterator")
838 );
839 }
840 };
841 if !iterating.to_boolean() {
842 return Ok(iterator_result(interp, Value::Undefined, true));
843 }
844 let matcher = interp
845 .get_property(&iterator, "_matcher")?
846 .unwrap_or(Value::Undefined);
847 let text = interp
848 .get_property(&iterator, "_string")?
849 .unwrap_or(Value::Undefined);
850 let global = interp
851 .get_property(&iterator, "_global")?
852 .unwrap_or(Value::Undefined)
853 .to_boolean();
854 let full_unicode = interp
855 .get_property(&iterator, "_fullUnicode")?
856 .unwrap_or(Value::Undefined)
857 .to_boolean();
858 let match_value = regexp_exec(interp, &matcher, &text)?;
859 if matches!(match_value, Value::Null) {
860 iterator.define_data("_iterating", Value::Bool(false));
861 return Ok(iterator_result(interp, Value::Undefined, true));
862 }
863 if !global {
864 iterator.define_data("_iterating", Value::Bool(false));
865 return Ok(iterator_result(interp, match_value, false));
866 }
867 let empty = {
871 let Value::Object(ref hit) = match_value else {
872 return Err(interp.type_error("exec did not answer an array"));
873 };
874 let first = interp.get_property(hit, "0")?.unwrap_or(Value::Undefined);
875 interp.to_js_string(&first)?.is_empty()
876 };
877 if empty {
878 let matcher_object = match matcher.as_object() {
879 Some(object) => object.clone(),
880 None => return Err(interp.type_error("exec did not answer an array")),
881 };
882 let index = interp
883 .get_property(&matcher_object, "lastIndex")?
884 .unwrap_or(Value::Int(0));
885 let index = interp.to_js_number(&index)?;
886 let units = text
887 .as_wtf8()
888 .map(|text| text.to_units())
889 .unwrap_or_default();
890 let next = advance_string_index(&units, index, full_unicode);
891 interp.set_property(&matcher_object, "lastIndex", Value::Float(next))?;
892 }
893 Ok(iterator_result(interp, match_value, false))
894}
895
896fn to_length(value: f64) -> f64 {
901 if value.is_nan() || value <= 0.0 {
902 return 0.0;
903 }
904 value.trunc().min(9_007_199_254_740_991.0)
905}
906
907fn advance_string_index(units: &[u16], index: f64, unicode: bool) -> f64 {
913 if !unicode || !index.is_finite() || index < 0.0 {
914 return index + 1.0;
915 }
916 let start = index as usize;
917 let Some(&lead) = units.get(start) else {
918 return index + 1.0;
919 };
920 if !(0xD800..=0xDBFF).contains(&lead) {
921 return index + 1.0;
922 }
923 match units.get(start + 1) {
924 Some(&trail) if (0xDC00..=0xDFFF).contains(&trail) => index + 2.0,
925 _ => index + 1.0,
926 }
927}
928
929pub(crate) fn regexp_exec(
936 interp: &mut Interp<'_>,
937 matcher: &Value,
938 text: &Value,
939) -> JsResult<Value> {
940 let exec_fn = match matcher.as_object() {
941 Some(object) => interp.get_property(object, "exec")?,
942 None => None,
943 };
944 if let Some(exec_fn) = exec_fn
945 && matches!(&exec_fn, Value::Object(function) if function.is_callable())
946 {
947 let result = interp.call_value(exec_fn, matcher.clone(), vec![text.clone()])?;
948 return match result {
949 Value::Object(_) | Value::Null => Ok(result),
950 _ => Err(interp.type_error("exec must answer an object or null")),
951 };
952 }
953 let Some(object) = matcher.as_object().cloned() else {
954 return Err(interp.type_error("method called on a non-RegExp"));
955 };
956 let text = interp.checked_to_wtf8(text)?;
957 exec_on(interp, &object, &text)
958}
959
960fn iterator_result(interp: &mut Interp<'_>, value: Value, done: bool) -> Value {
962 let proto = interp.realm.object_proto.clone();
963 let result = interp.new_object(Some(proto));
964 result.define_data("value", value);
965 result.define_data("done", Value::Bool(done));
966 Value::Object(result)
967}
968
969fn symbol_search(interp: &mut Interp<'_>, this: Value, args: &[Value]) -> JsResult<Value> {
993 let Some(object) = this.as_object().cloned() else {
994 return Err(interp.type_error("Symbol.search called on a non-object"));
995 };
996 let text = arg(args, 0);
997 let previous = interp.get_property(&object, "lastIndex")?;
1011 let previous_is_zero = matches!(previous, Some(Value::Int(0)) | None);
1012 if !previous_is_zero {
1013 interp.set_property(&object, "lastIndex", Value::Int(0))?;
1014 }
1015 let result = regexp_exec(interp, &this, &text)?;
1016 let current = interp.get_property(&object, "lastIndex")?;
1017 let unchanged = match (¤t, &previous) {
1018 (Some(a), Some(b)) => a.same_value(b),
1019 (None, None) => true,
1020 _ => false,
1021 };
1022 if !unchanged {
1023 let restore = previous.clone().unwrap_or(Value::Undefined);
1024 interp.set_property(&object, "lastIndex", restore)?;
1025 }
1026 let Value::Object(array) = result else {
1027 return Ok(Value::Int(-1));
1029 };
1030 Ok(interp
1031 .get_property(&array, "index")?
1032 .unwrap_or(Value::Int(-1)))
1033}
1034
1035fn symbol_split(interp: &mut Interp<'_>, this: Value, args: &[Value]) -> JsResult<Value> {
1056 let Some(object) = this.as_object().cloned() else {
1057 return Err(interp.type_error("Symbol.split called on a non-object"));
1058 };
1059 let text = interp.checked_to_wtf8(&arg(args, 0))?;
1061 let units = text.to_units();
1062 let default_constructor = match interp.realm.regexp_ctor.clone() {
1064 Some(constructor) => Value::Object(constructor),
1065 None => return Err(interp.type_error("the realm has no RegExp constructor")),
1066 };
1067 let constructor = interp.species_constructor(&object, default_constructor.clone())?;
1068 let flags = interp
1070 .get_property(&object, "flags")?
1071 .unwrap_or(Value::Undefined);
1072 let flags = interp.checked_to_string(&flags)?;
1073 let unicode_matching = flags.contains('u') || flags.contains('v');
1076 let sticky_flags = if flags.contains('y') {
1077 flags.clone()
1078 } else {
1079 format!("{flags}y")
1080 };
1081 let splitter = interp.construct(
1088 constructor.clone(),
1089 constructor,
1090 vec![Value::Object(object), interp.string(sticky_flags)],
1091 )?;
1092 let Some(splitter_object) = splitter.as_object().cloned() else {
1095 return Err(interp.type_error("species constructor did not answer an object"));
1096 };
1097 let limit = match arg(args, 1) {
1099 Value::Undefined => u32::MAX,
1100 other => Value::Float(interp.to_js_number(&other)?).to_uint32(),
1101 };
1102 let mut parts: Vec<Value> = Vec::new();
1103 if limit == 0 {
1104 return Ok(Value::Object(interp.new_array(parts)));
1105 }
1106 let size = units.len();
1107 if size == 0 {
1111 let subject = interp.string_wtf8(text.clone());
1112 let result = regexp_exec(interp, &splitter, &subject)?;
1113 if matches!(result, Value::Null) {
1114 parts.push(interp.string_wtf8(text));
1115 }
1116 return Ok(Value::Object(interp.new_array(parts)));
1117 }
1118 let mut last = 0usize;
1119 let mut scan = 0usize;
1120 while scan < size {
1122 interp.set_property(&splitter_object, "lastIndex", Value::Int(scan as i32))?;
1125 let subject = interp.string_wtf8(text.clone());
1126 let result = regexp_exec(interp, &splitter, &subject)?;
1127 let Value::Object(hit) = &result else {
1128 scan = advance_string_index(&units, scan as f64, unicode_matching) as usize;
1130 continue;
1131 };
1132 let end = interp
1134 .get_property(&splitter_object, "lastIndex")?
1135 .unwrap_or(Value::Undefined);
1136 let end = to_length(interp.to_js_number(&end)?);
1137 let end = if end > size as f64 {
1138 size
1139 } else {
1140 end as usize
1141 };
1142 if end == last {
1143 scan = advance_string_index(&units, scan as f64, unicode_matching) as usize;
1146 continue;
1147 }
1148 parts.push(interp.string_wtf8(crate::value::Wtf8::from_units(&units[last..scan])));
1151 if parts.len() as u32 == limit {
1152 return Ok(Value::Object(interp.new_array(parts)));
1153 }
1154 last = end;
1155 let length = interp
1158 .get_property(hit, "length")?
1159 .unwrap_or(Value::Undefined);
1160 let length = to_length(interp.to_js_number(&length)?) as usize;
1161 for i in 1..length {
1162 let capture = interp
1163 .get_property(hit, &i.to_string())?
1164 .unwrap_or(Value::Undefined);
1165 parts.push(capture);
1166 if parts.len() as u32 == limit {
1167 return Ok(Value::Object(interp.new_array(parts)));
1168 }
1169 }
1170 scan = last;
1172 }
1173 let last = last.min(size);
1175 parts.push(interp.string_wtf8(crate::value::Wtf8::from_units(&units[last..])));
1176 Ok(Value::Object(interp.new_array(parts)))
1177}
1178
1179fn symbol_replace(interp: &mut Interp<'_>, this: Value, args: &[Value]) -> JsResult<Value> {
1201 let Some(object) = this.as_object().cloned() else {
1202 return Err(interp.type_error("Symbol.replace called on a non-object"));
1203 };
1204 let matcher = Value::Object(object.clone());
1205 let text = interp.checked_to_wtf8(&arg(args, 0))?;
1207 let units = text.to_units();
1208 let replacement = arg(args, 1);
1211 let functional = matches!(&replacement, Value::Object(o) if o.is_callable());
1212 let template = if functional {
1213 None
1214 } else {
1215 Some(interp.checked_to_wtf8(&replacement)?)
1216 };
1217 let flags = interp
1220 .get_property(&object, "flags")?
1221 .unwrap_or(Value::Undefined);
1222 let flags = interp.checked_to_string(&flags)?;
1223 let global = interp
1227 .get_property(&object, "global")?
1228 .unwrap_or(Value::Undefined)
1229 .to_boolean();
1230 let mut full_unicode = false;
1233 if global {
1234 let unicode = interp
1235 .get_property(&object, "unicode")?
1236 .unwrap_or(Value::Undefined)
1237 .to_boolean();
1238 let unicode_sets = if unicode {
1239 false
1240 } else {
1241 flags.contains('v')
1244 };
1245 full_unicode = unicode || unicode_sets;
1246 interp.set_property(&object, "lastIndex", Value::Int(0))?;
1247 }
1248 struct Hit {
1254 result: Value,
1255 matched: Vec<u16>,
1257 position: usize,
1259 captures: Vec<Value>,
1261 }
1262 let mut hits: Vec<Hit> = Vec::new();
1263 loop {
1264 let subject = interp.string_wtf8(text.clone());
1265 let result = regexp_exec(interp, &matcher, &subject)?;
1266 let Value::Object(hit) = &result else {
1267 break;
1268 };
1269 let zero = interp.get_property(hit, "0")?.unwrap_or(Value::Undefined);
1270 let matched = interp.checked_to_wtf8(&zero)?.to_units();
1271 let index = interp
1272 .get_property(hit, "index")?
1273 .unwrap_or(Value::Undefined);
1274 let index = interp.to_js_number(&index)?;
1275 let position = to_length(index) as usize;
1278 let length = interp
1283 .get_property(hit, "length")?
1284 .unwrap_or(Value::Undefined);
1285 let length = to_length(interp.to_js_number(&length)?) as usize;
1286 let mut captures = Vec::with_capacity(length.saturating_sub(1));
1287 for i in 1..length {
1288 captures.push(
1289 interp
1290 .get_property(hit, &i.to_string())?
1291 .unwrap_or(Value::Undefined),
1292 );
1293 }
1294 hits.push(Hit {
1295 result,
1296 matched,
1297 position: position.min(units.len()),
1298 captures,
1299 });
1300 if !global {
1301 break;
1302 }
1303 if !hits.last().is_some_and(|h| h.matched.is_empty()) {
1306 continue;
1307 }
1308 let this_index = interp
1309 .get_property(&object, "lastIndex")?
1310 .unwrap_or(Value::Int(0));
1311 let this_index = interp.to_js_number(&this_index)?;
1312 let next = advance_string_index(&units, to_length(this_index), full_unicode);
1313 interp.set_property(&object, "lastIndex", Value::Float(next))?;
1314 }
1315 if hits.is_empty() {
1316 return Ok(interp.string_wtf8(text));
1317 }
1318 let mut out: Vec<u16> = Vec::new();
1320 let mut next_source_position = 0usize;
1321 for hit in &hits {
1322 let start = next_source_position.max(hit.position);
1323 if start > units.len() {
1324 break;
1325 }
1326 out.extend_from_slice(&units[next_source_position..start]);
1327 let substituted = substitute_generic(
1328 interp,
1329 &replacement,
1330 template.as_ref(),
1331 &hit.result,
1332 &hit.matched,
1333 &hit.captures,
1334 &units,
1335 start,
1336 )?;
1337 out.extend_from_slice(&substituted);
1338 next_source_position = start + hit.matched.len();
1339 }
1340 if next_source_position < units.len() {
1341 out.extend_from_slice(&units[next_source_position..]);
1342 }
1343 Ok(interp.string_wtf8(crate::value::Wtf8::from_units(&out)))
1344}
1345
1346#[allow(clippy::too_many_arguments)]
1352fn substitute_generic(
1353 interp: &mut Interp<'_>,
1354 replacement: &Value,
1355 template: Option<&crate::value::Wtf8>,
1356 result: &Value,
1357 matched: &[u16],
1358 captures: &[Value],
1359 units: &[u16],
1360 position: usize,
1361) -> JsResult<Vec<u16>> {
1362 if let Value::Object(function) = replacement
1364 && function.is_callable()
1365 {
1366 let mut args: Vec<Value> =
1367 vec![interp.string_wtf8(crate::value::Wtf8::from_units(matched))];
1368 args.extend(captures.iter().cloned());
1369 args.push(Value::Int(position as i32));
1370 args.push(interp.string_wtf8(crate::value::Wtf8::from_units(units)));
1371 let outcome = interp.call_value(Value::Object(function.clone()), Value::Undefined, args)?;
1374 return Ok(interp.checked_to_wtf8(&outcome)?.to_units());
1375 }
1376 let Some(template) = template else {
1377 return Err(interp.type_error("replacement was neither callable nor coerced"));
1380 };
1381 let named_captures = match result.as_object() {
1384 Some(hit) => interp
1385 .get_property(hit, "groups")?
1386 .unwrap_or(Value::Undefined),
1387 None => Value::Undefined,
1388 };
1389 let mut named: Vec<(String, Vec<u16>)> = Vec::new();
1390 let mut has_names = false;
1391 if let Value::Object(groups) = &named_captures {
1392 has_names = true;
1393 for key in groups.own_property_keys() {
1395 let Some(name) = key.as_str().map(str::to_string) else {
1396 continue;
1397 };
1398 let value = interp
1399 .get_property(groups, &name)?
1400 .unwrap_or(Value::Undefined);
1401 let units = match value {
1406 Value::Undefined => Vec::new(),
1407 other => interp.checked_to_wtf8(&other)?.to_units(),
1408 };
1409 named.push((name, units));
1410 }
1411 }
1412 let mut owned: Vec<Option<Vec<u16>>> = Vec::with_capacity(captures.len() + 1);
1413 owned.push(Some(matched.to_vec()));
1414 for capture in captures {
1415 owned.push(match capture {
1416 Value::Undefined => None,
1417 other => Some(interp.checked_to_wtf8(other)?.to_units()),
1418 });
1419 }
1420 let mut out: Vec<u16> = Vec::new();
1421 get_substitution(
1422 &mut out,
1423 template,
1424 &Substitution {
1425 input: units,
1426 position,
1427 match_len: matched.len(),
1428 captures: &owned,
1429 names: has_names.then_some(named.as_slice()),
1430 },
1431 );
1432 Ok(out)
1433}
1434
1435pub fn new_regexp(interp: &mut Interp<'_>, source: &str, flags: &str) -> JsResult<Gc<JsObject>> {
1438 let prototype = default_prototype(interp);
1439 let object = interp.new_object(Some(prototype));
1440 initialise(interp, object, source, flags)
1441}
1442
1443fn default_prototype(interp: &Interp<'_>) -> Gc<JsObject> {
1445 interp
1446 .realm
1447 .regexp_proto
1448 .clone()
1449 .unwrap_or_else(|| interp.realm.object_proto.clone())
1450}
1451
1452fn allocate(interp: &mut Interp<'_>) -> JsResult<Gc<JsObject>> {
1459 let fallback = default_prototype(interp);
1460 interp.new_ctor_instance(fallback)
1461}
1462
1463fn initialise(
1465 interp: &mut Interp<'_>,
1466 object: Gc<JsObject>,
1467 source: &str,
1468 flags: &str,
1469) -> JsResult<Gc<JsObject>> {
1470 let Some(parsed) = Flags::parse(flags) else {
1471 return Err(invalid_pattern(interp, String::new(), "flags"));
1472 };
1473 let regex = match Regex::compile(source, parsed) {
1474 Ok(regex) => regex,
1475 Err(error) => {
1476 return Err(invalid_pattern(interp, error.message, ""));
1478 }
1479 };
1480 object.set_regexp(RegExpData {
1481 regex: std::rc::Rc::new(regex),
1482 source: source.to_string(),
1483 flags: parsed.as_flag_string(),
1484 });
1485 object.define(
1486 "lastIndex",
1487 Property::with_attributes(Value::Int(0), true, false),
1488 );
1489 Ok(object)
1490}
1491
1492fn invalid_pattern(interp: &Interp<'_>, message: String, flags: &str) -> crate::interp::Signal {
1497 let text = if flags.is_empty() {
1498 message
1499 } else {
1500 "invalid regular expression flags".to_string()
1501 };
1502 crate::interp::Signal::Throw(interp.make_error("SyntaxError", &text))
1503}
1504
1505pub fn is_regexp(object: &Gc<JsObject>) -> bool {
1507 object.regexp().is_some()
1508}