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 ("dotAll", dot_all),
60 ("hasIndices", has_indices),
61 ] {
62 let getter = interp.new_native(name, 0, getter);
63 prototype.define(
64 name,
65 Property {
66 getter: Some(Value::Object(getter)),
67 enumerable: false,
68 configurable: true,
69 ..Property::default()
70 },
71 );
72 }
73
74 define_method(&constructor, "escape", 1, escape, interp);
76 install_species_accessor(&constructor, interp);
77
78 install_symbol_methods(interp, &prototype, &constructor);
81 interp.realm.regexp_proto = Some(prototype.clone());
82 interp.realm.regexp_ctor = Some(constructor.clone());
83 constructor
84}
85
86fn install_symbol_methods(
87 interp: &mut Interp<'_>,
88 prototype: &Gc<JsObject>,
89 constructor: &Gc<JsObject>,
90) {
91 use crate::interp::WellKnown;
92 for (which, name, func, length) in [
93 (
94 WellKnown::Match,
95 "[Symbol.match]",
96 symbol_match as crate::object::NativeFn,
97 1,
98 ),
99 (WellKnown::Replace, "[Symbol.replace]", symbol_replace, 2),
100 (WellKnown::Search, "[Symbol.search]", symbol_search, 1),
101 (WellKnown::Split, "[Symbol.split]", symbol_split, 2),
102 ] {
103 let method = interp.new_native(name, length, func);
104 prototype.define_key(
105 &interp.realm.well_known_key(which),
106 Property::with_attributes(Value::Object(method), true, false),
107 );
108 }
109 let _ = constructor;
110}
111
112fn escape(interp: &mut Interp<'_>, _this: Value, args: &[Value]) -> JsResult<Value> {
128 let arg = arg(args, 0);
129 if !matches!(arg, Value::String(_)) {
132 return Err(interp.type_error("not a string"));
133 }
134 let source = interp.checked_to_wtf8(&arg)?.code_point_values();
135 let mut out: Vec<u32> = Vec::with_capacity(source.len());
136 for (position, cp) in source.iter().enumerate() {
137 let leading = position == 0;
140 encode_for_regexp_escape(*cp, leading, &mut out);
141 }
142 Ok(interp.string_wtf8(points_to_wtf8(&out)))
143}
144
145fn encode_for_regexp_escape(c: u32, leading: bool, out: &mut Vec<u32>) {
148 let backslash = u32::from(b'\\');
149 let ascii_alnum = matches!(c, 0x30..=0x39 | 0x41..=0x5A | 0x61..=0x7A);
152 if leading && ascii_alnum {
153 push_hex_escape(c, out);
154 return;
155 }
156 if matches!(
158 c,
159 0x2E | 0x2A | 0x2B | 0x3F | 0x5E | 0x24 | 0x7C | 0x28 | 0x29 | 0x5B | 0x5D | 0x7B | 0x7D | 0x5C | 0x2F ) {
163 out.push(backslash);
164 out.push(c);
165 return;
166 }
167 if let Some(letter) = match c {
169 0x09 => Some('t'),
170 0x0A => Some('n'),
171 0x0B => Some('v'),
172 0x0C => Some('f'),
173 0x0D => Some('r'),
174 _ => None,
175 } {
176 out.push(backslash);
177 out.push(u32::from(letter as u8));
178 return;
179 }
180 let other_punctuator = matches!(
183 c,
184 0x2C | 0x2D | 0x3D | 0x3C | 0x3E | 0x23 | 0x26 | 0x21 | 0x25 | 0x3A | 0x3B | 0x40 | 0x7E | 0x27 | 0x60 | 0x22 );
187 if other_punctuator || quickjs_regexp::is_space(c) || (0xD800..=0xDFFF).contains(&c) {
188 if c <= 0xFF {
189 push_hex_escape(c, out);
190 } else {
191 out.push(backslash);
195 out.push(u32::from(b'u'));
196 for shift in [12, 8, 4, 0] {
197 out.push(u32::from(hex_digit((c >> shift) & 0xF)));
198 }
199 }
200 return;
201 }
202 out.push(c);
204}
205
206fn push_hex_escape(c: u32, out: &mut Vec<u32>) {
208 out.push(u32::from(b'\\'));
209 out.push(u32::from(b'x'));
210 out.push(u32::from(hex_digit((c >> 4) & 0xF)));
211 out.push(u32::from(hex_digit(c & 0xF)));
212}
213
214fn hex_digit(nibble: u32) -> u8 {
216 match nibble {
217 0..=9 => b'0' + nibble as u8,
218 _ => b'a' + (nibble as u8 - 10),
219 }
220}
221
222fn constructor(interp: &mut Interp<'_>, _this: Value, args: &[Value]) -> JsResult<Value> {
224 let pattern = arg(args, 0);
225 let flags = arg(args, 1);
226 let (source, flags) = match &pattern {
228 Value::Object(object) if object.regexp().is_some() => {
229 let data = object.regexp().expect("checked");
230 let flags = if matches!(flags, Value::Undefined) {
231 data.flags.clone()
232 } else {
233 interp.to_js_string(&flags)?
234 };
235 (data.source.clone(), flags)
236 }
237 Value::Undefined => (
243 String::new(),
244 if matches!(flags, Value::Undefined) {
245 String::new()
246 } else {
247 interp.to_js_string(&flags)?
248 },
249 ),
250 other => (
251 interp.to_js_string(other)?,
252 if matches!(flags, Value::Undefined) {
253 String::new()
254 } else {
255 interp.to_js_string(&flags)?
256 },
257 ),
258 };
259 let object = allocate(interp)?;
260 Ok(Value::Object(initialise(interp, object, &source, &flags)?))
261}
262
263fn exec(interp: &mut Interp<'_>, this: Value, args: &[Value]) -> JsResult<Value> {
265 let Some(object) = this.as_object() else {
266 return Err(interp.type_error("RegExp.prototype.exec called on a non-object"));
267 };
268 let text = interp.checked_to_wtf8(&arg(args, 0))?;
269 exec_on(interp, object, &text)
270}
271
272pub fn exec_on(
274 interp: &mut Interp<'_>,
275 object: &Gc<JsObject>,
276 text: &crate::value::Wtf8,
277) -> JsResult<Value> {
278 let Some(data) = object.regexp() else {
279 return Err(interp.type_error("method called on a non-RegExp"));
280 };
281 let sticky_or_global = data.regex.flags.global || data.regex.flags.sticky;
282 let mut start = if sticky_or_global {
283 let index = interp.get_property(object, "lastIndex")?;
284 let index = interp.to_js_number(&index.unwrap_or(Value::Int(0)))?;
285 if !index.is_finite() || index < 0.0 {
286 interp.set_property(object, "lastIndex", Value::Int(0))?;
287 return Ok(Value::Null);
288 }
289 index as usize
290 } else {
291 0
292 };
293 let input: Vec<u32> = text.code_point_values();
294 let mut unit_start = Vec::with_capacity(input.len() + 1);
298 let mut units = 0;
299 for character in &input {
300 unit_start.push(units);
301 units += if *character > 0xFFFF { 2 } else { 1 };
302 }
303 unit_start.push(units);
304 if start > units {
309 if sticky_or_global {
310 interp.set_property(object, "lastIndex", Value::Int(0))?;
311 }
312 return Ok(Value::Null);
313 }
314 start = unit_start
315 .partition_point(|offset| *offset <= start)
316 .saturating_sub(1);
317 let found = data.regex.exec_at(&input, start);
318 let Some(found) = found else {
319 if sticky_or_global {
320 interp.set_property(object, "lastIndex", Value::Int(0))?;
321 }
322 return Ok(Value::Null);
323 };
324 if sticky_or_global {
327 let units = unit_start[found.end.min(unit_start.len() - 1)];
328 interp.set_property(object, "lastIndex", Value::Int(units as i32))?;
329 }
330 let mut elements: Vec<Value> = Vec::with_capacity(found.captures.len());
333 for capture in &found.captures {
334 elements.push(match capture {
335 Some((start, end)) => interp.string_wtf8(slice(&input, *start, *end)),
336 None => Value::Undefined,
337 });
338 }
339 let array = interp.new_array(elements);
340 let index = unit_start[found.start.min(unit_start.len() - 1)];
341 let input_value = interp.string_wtf8(text.clone());
342 interp.set_property(&array, "index", Value::Int(index as i32))?;
343 interp.set_property(&array, "input", input_value.clone())?;
344 let groups = if data.regex.names.is_empty() {
351 Value::Undefined
352 } else {
353 let groups = interp.new_object(None);
354 for (name, index) in &data.regex.names {
355 let value = match found.captures.get(*index).copied().flatten() {
356 Some((start, end)) => interp.string_wtf8(slice(&input, start, end)),
357 None => Value::Undefined,
358 };
359 interp.set_property(&groups, name, value)?;
360 }
361 Value::Object(groups)
362 };
363 interp.set_property(&array, "groups", groups)?;
364 if data.regex.flags.has_indices {
365 let mut pairs = Vec::with_capacity(found.captures.len());
366 for capture in &found.captures {
367 pairs.push(match capture {
368 Some((start, end)) => {
369 let (start, end) = (
370 unit_start[(*start).min(unit_start.len() - 1)],
371 unit_start[(*end).min(unit_start.len() - 1)],
372 );
373 let pair =
374 interp.new_array(vec![Value::Int(start as i32), Value::Int(end as i32)]);
375 Value::Object(pair)
376 }
377 None => Value::Undefined,
378 });
379 }
380 let indices = interp.new_array(pairs);
381 interp.set_property(&array, "indices", Value::Object(indices))?;
382 }
383 Ok(Value::Object(array))
384}
385
386fn slice(input: &[u32], start: usize, end: usize) -> crate::value::Wtf8 {
392 points_to_wtf8(input.get(start..end).unwrap_or_default())
393}
394
395fn points_to_wtf8(points: &[u32]) -> crate::value::Wtf8 {
397 let mut units = Vec::with_capacity(points.len());
398 for point in points {
399 if *point > 0xFFFF {
400 let value = point - 0x10000;
401 units.push(0xD800 + (value >> 10) as u16);
402 units.push(0xDC00 + (value & 0x3FF) as u16);
403 } else {
404 units.push(*point as u16);
405 }
406 }
407 crate::value::Wtf8::from_units(&units)
408}
409
410fn test(interp: &mut Interp<'_>, this: Value, args: &[Value]) -> JsResult<Value> {
412 let result = exec(interp, this, args)?;
413 Ok(Value::Bool(!matches!(result, Value::Null)))
414}
415
416fn to_string(interp: &mut Interp<'_>, this: Value, _args: &[Value]) -> JsResult<Value> {
417 let Some(object) = this.as_object() else {
418 return Err(interp.type_error("RegExp.prototype.toString called on a non-object"));
419 };
420 let Some(data) = object.regexp() else {
421 return Err(interp.type_error("RegExp.prototype.toString called on a non-RegExp"));
422 };
423 let source = if data.source.is_empty() {
424 "(?:)".to_string()
425 } else {
426 data.source.clone()
427 };
428 Ok(interp.string(format!("/{source}/{}", data.flags)))
429}
430
431fn source(interp: &mut Interp<'_>, this: Value, _args: &[Value]) -> JsResult<Value> {
432 let data = data_of(interp, &this)?;
433 let text = if data.source.is_empty() {
435 "(?:)".to_string()
436 } else {
437 data.source.clone()
438 };
439 Ok(interp.string(&text))
440}
441
442fn flags(interp: &mut Interp<'_>, this: Value, _args: &[Value]) -> JsResult<Value> {
443 let data = data_of(interp, &this)?;
444 Ok(interp.string(&data.flags))
445}
446
447fn data_of(interp: &mut Interp<'_>, this: &Value) -> JsResult<RegExpData> {
448 match this.as_object().and_then(|object| object.regexp()) {
449 Some(data) => Ok(data.clone()),
450 None => Err(interp.type_error("method called on a non-RegExp")),
451 }
452}
453
454fn flag_getter(interp: &mut Interp<'_>, this: Value, pick: fn(&Flags) -> bool) -> JsResult<Value> {
456 let data = data_of(interp, &this)?;
457 Ok(Value::Bool(pick(&data.regex.flags)))
458}
459
460fn global(interp: &mut Interp<'_>, this: Value, _args: &[Value]) -> JsResult<Value> {
461 flag_getter(interp, this, |flags| flags.global)
462}
463fn ignore_case(interp: &mut Interp<'_>, this: Value, _args: &[Value]) -> JsResult<Value> {
464 flag_getter(interp, this, |flags| flags.ignore_case)
465}
466fn multiline(interp: &mut Interp<'_>, this: Value, _args: &[Value]) -> JsResult<Value> {
467 flag_getter(interp, this, |flags| flags.multiline)
468}
469fn sticky(interp: &mut Interp<'_>, this: Value, _args: &[Value]) -> JsResult<Value> {
470 flag_getter(interp, this, |flags| flags.sticky)
471}
472fn unicode(interp: &mut Interp<'_>, this: Value, _args: &[Value]) -> JsResult<Value> {
473 flag_getter(interp, this, |flags| flags.unicode)
474}
475fn dot_all(interp: &mut Interp<'_>, this: Value, _args: &[Value]) -> JsResult<Value> {
476 flag_getter(interp, this, |flags| flags.dot_all)
477}
478fn has_indices(interp: &mut Interp<'_>, this: Value, _args: &[Value]) -> JsResult<Value> {
479 flag_getter(interp, this, |flags| flags.has_indices)
480}
481
482fn symbol_match(interp: &mut Interp<'_>, this: Value, args: &[Value]) -> JsResult<Value> {
490 let Some(object) = this.as_object() else {
491 return Err(interp.type_error("Symbol.match called on a non-object"));
492 };
493 let text = interp.checked_to_wtf8(&arg(args, 0))?;
494 let is_global = interp
495 .get_property(object, "global")?
496 .unwrap_or(Value::Undefined)
497 .to_boolean();
498 if !is_global {
499 return exec_on(interp, object, &text);
500 }
501 interp.set_property(object, "lastIndex", Value::Int(0))?;
502 let mut results = Vec::new();
503 let input: Vec<u32> = text.code_point_values();
504 loop {
505 let result = exec_on(interp, object, &text)?;
506 if matches!(result, Value::Null) {
507 break;
508 }
509 let Value::Object(array) = &result else {
510 break;
511 };
512 let matched = interp.get_property(array, "0")?.unwrap_or(Value::Undefined);
513 let empty = interp.to_js_string(&matched)?.is_empty();
514 results.push(result);
515 if empty {
516 let next = interp
517 .get_property(object, "lastIndex")?
518 .unwrap_or(Value::Int(0));
519 let next = interp.to_js_number(&next)? as usize + 1;
520 interp.set_property(object, "lastIndex", Value::Int(next as i32))?;
521 if next > input.len() {
522 break;
523 }
524 }
525 }
526 if results.is_empty() {
527 return Ok(Value::Null);
528 }
529 Ok(Value::Object(interp.new_array(results)))
530}
531
532fn symbol_search(interp: &mut Interp<'_>, this: Value, args: &[Value]) -> JsResult<Value> {
534 let Some(object) = this.as_object() else {
535 return Err(interp.type_error("Symbol.search called on a non-object"));
536 };
537 let text = interp.checked_to_wtf8(&arg(args, 0))?;
538 interp.set_property(object, "lastIndex", Value::Int(0))?;
541 let result = exec_on(interp, object, &text)?;
542 match result {
543 Value::Null => Ok(Value::Int(-1)),
544 Value::Object(array) => Ok(interp
545 .get_property(&array, "index")?
546 .unwrap_or(Value::Int(-1))),
547 other => Ok(other),
548 }
549}
550
551fn symbol_split(interp: &mut Interp<'_>, this: Value, args: &[Value]) -> JsResult<Value> {
553 let Some(object) = this.as_object() else {
554 return Err(interp.type_error("Symbol.split called on a non-object"));
555 };
556 let text = interp.checked_to_wtf8(&arg(args, 0))?;
557 let limit = match arg(args, 1) {
558 Value::Undefined => u32::MAX,
559 other => {
560 let number = interp.to_js_number(&other)?;
561 if number.is_nan() || number < 0.0 {
562 0
563 } else {
564 number as u32
565 }
566 }
567 };
568 if limit == 0 {
569 return Ok(Value::Object(interp.new_array(Vec::new())));
570 }
571 let data = data_of(interp, &Value::Object(object.clone()))?;
572 let input: Vec<u32> = text.code_point_values();
573 let mut parts: Vec<Value> = Vec::new();
574 let mut last = 0usize;
575 let mut scan = 0usize;
576 while scan <= input.len() {
577 let Some(found) = data.regex.exec_at(&input, scan) else {
578 break;
579 };
580 if found.end == found.start {
582 scan = found.start + 1;
583 continue;
584 }
585 parts.push(interp.string_wtf8(slice(&input, last, found.start)));
586 if parts.len() as u32 >= limit {
587 return Ok(Value::Object(interp.new_array(parts)));
588 }
589 for group in found.captures.iter().skip(1) {
590 parts.push(match group {
591 Some((start, end)) => interp.string_wtf8(slice(&input, *start, *end)),
592 None => Value::Undefined,
593 });
594 if parts.len() as u32 >= limit {
595 return Ok(Value::Object(interp.new_array(parts)));
596 }
597 }
598 last = found.end;
599 scan = found.end;
600 }
601 parts.push(interp.string_wtf8(slice(&input, last, input.len())));
602 Ok(Value::Object(interp.new_array(parts)))
603}
604
605fn symbol_replace(interp: &mut Interp<'_>, this: Value, args: &[Value]) -> JsResult<Value> {
608 let Some(object) = this.as_object() else {
609 return Err(interp.type_error("Symbol.replace called on a non-object"));
610 };
611 let text = interp.checked_to_wtf8(&arg(args, 0))?;
612 let replacement = arg(args, 1);
613 let is_global = interp
614 .get_property(object, "global")?
615 .unwrap_or(Value::Undefined)
616 .to_boolean();
617 let data = data_of(interp, &Value::Object(object.clone()))?;
618 let input: Vec<u32> = text.code_point_values();
621 let units = text.to_units();
622 let mut unit_start = Vec::with_capacity(input.len() + 1);
623 let mut at = 0usize;
624 for character in &input {
625 unit_start.push(at);
626 at += if *character > 0xFFFF { 2 } else { 1 };
627 }
628 unit_start.push(at);
629 let to_units = |position: usize| unit_start[position.min(unit_start.len() - 1)];
630 let mut out: Vec<u16> = Vec::new();
631 let mut last = 0usize;
632 let mut scan = 0usize;
633 let mut replaced = false;
634 while scan <= input.len() {
635 let Some(found) = data.regex.exec_at(&input, scan) else {
636 break;
637 };
638 out.extend_from_slice(&units[to_units(last)..to_units(found.start)]);
639 let substituted = substitute(
640 interp,
641 &replacement,
642 &input,
643 &units,
644 &unit_start,
645 &found,
646 &data.regex.names,
647 )?;
648 out.extend_from_slice(&substituted);
649 last = found.end;
650 let empty = found.start == found.end;
651 scan = if empty { found.end + 1 } else { found.end };
652 replaced = true;
653 if !is_global {
654 break;
655 }
656 if empty && found.end >= input.len() {
657 break;
658 }
659 }
660 if !replaced {
661 return Ok(interp.string_wtf8(text.clone()));
662 }
663 out.extend_from_slice(&units[to_units(last)..]);
664 Ok(interp.string_wtf8(crate::value::Wtf8::from_units(&out)))
665}
666
667#[allow(clippy::too_many_arguments)]
672fn substitute(
673 interp: &mut Interp<'_>,
674 replacement: &Value,
675 input: &[u32],
676 units: &[u16],
677 unit_start: &[usize],
678 found: &crate::regexp::Match,
679 names: &[(String, usize)],
680) -> JsResult<Vec<u16>> {
681 let to_units = |position: usize| unit_start[position.min(unit_start.len() - 1)];
682 let start = to_units(found.start);
683 let end = to_units(found.end);
684 if let Value::Object(function) = replacement
685 && function.is_callable()
686 {
687 let mut args: Vec<Value> = vec![interp.string_wtf8(slice(input, found.start, found.end))];
688 for group in found.captures.iter().skip(1) {
689 args.push(match group {
690 Some((start, end)) => interp.string_wtf8(slice(input, *start, *end)),
691 None => Value::Undefined,
692 });
693 }
694 args.push(Value::Int(start as i32));
697 args.push(interp.string_wtf8(crate::value::Wtf8::from_units(units)));
698 let result = interp.call_value(Value::Object(function.clone()), Value::Undefined, args)?;
699 return Ok(interp.checked_to_wtf8(&result)?.to_units());
701 }
702 let template = interp.checked_to_wtf8(replacement)?;
703 let captures: Vec<Option<(usize, usize)>> = found
706 .captures
707 .iter()
708 .map(|group| group.map(|(start, end)| (to_units(start), to_units(end))))
709 .collect();
710 let mut out: Vec<u16> = Vec::new();
711 get_substitution(
712 &mut out,
713 &template,
714 &Substitution {
715 input: units,
716 position: start,
717 match_len: end - start,
718 captures: &captures,
719 names: (!names.is_empty()).then_some(names),
722 },
723 );
724 Ok(out)
725}
726
727pub fn new_regexp(interp: &mut Interp<'_>, source: &str, flags: &str) -> JsResult<Gc<JsObject>> {
730 let prototype = default_prototype(interp);
731 let object = interp.new_object(Some(prototype));
732 initialise(interp, object, source, flags)
733}
734
735fn default_prototype(interp: &Interp<'_>) -> Gc<JsObject> {
737 interp
738 .realm
739 .regexp_proto
740 .clone()
741 .unwrap_or_else(|| interp.realm.object_proto.clone())
742}
743
744fn allocate(interp: &mut Interp<'_>) -> JsResult<Gc<JsObject>> {
751 let fallback = default_prototype(interp);
752 interp.new_ctor_instance(fallback)
753}
754
755fn initialise(
757 interp: &mut Interp<'_>,
758 object: Gc<JsObject>,
759 source: &str,
760 flags: &str,
761) -> JsResult<Gc<JsObject>> {
762 let Some(parsed) = Flags::parse(flags) else {
763 return Err(invalid_pattern(interp, String::new(), "flags"));
764 };
765 let regex = match Regex::compile(source, parsed) {
766 Ok(regex) => regex,
767 Err(error) => {
768 return Err(invalid_pattern(interp, error.message, ""));
770 }
771 };
772 object.set_regexp(RegExpData {
773 regex: std::rc::Rc::new(regex),
774 source: source.to_string(),
775 flags: parsed.as_flag_string(),
776 });
777 object.define(
778 "lastIndex",
779 Property::with_attributes(Value::Int(0), true, false),
780 );
781 Ok(object)
782}
783
784fn invalid_pattern(interp: &Interp<'_>, message: String, flags: &str) -> crate::interp::Signal {
789 let text = if flags.is_empty() {
790 message
791 } else {
792 "invalid regular expression flags".to_string()
793 };
794 crate::interp::Signal::Throw(interp.make_error("SyntaxError", &text))
795}
796
797pub fn is_regexp(object: &Gc<JsObject>) -> bool {
799 object.regexp().is_some()
800}