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