use crate::builtins::substitution::{Substitution, get_substitution};
use crate::builtins::{arg, define_method, install_species_accessor};
use crate::interp::{Interp, JsResult};
use crate::object::{JsObject, Property};
use crate::regexp::{Flags, Regex};
use crate::value::Value;
use js_gc::Gc;
#[derive(Clone)]
pub struct RegExpData {
pub regex: std::rc::Rc<Regex>,
pub source: String,
pub flags: String,
}
pub fn install(interp: &mut Interp<'_>, object_proto: &Gc<JsObject>) -> Gc<JsObject> {
let prototype = interp.new_object(Some(object_proto.clone()));
let constructor = interp.new_native_constructor("RegExp", 2, constructor);
constructor.define(
"prototype",
Property::with_attributes(Value::Object(prototype.clone()), false, false),
);
prototype.define(
"constructor",
Property::with_attributes(Value::Object(constructor.clone()), true, false),
);
define_method(&prototype, "exec", 1, exec, interp);
define_method(&prototype, "test", 1, test, interp);
define_method(&prototype, "toString", 0, to_string, interp);
for (name, getter) in [
(
"source",
source as fn(&mut Interp<'_>, Value, &[Value]) -> JsResult<Value>,
),
("flags", flags),
("global", global),
("ignoreCase", ignore_case),
("multiline", multiline),
("sticky", sticky),
("unicode", unicode),
("dotAll", dot_all),
("hasIndices", has_indices),
] {
let getter = interp.new_native(name, 0, getter);
prototype.define(
name,
Property {
getter: Some(Value::Object(getter)),
enumerable: false,
configurable: true,
..Property::default()
},
);
}
define_method(&constructor, "escape", 1, escape, interp);
install_species_accessor(&constructor, interp);
install_symbol_methods(interp, &prototype, &constructor);
interp.realm.regexp_proto = Some(prototype.clone());
interp.realm.regexp_ctor = Some(constructor.clone());
constructor
}
fn install_symbol_methods(
interp: &mut Interp<'_>,
prototype: &Gc<JsObject>,
constructor: &Gc<JsObject>,
) {
use crate::interp::WellKnown;
for (which, name, func, length) in [
(
WellKnown::Match,
"[Symbol.match]",
symbol_match as crate::object::NativeFn,
1,
),
(WellKnown::Replace, "[Symbol.replace]", symbol_replace, 2),
(WellKnown::Search, "[Symbol.search]", symbol_search, 1),
(WellKnown::Split, "[Symbol.split]", symbol_split, 2),
] {
let method = interp.new_native(name, length, func);
prototype.define_key(
&interp.realm.well_known_key(which),
Property::with_attributes(Value::Object(method), true, false),
);
}
let _ = constructor;
}
fn escape(interp: &mut Interp<'_>, _this: Value, args: &[Value]) -> JsResult<Value> {
let arg = arg(args, 0);
if !matches!(arg, Value::String(_)) {
return Err(interp.type_error("not a string"));
}
let source = interp.checked_to_wtf8(&arg)?.code_point_values();
let mut out: Vec<u32> = Vec::with_capacity(source.len());
for (position, cp) in source.iter().enumerate() {
let leading = position == 0;
encode_for_regexp_escape(*cp, leading, &mut out);
}
Ok(interp.string_wtf8(points_to_wtf8(&out)))
}
fn encode_for_regexp_escape(c: u32, leading: bool, out: &mut Vec<u32>) {
let backslash = u32::from(b'\\');
let ascii_alnum = matches!(c, 0x30..=0x39 | 0x41..=0x5A | 0x61..=0x7A);
if leading && ascii_alnum {
push_hex_escape(c, out);
return;
}
if matches!(
c,
0x2E | 0x2A | 0x2B | 0x3F | 0x5E | 0x24 | 0x7C | 0x28 | 0x29 | 0x5B | 0x5D | 0x7B | 0x7D | 0x5C | 0x2F ) {
out.push(backslash);
out.push(c);
return;
}
if let Some(letter) = match c {
0x09 => Some('t'),
0x0A => Some('n'),
0x0B => Some('v'),
0x0C => Some('f'),
0x0D => Some('r'),
_ => None,
} {
out.push(backslash);
out.push(u32::from(letter as u8));
return;
}
let other_punctuator = matches!(
c,
0x2C | 0x2D | 0x3D | 0x3C | 0x3E | 0x23 | 0x26 | 0x21 | 0x25 | 0x3A | 0x3B | 0x40 | 0x7E | 0x27 | 0x60 | 0x22 );
if other_punctuator || quickjs_regexp::is_space(c) || (0xD800..=0xDFFF).contains(&c) {
if c <= 0xFF {
push_hex_escape(c, out);
} else {
out.push(backslash);
out.push(u32::from(b'u'));
for shift in [12, 8, 4, 0] {
out.push(u32::from(hex_digit((c >> shift) & 0xF)));
}
}
return;
}
out.push(c);
}
fn push_hex_escape(c: u32, out: &mut Vec<u32>) {
out.push(u32::from(b'\\'));
out.push(u32::from(b'x'));
out.push(u32::from(hex_digit((c >> 4) & 0xF)));
out.push(u32::from(hex_digit(c & 0xF)));
}
fn hex_digit(nibble: u32) -> u8 {
match nibble {
0..=9 => b'0' + nibble as u8,
_ => b'a' + (nibble as u8 - 10),
}
}
fn constructor(interp: &mut Interp<'_>, _this: Value, args: &[Value]) -> JsResult<Value> {
let pattern = arg(args, 0);
let flags = arg(args, 1);
let (source, flags) = match &pattern {
Value::Object(object) if object.regexp().is_some() => {
let data = object.regexp().expect("checked");
let flags = if matches!(flags, Value::Undefined) {
data.flags.clone()
} else {
interp.to_js_string(&flags)?
};
(data.source.clone(), flags)
}
Value::Undefined => (
String::new(),
if matches!(flags, Value::Undefined) {
String::new()
} else {
interp.to_js_string(&flags)?
},
),
other => (
interp.to_js_string(other)?,
if matches!(flags, Value::Undefined) {
String::new()
} else {
interp.to_js_string(&flags)?
},
),
};
let object = allocate(interp)?;
Ok(Value::Object(initialise(interp, object, &source, &flags)?))
}
fn exec(interp: &mut Interp<'_>, this: Value, args: &[Value]) -> JsResult<Value> {
let Some(object) = this.as_object() else {
return Err(interp.type_error("RegExp.prototype.exec called on a non-object"));
};
let text = interp.checked_to_wtf8(&arg(args, 0))?;
exec_on(interp, object, &text)
}
pub fn exec_on(
interp: &mut Interp<'_>,
object: &Gc<JsObject>,
text: &crate::value::Wtf8,
) -> JsResult<Value> {
let Some(data) = object.regexp() else {
return Err(interp.type_error("method called on a non-RegExp"));
};
let sticky_or_global = data.regex.flags.global || data.regex.flags.sticky;
let start = if sticky_or_global {
let index = interp.get_property(object, "lastIndex")?;
let index = interp.to_js_number(&index.unwrap_or(Value::Int(0)))?;
if !index.is_finite() || index < 0.0 {
interp.set_property(object, "lastIndex", Value::Int(0))?;
return Ok(Value::Null);
}
index as usize
} else {
0
};
let input = MatchInput::new(&data.regex, text);
if start > input.units_len() {
if sticky_or_global {
interp.set_property(object, "lastIndex", Value::Int(0))?;
}
return Ok(Value::Null);
}
let start = input.position(start);
let found = data.regex.exec_at(&input.units, start);
let Some(found) = found else {
if sticky_or_global {
interp.set_property(object, "lastIndex", Value::Int(0))?;
}
return Ok(Value::Null);
};
if sticky_or_global {
let end = input.offset(found.end);
interp.set_property(object, "lastIndex", Value::Int(end as i32))?;
}
let mut elements: Vec<Value> = Vec::with_capacity(found.captures.len());
for capture in &found.captures {
elements.push(match capture {
Some((start, end)) => interp.string_wtf8(input.slice(*start, *end)),
None => Value::Undefined,
});
}
let array = interp.new_array(elements);
let index = input.offset(found.start);
let input_value = interp.string_wtf8(text.clone());
interp.set_property(&array, "index", Value::Int(index as i32))?;
interp.set_property(&array, "input", input_value.clone())?;
let groups = if data.regex.names.is_empty() {
Value::Undefined
} else {
let groups = interp.new_object(None);
for (name, index) in &data.regex.names {
let value = match found.captures.get(*index).copied().flatten() {
Some((start, end)) => interp.string_wtf8(input.slice(start, end)),
None => Value::Undefined,
};
interp.set_property(&groups, name, value)?;
}
Value::Object(groups)
};
interp.set_property(&array, "groups", groups)?;
if data.regex.flags.has_indices {
let mut pairs = Vec::with_capacity(found.captures.len());
for capture in &found.captures {
pairs.push(match capture {
Some((start, end)) => {
let (start, end) = (input.offset(*start), input.offset(*end));
let pair =
interp.new_array(vec![Value::Int(start as i32), Value::Int(end as i32)]);
Value::Object(pair)
}
None => Value::Undefined,
});
}
let indices = interp.new_array(pairs);
interp.set_property(&array, "indices", Value::Object(indices))?;
}
Ok(Value::Object(array))
}
struct MatchInput {
units: Vec<u32>,
unit_start: Vec<usize>,
}
impl MatchInput {
fn new(regex: &quickjs_regexp::Regex, text: &crate::value::Wtf8) -> Self {
if regex.per_code_unit() {
let units: Vec<u32> = text.to_units().into_iter().map(u32::from).collect();
let unit_start = (0..=units.len()).collect();
Self { units, unit_start }
} else {
let units = text.code_point_values();
let mut unit_start = Vec::with_capacity(units.len() + 1);
let mut count = 0;
for point in &units {
unit_start.push(count);
count += if *point > 0xFFFF { 2 } else { 1 };
}
unit_start.push(count);
Self { units, unit_start }
}
}
fn units_len(&self) -> usize {
self.unit_start[self.unit_start.len() - 1]
}
fn position(&self, offset: usize) -> usize {
self.unit_start
.partition_point(|start| *start <= offset)
.saturating_sub(1)
}
fn offset(&self, position: usize) -> usize {
self.unit_start[position.min(self.unit_start.len() - 1)]
}
fn slice(&self, start: usize, end: usize) -> crate::value::Wtf8 {
points_to_wtf8(self.units.get(start..end).unwrap_or_default())
}
}
fn points_to_wtf8(points: &[u32]) -> crate::value::Wtf8 {
let mut units = Vec::with_capacity(points.len());
for point in points {
if *point > 0xFFFF {
let value = point - 0x10000;
units.push(0xD800 + (value >> 10) as u16);
units.push(0xDC00 + (value & 0x3FF) as u16);
} else {
units.push(*point as u16);
}
}
crate::value::Wtf8::from_units(&units)
}
fn test(interp: &mut Interp<'_>, this: Value, args: &[Value]) -> JsResult<Value> {
let result = exec(interp, this, args)?;
Ok(Value::Bool(!matches!(result, Value::Null)))
}
fn to_string(interp: &mut Interp<'_>, this: Value, _args: &[Value]) -> JsResult<Value> {
let Some(object) = this.as_object() else {
return Err(interp.type_error("RegExp.prototype.toString called on a non-object"));
};
let Some(data) = object.regexp() else {
return Err(interp.type_error("RegExp.prototype.toString called on a non-RegExp"));
};
let source = if data.source.is_empty() {
"(?:)".to_string()
} else {
data.source.clone()
};
Ok(interp.string(format!("/{source}/{}", data.flags)))
}
fn source(interp: &mut Interp<'_>, this: Value, _args: &[Value]) -> JsResult<Value> {
let data = data_of(interp, &this)?;
let text = if data.source.is_empty() {
"(?:)".to_string()
} else {
data.source.clone()
};
Ok(interp.string(&text))
}
fn flags(interp: &mut Interp<'_>, this: Value, _args: &[Value]) -> JsResult<Value> {
let data = data_of(interp, &this)?;
Ok(interp.string(&data.flags))
}
fn data_of(interp: &mut Interp<'_>, this: &Value) -> JsResult<RegExpData> {
match this.as_object().and_then(|object| object.regexp()) {
Some(data) => Ok(data.clone()),
None => Err(interp.type_error("method called on a non-RegExp")),
}
}
fn flag_getter(interp: &mut Interp<'_>, this: Value, pick: fn(&Flags) -> bool) -> JsResult<Value> {
let data = data_of(interp, &this)?;
Ok(Value::Bool(pick(&data.regex.flags)))
}
fn global(interp: &mut Interp<'_>, this: Value, _args: &[Value]) -> JsResult<Value> {
flag_getter(interp, this, |flags| flags.global)
}
fn ignore_case(interp: &mut Interp<'_>, this: Value, _args: &[Value]) -> JsResult<Value> {
flag_getter(interp, this, |flags| flags.ignore_case)
}
fn multiline(interp: &mut Interp<'_>, this: Value, _args: &[Value]) -> JsResult<Value> {
flag_getter(interp, this, |flags| flags.multiline)
}
fn sticky(interp: &mut Interp<'_>, this: Value, _args: &[Value]) -> JsResult<Value> {
flag_getter(interp, this, |flags| flags.sticky)
}
fn unicode(interp: &mut Interp<'_>, this: Value, _args: &[Value]) -> JsResult<Value> {
flag_getter(interp, this, |flags| flags.unicode)
}
fn dot_all(interp: &mut Interp<'_>, this: Value, _args: &[Value]) -> JsResult<Value> {
flag_getter(interp, this, |flags| flags.dot_all)
}
fn has_indices(interp: &mut Interp<'_>, this: Value, _args: &[Value]) -> JsResult<Value> {
flag_getter(interp, this, |flags| flags.has_indices)
}
fn symbol_match(interp: &mut Interp<'_>, this: Value, args: &[Value]) -> JsResult<Value> {
let Some(object) = this.as_object() else {
return Err(interp.type_error("Symbol.match called on a non-object"));
};
let text = interp.checked_to_wtf8(&arg(args, 0))?;
let is_global = interp
.get_property(object, "global")?
.unwrap_or(Value::Undefined)
.to_boolean();
if !is_global {
return exec_on(interp, object, &text);
}
interp.set_property(object, "lastIndex", Value::Int(0))?;
let mut results = Vec::new();
let input = MatchInput::new(
&data_of(interp, &Value::Object(object.clone()))?.regex,
&text,
);
loop {
let result = exec_on(interp, object, &text)?;
if matches!(result, Value::Null) {
break;
}
let Value::Object(array) = &result else {
break;
};
let matched = interp.get_property(array, "0")?.unwrap_or(Value::Undefined);
let empty = interp.to_js_string(&matched)?.is_empty();
results.push(result);
if empty {
let next = interp
.get_property(object, "lastIndex")?
.unwrap_or(Value::Int(0));
let next = interp.to_js_number(&next)? as usize + 1;
interp.set_property(object, "lastIndex", Value::Int(next as i32))?;
if next > input.units_len() {
break;
}
}
}
if results.is_empty() {
return Ok(Value::Null);
}
Ok(Value::Object(interp.new_array(results)))
}
fn symbol_search(interp: &mut Interp<'_>, this: Value, args: &[Value]) -> JsResult<Value> {
let Some(object) = this.as_object() else {
return Err(interp.type_error("Symbol.search called on a non-object"));
};
let text = interp.checked_to_wtf8(&arg(args, 0))?;
interp.set_property(object, "lastIndex", Value::Int(0))?;
let result = exec_on(interp, object, &text)?;
match result {
Value::Null => Ok(Value::Int(-1)),
Value::Object(array) => Ok(interp
.get_property(&array, "index")?
.unwrap_or(Value::Int(-1))),
other => Ok(other),
}
}
fn symbol_split(interp: &mut Interp<'_>, this: Value, args: &[Value]) -> JsResult<Value> {
let Some(object) = this.as_object() else {
return Err(interp.type_error("Symbol.split called on a non-object"));
};
let text = interp.checked_to_wtf8(&arg(args, 0))?;
let limit = match arg(args, 1) {
Value::Undefined => u32::MAX,
other => {
let number = interp.to_js_number(&other)?;
if number.is_nan() || number < 0.0 {
0
} else {
number as u32
}
}
};
if limit == 0 {
return Ok(Value::Object(interp.new_array(Vec::new())));
}
let data = data_of(interp, &Value::Object(object.clone()))?;
let input = MatchInput::new(&data.regex, &text);
let mut parts: Vec<Value> = Vec::new();
let mut last = 0usize;
let mut scan = 0usize;
while scan <= input.units.len() {
let Some(found) = data.regex.exec_at(&input.units, scan) else {
break;
};
if found.end == found.start {
scan = found.start + 1;
continue;
}
parts.push(interp.string_wtf8(input.slice(last, found.start)));
if parts.len() as u32 >= limit {
return Ok(Value::Object(interp.new_array(parts)));
}
for group in found.captures.iter().skip(1) {
parts.push(match group {
Some((start, end)) => interp.string_wtf8(input.slice(*start, *end)),
None => Value::Undefined,
});
if parts.len() as u32 >= limit {
return Ok(Value::Object(interp.new_array(parts)));
}
}
last = found.end;
scan = found.end;
}
parts.push(interp.string_wtf8(input.slice(last, input.units.len())));
Ok(Value::Object(interp.new_array(parts)))
}
fn symbol_replace(interp: &mut Interp<'_>, this: Value, args: &[Value]) -> JsResult<Value> {
let Some(object) = this.as_object() else {
return Err(interp.type_error("Symbol.replace called on a non-object"));
};
let text = interp.checked_to_wtf8(&arg(args, 0))?;
let replacement = arg(args, 1);
let is_global = interp
.get_property(object, "global")?
.unwrap_or(Value::Undefined)
.to_boolean();
let data = data_of(interp, &Value::Object(object.clone()))?;
let input = MatchInput::new(&data.regex, &text);
let units = text.to_units();
let mut out: Vec<u16> = Vec::new();
let mut last = 0usize;
let mut scan = 0usize;
let mut replaced = false;
while scan <= input.units.len() {
let Some(found) = data.regex.exec_at(&input.units, scan) else {
break;
};
out.extend_from_slice(&units[input.offset(last)..input.offset(found.start)]);
let substituted = substitute(
interp,
&replacement,
&input,
&units,
&found,
&data.regex.names,
)?;
out.extend_from_slice(&substituted);
last = found.end;
let empty = found.start == found.end;
scan = if empty { found.end + 1 } else { found.end };
replaced = true;
if !is_global {
break;
}
if empty && found.end >= input.units.len() {
break;
}
}
if !replaced {
return Ok(interp.string_wtf8(text.clone()));
}
out.extend_from_slice(&units[input.offset(last)..]);
Ok(interp.string_wtf8(crate::value::Wtf8::from_units(&out)))
}
#[allow(clippy::too_many_arguments)]
fn substitute(
interp: &mut Interp<'_>,
replacement: &Value,
input: &MatchInput,
units: &[u16],
found: &crate::regexp::Match,
names: &[(String, usize)],
) -> JsResult<Vec<u16>> {
let start = input.offset(found.start);
let end = input.offset(found.end);
if let Value::Object(function) = replacement
&& function.is_callable()
{
let mut args: Vec<Value> = vec![interp.string_wtf8(input.slice(found.start, found.end))];
for group in found.captures.iter().skip(1) {
args.push(match group {
Some((start, end)) => interp.string_wtf8(input.slice(*start, *end)),
None => Value::Undefined,
});
}
args.push(Value::Int(start as i32));
args.push(interp.string_wtf8(crate::value::Wtf8::from_units(units)));
let result = interp.call_value(Value::Object(function.clone()), Value::Undefined, args)?;
return Ok(interp.checked_to_wtf8(&result)?.to_units());
}
let template = interp.checked_to_wtf8(replacement)?;
let captures: Vec<Option<(usize, usize)>> = found
.captures
.iter()
.map(|group| group.map(|(start, end)| (input.offset(start), input.offset(end))))
.collect();
let mut out: Vec<u16> = Vec::new();
get_substitution(
&mut out,
&template,
&Substitution {
input: units,
position: start,
match_len: end - start,
captures: &captures,
names: (!names.is_empty()).then_some(names),
},
);
Ok(out)
}
pub fn new_regexp(interp: &mut Interp<'_>, source: &str, flags: &str) -> JsResult<Gc<JsObject>> {
let prototype = default_prototype(interp);
let object = interp.new_object(Some(prototype));
initialise(interp, object, source, flags)
}
fn default_prototype(interp: &Interp<'_>) -> Gc<JsObject> {
interp
.realm
.regexp_proto
.clone()
.unwrap_or_else(|| interp.realm.object_proto.clone())
}
fn allocate(interp: &mut Interp<'_>) -> JsResult<Gc<JsObject>> {
let fallback = default_prototype(interp);
interp.new_ctor_instance(fallback)
}
fn initialise(
interp: &mut Interp<'_>,
object: Gc<JsObject>,
source: &str,
flags: &str,
) -> JsResult<Gc<JsObject>> {
let Some(parsed) = Flags::parse(flags) else {
return Err(invalid_pattern(interp, String::new(), "flags"));
};
let regex = match Regex::compile(source, parsed) {
Ok(regex) => regex,
Err(error) => {
return Err(invalid_pattern(interp, error.message, ""));
}
};
object.set_regexp(RegExpData {
regex: std::rc::Rc::new(regex),
source: source.to_string(),
flags: parsed.as_flag_string(),
});
object.define(
"lastIndex",
Property::with_attributes(Value::Int(0), true, false),
);
Ok(object)
}
fn invalid_pattern(interp: &Interp<'_>, message: String, flags: &str) -> crate::interp::Signal {
let text = if flags.is_empty() {
message
} else {
"invalid regular expression flags".to_string()
};
crate::interp::Signal::Throw(interp.make_error("SyntaxError", &text))
}
pub fn is_regexp(object: &Gc<JsObject>) -> bool {
object.regexp().is_some()
}