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(name, 0, getter);
64 prototype.define(
65 name,
66 Property {
67 getter: Some(Value::Object(getter)),
68 enumerable: false,
69 configurable: true,
70 ..Property::default()
71 },
72 );
73 }
74
75 define_method(&constructor, "escape", 1, escape, interp);
77 install_species_accessor(&constructor, interp);
78
79 install_symbol_methods(interp, &prototype, &constructor);
82 interp.realm.regexp_proto = Some(prototype.clone());
83 interp.realm.regexp_ctor = Some(constructor.clone());
84 constructor
85}
86
87fn install_symbol_methods(
88 interp: &mut Interp<'_>,
89 prototype: &Gc<JsObject>,
90 constructor: &Gc<JsObject>,
91) {
92 use crate::interp::WellKnown;
93 for (which, name, func, length) in [
94 (
95 WellKnown::Match,
96 "[Symbol.match]",
97 symbol_match as crate::object::NativeFn,
98 1,
99 ),
100 (WellKnown::Replace, "[Symbol.replace]", symbol_replace, 2),
101 (
102 WellKnown::MatchAll,
103 "[Symbol.matchAll]",
104 symbol_match_all,
105 1,
106 ),
107 (WellKnown::Search, "[Symbol.search]", symbol_search, 1),
108 (WellKnown::Split, "[Symbol.split]", symbol_split, 2),
109 ] {
110 let method = interp.new_native(name, length, func);
111 prototype.define_key(
112 &interp.realm.well_known_key(which),
113 Property::with_attributes(Value::Object(method), true, false),
114 );
115 }
116 let _ = constructor;
117}
118
119fn escape(interp: &mut Interp<'_>, _this: Value, args: &[Value]) -> JsResult<Value> {
135 let arg = arg(args, 0);
136 if !matches!(arg, Value::String(_)) {
139 return Err(interp.type_error("not a string"));
140 }
141 let source = interp.checked_to_wtf8(&arg)?.code_point_values();
142 let mut out: Vec<u32> = Vec::with_capacity(source.len());
143 for (position, cp) in source.iter().enumerate() {
144 let leading = position == 0;
147 encode_for_regexp_escape(*cp, leading, &mut out);
148 }
149 Ok(interp.string_wtf8(points_to_wtf8(&out)))
150}
151
152fn encode_for_regexp_escape(c: u32, leading: bool, out: &mut Vec<u32>) {
155 let backslash = u32::from(b'\\');
156 let ascii_alnum = matches!(c, 0x30..=0x39 | 0x41..=0x5A | 0x61..=0x7A);
159 if leading && ascii_alnum {
160 push_hex_escape(c, out);
161 return;
162 }
163 if matches!(
165 c,
166 0x2E | 0x2A | 0x2B | 0x3F | 0x5E | 0x24 | 0x7C | 0x28 | 0x29 | 0x5B | 0x5D | 0x7B | 0x7D | 0x5C | 0x2F ) {
170 out.push(backslash);
171 out.push(c);
172 return;
173 }
174 if let Some(letter) = match c {
176 0x09 => Some('t'),
177 0x0A => Some('n'),
178 0x0B => Some('v'),
179 0x0C => Some('f'),
180 0x0D => Some('r'),
181 _ => None,
182 } {
183 out.push(backslash);
184 out.push(u32::from(letter as u8));
185 return;
186 }
187 let other_punctuator = matches!(
190 c,
191 0x2C | 0x2D | 0x3D | 0x3C | 0x3E | 0x23 | 0x26 | 0x21 | 0x25 | 0x3A | 0x3B | 0x40 | 0x7E | 0x27 | 0x60 | 0x22 );
194 if other_punctuator || quickjs_regexp::is_space(c) || (0xD800..=0xDFFF).contains(&c) {
195 if c <= 0xFF {
196 push_hex_escape(c, out);
197 } else {
198 out.push(backslash);
202 out.push(u32::from(b'u'));
203 for shift in [12, 8, 4, 0] {
204 out.push(u32::from(hex_digit((c >> shift) & 0xF)));
205 }
206 }
207 return;
208 }
209 out.push(c);
211}
212
213fn push_hex_escape(c: u32, out: &mut Vec<u32>) {
215 out.push(u32::from(b'\\'));
216 out.push(u32::from(b'x'));
217 out.push(u32::from(hex_digit((c >> 4) & 0xF)));
218 out.push(u32::from(hex_digit(c & 0xF)));
219}
220
221fn hex_digit(nibble: u32) -> u8 {
223 match nibble {
224 0..=9 => b'0' + nibble as u8,
225 _ => b'a' + (nibble as u8 - 10),
226 }
227}
228
229fn constructor(interp: &mut Interp<'_>, _this: Value, args: &[Value]) -> JsResult<Value> {
238 let pattern = arg(args, 0);
239 let flags = arg(args, 1);
240 let (source, flags) = if crate::builtins::string::is_regexp(interp, &pattern)? {
241 let Value::Object(object) = &pattern else {
242 return Err(interp.type_error("a regexp is not an object"));
243 };
244 let source = interp
245 .get_property(object, "source")?
246 .unwrap_or(Value::Undefined);
247 let source = interp.to_js_string(&source)?;
248 let flags = if matches!(flags, Value::Undefined) {
249 let flags = interp
250 .get_property(object, "flags")?
251 .unwrap_or(Value::Undefined);
252 interp.to_js_string(&flags)?
253 } else {
254 interp.to_js_string(&flags)?
255 };
256 (source, flags)
257 } else {
258 let source = match &pattern {
263 Value::Undefined => String::new(),
264 other => interp.to_js_string(other)?,
265 };
266 let flags = if matches!(flags, Value::Undefined) {
267 String::new()
268 } else {
269 interp.to_js_string(&flags)?
270 };
271 (source, flags)
272 };
273 let object = allocate(interp)?;
274 Ok(Value::Object(initialise(interp, object, &source, &flags)?))
275}
276
277fn exec(interp: &mut Interp<'_>, this: Value, args: &[Value]) -> JsResult<Value> {
279 let Some(object) = this.as_object() else {
280 return Err(interp.type_error("RegExp.prototype.exec called on a non-object"));
281 };
282 let text = interp.checked_to_wtf8(&arg(args, 0))?;
283 exec_on(interp, object, &text)
284}
285
286pub fn exec_on(
288 interp: &mut Interp<'_>,
289 object: &Gc<JsObject>,
290 text: &crate::value::Wtf8,
291) -> JsResult<Value> {
292 let Some(data) = object.regexp() else {
293 return Err(interp.type_error("method called on a non-RegExp"));
294 };
295 let sticky_or_global = data.regex.flags.global || data.regex.flags.sticky;
296 let start = if sticky_or_global {
297 let index = interp.get_property(object, "lastIndex")?;
298 let index = interp.to_js_number(&index.unwrap_or(Value::Int(0)))?;
299 if !index.is_finite() || index < 0.0 {
300 interp.set_property(object, "lastIndex", Value::Int(0))?;
301 return Ok(Value::Null);
302 }
303 index as usize
304 } else {
305 0
306 };
307 let input = MatchInput::new(&data.regex, text);
308 if start > input.units_len() {
313 if sticky_or_global {
314 interp.set_property(object, "lastIndex", Value::Int(0))?;
315 }
316 return Ok(Value::Null);
317 }
318 let start = input.position(start);
319 let found = data.regex.exec_at(&input.units, start);
320 let Some(found) = found else {
321 if sticky_or_global {
322 interp.set_property(object, "lastIndex", Value::Int(0))?;
323 }
324 return Ok(Value::Null);
325 };
326 if sticky_or_global {
329 let end = input.offset(found.end);
330 interp.set_property(object, "lastIndex", Value::Int(end as i32))?;
331 }
332 let mut elements: Vec<Value> = Vec::with_capacity(found.captures.len());
335 for capture in &found.captures {
336 elements.push(match capture {
337 Some((start, end)) => interp.string_wtf8(input.slice(*start, *end)),
338 None => Value::Undefined,
339 });
340 }
341 let array = interp.new_array(elements);
342 let index = input.offset(found.start);
343 let input_value = interp.string_wtf8(text.clone());
344 interp.set_property(&array, "index", Value::Int(index as i32))?;
345 interp.set_property(&array, "input", input_value.clone())?;
346 let groups = if data.regex.names.is_empty() {
353 Value::Undefined
354 } else {
355 let groups = interp.new_object(None);
356 for (name, index) in &data.regex.names {
357 let value = match found.captures.get(*index).copied().flatten() {
358 Some((start, end)) => interp.string_wtf8(input.slice(start, end)),
359 None => Value::Undefined,
360 };
361 interp.set_property(&groups, name, value)?;
362 }
363 Value::Object(groups)
364 };
365 interp.set_property(&array, "groups", groups)?;
366 if data.regex.flags.has_indices {
367 let mut pairs = Vec::with_capacity(found.captures.len());
368 for capture in &found.captures {
369 pairs.push(match capture {
370 Some((start, end)) => {
371 let (start, end) = (input.offset(*start), input.offset(*end));
372 let pair =
373 interp.new_array(vec![Value::Int(start as i32), Value::Int(end as i32)]);
374 Value::Object(pair)
375 }
376 None => Value::Undefined,
377 });
378 }
379 let indices = interp.new_array(pairs);
380 interp.set_property(&array, "indices", Value::Object(indices))?;
381 }
382 Ok(Value::Object(array))
383}
384
385struct MatchInput {
402 units: Vec<u32>,
404 unit_start: Vec<usize>,
407}
408
409impl MatchInput {
410 fn new(regex: &quickjs_regexp::Regex, text: &crate::value::Wtf8) -> Self {
411 if regex.per_code_unit() {
412 let units: Vec<u32> = text.to_units().into_iter().map(u32::from).collect();
413 let unit_start = (0..=units.len()).collect();
414 Self { units, unit_start }
415 } else {
416 let units = text.code_point_values();
417 let mut unit_start = Vec::with_capacity(units.len() + 1);
418 let mut count = 0;
419 for point in &units {
420 unit_start.push(count);
421 count += if *point > 0xFFFF { 2 } else { 1 };
422 }
423 unit_start.push(count);
424 Self { units, unit_start }
425 }
426 }
427
428 fn units_len(&self) -> usize {
431 self.unit_start[self.unit_start.len() - 1]
432 }
433
434 fn position(&self, offset: usize) -> usize {
439 self.unit_start
440 .partition_point(|start| *start <= offset)
441 .saturating_sub(1)
442 }
443
444 fn offset(&self, position: usize) -> usize {
446 self.unit_start[position.min(self.unit_start.len() - 1)]
447 }
448
449 fn slice(&self, start: usize, end: usize) -> crate::value::Wtf8 {
455 points_to_wtf8(self.units.get(start..end).unwrap_or_default())
456 }
457}
458
459fn points_to_wtf8(points: &[u32]) -> crate::value::Wtf8 {
461 let mut units = Vec::with_capacity(points.len());
462 for point in points {
463 if *point > 0xFFFF {
464 let value = point - 0x10000;
465 units.push(0xD800 + (value >> 10) as u16);
466 units.push(0xDC00 + (value & 0x3FF) as u16);
467 } else {
468 units.push(*point as u16);
469 }
470 }
471 crate::value::Wtf8::from_units(&units)
472}
473
474fn test(interp: &mut Interp<'_>, this: Value, args: &[Value]) -> JsResult<Value> {
476 let result = exec(interp, this, args)?;
477 Ok(Value::Bool(!matches!(result, Value::Null)))
478}
479
480fn to_string(interp: &mut Interp<'_>, this: Value, _args: &[Value]) -> JsResult<Value> {
481 let Some(object) = this.as_object() else {
482 return Err(interp.type_error("RegExp.prototype.toString called on a non-object"));
483 };
484 let Some(data) = object.regexp() else {
485 return Err(interp.type_error("RegExp.prototype.toString called on a non-RegExp"));
486 };
487 let source = if data.source.is_empty() {
488 "(?:)".to_string()
489 } else {
490 data.source.clone()
491 };
492 Ok(interp.string(format!("/{source}/{}", data.flags)))
493}
494
495fn source(interp: &mut Interp<'_>, this: Value, _args: &[Value]) -> JsResult<Value> {
496 let data = data_of(interp, &this)?;
497 let text = if data.source.is_empty() {
499 "(?:)".to_string()
500 } else {
501 data.source.clone()
502 };
503 Ok(interp.string(&text))
504}
505
506fn flags(interp: &mut Interp<'_>, this: Value, _args: &[Value]) -> JsResult<Value> {
517 let Some(object) = this.as_object().cloned() else {
518 return Err(interp.type_error("flags called on a non-object"));
519 };
520 let mut out = String::with_capacity(8);
521 for (name, letter) in [
522 ("hasIndices", 'd'),
523 ("global", 'g'),
524 ("ignoreCase", 'i'),
525 ("multiline", 'm'),
526 ("dotAll", 's'),
527 ("unicode", 'u'),
528 ("unicodeSets", 'v'),
529 ("sticky", 'y'),
530 ] {
531 let value = interp
532 .get_property(&object, name)?
533 .unwrap_or(Value::Undefined);
534 if value.to_boolean() {
535 out.push(letter);
536 }
537 }
538 Ok(interp.string(out))
539}
540
541fn data_of(interp: &mut Interp<'_>, this: &Value) -> JsResult<RegExpData> {
542 match this.as_object().and_then(|object| object.regexp()) {
543 Some(data) => Ok(data.clone()),
544 None => Err(interp.type_error("method called on a non-RegExp")),
545 }
546}
547
548fn flag_getter(interp: &mut Interp<'_>, this: Value, pick: fn(&Flags) -> bool) -> JsResult<Value> {
550 let data = data_of(interp, &this)?;
551 Ok(Value::Bool(pick(&data.regex.flags)))
552}
553
554fn global(interp: &mut Interp<'_>, this: Value, _args: &[Value]) -> JsResult<Value> {
555 flag_getter(interp, this, |flags| flags.global)
556}
557fn ignore_case(interp: &mut Interp<'_>, this: Value, _args: &[Value]) -> JsResult<Value> {
558 flag_getter(interp, this, |flags| flags.ignore_case)
559}
560fn multiline(interp: &mut Interp<'_>, this: Value, _args: &[Value]) -> JsResult<Value> {
561 flag_getter(interp, this, |flags| flags.multiline)
562}
563fn sticky(interp: &mut Interp<'_>, this: Value, _args: &[Value]) -> JsResult<Value> {
564 flag_getter(interp, this, |flags| flags.sticky)
565}
566fn unicode(interp: &mut Interp<'_>, this: Value, _args: &[Value]) -> JsResult<Value> {
567 flag_getter(interp, this, |flags| flags.unicode)
568}
569fn unicode_sets(interp: &mut Interp<'_>, this: Value, _args: &[Value]) -> JsResult<Value> {
570 flag_getter(interp, this, |flags| flags.unicode_sets)
571}
572fn dot_all(interp: &mut Interp<'_>, this: Value, _args: &[Value]) -> JsResult<Value> {
573 flag_getter(interp, this, |flags| flags.dot_all)
574}
575fn has_indices(interp: &mut Interp<'_>, this: Value, _args: &[Value]) -> JsResult<Value> {
576 flag_getter(interp, this, |flags| flags.has_indices)
577}
578
579fn symbol_match(interp: &mut Interp<'_>, this: Value, args: &[Value]) -> JsResult<Value> {
592 let Some(object) = this.as_object().cloned() else {
593 return Err(interp.type_error("Symbol.match called on a non-object"));
594 };
595 let text = interp.checked_to_wtf8(&arg(args, 0))?;
596 let text_value = interp.string_wtf8(text.clone());
597 let flags = interp
604 .get_property(&object, "flags")?
605 .unwrap_or(Value::Undefined);
606 let flags = interp.to_js_string(&flags)?;
607 let is_global = flags.contains('g');
608 let full_unicode = flags.contains('u') || flags.contains('v');
609 if !is_global {
610 return regexp_exec(interp, &Value::Object(object), &text_value);
611 }
612 interp.set_property(&object, "lastIndex", Value::Int(0))?;
613 let units = text.to_units();
614 let mut results = Vec::new();
615 loop {
616 let result = regexp_exec(interp, &Value::Object(object.clone()), &text_value)?;
617 let Value::Object(hit) = result else {
618 break;
620 };
621 let matched = interp.get_property(&hit, "0")?.unwrap_or(Value::Undefined);
622 let matched = interp.checked_to_wtf8(&matched)?;
626 let empty = matched.is_empty();
627 results.push(interp.string_wtf8(matched));
628 if empty {
629 let next = interp
632 .get_property(&object, "lastIndex")?
633 .unwrap_or(Value::Int(0));
634 let next = interp.to_js_number(&next)?;
635 let next = advance_string_index(&units, next, full_unicode);
636 interp.set_property(&object, "lastIndex", Value::Float(next))?;
637 }
638 }
639 if results.is_empty() {
640 return Ok(Value::Null);
641 }
642 Ok(Value::Object(interp.new_array(results)))
643}
644
645fn symbol_match_all(interp: &mut Interp<'_>, this: Value, args: &[Value]) -> JsResult<Value> {
663 let Some(object) = this.as_object().cloned() else {
664 return Err(interp.type_error("Symbol.matchAll called on a non-object"));
665 };
666 let text = interp.checked_to_wtf8(&arg(args, 0))?;
667 let default_constructor = match interp.realm.regexp_ctor.clone() {
670 Some(constructor) => Value::Object(constructor),
671 None => return Err(interp.type_error("the realm has no RegExp constructor")),
672 };
673 let constructor = interp.species_constructor(&object, default_constructor.clone())?;
674 let flags = interp
675 .get_property(&object, "flags")?
676 .unwrap_or(Value::Undefined);
677 let flags = interp.to_js_string(&flags)?;
678 let matcher = interp.construct(
679 constructor,
680 default_constructor,
681 vec![Value::Object(object.clone()), interp.string(flags.clone())],
682 )?;
683 let Some(matcher) = matcher.as_object().cloned() else {
684 return Err(interp.type_error("species constructor did not answer an object"));
685 };
686 let is_regexp = object.regexp().is_some();
693 if is_regexp {
694 let cached = interp
697 .get_property(&object, "lastIndex")?
698 .unwrap_or(Value::Undefined);
699 let cached = interp.to_js_number(&cached)?;
700 let cached = to_length(cached);
701 interp.set_property(&matcher, "lastIndex", Value::Float(cached))?;
702 }
703 let global = flags.contains('g');
707 let full_unicode = flags.contains('u') || flags.contains('v');
708 Ok(new_regexp_string_iterator(
709 interp,
710 matcher,
711 text,
712 global,
713 full_unicode,
714 ))
715}
716
717fn regexp_string_iterator_proto(interp: &mut Interp<'_>) -> Gc<JsObject> {
723 if let Some(proto) = interp.realm.iterator_protos.get(REGEXP_STRING_ITERATOR_TAG) {
724 return proto.clone();
725 }
726 interp.new_iterator_prototype(REGEXP_STRING_ITERATOR_TAG, regexp_string_iterator_next)
727}
728
729const REGEXP_STRING_ITERATOR_TAG: &str = "RegExp String Iterator";
730
731fn new_regexp_string_iterator(
737 interp: &mut Interp<'_>,
738 matcher: Gc<JsObject>,
739 text: crate::value::Wtf8,
740 global: bool,
741 full_unicode: bool,
742) -> Value {
743 let proto = regexp_string_iterator_proto(interp);
744 let object = interp.new_object(Some(proto));
745 let hidden = |value: Value| Property {
750 value: Some(value),
751 writable: true,
752 enumerable: false,
753 configurable: true,
754 ..Property::default()
755 };
756 object.define("_iterating", hidden(Value::Bool(true)));
757 object.define("_matcher", hidden(Value::Object(matcher)));
758 object.define("_string", hidden(interp.string_wtf8(text)));
759 object.define("_global", hidden(Value::Bool(global)));
760 object.define("_fullUnicode", hidden(Value::Bool(full_unicode)));
761 Value::Object(object)
762}
763
764fn regexp_string_iterator_next(
769 interp: &mut Interp<'_>,
770 this: Value,
771 _args: &[Value],
772) -> JsResult<Value> {
773 let Some(iterator) = this.as_object().cloned() else {
774 return Err(interp.type_error("next called on a non-object"));
775 };
776 let iterating = match iterator.own_property("_iterating") {
780 Some(property) => property.value.unwrap_or(Value::Undefined),
781 None => {
782 return Err(
783 interp.type_error("next called on an object that is not a RegExp String Iterator")
784 );
785 }
786 };
787 if !iterating.to_boolean() {
788 return Ok(iterator_result(interp, Value::Undefined, true));
789 }
790 let matcher = interp
791 .get_property(&iterator, "_matcher")?
792 .unwrap_or(Value::Undefined);
793 let text = interp
794 .get_property(&iterator, "_string")?
795 .unwrap_or(Value::Undefined);
796 let global = interp
797 .get_property(&iterator, "_global")?
798 .unwrap_or(Value::Undefined)
799 .to_boolean();
800 let full_unicode = interp
801 .get_property(&iterator, "_fullUnicode")?
802 .unwrap_or(Value::Undefined)
803 .to_boolean();
804 let match_value = regexp_exec(interp, &matcher, &text)?;
805 if matches!(match_value, Value::Null) {
806 iterator.define_data("_iterating", Value::Bool(false));
807 return Ok(iterator_result(interp, Value::Undefined, true));
808 }
809 if !global {
810 iterator.define_data("_iterating", Value::Bool(false));
811 return Ok(iterator_result(interp, match_value, false));
812 }
813 let empty = {
817 let Value::Object(ref hit) = match_value else {
818 return Err(interp.type_error("exec did not answer an array"));
819 };
820 let first = interp.get_property(hit, "0")?.unwrap_or(Value::Undefined);
821 interp.to_js_string(&first)?.is_empty()
822 };
823 if empty {
824 let matcher_object = match matcher.as_object() {
825 Some(object) => object.clone(),
826 None => return Err(interp.type_error("exec did not answer an array")),
827 };
828 let index = interp
829 .get_property(&matcher_object, "lastIndex")?
830 .unwrap_or(Value::Int(0));
831 let index = interp.to_js_number(&index)?;
832 let units = text
833 .as_wtf8()
834 .map(|text| text.to_units())
835 .unwrap_or_default();
836 let next = advance_string_index(&units, index, full_unicode);
837 interp.set_property(&matcher_object, "lastIndex", Value::Float(next))?;
838 }
839 Ok(iterator_result(interp, match_value, false))
840}
841
842fn to_length(value: f64) -> f64 {
847 if value.is_nan() || value <= 0.0 {
848 return 0.0;
849 }
850 value.trunc().min(9_007_199_254_740_991.0)
851}
852
853fn advance_string_index(units: &[u16], index: f64, unicode: bool) -> f64 {
859 if !unicode || !index.is_finite() || index < 0.0 {
860 return index + 1.0;
861 }
862 let start = index as usize;
863 let Some(&lead) = units.get(start) else {
864 return index + 1.0;
865 };
866 if !(0xD800..=0xDBFF).contains(&lead) {
867 return index + 1.0;
868 }
869 match units.get(start + 1) {
870 Some(&trail) if (0xDC00..=0xDFFF).contains(&trail) => index + 2.0,
871 _ => index + 1.0,
872 }
873}
874
875pub(crate) fn regexp_exec(
882 interp: &mut Interp<'_>,
883 matcher: &Value,
884 text: &Value,
885) -> JsResult<Value> {
886 let exec_fn = match matcher.as_object() {
887 Some(object) => interp.get_property(object, "exec")?,
888 None => None,
889 };
890 if let Some(exec_fn) = exec_fn
891 && matches!(&exec_fn, Value::Object(function) if function.is_callable())
892 {
893 let result = interp.call_value(exec_fn, matcher.clone(), vec![text.clone()])?;
894 return match result {
895 Value::Object(_) | Value::Null => Ok(result),
896 _ => Err(interp.type_error("exec must answer an object or null")),
897 };
898 }
899 let Some(object) = matcher.as_object().cloned() else {
900 return Err(interp.type_error("method called on a non-RegExp"));
901 };
902 let text = interp.checked_to_wtf8(text)?;
903 exec_on(interp, &object, &text)
904}
905
906fn iterator_result(interp: &mut Interp<'_>, value: Value, done: bool) -> Value {
908 let proto = interp.realm.object_proto.clone();
909 let result = interp.new_object(Some(proto));
910 result.define_data("value", value);
911 result.define_data("done", Value::Bool(done));
912 Value::Object(result)
913}
914
915fn symbol_search(interp: &mut Interp<'_>, this: Value, args: &[Value]) -> JsResult<Value> {
917 let Some(object) = this.as_object() else {
918 return Err(interp.type_error("Symbol.search called on a non-object"));
919 };
920 let text = interp.checked_to_wtf8(&arg(args, 0))?;
921 interp.set_property(object, "lastIndex", Value::Int(0))?;
924 let result = exec_on(interp, object, &text)?;
925 match result {
926 Value::Null => Ok(Value::Int(-1)),
927 Value::Object(array) => Ok(interp
928 .get_property(&array, "index")?
929 .unwrap_or(Value::Int(-1))),
930 other => Ok(other),
931 }
932}
933
934fn symbol_split(interp: &mut Interp<'_>, this: Value, args: &[Value]) -> JsResult<Value> {
936 let Some(object) = this.as_object() else {
937 return Err(interp.type_error("Symbol.split called on a non-object"));
938 };
939 let text = interp.checked_to_wtf8(&arg(args, 0))?;
940 let limit = match arg(args, 1) {
941 Value::Undefined => u32::MAX,
942 other => {
943 let number = interp.to_js_number(&other)?;
944 if number.is_nan() || number < 0.0 {
945 0
946 } else {
947 number as u32
948 }
949 }
950 };
951 if limit == 0 {
952 return Ok(Value::Object(interp.new_array(Vec::new())));
953 }
954 let data = data_of(interp, &Value::Object(object.clone()))?;
955 let input = MatchInput::new(&data.regex, &text);
956 let mut parts: Vec<Value> = Vec::new();
957 let mut last = 0usize;
958 let mut scan = 0usize;
959 while scan <= input.units.len() {
960 let Some(found) = data.regex.exec_at(&input.units, scan) else {
961 break;
962 };
963 if found.end == found.start {
965 scan = found.start + 1;
966 continue;
967 }
968 parts.push(interp.string_wtf8(input.slice(last, found.start)));
969 if parts.len() as u32 >= limit {
970 return Ok(Value::Object(interp.new_array(parts)));
971 }
972 for group in found.captures.iter().skip(1) {
973 parts.push(match group {
974 Some((start, end)) => interp.string_wtf8(input.slice(*start, *end)),
975 None => Value::Undefined,
976 });
977 if parts.len() as u32 >= limit {
978 return Ok(Value::Object(interp.new_array(parts)));
979 }
980 }
981 last = found.end;
982 scan = found.end;
983 }
984 parts.push(interp.string_wtf8(input.slice(last, input.units.len())));
985 Ok(Value::Object(interp.new_array(parts)))
986}
987
988fn symbol_replace(interp: &mut Interp<'_>, this: Value, args: &[Value]) -> JsResult<Value> {
991 let Some(object) = this.as_object() else {
992 return Err(interp.type_error("Symbol.replace called on a non-object"));
993 };
994 let text = interp.checked_to_wtf8(&arg(args, 0))?;
995 let replacement = arg(args, 1);
996 let is_global = interp
997 .get_property(object, "global")?
998 .unwrap_or(Value::Undefined)
999 .to_boolean();
1000 let data = data_of(interp, &Value::Object(object.clone()))?;
1001 let input = MatchInput::new(&data.regex, &text);
1002 let units = text.to_units();
1004 let mut out: Vec<u16> = Vec::new();
1005 let mut last = 0usize;
1006 let mut scan = 0usize;
1007 let mut replaced = false;
1008 while scan <= input.units.len() {
1009 let Some(found) = data.regex.exec_at(&input.units, scan) else {
1010 break;
1011 };
1012 out.extend_from_slice(&units[input.offset(last)..input.offset(found.start)]);
1013 let substituted = substitute(
1014 interp,
1015 &replacement,
1016 &input,
1017 &units,
1018 &found,
1019 &data.regex.names,
1020 )?;
1021 out.extend_from_slice(&substituted);
1022 last = found.end;
1023 let empty = found.start == found.end;
1024 scan = if empty { found.end + 1 } else { found.end };
1025 replaced = true;
1026 if !is_global {
1027 break;
1028 }
1029 if empty && found.end >= input.units.len() {
1030 break;
1031 }
1032 }
1033 if !replaced {
1034 return Ok(interp.string_wtf8(text.clone()));
1035 }
1036 out.extend_from_slice(&units[input.offset(last)..]);
1037 Ok(interp.string_wtf8(crate::value::Wtf8::from_units(&out)))
1038}
1039
1040#[allow(clippy::too_many_arguments)]
1045fn substitute(
1046 interp: &mut Interp<'_>,
1047 replacement: &Value,
1048 input: &MatchInput,
1049 units: &[u16],
1050 found: &crate::regexp::Match,
1051 names: &[(String, usize)],
1052) -> JsResult<Vec<u16>> {
1053 let start = input.offset(found.start);
1054 let end = input.offset(found.end);
1055 if let Value::Object(function) = replacement
1056 && function.is_callable()
1057 {
1058 let mut args: Vec<Value> = vec![interp.string_wtf8(input.slice(found.start, found.end))];
1059 for group in found.captures.iter().skip(1) {
1060 args.push(match group {
1061 Some((start, end)) => interp.string_wtf8(input.slice(*start, *end)),
1062 None => Value::Undefined,
1063 });
1064 }
1065 args.push(Value::Int(start as i32));
1068 args.push(interp.string_wtf8(crate::value::Wtf8::from_units(units)));
1069 let result = interp.call_value(Value::Object(function.clone()), Value::Undefined, args)?;
1070 return Ok(interp.checked_to_wtf8(&result)?.to_units());
1072 }
1073 let template = interp.checked_to_wtf8(replacement)?;
1074 let captures: Vec<Option<(usize, usize)>> = found
1077 .captures
1078 .iter()
1079 .map(|group| group.map(|(start, end)| (input.offset(start), input.offset(end))))
1080 .collect();
1081 let mut out: Vec<u16> = Vec::new();
1082 get_substitution(
1083 &mut out,
1084 &template,
1085 &Substitution {
1086 input: units,
1087 position: start,
1088 match_len: end - start,
1089 captures: &captures,
1090 names: (!names.is_empty()).then_some(names),
1093 },
1094 );
1095 Ok(out)
1096}
1097
1098pub fn new_regexp(interp: &mut Interp<'_>, source: &str, flags: &str) -> JsResult<Gc<JsObject>> {
1101 let prototype = default_prototype(interp);
1102 let object = interp.new_object(Some(prototype));
1103 initialise(interp, object, source, flags)
1104}
1105
1106fn default_prototype(interp: &Interp<'_>) -> Gc<JsObject> {
1108 interp
1109 .realm
1110 .regexp_proto
1111 .clone()
1112 .unwrap_or_else(|| interp.realm.object_proto.clone())
1113}
1114
1115fn allocate(interp: &mut Interp<'_>) -> JsResult<Gc<JsObject>> {
1122 let fallback = default_prototype(interp);
1123 interp.new_ctor_instance(fallback)
1124}
1125
1126fn initialise(
1128 interp: &mut Interp<'_>,
1129 object: Gc<JsObject>,
1130 source: &str,
1131 flags: &str,
1132) -> JsResult<Gc<JsObject>> {
1133 let Some(parsed) = Flags::parse(flags) else {
1134 return Err(invalid_pattern(interp, String::new(), "flags"));
1135 };
1136 let regex = match Regex::compile(source, parsed) {
1137 Ok(regex) => regex,
1138 Err(error) => {
1139 return Err(invalid_pattern(interp, error.message, ""));
1141 }
1142 };
1143 object.set_regexp(RegExpData {
1144 regex: std::rc::Rc::new(regex),
1145 source: source.to_string(),
1146 flags: parsed.as_flag_string(),
1147 });
1148 object.define(
1149 "lastIndex",
1150 Property::with_attributes(Value::Int(0), true, false),
1151 );
1152 Ok(object)
1153}
1154
1155fn invalid_pattern(interp: &Interp<'_>, message: String, flags: &str) -> crate::interp::Signal {
1160 let text = if flags.is_empty() {
1161 message
1162 } else {
1163 "invalid regular expression flags".to_string()
1164 };
1165 crate::interp::Signal::Throw(interp.make_error("SyntaxError", &text))
1166}
1167
1168pub fn is_regexp(object: &Gc<JsObject>) -> bool {
1170 object.regexp().is_some()
1171}