use crate::host::{self, with_host, JsObj, RegExpObj};
use crate::utf16::{self, U16Index};
use fancy_regex::{Captures, Match, Regex};
use fusevm::Value;
use indexmap::IndexMap;
use rustc_hash::FxHashMap;
use std::cell::RefCell;
use std::rc::Rc;
const SURROGATE_LO: u32 = 0xD800;
const SURROGATE_HI: u32 = 0xDFFF;
const SURROGATE_PUA_BASE: u32 = 0xF_0000;
fn remap_surrogate(cp: u32) -> u32 {
if (SURROGATE_LO..=SURROGATE_HI).contains(&cp) {
SURROGATE_PUA_BASE + (cp - SURROGATE_LO)
} else {
cp
}
}
fn escape_regexp_pattern(pattern: &str) -> String {
if pattern.is_empty() {
return "(?:)".to_string();
}
let mut out = String::with_capacity(pattern.len());
let mut in_class = false;
let mut chars = pattern.chars();
while let Some(c) = chars.next() {
match c {
'\\' => {
out.push(c);
if let Some(next) = chars.next() {
out.push(next);
}
}
'[' if !in_class => {
in_class = true;
out.push(c);
}
']' if in_class => {
in_class = false;
out.push(c);
}
'/' if !in_class => out.push_str("\\/"),
'\n' => out.push_str("\\n"),
'\r' => out.push_str("\\r"),
'\u{2028}' => out.push_str("\\u2028"),
'\u{2029}' => out.push_str("\\u2029"),
_ => out.push(c),
}
}
out
}
pub fn check_literal(pattern: &str, flags: &str) -> Result<(), String> {
let mut seen = String::new();
for c in flags.chars() {
if !"dgimsuvy".contains(c) || seen.contains(c) {
return Err("SyntaxError: Invalid regular expression flags".to_string());
}
seen.push(c);
}
if flags.contains('u') && flags.contains('v') {
return Err("SyntaxError: Invalid regular expression flags".to_string());
}
let sets = flags.contains('v');
crate::regexp_syntax::validate(pattern, flags.contains('u') || sets, sets).map_err(|reason| {
format!("SyntaxError: Invalid regular expression: /{pattern}/{flags}: {reason}")
})
}
pub fn build_regexp(pattern: &str, flags: &str) -> Result<Value, String> {
let mut seen = String::new();
for c in flags.chars() {
if !"dgimsuvy".contains(c)
|| seen.contains(c)
|| (c == 'v' && seen.contains('u'))
|| (c == 'u' && seen.contains('v'))
{
return Err(format!(
"SyntaxError: Invalid flags supplied to RegExp constructor '{flags}'"
));
}
seen.push(c);
}
let global = flags.contains('g');
let ignore_case = flags.contains('i');
let multiline = flags.contains('m');
let dot_all = flags.contains('s');
let sticky = flags.contains('y');
let sets = flags.contains('v');
let unicode = flags.contains('u') || sets;
let invalid = |reason: &str| {
format!("SyntaxError: Invalid regular expression: /{pattern}/{flags}: {reason}")
};
crate::regexp_syntax::validate(pattern, unicode, sets).map_err(|r| invalid(&r))?;
let (rust_pat, capture_map) =
translate(pattern, unicode, sets, dot_all, multiline).map_err(|r| invalid(&r))?;
let mut prefixed = String::new();
if ignore_case || multiline || dot_all {
prefixed.push_str("(?");
if ignore_case {
prefixed.push('i');
}
if multiline {
prefixed.push('m');
}
if dot_all {
prefixed.push('s');
}
prefixed.push(')');
}
prefixed.push_str(&rust_pat);
let re = compiled(&prefixed).map_err(|e| {
invalid(&e.lines().collect::<Vec<_>>().join(" "))
})?;
let obj = RegExpObj {
re: Rc::new(Engine {
re,
map: Rc::new(capture_map),
}),
source: escape_regexp_pattern(pattern),
flags: flags.to_string(),
global,
ignore_case,
multiline,
dot_all,
sticky,
unicode: flags.contains('u'),
last_index: U16Index::ZERO,
};
Ok(with_host(|h| h.alloc(JsObj::RegExp(Box::new(obj)))))
}
fn compiled(prefixed: &str) -> Result<Rc<Regex>, String> {
thread_local! {
static CACHE: RefCell<FxHashMap<String, Rc<Regex>>> =
RefCell::new(FxHashMap::default());
}
if let Some(hit) = CACHE.with(|c| c.borrow().get(prefixed).cloned()) {
return Ok(hit);
}
let re = Rc::new(Regex::new(prefixed).map_err(|e| e.to_string())?);
CACHE.with(|c| {
c.borrow_mut().insert(prefixed.to_string(), re.clone());
});
Ok(re)
}
fn scan_groups(chars: &[char]) -> (usize, Vec<(String, usize)>) {
let mut count = 0usize;
let mut names = Vec::new();
let mut in_class = false;
let mut i = 0;
while i < chars.len() {
match chars[i] {
'\\' => i += 1,
'[' if !in_class => in_class = true,
']' if in_class => in_class = false,
'(' if !in_class => {
if chars.get(i + 1) != Some(&'?') {
count += 1;
} else if chars.get(i + 2) == Some(&'<')
&& !matches!(chars.get(i + 3), Some('=') | Some('!'))
{
count += 1;
let name: String = chars[i + 3..].iter().take_while(|c| **c != '>').collect();
names.push((name, count));
}
}
_ => {}
}
i += 1;
}
(count, names)
}
pub struct CaptureMap {
fancy_of_js: Vec<usize>,
guards: Vec<Vec<(usize, Within)>>,
never_empty: Vec<bool>,
names: Vec<(String, usize)>,
}
#[derive(Clone, Copy)]
enum Within {
Whole,
Start,
End,
}
impl CaptureMap {
fn identity(count: usize, names: Vec<(String, usize)>) -> CaptureMap {
CaptureMap {
fancy_of_js: (0..=count).collect(),
guards: vec![Vec::new(); count + 1],
never_empty: vec![false; count + 1],
names,
}
}
}
#[derive(Clone, Copy, PartialEq)]
enum GroupKind {
Capture,
Plain,
LookAhead,
LookBehind,
Other,
}
struct GroupPlan {
hidden: Vec<bool>,
map: CaptureMap,
}
fn quantifier_repeats(chars: &[char], at: usize) -> bool {
match chars.get(at) {
Some('*' | '+') => true,
Some('{') => {
let body: String = chars[at + 1..].iter().take_while(|c| **c != '}').collect();
if chars.get(at + 1 + body.chars().count()) != Some(&'}') {
return false;
}
match body.split_once(',') {
None => body.parse::<u64>().is_ok_and(|n| n > 1),
Some((lo, "")) => lo.parse::<u64>().is_ok(),
Some((lo, hi)) => {
lo.parse::<u64>().is_ok() && hi.parse::<u64>().is_ok_and(|n| n > 1)
}
}
}
_ => false,
}
}
fn plan_groups(chars: &[char], names: Vec<(String, usize)>) -> GroupPlan {
let mut kind: Vec<GroupKind> = Vec::new();
let mut parent: Vec<Option<usize>> = Vec::new();
let mut repeats: Vec<bool> = Vec::new();
let mut min_zero: Vec<bool> = Vec::new();
let mut has_capture: Vec<bool> = Vec::new();
let mut open: Vec<usize> = Vec::new();
let mut in_class = false;
let mut i = 0;
while i < chars.len() {
match chars[i] {
'\\' => i += 1,
'[' if !in_class => in_class = true,
']' if in_class => in_class = false,
'(' if !in_class => {
let k = if chars.get(i + 1) != Some(&'?') {
GroupKind::Capture
} else {
match (chars.get(i + 2), chars.get(i + 3)) {
(Some(':'), _) => GroupKind::Plain,
(Some('=' | '!'), _) => GroupKind::LookAhead,
(Some('<'), Some('=' | '!')) => GroupKind::LookBehind,
(Some('<'), _) => GroupKind::Capture,
_ => GroupKind::Other,
}
};
parent.push(open.last().copied());
open.push(kind.len());
kind.push(k);
repeats.push(false);
min_zero.push(false);
has_capture.push(false);
}
')' if !in_class => {
if let Some(id) = open.pop() {
repeats[id] = quantifier_repeats(chars, i + 1);
min_zero[id] = quantifier_at(chars, i + 1).is_some_and(|(_, min)| min == 0);
if kind[id] == GroupKind::Capture || has_capture[id] {
if let Some(p) = parent[id] {
has_capture[p] = true;
}
}
}
}
_ => {}
}
i += 1;
}
let hidden: Vec<bool> = (0..kind.len())
.map(|g| kind[g] == GroupKind::Plain && (repeats[g] || min_zero[g]) && has_capture[g])
.collect();
let mut fancy: Vec<usize> = vec![0; kind.len()];
let mut fancy_of_js = vec![0usize];
let mut next = 0;
for g in 0..kind.len() {
if kind[g] == GroupKind::Capture || hidden[g] {
next += 1;
fancy[g] = next;
if kind[g] == GroupKind::Capture {
fancy_of_js.push(next);
}
}
}
let mut guards: Vec<Vec<(usize, Within)>> = vec![Vec::new(); next + 1];
let mut never_empty = vec![false; next + 1];
for g in 0..kind.len() {
if fancy[g] == 0 {
continue;
}
never_empty[fancy[g]] = min_zero[g];
let mut chain = Vec::new();
let mut within = Within::Whole;
let mut p = parent[g];
while let Some(a) = p {
within = match (kind[a], within) {
(GroupKind::LookAhead, Within::Whole | Within::Start) => Within::Start,
(GroupKind::LookBehind, Within::Whole | Within::End) => Within::End,
(GroupKind::LookAhead | GroupKind::LookBehind, _) => break,
_ => within,
};
if fancy[a] != 0 && (repeats[a] || min_zero[a]) {
chain.push((fancy[a], within));
}
p = parent[a];
}
chain.reverse();
guards[fancy[g]] = chain;
}
GroupPlan {
hidden,
map: CaptureMap {
fancy_of_js,
guards,
never_empty,
names,
},
}
}
pub struct Engine {
re: Rc<Regex>,
map: Rc<CaptureMap>,
}
impl std::ops::Deref for Engine {
type Target = Regex;
fn deref(&self) -> &Regex {
&self.re
}
}
impl Engine {
pub fn captures_from_pos<'t>(
&self,
s: &'t str,
pos: usize,
) -> Result<Option<Caps<'t>>, fancy_regex::Error> {
Ok(self.re.captures_from_pos(s, pos)?.map(|inner| Caps {
inner,
map: self.map.clone(),
}))
}
pub fn captures<'t>(&self, s: &'t str) -> Result<Option<Caps<'t>>, fancy_regex::Error> {
Ok(self.re.captures(s)?.map(|inner| Caps {
inner,
map: self.map.clone(),
}))
}
}
pub struct Caps<'t> {
inner: Captures<'t>,
map: Rc<CaptureMap>,
}
impl<'t> Caps<'t> {
pub fn len(&self) -> usize {
self.map.fancy_of_js.len()
}
pub fn is_empty(&self) -> bool {
false
}
pub fn get(&self, i: usize) -> Option<Match<'t>> {
let f = *self.map.fancy_of_js.get(i)?;
self.valid(f).then(|| self.inner.get(f)).flatten()
}
pub fn name(&self, name: &str) -> Option<Match<'t>> {
let (_, i) = self.map.names.iter().find(|(n, _)| n == name)?;
self.get(*i)
}
fn valid(&self, f: usize) -> bool {
let Some(m) = self.inner.get(f) else {
return false;
};
if self.map.never_empty[f] && m.start() == m.end() {
return false;
}
self.map.guards[f].iter().all(|&(q, within)| {
self.inner.get(q).is_some_and(|g| {
let inside = |at: usize| g.start() <= at && at <= g.end();
match within {
Within::Whole => inside(m.start()) && inside(m.end()),
Within::Start => inside(m.start()),
Within::End => inside(m.end()),
}
}) && self.valid(q)
})
}
}
fn hex_escape(cp: u32) -> String {
format!("\\x{{{cp:X}}}")
}
fn legacy_octal(chars: &[char], i: usize) -> (u32, usize) {
let oct = |k: usize| chars.get(k).and_then(|c| c.to_digit(8));
let first = oct(i).unwrap_or(0);
let max = if first <= 3 { 3 } else { 2 };
let mut value = first;
let mut len = 1;
while len < max {
match oct(i + len) {
Some(d) => {
value = value * 8 + d;
len += 1;
}
None => break,
}
}
(value, len)
}
fn check_group(chars: &[char], i: usize) -> Result<(), &'static str> {
match chars.get(i + 2) {
Some(':') | Some('=') | Some('!') | Some('<') => return Ok(()),
_ => {}
}
let mut seen = String::new();
let mut k = i + 2;
let mut saw_dash = false;
while let Some(&c) = chars.get(k) {
match c {
'i' | 'm' | 's' => {
if seen.contains(c) {
return Err("Repeated flag in flag group");
}
seen.push(c);
}
'-' if !saw_dash => saw_dash = true,
':' if seen.is_empty() => return Err("Invalid flag group"),
':' => return Ok(()),
_ => return Err("Invalid group"),
}
k += 1;
}
Err("Invalid group")
}
const WORD_BOUNDARY: &str =
"(?:(?<=[0-9A-Za-z_])(?![0-9A-Za-z_])|(?<![0-9A-Za-z_])(?=[0-9A-Za-z_]))";
const NOT_WORD_BOUNDARY: &str =
"(?:(?<=[0-9A-Za-z_])(?=[0-9A-Za-z_])|(?<![0-9A-Za-z_])(?![0-9A-Za-z_]))";
fn quantifier_at(chars: &[char], at: usize) -> Option<(usize, u64)> {
let (mut end, min) = match chars.get(at)? {
'*' | '?' => (at + 1, 0),
'+' => (at + 1, 1),
'{' => {
let mut j = at + 1;
let lo_start = j;
while chars.get(j).is_some_and(char::is_ascii_digit) {
j += 1;
}
if j == lo_start {
return None;
}
let min: u64 = chars[lo_start..j]
.iter()
.collect::<String>()
.parse()
.unwrap_or(u64::MAX);
if chars.get(j) == Some(&',') {
j += 1;
while chars.get(j).is_some_and(char::is_ascii_digit) {
j += 1;
}
}
if chars.get(j) != Some(&'}') {
return None;
}
(j + 1, min)
}
_ => return None,
};
if chars.get(end) == Some(&'?') {
end += 1;
}
Some((end, min))
}
fn four_hex(chars: &[char], at: usize) -> bool {
chars
.get(at..at + 4)
.is_some_and(|h| h.iter().all(|c| c.is_ascii_hexdigit()))
}
fn class_escape(e: char, in_class: bool) -> String {
const WS: &str = r"\t\n\x{B}\x{C}\r \x{A0}\x{1680}\x{2000}-\x{200A}\x{2028}\x{2029}\x{202F}\x{205F}\x{3000}\x{FEFF}";
const WORD: &str = "0-9A-Za-z_";
let members = match e.to_ascii_lowercase() {
'd' => "0-9",
'w' => WORD,
_ => WS,
};
match (e.is_ascii_lowercase(), in_class) {
(true, true) => members.to_string(),
(true, false) => format!("[{members}]"),
(false, _) => format!("[^{members}]"),
}
}
fn translate(
pat: &str,
unicode: bool,
sets: bool,
dot_all: bool,
multiline: bool,
) -> Result<(String, CaptureMap), String> {
match translate_with(pat, unicode, sets, dot_all, multiline, true)? {
(out, map, true) => Ok((out, map)),
_ => translate_with(pat, unicode, sets, dot_all, multiline, false).map(|(o, m, _)| (o, m)),
}
}
fn translate_with(
pat: &str,
unicode: bool,
sets: bool,
dot_all: bool,
multiline: bool,
allow_hidden: bool,
) -> Result<(String, CaptureMap, bool), String> {
let chars: Vec<char> = pat.chars().collect();
let (group_count, group_names) = scan_groups(&chars);
let mut plan = plan_groups(&chars, group_names.clone());
if !allow_hidden {
plan = GroupPlan {
hidden: vec![false; plan.hidden.len()],
map: CaptureMap::identity(group_count, group_names.clone()),
};
}
let mut paren_seen = 0usize;
let mut out = String::new();
let mut i = 0;
let mut in_class = false;
let mut class_pos = 0usize;
let mut class_depth = 0usize;
let mut prev_set = false;
let mut group_open: Vec<Option<usize>> = Vec::new();
while i < chars.len() {
let c = chars[i];
let after_set = std::mem::take(&mut prev_set);
if c != '\\' {
if (!in_class || sets) && c == '[' {
let negated = chars.get(i + 1) == Some(&'^');
let close_at = i + 1 + usize::from(negated);
if chars.get(close_at) == Some(&']') {
out.push_str(if negated { r"[\s\S]" } else { r"[^\s\S]" });
if in_class {
class_pos += 1;
}
i = close_at + 1;
continue;
}
in_class = true;
class_depth += 1;
class_pos = 0;
out.push('[');
i += 1;
if negated {
out.push('^');
i += 1;
}
continue;
}
if in_class {
if c == ']' && (class_pos > 0 || sets) {
class_depth = class_depth.saturating_sub(1);
in_class = class_depth > 0;
out.push(']');
i += 1;
continue;
}
if c == '[' {
out.push_str("\\[");
class_pos += 1;
i += 1;
continue;
}
} else if c == '(' && chars.get(i + 1) == Some(&'?') {
check_group(&chars, i).map_err(str::to_string)?;
}
}
match c {
'\\' => {
class_pos += 1;
match chars.get(i + 1).copied() {
Some('u') if !unicode && !four_hex(&chars, i + 2) => {
out.push('u');
i += 2;
continue;
}
Some('u') if !unicode && chars.get(i + 2) == Some(&'{') => {
out.push('u');
i += 2;
continue;
}
Some('u') => {
i += 2;
let cp_hex: String;
if chars.get(i) == Some(&'{') {
i += 1;
let mut hex = String::new();
while i < chars.len() && chars[i] != '}' {
hex.push(chars[i]);
i += 1;
}
i += 1; cp_hex = hex;
} else {
cp_hex = chars[i..(i + 4).min(chars.len())].iter().collect();
i += 4;
}
match u32::from_str_radix(cp_hex.trim(), 16) {
Ok(cp) => out.push_str(&hex_escape(remap_surrogate(cp))),
Err(_) => out.push_str(&format!("\\x{{{cp_hex}}}")),
}
continue;
}
Some('x') => {
let hex: String = chars
.get(i + 2..i + 4)
.map(|h| h.iter().collect())
.unwrap_or_default();
match u32::from_str_radix(&hex, 16) {
Ok(v)
if hex.len() == 2 && hex.chars().all(|c| c.is_ascii_hexdigit()) =>
{
out.push_str(&hex_escape(v));
i += 4;
}
_ => {
out.push('x');
i += 2;
}
}
continue;
}
Some('/') => {
out.push('/');
i += 2;
continue;
}
Some('c') => {
let control = match chars.get(i + 2) {
Some(x) if x.is_ascii_alphabetic() => Some(*x),
Some(x)
if in_class && !unicode && (x.is_ascii_digit() || *x == '_') =>
{
Some(*x)
}
_ => None,
};
match control {
Some(x) => {
out.push_str(&hex_escape(x as u32 % 32));
i += 3;
}
None if unicode => return Err("Invalid Unicode escape".into()),
None => {
out.push_str("\\\\");
i += 1;
}
}
continue;
}
Some(d) if d.is_ascii_digit() => {
let lone_zero =
d == '0' && !chars.get(i + 2).is_some_and(|n| n.is_ascii_digit());
if lone_zero {
out.push_str(&hex_escape(0));
i += 2;
continue;
}
if !in_class && d != '0' {
let digits: String = chars[i + 1..]
.iter()
.take_while(|c| c.is_ascii_digit())
.collect();
let n = digits.parse::<usize>().unwrap_or(usize::MAX);
if n <= group_count {
let n = plan.map.fancy_of_js[n];
out.push_str(&format!("(?({n})\\{n}|)"));
i += 1 + digits.len();
continue;
}
}
if unicode {
let reason = if in_class || d == '0' {
"Invalid decimal escape"
} else {
"Invalid escape"
};
return Err(reason.into());
}
if d == '8' || d == '9' {
out.push(d);
i += 2;
} else {
let (cp, len) = legacy_octal(&chars, i + 1);
out.push_str(&hex_escape(cp));
i += 1 + len;
}
continue;
}
Some('k') if in_class || (group_names.is_empty() && !unicode) => {
if unicode {
return Err("Invalid class escape".into());
}
out.push('k');
i += 2;
continue;
}
Some('k') => {
if chars.get(i + 2) != Some(&'<') {
return Err("Invalid named reference".into());
}
let Some(close) = chars[i + 3..].iter().position(|c| *c == '>') else {
return Err("Invalid capture group name".into());
};
let name: String = chars[i + 3..i + 3 + close].iter().collect();
let Some((_, index)) = group_names.iter().find(|(n, _)| *n == name) else {
return Err("Invalid named capture referenced".into());
};
let index = plan.map.fancy_of_js[*index];
out.push_str(&format!("(?({index})\\{index}|)"));
i += 4 + close;
continue;
}
Some(pc @ ('p' | 'P')) if !unicode => {
out.push(pc);
i += 2;
continue;
}
Some(e @ ('d' | 'D' | 'w' | 'W' | 's' | 'S')) => {
out.push_str(&class_escape(e, in_class));
prev_set = in_class;
i += 2;
continue;
}
Some('b') if in_class => {
out.push_str(&hex_escape(8));
i += 2;
continue;
}
Some(b @ ('b' | 'B')) => {
out.push_str(if b == 'b' {
WORD_BOUNDARY
} else {
NOT_WORD_BOUNDARY
});
i += 2;
continue;
}
Some(other) => {
out.push('\\');
out.push(other);
i += 2;
continue;
}
None => {
out.push('\\');
i += 1;
}
}
}
'(' if !in_class => {
let source_paren = paren_seen;
paren_seen += 1;
if plan.hidden.get(source_paren) == Some(&true) {
group_open.push(None);
out.push('(');
i += 3;
continue;
}
let lookahead =
chars.get(i + 1) == Some(&'?') && matches!(chars.get(i + 2), Some('=' | '!'));
group_open.push(lookahead.then_some(out.len()));
out.push('(');
i += 1;
}
')' if !in_class => {
out.push(')');
i += 1;
if let Some(Some(at)) = group_open.pop() {
if let Some((next, min)) = quantifier_at(&chars, i).filter(|_| !unicode) {
if min == 0 {
out.insert_str(at, "(?:(?!)");
out.push_str(")?");
}
i = next;
}
}
}
'.' if !in_class && !dot_all => {
out.push_str(r"[^\n\r\x{2028}\x{2029}]");
i += 1;
}
'^' if !in_class && multiline => {
out.push_str(r"(?:^|(?<=[\r\x{2028}\x{2029}]))");
i += 1;
}
'$' if !in_class && multiline => {
out.push_str(r"(?:$|(?=[\r\x{2028}\x{2029}]))");
i += 1;
}
'-' if in_class
&& (after_set
|| (chars.get(i + 1) == Some(&'\\')
&& matches!(
chars.get(i + 2),
Some('d' | 'D' | 'w' | 'W' | 's' | 'S')
))) =>
{
out.push_str("\\-");
class_pos += 1;
i += 1;
}
_ => {
if in_class {
class_pos += 1;
}
out.push(c);
i += 1;
}
}
}
Ok((out, plan.map, paren_seen == plan.hidden.len()))
}
fn canonical_flags(flags: &str) -> String {
"dgimsuvy"
.chars()
.filter(|c| flags.contains(*c))
.collect::<String>()
}
pub fn regexp_property(r: &RegExpObj, name: &str) -> Option<Value> {
Some(match name {
"source" => with_host(|h| h.new_str(r.source.clone())),
"flags" => with_host(|h| h.new_str(canonical_flags(&r.flags))),
"global" => Value::Bool(r.global),
"ignoreCase" => Value::Bool(r.ignore_case),
"multiline" => Value::Bool(r.multiline),
"dotAll" => Value::Bool(r.dot_all),
"sticky" => Value::Bool(r.sticky),
"unicode" => Value::Bool(r.unicode),
"hasIndices" => Value::Bool(r.flags.contains('d')),
"unicodeSets" => Value::Bool(r.flags.contains('v')),
"lastIndex" => Value::Float(r.last_index.get() as f64),
_ => return None,
})
}
pub fn is_regexp_method(name: &str) -> bool {
matches!(name, "test" | "exec" | "toString" | "compile")
|| matches!(
name,
"@@match" | "@@matchAll" | "@@search" | "@@split" | "@@replace"
)
}
pub fn incompatible_receiver(method: &str, recv: &Value) -> String {
host::type_error(&format!(
"Method RegExp.prototype.{method} called on incompatible receiver {}",
crate::builtins::no_side_effects_string_pub(recv)
))
}
fn is_builtin_exec(f: &Value) -> bool {
with_host(|h| match h.get(f) {
Some(JsObj::BoundMethod { recv, name }) => {
name == "exec" && matches!(h.get(recv), Some(JsObj::RegExp(_)))
}
Some(JsObj::Builtin(n)) => n == "@proto:RegExp:exec",
_ => false,
})
}
pub fn regexp_exec_generic(r: &Value, s: &str) -> Result<Value, String> {
match user_exec(r)? {
Some(exec) => call_user_exec(r, &exec, s),
None => regexp_exec(require_regexp(r, "exec")?, s),
}
}
fn user_exec(r: &Value) -> Result<Option<Value>, String> {
let untouched = with_host(|h| {
matches!(h.get(r), Some(JsObj::RegExp(_)))
&& h.fn_prop(r, "exec").is_none()
&& h.proto_of(r).is_none()
&& h.builtin_static("RegExp.prototype", "exec").is_none()
});
if untouched {
return Ok(None);
}
let exec = crate::builtins::get_property(r, "exec")?;
Ok((!is_builtin_exec(&exec) && with_host(|h| host::is_callable(h, &exec))).then_some(exec))
}
fn call_user_exec(r: &Value, exec: &Value, s: &str) -> Result<Value, String> {
let subject = with_host(|h| h.new_str(s));
let result = host::invoke(exec, vec![subject], Some(r.clone()))?;
let ok = with_host(|h| {
h.is_null(&result) || (matches!(result, Value::Obj(_)) && !host::is_primitive(h, &result))
});
if !ok {
return Err(host::type_error(
"RegExp exec method returned something other than an Object or null",
));
}
Ok(result)
}
fn require_regexp<'a>(r: &'a Value, method: &str) -> Result<&'a Value, String> {
if with_host(|h| matches!(h.get(r), Some(JsObj::RegExp(_)))) {
Ok(r)
} else {
Err(incompatible_receiver(method, r))
}
}
pub fn regexp_test_generic(r: &Value, arg: &Value) -> Result<Value, String> {
let s = match with_host(|h| h.as_str(arg)) {
Some(s) => s,
None => {
let v = host::to_string_value(arg)?;
with_host(|h| h.str_of(&v))
}
};
Ok(Value::Bool(match user_exec(r)? {
Some(exec) => {
let result = call_user_exec(r, &exec, &s)?;
!with_host(|h| h.is_null(&result))
}
None => regexp_test(require_regexp(r, "exec")?, &s),
}))
}
pub fn regexp_to_string_generic(r: &Value) -> Result<Value, String> {
let read = |k: &str| -> Result<String, String> {
let v = crate::builtins::get_property(r, k)?;
let s = host::to_string_value(&v)?;
Ok(with_host(|h| h.str_of(&s)))
};
let source = read("source")?;
let flags = read("flags")?;
Ok(with_host(|h| h.new_str(format!("/{source}/{flags}"))))
}
pub fn regexp_method(recv: &Value, name: &str, args: Vec<Value>) -> Result<Value, String> {
match name {
"test" => regexp_test_generic(recv, &args.first().cloned().unwrap_or(Value::Undef)),
"exec" => {
let s = host::to_string_value(&args.first().cloned().unwrap_or(Value::Undef))?;
let s = with_host(|h| h.str_of(&s));
regexp_exec(recv, &s)
}
"toString" => Ok(with_host(|h| {
let s = h.str_of(recv);
h.new_str(s)
})),
"compile" => Ok(recv.clone()),
"@@match" | "@@matchAll" | "@@search" | "@@split" | "@@replace" => {
let s = with_host(|h| h.str_of(&args.first().cloned().unwrap_or(Value::Undef)));
match name {
"@@match" => str_match(&s, recv),
"@@matchAll" => str_match_all(&s, recv),
"@@search" => str_search(&s, recv),
"@@split" => {
let limit = args.get(1).and_then(|v| {
let n = with_host(|h| h.to_number(v));
n.is_finite().then_some(n.max(0.0) as usize)
});
str_split_regex(&s, recv, limit)
}
_ => str_replace_regex(
&s,
recv,
&args.get(1).cloned().unwrap_or(Value::Undef),
false,
),
}
}
_ => Err(host::type_error(&format!("{name} is not a function"))),
}
}
fn regexp_snapshot(recv: &Value) -> Option<(Rc<Engine>, bool, bool, U16Index)> {
with_host(|h| match h.get(recv) {
Some(JsObj::RegExp(r)) => Some((r.re.clone(), r.global, r.sticky, r.last_index)),
_ => None,
})
}
fn has_indices(recv: &Value) -> bool {
with_host(|h| match h.get(recv) {
Some(JsObj::RegExp(r)) => r.flags.contains('d'),
_ => false,
})
}
fn set_last_index(recv: &Value, idx: U16Index) {
with_host(|h| {
if let Some(JsObj::RegExp(r)) = h.get_mut(recv) {
r.last_index = idx;
}
});
}
fn byte_of_index(s: &str, n: U16Index) -> usize {
utf16::byte_of_index(s, n)
}
fn index_of_byte(s: &str, byte: usize) -> U16Index {
utf16::index_of_byte(s, byte)
}
pub fn regexp_test(recv: &Value, s: &str) -> bool {
let Some((re, global, sticky, last)) = regexp_snapshot(recv) else {
return false;
};
let start_idx = if global || sticky {
last
} else {
U16Index::ZERO
};
if start_idx.get() > utf16::len(s) {
if global || sticky {
set_last_index(recv, U16Index::ZERO);
}
return false;
}
let start_byte = byte_of_index(s, start_idx);
match re.find_from_pos(s, start_byte) {
Ok(Some(m)) if !sticky || m.start() == start_byte => {
if global || sticky {
set_last_index(recv, index_of_byte(s, m.end()));
}
true
}
_ => {
if global || sticky {
set_last_index(recv, U16Index::ZERO);
}
false
}
}
}
pub fn regexp_exec(recv: &Value, s: &str) -> Result<Value, String> {
let Some((re, global, sticky, last)) = regexp_snapshot(recv) else {
return Ok(with_host(|h| h.null()));
};
let start_idx = if global || sticky {
last
} else {
U16Index::ZERO
};
if start_idx.get() > utf16::len(s) {
if global || sticky {
set_last_index(recv, U16Index::ZERO);
}
return Ok(with_host(|h| h.null()));
}
let start_byte = byte_of_index(s, start_idx);
let caps = re.captures_from_pos(s, start_byte).ok().flatten();
let caps = match caps {
Some(c) if !sticky || c.get(0).map(|m| m.start()) == Some(start_byte) => c,
_ => {
if global || sticky {
set_last_index(recv, U16Index::ZERO);
}
return Ok(with_host(|h| h.null()));
}
};
let whole = caps.get(0).unwrap();
if global || sticky {
set_last_index(recv, index_of_byte(s, whole.end()));
}
Ok(build_match_array(&re, &caps, s, has_indices(recv)))
}
fn build_match_array(re: &Engine, caps: &Caps, s: &str, indices: bool) -> Value {
let mut items: Vec<Value> = Vec::with_capacity(caps.len());
for i in 0..caps.len() {
items.push(match caps.get(i) {
Some(m) => with_host(|h| h.new_str(m.as_str().to_string())),
None => Value::Undef, });
}
let whole = caps.get(0).unwrap();
let arr = with_host(|h| h.new_array(items));
let index = index_of_byte(s, whole.start()).get();
with_host(|h| {
let idx = Value::Float(index as f64);
h.set_fn_prop(&arr, "index", idx);
let input = h.new_str(s.to_string());
h.set_fn_prop(&arr, "input", input);
});
let names: Vec<&str> = re.capture_names().flatten().collect();
if indices {
attach_indices(caps, s, &arr, &names);
}
if names.is_empty() {
with_host(|h| h.set_fn_prop(&arr, "groups", Value::Undef));
} else {
let mut g: IndexMap<String, Value> = IndexMap::new();
for name in names {
let v = match caps.name(name) {
Some(m) => with_host(|h| h.new_str(m.as_str().to_string())),
None => Value::Undef,
};
g.insert(name.to_string(), v);
}
with_host(|h| {
let obj = h.new_object(g);
let null = h.null();
h.set_proto(&obj, null);
h.set_fn_prop(&arr, "groups", obj);
});
}
arr
}
fn attach_indices(caps: &Caps, s: &str, arr: &Value, names: &[&str]) {
let pair = |m: Option<fancy_regex::Match>| match m {
Some(m) => {
let (a, b) = (index_of_byte(s, m.start()), index_of_byte(s, m.end()));
with_host(|h| {
h.new_array(vec![
Value::Float(a.get() as f64),
Value::Float(b.get() as f64),
])
})
}
None => Value::Undef,
};
let mut pairs: Vec<Value> = Vec::with_capacity(caps.len());
for i in 0..caps.len() {
pairs.push(pair(caps.get(i)));
}
let idx_arr = with_host(|h| h.new_array(pairs));
if names.is_empty() {
with_host(|h| h.set_fn_prop(&idx_arr, "groups", Value::Undef));
} else {
let mut g: IndexMap<String, Value> = IndexMap::new();
for name in names {
g.insert((*name).to_string(), pair(caps.name(name)));
}
with_host(|h| {
let obj = h.new_object(g);
let null = h.null();
h.set_proto(&obj, null);
h.set_fn_prop(&idx_arr, "groups", obj);
});
}
with_host(|h| h.set_fn_prop(arr, "indices", idx_arr));
}
fn collect_matches<'s>(re: &Engine, s: &'s str, start: usize, sticky: bool) -> Vec<Caps<'s>> {
let mut out = Vec::new();
let mut pos = start;
while pos <= s.len() {
let Some(caps) = re.captures_from_pos(s, pos).ok().flatten() else {
break;
};
let m = caps.get(0).expect("group 0 always participates");
if sticky && m.start() != pos {
break;
}
pos = match m.end() == m.start() {
true => match s[m.end()..].chars().next() {
Some(c) => m.end() + c.len_utf8(),
None => s.len() + 1,
},
false => m.end(),
};
out.push(caps);
}
out
}
pub fn str_match(s: &str, re_val: &Value) -> Result<Value, String> {
let Some((re, global, sticky, _)) = regexp_snapshot(re_val) else {
return Ok(with_host(|h| h.null()));
};
if !global {
if sticky {
return regexp_exec(re_val, s);
}
return regexp_exec_from_zero(&re, s, has_indices(re_val));
}
set_last_index(re_val, U16Index::ZERO);
let matches: Vec<Value> = collect_matches(&re, s, 0, sticky)
.iter()
.map(|c| with_host(|h| h.new_str(c.get(0).map_or("", |m| m.as_str()).to_string())))
.collect();
if matches.is_empty() {
Ok(with_host(|h| h.null()))
} else {
Ok(with_host(|h| h.new_array(matches)))
}
}
fn regexp_exec_from_zero(re: &Engine, s: &str, indices: bool) -> Result<Value, String> {
match re.captures(s).ok().flatten() {
Some(caps) => Ok(build_match_array(re, &caps, s, indices)),
None => Ok(with_host(|h| h.null())),
}
}
pub fn str_match_all(s: &str, re_val: &Value) -> Result<Value, String> {
let Some((re, global, sticky, last)) = regexp_snapshot(re_val) else {
return Ok(with_host(|h| h.new_array(Vec::new())));
};
let indices = has_indices(re_val);
if !global {
return Err(host::type_error(
"String.prototype.matchAll called with a non-global RegExp argument",
));
}
let mut items = Vec::new();
if last.get() <= utf16::len(s) {
let start = byte_of_index(s, last);
for caps in collect_matches(&re, s, start, sticky) {
items.push(build_match_array(&re, &caps, s, indices));
}
}
Ok(with_host(|h| {
h.alloc_iter(JsObj::Iter {
items,
idx: 0,
array: None,
brand: Some("RegExp String Iterator"),
})
}))
}
pub fn str_search(s: &str, re_val: &Value) -> Result<Value, String> {
let Some((re, _, sticky, _)) = regexp_snapshot(re_val) else {
return Ok(Value::Float(-1.0));
};
Ok(match re.find(s).ok().flatten() {
Some(m) if !sticky || m.start() == 0 => {
Value::Float(index_of_byte(s, m.start()).get() as f64)
}
_ => Value::Float(-1.0),
})
}
pub fn str_split_regex(s: &str, re_val: &Value, limit: Option<usize>) -> Result<Value, String> {
let Some((re, _, _, _)) = regexp_snapshot(re_val) else {
return Ok(with_host(|h| h.new_array(Vec::new())));
};
let lim = limit.unwrap_or(usize::MAX);
if lim == 0 {
return Ok(with_host(|h| h.new_array(Vec::new())));
}
let size = utf16::len(s);
let units = |i: usize| byte_of_index(s, U16Index::new(i));
if size == 0 {
let out = if matches!(re.find(s), Ok(Some(_))) {
Vec::new()
} else {
vec![with_host(|h| h.new_str(String::new()))]
};
return Ok(with_host(|h| h.new_array(out)));
}
let mut out: Vec<Value> = Vec::new();
let mut p = 0usize; let mut q = 0usize; while q < size {
let Some(caps) = re.captures_from_pos(s, units(q)).ok().flatten() else {
break;
};
let m = caps.get(0).expect("group 0 always participates");
let m_start = index_of_byte(s, m.start()).get();
if m_start >= size {
break;
}
let e = index_of_byte(s, m.end()).get().min(size);
if e == p {
q = m_start.max(q) + 1;
continue;
}
out.push(with_host(|h| {
h.new_str(utf16::Units::of(s).slice(p, m_start))
}));
if out.len() >= lim {
return Ok(with_host(|h| h.new_array(out)));
}
for i in 1..caps.len() {
out.push(match caps.get(i) {
Some(g) => with_host(|h| h.new_str(g.as_str().to_string())),
None => Value::Undef,
});
if out.len() >= lim {
return Ok(with_host(|h| h.new_array(out)));
}
}
p = e;
q = p;
}
out.push(with_host(|h| h.new_str(utf16::Units::of(s).slice(p, size))));
out.truncate(lim);
Ok(with_host(|h| h.new_array(out)))
}
pub fn str_replace_regex(
s: &str,
re_val: &Value,
repl: &Value,
all: bool,
) -> Result<Value, String> {
let Some((re, global, sticky, last_index)) = regexp_snapshot(re_val) else {
return Ok(with_host(|h| h.new_str(s.to_string())));
};
let replace_all = all || global;
let has_named_groups = re.capture_names().flatten().next().is_some();
let is_fn = with_host(|h| host::is_callable(h, repl));
let mut out = String::new();
let mut last = 0usize;
let mut count = 0;
let found: Vec<Caps> = if global {
collect_matches(&re, s, 0, sticky)
} else if sticky {
let all_from_here = if last_index.get() <= utf16::len(s) {
collect_matches(&re, s, byte_of_index(s, last_index), true)
} else {
Vec::new()
};
let first: Vec<Caps> = all_from_here.into_iter().take(1).collect();
let next = first
.first()
.and_then(|c| c.get(0))
.map_or(U16Index::ZERO, |m| index_of_byte(s, m.end()));
set_last_index(re_val, next);
first
} else {
collect_matches(&re, s, 0, false)
};
for caps in found {
let m = caps.get(0).unwrap();
out.push_str(&s[last..m.start()]);
if is_fn {
let mut call_args: Vec<Value> = Vec::new();
for i in 0..caps.len() {
call_args.push(match caps.get(i) {
Some(g) => with_host(|h| h.new_str(g.as_str().to_string())),
None => Value::Undef,
});
}
call_args.push(Value::Float(index_of_byte(s, m.start()).get() as f64));
call_args.push(with_host(|h| h.new_str(s.to_string())));
if let Some(groups) = named_groups_object(&re, &caps) {
call_args.push(groups);
}
let r = host::invoke(repl, call_args, None)?;
out.push_str(&with_host(|h| h.str_of(&r)));
} else {
let repl_str = with_host(|h| h.str_of(repl));
out.push_str(&expand_replacement(&repl_str, &caps, s, has_named_groups));
}
last = m.end();
count += 1;
if !replace_all && count >= 1 {
break;
}
}
out.push_str(&s[last..]);
if global {
set_last_index(re_val, U16Index::ZERO);
}
Ok(with_host(|h| h.new_str(out)))
}
fn named_groups_object(re: &Engine, caps: &Caps) -> Option<Value> {
let names: Vec<&str> = re.capture_names().flatten().collect();
if names.is_empty() {
return None;
}
let mut g: IndexMap<String, Value> = IndexMap::new();
for name in names {
let v = match caps.name(name) {
Some(m) => with_host(|h| h.new_str(m.as_str().to_string())),
None => Value::Undef,
};
g.insert(name.to_string(), v);
}
Some(with_host(|h| {
let obj = h.new_object(g);
let null = h.null();
h.set_proto(&obj, null);
obj
}))
}
fn expand_replacement(templ: &str, caps: &Caps, s: &str, has_named_groups: bool) -> String {
let chars: Vec<char> = templ.chars().collect();
let mut out = String::new();
let mut i = 0;
let whole = caps.get(0).unwrap();
while i < chars.len() {
if chars[i] == '$' && i + 1 < chars.len() {
let n = chars[i + 1];
match n {
'$' => {
out.push('$');
i += 2;
}
'&' => {
out.push_str(whole.as_str());
i += 2;
}
'`' => {
out.push_str(&s[..whole.start()]);
i += 2;
}
'\'' => {
out.push_str(&s[whole.end()..]);
i += 2;
}
'<' if has_named_groups && chars[i + 2..].contains(&'>') => {
let close = i + 2 + chars[i + 2..].iter().position(|c| *c == '>').unwrap_or(0);
let name: String = chars[i + 2..close].iter().collect();
if let Some(m) = caps.name(&name) {
out.push_str(m.as_str());
}
i = close + 1;
}
d if d.is_ascii_digit() => {
let d2 = chars.get(i + 2).copied().filter(|c| c.is_ascii_digit());
let two = d2.and_then(|c2| format!("{d}{c2}").parse::<usize>().ok());
if let Some(gi) = two.filter(|gi| *gi < caps.len()) {
if let Some(g) = caps.get(gi) {
out.push_str(g.as_str());
}
i += 3;
} else {
let gi = d.to_digit(10).unwrap() as usize;
if gi >= 1 && gi < caps.len() {
if let Some(g) = caps.get(gi) {
out.push_str(g.as_str());
}
i += 2;
} else {
out.push('$');
i += 1;
}
}
}
_ => {
out.push('$');
i += 1;
}
}
} else {
out.push(chars[i]);
i += 1;
}
}
out
}