1use crate::builtins::{arg, define_method};
11use crate::interp::{Interp, JsResult};
12use crate::object::{JsObject, Property};
13use crate::regexp::{Flags, Regex};
14use crate::value::Value;
15use js_gc::Gc;
16
17#[derive(Clone)]
22pub struct RegExpData {
23 pub regex: std::rc::Rc<Regex>,
25 pub source: String,
27 pub flags: String,
29}
30
31pub fn install(interp: &mut Interp<'_>, object_proto: &Gc<JsObject>) -> Gc<JsObject> {
33 let prototype = interp.new_object(Some(object_proto.clone()));
34 let constructor = interp.new_native_constructor("RegExp", 2, constructor);
35 constructor.define(
36 "prototype",
37 Property::with_attributes(Value::Object(prototype.clone()), false, false),
38 );
39 prototype.define(
40 "constructor",
41 Property::with_attributes(Value::Object(constructor.clone()), true, false),
42 );
43
44 define_method(&prototype, "exec", 1, exec, interp);
45 define_method(&prototype, "test", 1, test, interp);
46 define_method(&prototype, "toString", 0, to_string, interp);
47 for (name, getter) in [
48 (
49 "source",
50 source as fn(&mut Interp<'_>, Value, &[Value]) -> JsResult<Value>,
51 ),
52 ("flags", flags),
53 ("global", global),
54 ("ignoreCase", ignore_case),
55 ("multiline", multiline),
56 ("sticky", sticky),
57 ("unicode", unicode),
58 ("dotAll", dot_all),
59 ("hasIndices", has_indices),
60 ] {
61 let getter = interp.new_native(name, 0, getter);
62 prototype.define(
63 name,
64 Property {
65 getter: Some(Value::Object(getter)),
66 enumerable: false,
67 configurable: true,
68 ..Property::default()
69 },
70 );
71 }
72
73 install_symbol_methods(interp, &prototype, &constructor);
76 interp.realm.regexp_proto = Some(prototype.clone());
77 interp.realm.regexp_ctor = Some(constructor.clone());
78 constructor
79}
80
81fn install_symbol_methods(
82 interp: &mut Interp<'_>,
83 prototype: &Gc<JsObject>,
84 constructor: &Gc<JsObject>,
85) {
86 use crate::interp::WellKnown;
87 for (which, name, func, length) in [
88 (
89 WellKnown::Match,
90 "[Symbol.match]",
91 symbol_match as crate::object::NativeFn,
92 1,
93 ),
94 (WellKnown::Replace, "[Symbol.replace]", symbol_replace, 2),
95 (WellKnown::Search, "[Symbol.search]", symbol_search, 1),
96 (WellKnown::Split, "[Symbol.split]", symbol_split, 2),
97 ] {
98 let method = interp.new_native(name, length, func);
99 prototype.define_key(
100 &interp.realm.well_known_key(which),
101 Property::with_attributes(Value::Object(method), true, false),
102 );
103 }
104 let _ = constructor;
105}
106
107fn constructor(interp: &mut Interp<'_>, _this: Value, args: &[Value]) -> JsResult<Value> {
109 let pattern = arg(args, 0);
110 let flags = arg(args, 1);
111 let (source, flags) = match &pattern {
113 Value::Object(object) if object.regexp().is_some() => {
114 let data = object.regexp().expect("checked");
115 let flags = if matches!(flags, Value::Undefined) {
116 data.flags.clone()
117 } else {
118 interp.to_js_string(&flags)?
119 };
120 (data.source.clone(), flags)
121 }
122 Value::Undefined => (String::new(), String::new()),
123 other => (
124 interp.to_js_string(other)?,
125 if matches!(flags, Value::Undefined) {
126 String::new()
127 } else {
128 interp.to_js_string(&flags)?
129 },
130 ),
131 };
132 Ok(Value::Object(new_regexp(interp, &source, &flags)?))
133}
134
135fn exec(interp: &mut Interp<'_>, this: Value, args: &[Value]) -> JsResult<Value> {
137 let Some(object) = this.as_object() else {
138 return Err(interp.type_error("RegExp.prototype.exec called on a non-object"));
139 };
140 let text = interp.checked_to_wtf8(&arg(args, 0))?;
141 exec_on(interp, object, &text)
142}
143
144pub fn exec_on(
146 interp: &mut Interp<'_>,
147 object: &Gc<JsObject>,
148 text: &crate::value::Wtf8,
149) -> JsResult<Value> {
150 let Some(data) = object.regexp() else {
151 return Err(interp.type_error("method called on a non-RegExp"));
152 };
153 let sticky_or_global = data.regex.flags.global || data.regex.flags.sticky;
154 let mut start = if sticky_or_global {
155 let index = interp.get_property(object, "lastIndex")?;
156 let index = interp.to_js_number(&index.unwrap_or(Value::Int(0)))?;
157 if !index.is_finite() || index < 0.0 {
158 interp.set_property(object, "lastIndex", Value::Int(0))?;
159 return Ok(Value::Null);
160 }
161 index as usize
162 } else {
163 0
164 };
165 let input: Vec<u32> = text.code_point_values();
166 let mut unit_start = Vec::with_capacity(input.len() + 1);
170 let mut units = 0;
171 for character in &input {
172 unit_start.push(units);
173 units += if *character > 0xFFFF { 2 } else { 1 };
174 }
175 unit_start.push(units);
176 if start > units {
181 if sticky_or_global {
182 interp.set_property(object, "lastIndex", Value::Int(0))?;
183 }
184 return Ok(Value::Null);
185 }
186 start = unit_start
187 .partition_point(|offset| *offset <= start)
188 .saturating_sub(1);
189 let found = data.regex.exec_at(&input, start);
190 let Some(found) = found else {
191 if sticky_or_global {
192 interp.set_property(object, "lastIndex", Value::Int(0))?;
193 }
194 return Ok(Value::Null);
195 };
196 if sticky_or_global {
199 let units = unit_start[found.end.min(unit_start.len() - 1)];
200 interp.set_property(object, "lastIndex", Value::Int(units as i32))?;
201 }
202 let mut elements: Vec<Value> = Vec::with_capacity(found.captures.len());
205 for capture in &found.captures {
206 elements.push(match capture {
207 Some((start, end)) => interp.string_wtf8(slice(&input, *start, *end)),
208 None => Value::Undefined,
209 });
210 }
211 let array = interp.new_array(elements);
212 let index = unit_start[found.start.min(unit_start.len() - 1)];
213 let input_value = interp.string_wtf8(text.clone());
214 interp.set_property(&array, "index", Value::Int(index as i32))?;
215 interp.set_property(&array, "input", input_value.clone())?;
216 interp.set_property(
217 &array,
218 "groups",
219 if found.captures.len() > 1 {
220 Value::Undefined
222 } else {
223 Value::Undefined
224 },
225 )?;
226 if data.regex.flags.has_indices {
227 let mut pairs = Vec::with_capacity(found.captures.len());
228 for capture in &found.captures {
229 pairs.push(match capture {
230 Some((start, end)) => {
231 let (start, end) = (
232 unit_start[(*start).min(unit_start.len() - 1)],
233 unit_start[(*end).min(unit_start.len() - 1)],
234 );
235 let pair =
236 interp.new_array(vec![Value::Int(start as i32), Value::Int(end as i32)]);
237 Value::Object(pair)
238 }
239 None => Value::Undefined,
240 });
241 }
242 let indices = interp.new_array(pairs);
243 interp.set_property(&array, "indices", Value::Object(indices))?;
244 }
245 Ok(Value::Object(array))
246}
247
248fn slice(input: &[u32], start: usize, end: usize) -> crate::value::Wtf8 {
254 points_to_wtf8(input.get(start..end).unwrap_or_default())
255}
256
257fn points_to_wtf8(points: &[u32]) -> crate::value::Wtf8 {
259 let mut units = Vec::with_capacity(points.len());
260 for point in points {
261 if *point > 0xFFFF {
262 let value = point - 0x10000;
263 units.push(0xD800 + (value >> 10) as u16);
264 units.push(0xDC00 + (value & 0x3FF) as u16);
265 } else {
266 units.push(*point as u16);
267 }
268 }
269 crate::value::Wtf8::from_units(&units)
270}
271
272fn test(interp: &mut Interp<'_>, this: Value, args: &[Value]) -> JsResult<Value> {
274 let result = exec(interp, this, args)?;
275 Ok(Value::Bool(!matches!(result, Value::Null)))
276}
277
278fn to_string(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.toString called on a non-object"));
281 };
282 let Some(data) = object.regexp() else {
283 return Err(interp.type_error("RegExp.prototype.toString called on a non-RegExp"));
284 };
285 let source = if data.source.is_empty() {
286 "(?:)".to_string()
287 } else {
288 data.source.clone()
289 };
290 Ok(interp.string(format!("/{source}/{}", data.flags)))
291}
292
293fn source(interp: &mut Interp<'_>, this: Value, _args: &[Value]) -> JsResult<Value> {
294 let data = data_of(interp, &this)?;
295 let text = if data.source.is_empty() {
297 "(?:)".to_string()
298 } else {
299 data.source.clone()
300 };
301 Ok(interp.string(&text))
302}
303
304fn flags(interp: &mut Interp<'_>, this: Value, _args: &[Value]) -> JsResult<Value> {
305 let data = data_of(interp, &this)?;
306 Ok(interp.string(&data.flags))
307}
308
309fn data_of(interp: &mut Interp<'_>, this: &Value) -> JsResult<RegExpData> {
310 match this.as_object().and_then(|object| object.regexp()) {
311 Some(data) => Ok(data.clone()),
312 None => Err(interp.type_error("method called on a non-RegExp")),
313 }
314}
315
316fn flag_getter(interp: &mut Interp<'_>, this: Value, pick: fn(&Flags) -> bool) -> JsResult<Value> {
318 let data = data_of(interp, &this)?;
319 Ok(Value::Bool(pick(&data.regex.flags)))
320}
321
322fn global(interp: &mut Interp<'_>, this: Value, _args: &[Value]) -> JsResult<Value> {
323 flag_getter(interp, this, |flags| flags.global)
324}
325fn ignore_case(interp: &mut Interp<'_>, this: Value, _args: &[Value]) -> JsResult<Value> {
326 flag_getter(interp, this, |flags| flags.ignore_case)
327}
328fn multiline(interp: &mut Interp<'_>, this: Value, _args: &[Value]) -> JsResult<Value> {
329 flag_getter(interp, this, |flags| flags.multiline)
330}
331fn sticky(interp: &mut Interp<'_>, this: Value, _args: &[Value]) -> JsResult<Value> {
332 flag_getter(interp, this, |flags| flags.sticky)
333}
334fn unicode(interp: &mut Interp<'_>, this: Value, _args: &[Value]) -> JsResult<Value> {
335 flag_getter(interp, this, |flags| flags.unicode)
336}
337fn dot_all(interp: &mut Interp<'_>, this: Value, _args: &[Value]) -> JsResult<Value> {
338 flag_getter(interp, this, |flags| flags.dot_all)
339}
340fn has_indices(interp: &mut Interp<'_>, this: Value, _args: &[Value]) -> JsResult<Value> {
341 flag_getter(interp, this, |flags| flags.has_indices)
342}
343
344fn symbol_match(interp: &mut Interp<'_>, this: Value, args: &[Value]) -> JsResult<Value> {
352 let Some(object) = this.as_object() else {
353 return Err(interp.type_error("Symbol.match called on a non-object"));
354 };
355 let text = interp.checked_to_wtf8(&arg(args, 0))?;
356 let is_global = interp
357 .get_property(object, "global")?
358 .unwrap_or(Value::Undefined)
359 .to_boolean();
360 if !is_global {
361 return exec_on(interp, object, &text);
362 }
363 interp.set_property(object, "lastIndex", Value::Int(0))?;
364 let mut results = Vec::new();
365 let input: Vec<u32> = text.code_point_values();
366 loop {
367 let result = exec_on(interp, object, &text)?;
368 if matches!(result, Value::Null) {
369 break;
370 }
371 let Value::Object(array) = &result else {
372 break;
373 };
374 let matched = interp.get_property(array, "0")?.unwrap_or(Value::Undefined);
375 let empty = interp.to_js_string(&matched)?.is_empty();
376 results.push(result);
377 if empty {
378 let next = interp
379 .get_property(object, "lastIndex")?
380 .unwrap_or(Value::Int(0));
381 let next = interp.to_js_number(&next)? as usize + 1;
382 interp.set_property(object, "lastIndex", Value::Int(next as i32))?;
383 if next > input.len() {
384 break;
385 }
386 }
387 }
388 if results.is_empty() {
389 return Ok(Value::Null);
390 }
391 Ok(Value::Object(interp.new_array(results)))
392}
393
394fn symbol_search(interp: &mut Interp<'_>, this: Value, args: &[Value]) -> JsResult<Value> {
396 let Some(object) = this.as_object() else {
397 return Err(interp.type_error("Symbol.search called on a non-object"));
398 };
399 let text = interp.checked_to_wtf8(&arg(args, 0))?;
400 interp.set_property(object, "lastIndex", Value::Int(0))?;
403 let result = exec_on(interp, object, &text)?;
404 match result {
405 Value::Null => Ok(Value::Int(-1)),
406 Value::Object(array) => Ok(interp
407 .get_property(&array, "index")?
408 .unwrap_or(Value::Int(-1))),
409 other => Ok(other),
410 }
411}
412
413fn symbol_split(interp: &mut Interp<'_>, this: Value, args: &[Value]) -> JsResult<Value> {
415 let Some(object) = this.as_object() else {
416 return Err(interp.type_error("Symbol.split called on a non-object"));
417 };
418 let text = interp.checked_to_wtf8(&arg(args, 0))?;
419 let limit = match arg(args, 1) {
420 Value::Undefined => u32::MAX,
421 other => {
422 let number = interp.to_js_number(&other)?;
423 if number.is_nan() || number < 0.0 {
424 0
425 } else {
426 number as u32
427 }
428 }
429 };
430 if limit == 0 {
431 return Ok(Value::Object(interp.new_array(Vec::new())));
432 }
433 let data = data_of(interp, &Value::Object(object.clone()))?;
434 let input: Vec<u32> = text.code_point_values();
435 let mut parts: Vec<Value> = Vec::new();
436 let mut last = 0usize;
437 let mut scan = 0usize;
438 while scan <= input.len() {
439 let Some(found) = data.regex.exec_at(&input, scan) else {
440 break;
441 };
442 if found.end == found.start {
444 scan = found.start + 1;
445 continue;
446 }
447 parts.push(interp.string_wtf8(slice(&input, last, found.start)));
448 if parts.len() as u32 >= limit {
449 return Ok(Value::Object(interp.new_array(parts)));
450 }
451 for group in found.captures.iter().skip(1) {
452 parts.push(match group {
453 Some((start, end)) => interp.string_wtf8(slice(&input, *start, *end)),
454 None => Value::Undefined,
455 });
456 if parts.len() as u32 >= limit {
457 return Ok(Value::Object(interp.new_array(parts)));
458 }
459 }
460 last = found.end;
461 scan = found.end;
462 }
463 parts.push(interp.string_wtf8(slice(&input, last, input.len())));
464 Ok(Value::Object(interp.new_array(parts)))
465}
466
467fn symbol_replace(interp: &mut Interp<'_>, this: Value, args: &[Value]) -> JsResult<Value> {
469 let Some(object) = this.as_object() else {
470 return Err(interp.type_error("Symbol.replace called on a non-object"));
471 };
472 let text = interp.checked_to_wtf8(&arg(args, 0))?;
473 let replacement = arg(args, 1);
474 let is_global = interp
475 .get_property(object, "global")?
476 .unwrap_or(Value::Undefined)
477 .to_boolean();
478 let data = data_of(interp, &Value::Object(object.clone()))?;
479 let input: Vec<u32> = text.code_point_values();
480 let mut out: Vec<u32> = Vec::new();
483 let mut last = 0usize;
484 let mut scan = 0usize;
485 let mut replaced = false;
486 while scan <= input.len() {
487 let Some(found) = data.regex.exec_at(&input, scan) else {
488 break;
489 };
490 out.extend_from_slice(&input[last..found.start]);
491 let matched = slice(&input, found.start, found.end);
492 let substituted = substitute(interp, &replacement, &matched, &input, &found)?;
493 out.extend_from_slice(&substituted);
494 last = found.end;
495 let empty = found.start == found.end;
496 scan = if empty { found.end + 1 } else { found.end };
497 replaced = true;
498 if !is_global {
499 break;
500 }
501 if empty && found.end >= input.len() {
502 break;
503 }
504 }
505 if !replaced {
506 return Ok(interp.string_wtf8(text.clone()));
507 }
508 out.extend_from_slice(&input[last.min(input.len())..]);
509 Ok(interp.string_wtf8(points_to_wtf8(&out)))
510}
511
512fn substitute(
515 interp: &mut Interp<'_>,
516 replacement: &Value,
517 matched: &crate::value::Wtf8,
518 input: &[u32],
519 found: &crate::regexp::Match,
520) -> JsResult<Vec<u32>> {
521 if let Value::Object(function) = replacement
522 && function.is_callable()
523 {
524 let mut args: Vec<Value> = vec![interp.string_wtf8(matched.clone())];
525 for group in found.captures.iter().skip(1) {
526 args.push(match group {
527 Some((start, end)) => interp.string_wtf8(slice(input, *start, *end)),
528 None => Value::Undefined,
529 });
530 }
531 args.push(Value::Int(found.start as i32));
532 args.push(interp.string_wtf8(points_to_wtf8(input)));
533 let this = Value::Undefined;
534 let result = interp.call_value(Value::Object(function.clone()), this, args)?;
535 return Ok(interp.checked_to_wtf8(&result)?.code_point_values());
537 }
538 let template = interp.checked_to_wtf8(replacement)?;
539 let mut out: Vec<u32> = Vec::new();
540 let mut chars = template.code_point_values().into_iter().peekable();
541 while let Some(c) = chars.next() {
542 if c != u32::from(b'$') {
543 out.push(c);
544 continue;
545 }
546 match chars.peek().copied() {
547 Some(dollar) if dollar == u32::from(b'$') => {
548 chars.next();
549 out.push(u32::from(b'$'));
550 }
551 Some(amp) if amp == u32::from(b'&') => {
552 chars.next();
553 out.extend_from_slice(&matched.code_point_values());
554 }
555 Some(back) if back == u32::from(b'`') => {
556 chars.next();
557 out.extend_from_slice(&input[..found.start]);
558 }
559 Some(quote) if quote == u32::from(b'\'') => {
560 chars.next();
561 out.extend_from_slice(&input[found.end..]);
562 }
563 Some(digit) if (u32::from(b'0')..=u32::from(b'9')).contains(&digit) => {
564 let mut digits = String::new();
565 while let Some(digit) = chars.peek().copied() {
566 if !(u32::from(b'0')..=u32::from(b'9')).contains(&digit) || digits.len() == 2 {
567 break;
568 }
569 digits.push(char::from_u32(digit).unwrap_or('0'));
570 chars.next();
571 }
572 let index: usize = digits.parse().unwrap_or(0);
573 match found.captures.get(index) {
574 Some(Some((start, end))) => out.extend_from_slice(&input[*start..*end]),
575 _ => {
577 out.push(u32::from(b'$'));
578 out.extend(digits.chars().map(|c| c as u32));
579 }
580 }
581 }
582 _ => out.push(u32::from(b'$')),
583 }
584 }
585 Ok(out)
586}
587
588pub fn new_regexp(interp: &mut Interp<'_>, source: &str, flags: &str) -> JsResult<Gc<JsObject>> {
591 let Some(parsed) = Flags::parse(flags) else {
592 return Err(invalid_pattern(interp, String::new(), "flags"));
593 };
594 let regex = match Regex::compile(source, parsed) {
595 Ok(regex) => regex,
596 Err(error) => {
597 return Err(invalid_pattern(interp, error.message, ""));
599 }
600 };
601 let prototype = interp
602 .realm
603 .regexp_proto
604 .clone()
605 .unwrap_or_else(|| interp.realm.object_proto.clone());
606 let object = interp.new_object(Some(prototype));
607 object.set_regexp(RegExpData {
608 regex: std::rc::Rc::new(regex),
609 source: source.to_string(),
610 flags: parsed.as_flag_string(),
611 });
612 object.define(
613 "lastIndex",
614 Property::with_attributes(Value::Int(0), true, false),
615 );
616 Ok(object)
617}
618
619fn invalid_pattern(interp: &Interp<'_>, message: String, flags: &str) -> crate::interp::Signal {
624 let text = if flags.is_empty() {
625 message
626 } else {
627 "invalid regular expression flags".to_string()
628 };
629 crate::interp::Signal::Throw(interp.make_error("SyntaxError", &text))
630}
631
632pub fn is_regexp(object: &Gc<JsObject>) -> bool {
634 object.regexp().is_some()
635}