use std::collections::HashMap;
use std::sync::OnceLock;
use super::charset::{self, Set};
use super::dialect::{
self, BACKREFERENCE, JAVA_CATEGORIES, JAVA_SCRIPTS, LOOKAROUND, NEST_LIMIT, Read, TOO_DEEP,
literal,
};
const INTERVAL_MAX: u32 = 1000;
const MULTILINE: &str = "a multi-line ^ or $ runs only on the backtracking tier, since \
JavaScript's also hold at \\r, U+2028 and U+2029: turn on StrMatcherBuilder::backtracking \
(the strmatch-backtracking feature)";
const TERMINATORS: &str = r"\n\r\x{2028}\x{2029}";
#[derive(Clone, Copy, Default)]
#[allow(
clippy::struct_excessive_bools,
reason = "one switch per flag the literal can carry"
)]
struct Flags {
i: bool,
m: bool,
s: bool,
u: bool,
}
struct Frame {
closed: bool,
around: Vec<(usize, usize)>,
branches: usize,
optional: bool,
capture: bool,
}
pub(super) fn syntax(pattern: &str) -> Result<Read, &'static str> {
let (source, flags, literal_form) = split(pattern)?;
let first = read(source, flags, literal_form, false)?;
let read = if first.0.backtrack.is_some() && first.1 {
read(source, flags, literal_form, true)?.0
} else {
first.0
};
check_empty_iteration(&read.text)?;
Ok(read)
}
const EMPTY_ITERATION: &str = "a group repeated more than once that can match empty, where \
JavaScript rejects an iteration that matches nothing and backtracks into a longer one: \
make the group need a character";
fn check_empty_iteration(text: &str) -> Result<(), &'static str> {
let proxy = super::pcre::proxy_of(text);
let hir = regex_syntax::ParserBuilder::new()
.utf8(false)
.build()
.parse(&proxy)
.map_err(|_| EMPTY_ITERATION)?;
if repeats_empty(&hir) {
return Err(EMPTY_ITERATION);
}
Ok(())
}
fn repeats_empty(hir: ®ex_syntax::hir::Hir) -> bool {
use regex_syntax::hir::HirKind;
match hir.kind() {
HirKind::Repetition(r) => {
let more = r.max.is_none_or(|m| m > r.min.max(1));
(more && r.sub.properties().minimum_len().is_none_or(|n| n == 0))
|| repeats_empty(&r.sub)
}
HirKind::Capture(c) => repeats_empty(&c.sub),
HirKind::Concat(parts) | HirKind::Alternation(parts) => parts.iter().any(repeats_empty),
HirKind::Empty | HirKind::Literal(_) | HirKind::Class(_) | HirKind::Look(_) => false,
}
}
fn split(pattern: &str) -> Result<(&str, Flags, bool), &'static str> {
let Some(rest) = pattern.strip_prefix('/') else {
return Ok((pattern, Flags::default(), false));
};
let close = rest.rfind('/').ok_or(
"a pattern starting with / must be a /source/flags literal: write \\/ for a \
slash at the start",
)?;
let (source, letters) = (&rest[..close], &rest[close + 1..]);
if source.is_empty() {
return Err(
"an empty /source/ is a comment in JavaScript: write (?:) for an empty \
pattern",
);
}
let mut flags = Flags::default();
let mut seen = String::new();
for f in letters.chars() {
if seen.contains(f) {
return Err("a flag given twice, which JavaScript rejects");
}
seen.push(f);
match f {
'i' => flags.i = true,
'm' => flags.m = true,
's' => flags.s = true,
'u' => flags.u = true,
'g' | 'd' => {}
'y' => {
return Err(
"the y flag makes a match start where the last ended, which a \
search for every match doesn't read",
);
}
'v' => {
return Err(
"the v flag's class grammar, with nested classes and set operators, \
isn't read: use u",
);
}
_ => return Err("a flag JavaScript doesn't have after the closing /"),
}
}
Ok((source, flags, true))
}
fn read(
source: &str,
flags: Flags,
literal_form: bool,
lookaround_boundary: bool,
) -> Result<(Read, bool), &'static str> {
let mut p = Js {
src: source,
at: 0,
out: String::with_capacity(source.len() + 16),
flags,
literal_form,
lookaround_boundary,
boundary: false,
total: count_groups(source),
open: Vec::new(),
frames: Vec::new(),
names: Vec::new(),
last_closed: None,
backtrack: None,
};
if flags.i && flags.u {
p.out.push_str("(?i)");
}
p.open_frame(false, Look::No);
p.sequence()?;
if p.open.len() != 1 {
return Err("a ( with no ) to close it");
}
Ok((
Read {
text: p.out,
backtrack: p.backtrack,
},
p.boundary,
))
}
fn count_groups(src: &str) -> usize {
let b = src.as_bytes();
let (mut i, mut n, mut in_class) = (0, 0, false);
while i < b.len() {
match b[i] {
b'\\' => i += 1,
b'[' => in_class = true,
b']' => in_class = false,
b'(' if !in_class => {
let named = b.get(i + 1) == Some(&b'?')
&& b.get(i + 2) == Some(&b'<')
&& !matches!(b.get(i + 3), Some(b'=' | b'!'));
if b.get(i + 1) != Some(&b'?') || named {
n += 1;
}
}
_ => {}
}
i += 1;
}
n
}
enum Member {
Char(char),
Set(Set, bool),
}
struct Js<'p> {
src: &'p str,
at: usize,
out: String,
flags: Flags,
literal_form: bool,
lookaround_boundary: bool,
boundary: bool,
total: usize,
open: Vec<Open>,
frames: Vec<Frame>,
names: Vec<(&'p str, usize)>,
last_closed: Option<usize>,
backtrack: Option<&'static str>,
}
struct Open {
frame: usize,
branch: usize,
look: Look,
}
#[derive(Clone, Copy, PartialEq, Eq)]
enum Look {
No,
Ahead,
Behind,
}
impl<'p> Js<'p> {
fn byte(&self, ahead: usize) -> Option<u8> {
self.src.as_bytes().get(self.at + ahead).copied()
}
fn rest(&self) -> &'p str {
&self.src[self.at..]
}
fn push(&mut self, text: &str, width: usize) {
self.out.push_str(text);
self.at += width;
}
fn need_backtracking(&mut self, why: &'static str) {
self.backtrack.get_or_insert(why);
}
fn push_char(&mut self, c: char, quantified: bool) -> Result<(), &'static str> {
if !self.flags.u && u32::from(c) > 0xFFFF && quantified {
return Err(ASTRAL_QUANTIFIED);
}
if self.flags.i && !self.flags.u && fold_index().contains_key(&c) {
self.out
.push_str(&charset::render(&upper_folded(charset::single(c))));
} else {
literal(c, &mut self.out);
}
Ok(())
}
fn push_set(&mut self, set: Set, fold: bool) {
let set = if fold { self.folded(set) } else { set };
if self.flags.i && self.flags.u {
self.out.push_str(&charset::render_exact(&set));
} else {
self.out.push_str(&charset::render(&set));
}
}
fn folded(&self, set: Set) -> Set {
if !self.flags.i {
set
} else if self.flags.u {
charset::folded(set)
} else {
upper_folded(set)
}
}
fn sequence(&mut self) -> Result<(), &'static str> {
let mut atom = false;
while let Some(b) = self.byte(0) {
let now = match b {
b'\\' => self.escape()?,
b'[' => {
self.class()?;
Some(true)
}
b'(' => self.group()?,
b')' => self.close_group()?,
b'.' => {
if self.flags.s {
self.push("(?s:.)", 1);
} else {
self.push(&format!("[^{TERMINATORS}]"), 1);
}
Some(true)
}
b'|' => {
if let Some(open) = self.open.last_mut() {
open.branch += 1;
let frame = open.frame;
self.frames[frame].branches += 1;
}
self.push("|", 1);
Some(false)
}
b'^' => {
if self.flags.m {
self.need_backtracking(MULTILINE);
self.push(&format!(r"(?:\A|(?<=[{TERMINATORS}]))"), 1);
} else {
self.push(r"\A", 1);
}
Some(false)
}
b'$' => {
if self.flags.m {
self.need_backtracking(MULTILINE);
self.push(&format!(r"(?:\z|(?=[{TERMINATORS}]))"), 1);
} else {
self.push(r"\z", 1);
}
Some(false)
}
b'/' if self.literal_form => {
return Err(
"a / outside a class in a /source/flags literal, which ends \
the literal: write \\/",
);
}
b'*' | b'+' | b'?' if !atom => {
return Err(
"a quantifier with nothing before it to repeat, or after an \
anchor, lookaround or another quantifier",
);
}
b'*' | b'+' | b'?' => {
self.quantifier(1);
Some(false)
}
b'{' => match self.interval()? {
Some(()) if !atom => {
return Err("a quantifier with nothing before it to repeat, or after \
an anchor, lookaround or another quantifier");
}
Some(()) => Some(false),
None if self.flags.u => {
return Err("a lone { or } in a u-flag pattern, which JavaScript \
rejects: write \\{");
}
None => {
self.push("\\x{7B}", 1);
Some(true)
}
},
b'}' | b']' if self.flags.u => {
return Err("a lone { or } or ] in a u-flag pattern, which JavaScript \
rejects: write the escape");
}
_ => {
let c = self.rest().chars().next().unwrap_or_default();
let width = c.len_utf8();
let quantified = matches!(
self.src.as_bytes().get(self.at + width),
Some(b'*' | b'+' | b'?' | b'{')
);
self.push_char(c, quantified)?;
self.at += width;
Some(true)
}
};
if let Some(now) = now {
atom = now;
}
}
Ok(())
}
fn quantifier(&mut self, width: usize) {
let min0 = !matches!(self.byte(0), Some(b'+'));
self.note_quantified(min0);
let q = &self.rest()[..width];
self.push(q, width);
if self.byte(0) == Some(b'?') {
self.push("?", 1);
}
}
fn note_quantified(&mut self, min0: bool) {
if let Some(frame) = self.last_closed.take() {
self.frames[frame].optional |= min0;
}
}
fn interval(&mut self) -> Result<Option<()>, &'static str> {
let rest = self.rest().as_bytes();
let digits = |from: usize| {
rest[from..]
.iter()
.take_while(|d| d.is_ascii_digit())
.count()
};
let low = digits(1);
let mut end = 1 + low;
let mut high: Option<&[u8]> = None;
if low > 0 && rest.get(end) == Some(&b',') {
let n = digits(end + 1);
high = Some(&rest[end + 1..end + 1 + n]);
end += 1 + n;
}
if low == 0 || rest.get(end) != Some(&b'}') {
return Ok(None);
}
let number = |bytes: &[u8]| -> u32 {
std::str::from_utf8(bytes)
.ok()
.and_then(|t| t.parse().ok())
.unwrap_or(u32::MAX)
};
let (n, m) = (
number(&rest[1..=low]),
high.filter(|h| !h.is_empty()).map(number),
);
if n > INTERVAL_MAX || m.is_some_and(|m| m > INTERVAL_MAX) {
return Err("an interval count past 1000, which this dialect doesn't build");
}
if m.is_some_and(|m| m < n) {
return Err("an interval whose upper count is under its lower");
}
self.note_quantified(n == 0);
let interval = &self.rest()[..=end];
self.push(interval, end + 1);
if self.byte(0) == Some(b'?') {
self.push("?", 1);
}
Ok(Some(()))
}
fn group(&mut self) -> Result<Option<bool>, &'static str> {
if self.open.len() >= NEST_LIMIT {
return Err(TOO_DEEP);
}
let capture = self.byte(1) != Some(b'?')
|| (self.byte(2) == Some(b'<') && self.byte(3).is_some_and(|b| b != b'=' && b != b'!'));
if self.in_lookbehind() && capture {
return Err("a capture group in a lookbehind, which JavaScript matches backwards");
}
if self.byte(1) != Some(b'?') {
self.open_frame(true, Look::No);
self.push("(", 1);
return Ok(Some(false));
}
let (a, b) = (self.byte(2), self.byte(3));
let (text, width, look, why) = match (a, b) {
(Some(b':'), _) => ("(?:", 3, Look::No, None),
(Some(b'='), _) => ("(?=", 3, Look::Ahead, Some(LOOKAROUND)),
(Some(b'!'), _) => ("(?!", 3, Look::Ahead, Some(LOOKAROUND)),
(Some(b'<'), Some(b'=')) => ("(?<=", 4, Look::Behind, Some(LOOKAROUND)),
(Some(b'<'), Some(b'!')) => ("(?<!", 4, Look::Behind, Some(LOOKAROUND)),
(Some(b'<'), _) => return self.named(),
_ => {
return Err("a (? construct JavaScript's regex doesn't have, or a flag \
modifier (?i:...), which isn't read");
}
};
if let Some(why) = why {
self.need_backtracking(why);
}
let negative = text.ends_with('!');
self.open_frame(false, look);
if negative && let Some(open) = self.open.last() {
self.frames[open.frame].optional = true;
}
self.push(text, width);
Ok(Some(false))
}
fn open_frame(&mut self, capture: bool, look: Look) -> usize {
let around = self.open.iter().map(|o| (o.frame, o.branch)).collect();
let inside_negative = self
.open
.iter()
.any(|o| self.frames[o.frame].optional && o.look == Look::Ahead);
self.frames.push(Frame {
closed: false,
around,
branches: 1,
optional: inside_negative,
capture,
});
let frame = self.frames.len() - 1;
self.open.push(Open {
frame,
branch: 0,
look,
});
frame
}
fn named(&mut self) -> Result<Option<bool>, &'static str> {
let text = &self.rest()[3..];
let len = text
.bytes()
.take_while(|b| b.is_ascii_alphanumeric() || *b == b'_')
.count();
let name = &text[..len];
if name.is_empty()
|| name.as_bytes()[0].is_ascii_digit()
|| text.as_bytes().get(len) != Some(&b'>')
{
return Err(
"a JavaScript group name here is ASCII letters, digits and _, not \
starting with a digit, closed by >",
);
}
if self.names.iter().any(|(n, _)| *n == name) {
return Err(
"a group name used twice, which JavaScript allows only in separate \
alternatives of newer engines",
);
}
let frame = self.open_frame(true, Look::No);
self.names.push((name, frame));
let open = format!("(?<{name}>");
self.push(&open, 4 + len);
Ok(Some(false))
}
fn close_group(&mut self) -> Result<Option<bool>, &'static str> {
if self.open.len() <= 1 {
return Err("a ) with no ( before it");
}
let Some(open) = self.open.pop() else {
return Err("a ) with no ( before it");
};
self.frames[open.frame].closed = true;
self.last_closed = Some(open.frame);
self.push(")", 1);
Ok(Some(open.look == Look::No))
}
fn in_lookbehind(&self) -> bool {
self.open.iter().any(|o| o.look == Look::Behind)
}
fn escape(&mut self) -> Result<Option<bool>, &'static str> {
let Some(letter) = self.byte(1) else {
return Err("a pattern can't end in a backslash");
};
match letter {
b'd' | b'D' | b'w' | b'W' | b's' | b'S' => {
let set = self.class_set(letter);
self.push_set(set, false);
self.at += 2;
}
b'b' | b'B' => {
self.word_boundary(letter == b'B')?;
return Ok(Some(false));
}
b'p' | b'P' if self.flags.u => {
let set = self.property()?;
self.push_set(set, true);
}
b'1'..=b'9' => self.backreference()?,
b'k' => self.named_backreference()?,
_ => {
let (c, width) = self.escaped_char(false)?;
let quantified = matches!(
self.src.as_bytes().get(self.at + width),
Some(b'*' | b'+' | b'?' | b'{')
);
self.push_char(c, quantified)?;
self.at += width;
}
}
Ok(Some(true))
}
fn class_set(&self, letter: u8) -> Set {
let mut positive = match letter.to_ascii_lowercase() {
b'd' => charset::digits(),
b'w' => charset::word(),
_ => js_space(),
};
if letter.eq_ignore_ascii_case(&b'w') && self.flags.i && self.flags.u {
positive.union(&charset::set([
('\u{17F}', '\u{17F}'),
('\u{212A}', '\u{212A}'),
]));
}
if letter.is_ascii_uppercase() {
charset::negated(positive)
} else {
positive
}
}
fn word_boundary(&mut self, not: bool) -> Result<(), &'static str> {
if self.flags.i && self.flags.u {
return Err(
"\\b or \\B under the i and u flags, where the word characters also \
include U+017F and U+212A: drop one of the flags",
);
}
self.boundary = true;
let text = match (self.lookaround_boundary, not) {
(false, false) => r"(?-u:\b)",
(false, true) => r"(?-u:\B)",
(true, false) => dialect::WORD_BOUNDARY_LOOKAROUND,
(true, true) => dialect::NOT_WORD_BOUNDARY_LOOKAROUND,
};
self.push(text, 2);
Ok(())
}
fn property(&mut self) -> Result<Set, &'static str> {
let negated = self.byte(1) == Some(b'P');
if self.byte(2) != Some(b'{') {
return Err("a \\p with no braced name, which a u-flag pattern rejects");
}
let close = self.rest()[3..].find('}').ok_or("a \\p{ with no }")?;
let name = &self.rest()[3..3 + close];
let set = property_set(name)?;
self.at += 4 + close;
Ok(if negated { charset::negated(set) } else { set })
}
fn backreference(&mut self) -> Result<(), &'static str> {
let digits = self.rest().as_bytes()[1..]
.iter()
.take_while(|d| d.is_ascii_digit())
.count();
let number: usize = self.rest()[1..=digits].parse().unwrap_or(usize::MAX);
if number > self.total {
return Err(
"a backslash and digits that name no group, which JavaScript reads as \
an octal escape without the u flag and rejects with it",
);
}
self.reference(number - 1, 1 + digits)
}
fn named_backreference(&mut self) -> Result<(), &'static str> {
if self.names.is_empty() {
return Err(
"a \\k with no named group in the pattern, which JavaScript reads as \
the letter k without the u flag and rejects with it",
);
}
if self.byte(2) != Some(b'<') {
return Err("a \\k needs a group name in <>");
}
let text = &self.rest()[3..];
let close = text.find('>').ok_or("a \\k< with no >")?;
let name = &text[..close];
let Some(&(_, frame)) = self.names.iter().find(|(n, _)| *n == name) else {
return Err("a \\k<name> that names no group opened before it");
};
self.reference_text(frame, &format!(r"(?:\k<{name}>)"), 3 + close + 1)
}
fn reference(&mut self, index: usize, width: usize) -> Result<(), &'static str> {
let Some(frame) = self
.frames
.iter()
.enumerate()
.filter(|(_, f)| f.capture)
.nth(index)
.map(|(i, _)| i)
else {
return Err("a backreference to a group that isn't opened before it");
};
let number = index + 1;
self.reference_text(frame, &format!(r"(?:\{number})"), width)
}
fn reference_text(
&mut self,
frame: usize,
text: &str,
width: usize,
) -> Result<(), &'static str> {
if self.flags.i {
return Err(
"a backreference under the i flag, which JavaScript compares by case \
folding and the backtracking tier compares as written",
);
}
if self.in_lookbehind() || !self.certain(frame) {
return Err(
"a backreference to a group that may not have taken part, or inside a \
lookbehind, where JavaScript matches the empty string and the \
backtracking tier fails",
);
}
self.need_backtracking(BACKREFERENCE);
self.push(text, width);
Ok(())
}
fn certain(&self, frame: usize) -> bool {
let f = &self.frames[frame];
if !f.closed || f.optional {
return false;
}
f.around.iter().all(|&(id, branch)| {
let around = &self.frames[id];
self.open
.iter()
.find(|o| o.frame == id)
.map_or(around.branches == 1 && !around.optional, |open| {
open.branch == branch
})
})
}
fn escaped_char(&self, in_class: bool) -> Result<(char, usize), &'static str> {
let text = self.rest();
let b = text.as_bytes();
let letter = b[1];
let simple = match letter {
b't' => '\t',
b'n' => '\n',
b'r' => '\r',
b'f' => '\u{c}',
b'v' => '\u{b}',
b'0' if !b.get(2).is_some_and(u8::is_ascii_digit) => '\0',
b'0'..=b'9' => {
return Err(
"a legacy octal escape or a backslash and a digit, which a u-flag \
pattern rejects: write \\x.. or \\u....",
);
}
b'c' => {
return match b.get(2) {
Some(&x) if x.is_ascii_alphabetic() => Ok((char::from(x % 32), 3)),
_ => Err("JavaScript's \\c needs a letter after it"),
};
}
b'x' => return self.hex2(),
b'u' => return self.unicode_escape(),
_ if letter.is_ascii_alphanumeric() => {
return Err(
"a backslash before a letter JavaScript has no escape for, which \
it reads as the letter without the u flag and rejects with it",
);
}
_ => {
let c = text[1..].chars().next().unwrap_or_default();
let syntax = "^$\\.*+?()[]{}|/".contains(c) || (in_class && c == '-');
if self.flags.u && !syntax {
return Err(
"a backslash before a character a u-flag pattern doesn't allow \
escaped",
);
}
return Ok((c, 1 + c.len_utf8()));
}
};
Ok((simple, 2))
}
fn hex2(&self) -> Result<(char, usize), &'static str> {
let digits = self.rest().get(2..4).unwrap_or_default();
if digits.len() == 2 && digits.bytes().all(|d| d.is_ascii_hexdigit()) {
let value = u32::from_str_radix(digits, 16).unwrap_or(0);
return Ok((char::from_u32(value).unwrap_or_default(), 4));
}
Err("JavaScript's \\x needs two hex digits, and reads the letter x without them")
}
fn unicode_escape(&self) -> Result<(char, usize), &'static str> {
let text = self.rest();
let unit = |at: usize| {
text.get(at..at + 4)
.filter(|d| d.bytes().all(|x| x.is_ascii_hexdigit()))
.and_then(|d| u32::from_str_radix(d, 16).ok())
};
if text.as_bytes().get(2) == Some(&b'{') {
if !self.flags.u {
return Err("\\u{...} without the u flag, which JavaScript reads as u repeated");
}
let close = text[3..].find('}').ok_or("a \\u{ with no }")?;
let digits = &text[3..3 + close];
let value = (!digits.is_empty() && digits.bytes().all(|d| d.is_ascii_hexdigit()))
.then(|| u32::from_str_radix(digits, 16).ok())
.flatten()
.and_then(char::from_u32)
.ok_or("a \\u{...} that names no character")?;
return Ok((value, 4 + close));
}
let first = unit(2).ok_or("JavaScript's \\u needs four hex digits")?;
if let Some(c) = char::from_u32(first) {
return Ok((c, 6));
}
let low = (self.flags.u && text.get(6..8) == Some("\\u"))
.then(|| unit(8))
.flatten()
.filter(|low| (0xDC00..=0xDFFF).contains(low) && (0xD800..=0xDBFF).contains(&first));
match low {
Some(low) => {
let c = char::from_u32(0x10000 + ((first - 0xD800) << 10) + (low - 0xDC00))
.ok_or("a \\u surrogate pair that names no character")?;
Ok((c, 12))
}
None => Err(
"a \\u surrogate escape, which no UTF-8 text holds alone and which is \
read as one character only in a u-flag pattern",
),
}
}
fn class(&mut self) -> Result<(), &'static str> {
if self.open.len() >= NEST_LIMIT {
return Err(TOO_DEEP);
}
self.at += 1;
let negated = self.byte(0) == Some(b'^');
if negated {
self.at += 1;
}
let mut members = Set::empty();
let mut exact = Set::empty();
let mut after_set = false;
loop {
let Some(c) = self.rest().chars().next() else {
return Err("a [ with no ] to close it");
};
if c == ']' {
self.at += 1;
break;
}
let member = self.member(c)?;
match member {
Member::Set(set, true) => {
members.union(&set);
after_set = true;
}
Member::Set(set, false) => {
exact.union(&set);
after_set = true;
}
Member::Char(_) if c == '-' && after_set && self.byte(0) != Some(b']') => {
return Err("a - after a class such as \\d, which a u-flag pattern \
rejects and Annex B reads as a hyphen: escape it as \\-");
}
Member::Char(a) => {
let end = self.range_end(a)?;
members.union(&charset::set([(a, end)]));
after_set = false;
}
}
}
let mut set = self.folded(members);
set.union(&exact);
if negated {
set.negate();
}
if self.flags.i && self.flags.u {
self.out.push_str(&charset::render_exact(&set));
} else {
self.out.push_str(&charset::render(&set));
}
Ok(())
}
fn range_end(&mut self, a: char) -> Result<char, &'static str> {
if self.byte(0) != Some(b'-') || self.byte(1) == Some(b']') || self.byte(1).is_none() {
return Ok(a);
}
self.at += 1;
let Some(c) = self.rest().chars().next() else {
return Err("a [ with no ] to close it");
};
match self.member(c)? {
Member::Char(z) if z >= a => Ok(z),
Member::Char(_) => Err("a class range whose end comes before its start"),
Member::Set(..) => Err("a range whose end is a class such as \\d, which a u-flag \
pattern rejects and Annex B reads as a hyphen"),
}
}
fn member(&mut self, c: char) -> Result<Member, &'static str> {
if c != '\\' {
if !self.flags.u && u32::from(c) > 0xFFFF {
return Err(ASTRAL_IN_CLASS);
}
self.at += c.len_utf8();
return Ok(Member::Char(c));
}
let Some(letter) = self.byte(1) else {
return Err("a pattern can't end in a backslash");
};
match letter {
b'd' | b'D' | b'w' | b'W' | b's' | b'S' => {
self.at += 2;
Ok(Member::Set(self.class_set(letter), false))
}
b'b' => {
self.at += 2;
Ok(Member::Char('\u{8}'))
}
b'-' if self.flags.u => {
self.at += 2;
Ok(Member::Char('-'))
}
b'p' | b'P' if self.flags.u => self.property().map(|set| Member::Set(set, true)),
b'B' | b'k' | b'1'..=b'9' => Err("a \\B, \\k or backreference in a class, which a \
u-flag pattern rejects and Annex B reads \
differently"),
_ => {
let (c, width) = self.escaped_char(true)?;
if !self.flags.u && u32::from(c) > 0xFFFF {
return Err(ASTRAL_IN_CLASS);
}
self.at += width;
Ok(Member::Char(c))
}
}
}
}
const ASTRAL_QUANTIFIED: &str = "a character past U+FFFF before a quantifier without the u \
flag, which JavaScript reads as two units and repeats the second: add the u flag";
const ASTRAL_IN_CLASS: &str = "a character past U+FFFF in a class without the u flag, which \
JavaScript reads as two units: add the u flag";
fn canonical(c: char) -> char {
let mut up = c.to_uppercase();
let (Some(u), None) = (up.next(), up.next()) else {
return c;
};
if !c.is_ascii() && u.is_ascii() { c } else { u }
}
fn fold_index() -> &'static HashMap<char, usize> {
&fold_groups().0
}
fn fold_groups() -> &'static (HashMap<char, usize>, Vec<Vec<char>>) {
static GROUPS: OnceLock<(HashMap<char, usize>, Vec<Vec<char>>)> = OnceLock::new();
GROUPS.get_or_init(|| {
let mut by_canonical: HashMap<char, Vec<char>> = HashMap::new();
for c in '\0'..='\u{FFFF}' {
by_canonical.entry(canonical(c)).or_default().push(c);
}
let mut groups: Vec<Vec<char>> = by_canonical
.into_values()
.filter(|members| members.len() > 1)
.collect();
groups.sort();
let index = groups
.iter()
.enumerate()
.flat_map(|(i, members)| members.iter().map(move |c| (*c, i)))
.collect();
(index, groups)
})
}
fn upper_folded(mut set: Set) -> Set {
let has = |c: char| {
set.ranges()
.binary_search_by(|r| {
if r.end() < c {
std::cmp::Ordering::Less
} else if r.start() > c {
std::cmp::Ordering::Greater
} else {
std::cmp::Ordering::Equal
}
})
.is_ok()
};
let extra: Vec<char> = fold_groups()
.1
.iter()
.filter(|members| members.iter().any(|c| has(*c)))
.flatten()
.copied()
.collect();
for c in extra {
set.union(&charset::single(c));
}
set
}
fn js_space() -> Set {
charset::set([
('\t', '\r'),
(' ', ' '),
('\u{A0}', '\u{A0}'),
('\u{1680}', '\u{1680}'),
('\u{2000}', '\u{200A}'),
('\u{2028}', '\u{2029}'),
('\u{202F}', '\u{202F}'),
('\u{205F}', '\u{205F}'),
('\u{3000}', '\u{3000}'),
('\u{FEFF}', '\u{FEFF}'),
])
}
fn property_set(name: &str) -> Result<Set, &'static str> {
let unread = "a \\p{...} name outside the general categories, scripts and few binary \
properties the JavaScript dialect reads";
let canonical = match name.split_once('=') {
Some(("General_Category" | "gc", value)) if category(value) => value.to_owned(),
Some(("Script" | "sc", value)) if script(value) => format!("sc={value}"),
Some(("Script_Extensions" | "scx", value)) if script(value) => format!("scx={value}"),
Some(_) => return Err(unread),
None if category(name) => name.to_owned(),
None => match name {
"Any" => return Ok(charset::set([('\0', char::MAX)])),
"ASCII" => return Ok(charset::set([('\0', '\x7F')])),
"Alphabetic" | "Lowercase" | "Uppercase" | "White_Space" => name.to_owned(),
_ => return Err(unread),
},
};
charset::property(&canonical).ok_or(unread)
}
fn category(name: &str) -> bool {
(JAVA_CATEGORIES.contains(&name) && name != "Cs") || LONG_CATEGORIES.contains(&name)
}
const LONG_CATEGORIES: &[&str] = &[
"Letter",
"Cased_Letter",
"Uppercase_Letter",
"Lowercase_Letter",
"Titlecase_Letter",
"Modifier_Letter",
"Other_Letter",
"Mark",
"Nonspacing_Mark",
"Spacing_Mark",
"Enclosing_Mark",
"Number",
"Decimal_Number",
"Letter_Number",
"Other_Number",
"Punctuation",
"Connector_Punctuation",
"Dash_Punctuation",
"Open_Punctuation",
"Close_Punctuation",
"Initial_Punctuation",
"Final_Punctuation",
"Other_Punctuation",
"Symbol",
"Math_Symbol",
"Currency_Symbol",
"Modifier_Symbol",
"Other_Symbol",
"Separator",
"Space_Separator",
"Line_Separator",
"Paragraph_Separator",
"Other",
"Control",
"Format",
"Private_Use",
"Unassigned",
];
fn script(name: &str) -> bool {
JAVA_SCRIPTS.contains(&name)
}