use std::borrow::Cow;
use std::fmt::Write as _;
use super::ops::ReplaceError;
use regex_syntax::ast::{
self, AssertionKind, Ast, ClassAsciiKind, ClassBracketed, ClassSet, ClassSetItem,
ClassSetRange, ClassSetUnion, ClassUnicodeKind, Group, GroupKind, LiteralKind, Span,
};
use regex_syntax::hir::translate::TranslatorBuilder;
use regex_syntax::hir::{
Capture, Class, ClassBytes, ClassBytesRange, ClassUnicode, ClassUnicodeRange, Hir, HirKind,
Look, Repetition,
};
pub(super) const VERBOSE_REFUSED: &str =
"verbose mode (the x flag) is not supported with ascii_classes; drop the flag and its comments";
pub(super) const MULTILINE_END_REFUSED: &str = "a multi-line `$` can't be read as Java's, which also \
holds before \\r, U+0085, U+2028 and U+2029: drop the m flag, or build without java_line_end";
pub(super) const NOT_LAST_END_REFUSED: &str = "a `$` followed by more pattern that can match \
text or test a position can't be read at linear cost: end its branch with the \
`$`, or turn on backtracking (the strmatch-backtracking feature)";
#[cfg(feature = "strmatch-backtracking")]
pub(super) const VERBOSE_END_REFUSED: &str = "verbose mode (the x flag) is not supported with \
java_line_end on the backtracking tier: drop the flag and its comments";
#[cfg(feature = "strmatch-backtracking")]
pub(super) const VERBOSE_DOT_REFUSED: &str = "verbose mode (the x flag) is not supported with \
java_dot on the backtracking tier: drop the flag and its comments";
#[cfg(feature = "strmatch-backtracking")]
const JAVA_END_LOOKAHEAD: &str = r"(?:\z|(?=(?:\r\n|(?<!\r)\n|[\r\x{85}\x{2028}\x{2029}])\z))";
#[cfg(feature = "strmatch-backtracking")]
const LF_END_LOOKAHEAD: &str = r"(?:\z|(?=\n\z))";
pub(super) const WORD_BOUNDARY_LOOKAROUND: &str = r"(?:(?<=(?-i:[0-9A-Za-z_]))(?!(?-i:[0-9A-Za-z_]))|(?<!(?-i:[0-9A-Za-z_]))(?=(?-i:[0-9A-Za-z_])))";
pub(super) const NOT_WORD_BOUNDARY_LOOKAROUND: &str = r"(?:(?<=(?-i:[0-9A-Za-z_]))(?=(?-i:[0-9A-Za-z_]))|(?<!(?-i:[0-9A-Za-z_]))(?!(?-i:[0-9A-Za-z_])))";
pub(super) struct Read {
pub(super) text: String,
pub(super) backtrack: Option<&'static str>,
}
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
pub(super) enum Terminators {
#[default]
Java,
Lf,
}
impl Terminators {
#[inline]
pub(super) fn final_in(self, hay: &[u8]) -> Option<usize> {
match self {
Self::Java => final_terminator(hay),
Self::Lf => hay.ends_with(b"\n").then(|| hay.len() - 1),
}
}
}
#[cfg(feature = "strmatch-backtracking")]
const JAVA_DOT_CLASS: &str = r"[^\n\r\x{85}\x{2028}\x{2029}]";
const DOT_TERMINATORS: [char; 4] = ['\r', '\u{85}', '\u{2028}', '\u{2029}'];
pub(super) fn ascii_classes(pattern: &str) -> Result<Cow<'_, str>, &'static str> {
rewrite_text(pattern, |spot| match spot {
Spot::Escape(c, in_class) => Ok(ascii_set(c, in_class)),
Spot::Flags(on) if on.contains(&b'x') => Err(VERBOSE_REFUSED),
_ => Ok(None),
})
}
#[cfg(feature = "strmatch-backtracking")]
pub(super) fn java_line_ends_text(
pattern: &str,
terminators: Terminators,
) -> Result<Cow<'_, str>, &'static str> {
rewrite_text(pattern, |spot| match spot {
Spot::Dollar => Ok(Some(match terminators {
Terminators::Java => JAVA_END_LOOKAHEAD,
Terminators::Lf => LF_END_LOOKAHEAD,
})),
Spot::Flags(on) if on.contains(&b'x') => Err(VERBOSE_END_REFUSED),
Spot::Flags(on) if on.contains(&b'm') && terminators == Terminators::Java => {
Err(MULTILINE_END_REFUSED)
}
_ => Ok(None),
})
}
#[cfg(feature = "strmatch-backtracking")]
pub(super) fn java_dots_text(pattern: &str) -> Result<Cow<'_, str>, &'static str> {
rewrite_text(pattern, |spot| match spot {
Spot::Dot { dot_all: false } => Ok(Some(JAVA_DOT_CLASS)),
Spot::Flags(on) if on.contains(&b'x') => Err(VERBOSE_DOT_REFUSED),
_ => Ok(None),
})
}
enum Spot<'p> {
Escape(u8, bool),
Dollar,
Dot {
#[cfg_attr(
not(feature = "strmatch-backtracking"),
expect(dead_code, reason = "only the backtracking tier's rewrite reads it")
)]
dot_all: bool,
},
Flags(&'p [u8]),
}
fn rewrite_text<'p>(
pattern: &'p str,
mut edit: impl FnMut(Spot<'p>) -> Result<Option<&'static str>, &'static str>,
) -> Result<Cow<'p, str>, &'static str> {
let b = pattern.as_bytes();
let mut out = String::new();
let mut copied = 0;
let mut depth = 0_usize;
let mut dot_all = false;
let mut outer: Vec<bool> = Vec::new();
let mut i = 0;
while i < b.len() {
let (spot, width) = match b[i] {
b'\\' => {
let Some(&c) = b.get(i + 1) else { break };
(Some(Spot::Escape(c, depth > 0)), 2)
}
b'[' => {
depth += 1;
i += 1;
if b.get(i) == Some(&b'^') {
i += 1;
}
if b.get(i) == Some(&b']') {
i += 1;
}
continue;
}
b']' if depth > 0 => {
depth -= 1;
(None, 1)
}
b'(' if depth == 0 => {
outer.push(dot_all);
if b.get(i + 1) != Some(&b'?') {
i += 1;
continue;
}
let (on, off, rest) = flag_runs(&b[i + 2..]);
edit(Spot::Flags(on))?;
if on.contains(&b's') {
dot_all = true;
}
if off.contains(&b's') {
dot_all = false;
}
if rest.first() == Some(&b')') {
outer.pop();
(None, b.len() - i - rest.len() + 1)
} else {
(None, 2)
}
}
b')' if depth == 0 => {
if let Some(was) = outer.pop() {
dot_all = was;
}
(None, 1)
}
b'$' if depth == 0 => (Some(Spot::Dollar), 1),
b'.' if depth == 0 => (Some(Spot::Dot { dot_all }), 1),
_ => (None, 1),
};
if let Some(spot) = spot
&& let Some(with) = edit(spot)?
{
out.push_str(&pattern[copied..i]);
out.push_str(with);
copied = i + width;
}
i += width;
}
if copied == 0 {
return Ok(Cow::Borrowed(pattern));
}
out.push_str(&pattern[copied..]);
Ok(Cow::Owned(out))
}
fn flag_runs(text: &[u8]) -> (&[u8], &[u8], &[u8]) {
let letters = |t: &[u8]| t.iter().take_while(|f| f.is_ascii_alphabetic()).count();
let (on, rest) = text.split_at(letters(text));
match rest.split_first() {
Some((b'-', after)) => {
let (off, rest) = after.split_at(letters(after));
(on, off, rest)
}
_ => (on, &[], rest),
}
}
pub const fn ascii_set(letter: u8, in_class: bool) -> Option<&'static str> {
Some(match (letter, in_class) {
(b'd', false) => "[0-9]",
(b'd', true) => "0-9",
(b'w', false) => "[0-9A-Za-z_]",
(b'w', true) => "0-9A-Za-z_",
(b's', false) => r"[\t\n\x0B\x0C\r ]",
(b's', true) => r"\t\n\x0B\x0C\r ",
(b'D', _) => "[^0-9]",
(b'W', _) => "[^0-9A-Za-z_]",
(b'S', _) => r"[^\t\n\x0B\x0C\r ]",
_ => return None,
})
}
pub(super) fn parse(pattern: &str, reading: Reading) -> Result<Hir, Box<regex_syntax::Error>> {
read(pattern, reading, false)
}
#[derive(Debug, Clone, Copy)]
pub(super) struct Reading {
pub(super) fold: bool,
pub(super) java_dot: bool,
pub(super) terminators: Terminators,
pub(super) crlf: bool,
}
fn read(
pattern: &str,
reading: Reading,
mark_dollars: bool,
) -> Result<Hir, Box<regex_syntax::Error>> {
let mut ast = parse_ast(pattern)?;
if reading.fold {
fold_ast(&mut ast, pattern);
}
if reading.java_dot {
mark(&mut ast, DOT_MARK, &|a| matches!(a, Ast::Dot(_)));
}
if mark_dollars {
mark(
&mut ast,
MARK,
&|a| matches!(a, Ast::Assertion(x) if x.kind == AssertionKind::EndLine),
);
}
let hir = translate(pattern, &ast, reading.crlf)?;
if !reading.java_dot {
return Ok(hir);
}
Ok(rebuild(&hir, &|c, sub| {
if c.index == DOT_MARK {
java_dot(sub)
} else {
Hir::capture(Capture {
index: c.index,
name: c.name.clone(),
sub: Box::new(sub),
})
}
}))
}
fn java_dot(dot: Hir) -> Hir {
match dot.kind() {
HirKind::Class(Class::Unicode(set))
if !set
.ranges()
.iter()
.any(|r| r.start() <= '\n' && '\n' <= r.end()) =>
{
let mut set = set.clone();
set.difference(&ClassUnicode::new(
DOT_TERMINATORS.map(|c| ClassUnicodeRange::new(c, c)),
));
Hir::class(Class::Unicode(set))
}
HirKind::Class(Class::Bytes(set))
if !set
.ranges()
.iter()
.any(|r| r.start() <= b'\n' && b'\n' <= r.end()) =>
{
let mut set = set.clone();
set.difference(&ClassBytes::new([ClassBytesRange::new(b'\r', b'\r')]));
Hir::class(Class::Bytes(set))
}
_ => dot,
}
}
fn parse_ast(pattern: &str) -> Result<Ast, Box<regex_syntax::Error>> {
ast::parse::Parser::new()
.parse(pattern)
.map_err(|e| Box::new(e.into()))
}
fn translate(pattern: &str, ast: &Ast, crlf: bool) -> Result<Hir, Box<regex_syntax::Error>> {
TranslatorBuilder::new()
.utf8(false)
.crlf(crlf)
.build()
.translate(pattern, ast)
.map_err(|e| Box::new(e.into()))
}
const MARK: u32 = u32::MAX;
const DOT_MARK: u32 = u32::MAX - 1;
pub(super) enum EndRefusal {
Syntax(Box<regex_syntax::Error>),
NotLast,
Multiline,
}
pub(super) struct JavaEnds {
hir: Hir,
pub(super) terminators: Terminators,
pub(super) count: usize,
}
pub(super) fn java_line_ends(
pattern: &str,
reading: Reading,
) -> Result<Option<JavaEnds>, EndRefusal> {
let hir = read(pattern, reading, true).map_err(EndRefusal::Syntax)?;
let mut count = 0;
check_ends(&hir, false, &mut count)?;
Ok((count > 0).then_some(JavaEnds {
hir,
terminators: reading.terminators,
count,
}))
}
impl JavaEnds {
pub(super) fn rewrite(&self, marker: u32, keep_groups: bool) -> Hir {
rewrite_ends(&self.hir, marker, keep_groups, self.terminators)
}
}
fn mark(node: &mut Ast, index: u32, hit: &impl Fn(&Ast) -> bool) {
if hit(node) {
let span = *node.span();
let inner = std::mem::replace(node, Ast::empty(span));
*node = Ast::group(Group {
span,
kind: GroupKind::CaptureIndex(index),
ast: Box::new(inner),
});
return;
}
match node {
Ast::Repetition(r) => mark(&mut r.ast, index, hit),
Ast::Group(g) => mark(&mut g.ast, index, hit),
Ast::Alternation(a) => a.asts.iter_mut().for_each(|n| mark(n, index, hit)),
Ast::Concat(c) => c.asts.iter_mut().for_each(|n| mark(n, index, hit)),
_ => {}
}
}
fn rebuild(hir: &Hir, capture: &impl Fn(&Capture, Hir) -> Hir) -> Hir {
match hir.kind() {
HirKind::Capture(c) => capture(c, rebuild(&c.sub, capture)),
HirKind::Concat(parts) => Hir::concat(parts.iter().map(|p| rebuild(p, capture)).collect()),
HirKind::Alternation(branches) => {
Hir::alternation(branches.iter().map(|b| rebuild(b, capture)).collect())
}
HirKind::Repetition(r) => Hir::repetition(Repetition {
min: r.min,
max: r.max,
greedy: r.greedy,
sub: Box::new(rebuild(&r.sub, capture)),
}),
HirKind::Empty | HirKind::Literal(_) | HirKind::Class(_) | HirKind::Look(_) => hir.clone(),
}
}
fn check_ends(hir: &Hir, followed: bool, count: &mut usize) -> Result<(), EndRefusal> {
match hir.kind() {
HirKind::Capture(c) if c.index == MARK => match c.sub.kind() {
HirKind::Look(Look::End) if followed => Err(EndRefusal::NotLast),
HirKind::Look(Look::End) => {
*count += 1;
Ok(())
}
_ => Err(EndRefusal::Multiline),
},
HirKind::Capture(c) => check_ends(&c.sub, followed, count),
HirKind::Concat(parts) => {
let mut followed = followed;
for part in parts.iter().rev() {
check_ends(part, followed, count)?;
followed |= reads_on(part);
}
Ok(())
}
HirKind::Alternation(branches) => branches
.iter()
.try_for_each(|b| check_ends(b, followed, count)),
HirKind::Repetition(r) => {
let again = r.max.is_none_or(|max| max > 1) && reads_on(&r.sub);
check_ends(&r.sub, followed || again, count)
}
HirKind::Empty | HirKind::Literal(_) | HirKind::Class(_) | HirKind::Look(_) => Ok(()),
}
}
fn reads_on(hir: &Hir) -> bool {
hir.properties().maximum_len() != Some(0)
|| (!hir.properties().look_set().is_empty() && asserts(hir))
}
fn asserts(hir: &Hir) -> bool {
match hir.kind() {
HirKind::Look(_) => true,
HirKind::Capture(c) => c.index != MARK && asserts(&c.sub),
HirKind::Concat(parts) | HirKind::Alternation(parts) => parts.iter().any(asserts),
HirKind::Repetition(r) => asserts(&r.sub),
HirKind::Empty | HirKind::Literal(_) | HirKind::Class(_) => false,
}
}
fn rewrite_ends(hir: &Hir, marker: u32, keep: bool, terminators: Terminators) -> Hir {
rebuild(hir, &|c, sub| {
if c.index == MARK {
java_end(marker, terminators)
} else if keep {
Hir::capture(Capture {
index: c.index,
name: c.name.clone(),
sub: Box::new(sub),
})
} else {
sub
}
})
}
fn java_end(marker: u32, terminators: Terminators) -> Hir {
let terminator = match terminators {
Terminators::Java => Hir::alternation(vec![
Hir::literal(*b"\r\n"),
Hir::literal(*b"\r"),
Hir::concat(vec![Hir::look(Look::EndCRLF), Hir::literal(*b"\n")]),
Hir::literal("\u{85}".as_bytes()),
Hir::literal("\u{2028}".as_bytes()),
Hir::literal("\u{2029}".as_bytes()),
]),
Terminators::Lf => Hir::literal(*b"\n"),
};
let group = Hir::capture(Capture {
index: marker,
name: None,
sub: Box::new(terminator),
});
Hir::concat(vec![
Hir::repetition(Repetition {
min: 0,
max: Some(1),
greedy: true,
sub: Box::new(group),
}),
Hir::look(Look::End),
])
}
#[inline]
pub(super) fn final_terminator(hay: &[u8]) -> Option<usize> {
let n = hay.len();
match hay.last()? {
b'\n' if n >= 2 && hay[n - 2] == b'\r' => Some(n - 2),
b'\n' | b'\r' => Some(n - 1),
0x85 if hay[..n - 1].ends_with(&[0xC2]) => Some(n - 2),
0xA8 | 0xA9 if hay[..n - 1].ends_with(&[0xE2, 0x80]) => Some(n - 3),
_ => None,
}
}
fn fold_ast(node: &mut Ast, pattern: &str) {
match node {
Ast::Literal(lit) if lit.c.is_ascii_alphabetic() => {
let span = lit.span;
*node = Ast::class_bracketed(ClassBracketed {
span,
negated: false,
kind: ClassSet::Item(both_cases(lit)),
});
}
Ast::ClassBracketed(class) => fold_set(&mut class.kind, pattern),
Ast::ClassUnicode(class) => {
if let Some(folded) = fold_unicode(class, pattern) {
*node = Ast::class_bracketed(folded);
}
}
Ast::Repetition(r) => fold_ast(&mut r.ast, pattern),
Ast::Group(g) => fold_ast(&mut g.ast, pattern),
Ast::Alternation(a) => a.asts.iter_mut().for_each(|n| fold_ast(n, pattern)),
Ast::Concat(c) => c.asts.iter_mut().for_each(|n| fold_ast(n, pattern)),
_ => {}
}
}
fn fold_set(set: &mut ClassSet, pattern: &str) {
match set {
ClassSet::Item(item) => fold_item(item, pattern),
ClassSet::BinaryOp(op) => {
fold_set(&mut op.lhs, pattern);
fold_set(&mut op.rhs, pattern);
}
}
}
fn fold_item(item: &mut ClassSetItem, pattern: &str) {
match item {
ClassSetItem::Literal(lit) if lit.c.is_ascii_alphabetic() => {
*item = both_cases(lit);
}
ClassSetItem::Range(range) => {
let extra: Vec<ClassSetItem> =
other_case(u32::from(range.start.c), u32::from(range.end.c))
.map(|(a, z)| range_item(range.span, a, z))
.collect();
if !extra.is_empty() {
let mut items = vec![ClassSetItem::Range(range.clone())];
items.extend(extra);
*item = ClassSetItem::Union(ClassSetUnion {
span: range.span,
items,
});
}
}
ClassSetItem::Ascii(ascii) => {
if matches!(ascii.kind, ClassAsciiKind::Upper | ClassAsciiKind::Lower) {
ascii.kind = ClassAsciiKind::Alpha;
}
}
ClassSetItem::Unicode(class) => {
if let Some(folded) = fold_unicode(class, pattern) {
*item = ClassSetItem::Bracketed(Box::new(folded));
}
}
ClassSetItem::Bracketed(class) => fold_set(&mut class.kind, pattern),
ClassSetItem::Union(union) => union.items.iter_mut().for_each(|i| fold_item(i, pattern)),
_ => {}
}
}
fn both_cases(lit: &ast::Literal) -> ClassSetItem {
let mut other = lit.clone();
other.kind = LiteralKind::Verbatim;
other.c = if lit.c.is_ascii_lowercase() {
lit.c.to_ascii_uppercase()
} else {
lit.c.to_ascii_lowercase()
};
ClassSetItem::Union(ClassSetUnion {
span: lit.span,
items: vec![
ClassSetItem::Literal(lit.clone()),
ClassSetItem::Literal(other),
],
})
}
fn range_item(span: Span, a: u8, z: u8) -> ClassSetItem {
let literal = |c: u8| ast::Literal {
span,
kind: LiteralKind::Verbatim,
c: char::from(c),
};
ClassSetItem::Range(ClassSetRange {
span,
start: literal(a),
end: literal(z),
})
}
fn fold_unicode(class: &ast::ClassUnicode, pattern: &str) -> Option<ClassBracketed> {
let mut positive = class.clone();
positive.negated = false;
if matches!(
positive.kind,
ClassUnicodeKind::NamedValue {
op: ast::ClassUnicodeOpKind::NotEqual,
..
}
) {
return None;
}
let text = &pattern[class.span.start.offset..class.span.end.offset];
let parsed = regex_syntax::ParserBuilder::new()
.build()
.parse(text)
.ok()?;
let HirKind::Class(Class::Unicode(mut set)) = parsed.into_kind() else {
return None;
};
if class.negated {
set.negate();
}
let extra: Vec<ClassSetItem> = set
.iter()
.flat_map(|r| other_case(u32::from(r.start()), u32::from(r.end())))
.map(|(a, z)| range_item(class.span, a, z))
.collect();
if extra.is_empty() {
return None;
}
let mut items = vec![ClassSetItem::Unicode(positive)];
items.extend(extra);
Some(ClassBracketed {
span: class.span,
negated: class.negated,
kind: ClassSet::Item(ClassSetItem::Union(ClassSetUnion {
span: class.span,
items,
})),
})
}
fn other_case(lo: u32, hi: u32) -> impl Iterator<Item = (u8, u8)> {
[
(u32::from(b'a'), u32::from(b'z')),
(u32::from(b'A'), u32::from(b'Z')),
]
.into_iter()
.filter_map(move |(a, z)| {
let (from, to) = (lo.max(a), hi.min(z));
let from = u8::try_from(from).ok()?;
let to = u8::try_from(to).ok()?;
(from <= to).then_some((from ^ 0x20, to ^ 0x20))
})
}
pub(super) fn java_replacement(text: &[u8], group_len: usize) -> Vec<u8> {
let mut out: Vec<u8> = Vec::with_capacity(text.len() + 8);
let mut i = 0;
while i < text.len() {
match text[i] {
b'\\' => {
match text.get(i + 1) {
Some(b'$') => out.extend_from_slice(b"$$"),
Some(&c) => out.push(c),
None => out.push(b'\\'),
}
i += 2;
}
b'$' => i = java_reference(text, i + 1, group_len, &mut out),
c => {
out.push(c);
i += 1;
}
}
}
out
}
pub(super) fn java_replacement_check(
text: &[u8],
group_len: usize,
named: impl Fn(&str) -> bool,
) -> Result<(), ReplaceError> {
let mut i = 0;
while i < text.len() {
i = match text[i] {
b'\\' if i + 1 == text.len() => return Err(ReplaceError::TrailingBackslash { at: i }),
b'\\' => i + 2,
b'$' => java_reference_check(text, i, group_len, &named)?,
_ => i + 1,
};
}
Ok(())
}
fn java_reference_check(
text: &[u8],
at: usize,
group_len: usize,
named: &impl Fn(&str) -> bool,
) -> Result<usize, ReplaceError> {
match text.get(at + 1) {
None => Err(ReplaceError::MissingGroup { at }),
Some(d) if d.is_ascii_digit() => {
let number = usize::from(d - b'0');
if number < group_len {
Ok(at + 2)
} else {
Err(ReplaceError::NoGroup { number, at })
}
}
Some(b'{') => {
let name = &text[at + 2..];
let name = &name[..name
.iter()
.take_while(|c| c.is_ascii_alphanumeric())
.count()];
let close = at + 2 + name.len();
if !name.first().is_some_and(u8::is_ascii_alphabetic) || text.get(close) != Some(&b'}')
{
return Err(ReplaceError::BadName { at });
}
let name = String::from_utf8_lossy(name);
if named(&name) {
Ok(close + 1)
} else {
Err(ReplaceError::NoGroupNamed {
name: name.into_owned(),
at,
})
}
}
Some(_) => Err(ReplaceError::IllegalReference { at }),
}
}
fn java_reference(text: &[u8], at: usize, group_len: usize, out: &mut Vec<u8>) -> usize {
match text.get(at) {
Some(d) if d.is_ascii_digit() => {
let mut number = usize::from(d - b'0');
let mut end = at + 1;
while let Some(next) = text.get(end).filter(|c| c.is_ascii_digit()) {
let longer = number * 10 + usize::from(next - b'0');
if longer >= group_len {
break;
}
number = longer;
end += 1;
}
out.extend_from_slice(b"${");
out.extend_from_slice(&text[at..end]);
out.push(b'}');
end
}
Some(b'{') => {
let name_len = text[at + 1..]
.iter()
.take_while(|c| c.is_ascii_alphanumeric() || **c == b'_')
.count();
let close = at + 1 + name_len;
if name_len > 0 && text.get(close) == Some(&b'}') {
out.extend_from_slice(&text[at - 1..=close]);
close + 1
} else {
out.extend_from_slice(b"$$");
at
}
}
_ => {
out.extend_from_slice(b"$$");
at
}
}
}
const JAVA_H: &str = r"\x20\t\xA0\x{1680}\x{180E}\x{2000}-\x{200A}\x{202F}\x{205F}\x{3000}";
const JAVA_V: &str = r"\n\x0B\f\r\x85\x{2028}\x{2029}";
const JAVA_LINEBREAK: &str = r"(?:\r\n|[\n\x0B\f\r\x85\x{2028}\x{2029}])";
const JAVA_POSIX: [(&str, &str); 13] = [
("Lower", "lower"),
("Upper", "upper"),
("ASCII", "ascii"),
("Alpha", "alpha"),
("Digit", "digit"),
("Alnum", "alnum"),
("Punct", "punct"),
("Graph", "graph"),
("Print", "print"),
("Blank", "blank"),
("Cntrl", "cntrl"),
("XDigit", "xdigit"),
("Space", "space"),
];
pub(super) const JAVA_CATEGORIES: &[&str] = &[
"L", "Lu", "Ll", "Lt", "Lm", "Lo", "M", "Mn", "Mc", "Me", "N", "Nd", "Nl", "No", "P", "Pc",
"Pd", "Ps", "Pe", "Pi", "Pf", "Po", "S", "Sm", "Sc", "Sk", "So", "Z", "Zs", "Zl", "Zp", "C",
"Cc", "Cf", "Co", "Cn",
];
pub(super) const JAVA_SCRIPTS: &[&str] = &[
"Arabic",
"Armenian",
"Bengali",
"Bopomofo",
"Cherokee",
"Common",
"Cyrillic",
"Devanagari",
"Ethiopic",
"Georgian",
"Greek",
"Gujarati",
"Gurmukhi",
"Han",
"Hangul",
"Hebrew",
"Hiragana",
"Inherited",
"Kannada",
"Katakana",
"Khmer",
"Lao",
"Latin",
"Malayalam",
"Mongolian",
"Myanmar",
"Oriya",
"Sinhala",
"Syriac",
"Tamil",
"Telugu",
"Thaana",
"Thai",
"Tibetan",
"Yi",
];
const FOLD_PROPERTY: &str = "under Java's (?i) a \\p{...} class takes the other cases of its \
members, which isn't read: drop the (?i) or the \\p{...}";
pub(super) const NEST_LIMIT: usize = 128;
pub(super) const TOO_DEEP: &str = "groups and classes nested more than 128 deep";
pub(super) const LINEBREAK_REPEATED: &str = "a repeated Java \\R, alone or in a group, which never \
gives back the \\n of a \\r\\n it took";
pub(super) const EMPTY_RETRY: &str = "a pattern that can match empty and has a lazy repeat or \
an alternation with an empty branch before another, where PCRE2 and Python look for a \
non-empty match at the place an empty one was found: make the pattern need at least one \
character";
pub(super) fn empty_retry(hir: &Hir) -> bool {
let reads = |h: &Hir| h.properties().maximum_len() != Some(0);
match hir.kind() {
HirKind::Repetition(r) => (!r.greedy && r.min == 0 && reads(&r.sub)) || empty_retry(&r.sub),
HirKind::Alternation(branches) => {
let empty_then_reads = branches.iter().enumerate().any(|(i, b)| {
b.properties().minimum_len() == Some(0) && branches[i + 1..].iter().any(reads)
});
empty_then_reads || branches.iter().any(empty_retry)
}
HirKind::Capture(c) => empty_retry(&c.sub),
HirKind::Concat(parts) => parts.iter().any(empty_retry),
HirKind::Empty | HirKind::Literal(_) | HirKind::Class(_) | HirKind::Look(_) => false,
}
}
pub(super) const POSSESSIVE: &str = "a possessive quantifier, *+ ++ ?+ or {n,m}+, runs only on the \
backtracking tier: turn on StrMatcherBuilder::backtracking (the strmatch-backtracking \
feature)";
pub(super) const ATOMIC: &str = "an atomic group, (?>...), runs only on the backtracking tier: turn on \
StrMatcherBuilder::backtracking (the strmatch-backtracking feature)";
pub(super) const LOOKAROUND: &str = "lookaround, (?=...) (?!...) (?<=...) (?<!...), runs only on the \
backtracking tier: turn on StrMatcherBuilder::backtracking (the strmatch-backtracking \
feature)";
pub(super) const BACKREFERENCE: &str = "a backreference, \\1 or \\k<name>, runs only on the backtracking \
tier: turn on StrMatcherBuilder::backtracking (the strmatch-backtracking feature)";
pub(super) struct JavaPattern {
pub(super) text: String,
pub(super) fold: bool,
pub(super) backtrack: Option<&'static str>,
}
pub(super) fn java_syntax(pattern: &str) -> Result<JavaPattern, &'static str> {
if pattern.starts_with("(?iu)") || pattern.starts_with("(?ui)") {
return Err(
"Java's (?iu) folds case by Java's own Unicode rules, which aren't read: \
drop the u, or the flag",
);
}
let (body, fold) = pattern
.strip_prefix("(?i)")
.map_or((pattern, false), |rest| (rest, true));
let mut java = read_java(body, false)?;
if java.backtrack.is_some() && java.boundary {
java = read_java(body, true)?;
}
if fold && java.property {
return Err(FOLD_PROPERTY);
}
Ok(JavaPattern {
text: java.out,
fold,
backtrack: java.backtrack,
})
}
fn read_java(body: &str, lookaround_boundary: bool) -> Result<Java<'_>, &'static str> {
let mut java = Java {
src: body,
at: 0,
out: String::with_capacity(body.len() + 16),
groups: 0,
backtrack: None,
property: false,
names: Vec::new(),
depth: 0,
linebreaks: Vec::new(),
lookaround_boundary,
boundary: false,
};
java.sequence()?;
Ok(java)
}
struct Java<'p> {
src: &'p str,
at: usize,
out: String,
groups: usize,
backtrack: Option<&'static str>,
property: bool,
names: Vec<&'p str>,
depth: usize,
linebreaks: Vec<bool>,
lookaround_boundary: bool,
boundary: bool,
}
#[derive(Clone, Copy, PartialEq, Eq)]
enum Item {
Start,
Char,
Range,
Set,
And,
}
impl<'p> Java<'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 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()?;
Some(false)
}
b')' => {
self.close_group()?;
Some(true)
}
b'.' => {
self.push(".", 1);
Some(true)
}
b'|' | b'^' | b'$' => {
let src = self.src;
self.push(&src[self.at..=self.at], 1);
Some(false)
}
b'*' | b'+' | b'?' | b'{' if !atom => {
return Err(
"a quantifier with nothing before it to repeat, or after an \
anchor or another quantifier",
);
}
b'*' | b'+' | b'?' | b'{' => {
self.quantifier()?;
Some(false)
}
_ => {
let c = self.rest().chars().next().unwrap_or_default();
literal(c, &mut self.out);
self.at += c.len_utf8();
Some(true)
}
};
if let Some(now) = now {
atom = now;
}
}
Ok(())
}
fn quantifier(&mut self) -> Result<(), &'static str> {
if self.byte(0) == Some(b'{') {
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;
if rest.get(end) == Some(&b',') {
end += 1 + digits(end + 1);
}
if low == 0 || rest.get(end) != Some(&b'}') {
return Err(
"a { that isn't a Java interval {n}, {n,} or {n,m}: write \\{ for the \
brace",
);
}
let interval = &self.rest()[..=end];
self.push(interval, end + 1);
} else {
let q = &self.rest()[..1];
self.push(q, 1);
}
match self.byte(0) {
Some(b'?') => self.push("?", 1),
Some(b'+') => {
self.backtrack = Some(POSSESSIVE);
self.push("+", 1);
}
_ => {}
}
Ok(())
}
fn group(&mut self) -> Result<(), &'static str> {
self.enter()?;
self.linebreaks.push(false);
if self.byte(1) != Some(b'?') {
self.groups += 1;
self.push("(", 1);
return Ok(());
}
match (self.byte(2), self.byte(3)) {
(Some(b':'), _) => self.push("(?:", 3),
(Some(b'='), _) => self.backtracking("(?=", 3, LOOKAROUND),
(Some(b'!'), _) => self.backtracking("(?!", 3, LOOKAROUND),
(Some(b'>'), _) => self.backtracking("(?>", 3, ATOMIC),
(Some(b'<'), Some(b'=')) => self.backtracking("(?<=", 4, LOOKAROUND),
(Some(b'<'), Some(b'!')) => self.backtracking("(?<!", 4, LOOKAROUND),
(Some(b'<'), _) => {
let name = group_name(&self.rest()[3..])?;
if self.names.contains(&name) {
return Err("a group name used twice, which Java rejects");
}
self.names.push(name);
let open = format!("(?<{name}>");
self.groups += 1;
self.push(&open, 4 + name.len());
}
(Some(b'P'), _) => {
return Err("Java names a group (?<name>...), and has no (?P<name>...)");
}
_ => self.flags()?,
}
Ok(())
}
fn backtracking(&mut self, text: &str, width: usize, why: &'static str) {
self.backtrack = Some(why);
self.push(text, width);
}
fn flags(&mut self) -> Result<(), &'static str> {
let (on, off, rest) = flag_runs(&self.rest().as_bytes()[2..]);
if let Some(hint) = [on, off].iter().find_map(|f| java_flag_refusal(f)) {
return Err(hint);
}
let close = match rest.first() {
Some(b')' | b':') if !on.is_empty() || !off.is_empty() => rest[0],
_ => return Err("a (? construct Java's regex doesn't have"),
};
let width = self.rest().len() - rest.len() + 1;
if close == b')' {
self.depth -= 1;
self.linebreaks.pop();
}
let text = format!(
"(?{}{}{}{}",
String::from_utf8_lossy(on),
if off.is_empty() { "" } else { "-" },
String::from_utf8_lossy(off),
char::from(close),
);
self.push(&text, width);
Ok(())
}
fn escape(&mut self) -> Result<Option<bool>, &'static str> {
if let Some((c, width)) = escaped_char(self.rest())? {
literal(c, &mut self.out);
self.at += width;
return Ok(Some(true));
}
let Some(letter) = self.byte(1) else {
return Err("a pattern can't end in a backslash");
};
match letter {
b'Q' => return Ok(self.quote().then_some(true)),
b'E' => {
self.at += 2;
return Ok(None);
}
b'd' | b'D' | b'w' | b'W' | b's' | b'S' => {
let class = &self.rest()[..2];
self.push(class, 2);
}
b'h' | b'H' | b'v' | b'V' => self.space(letter),
b'R' if self.quantified(2) => return Err(LINEBREAK_REPEATED),
b'R' => {
if let Some(last) = self.linebreaks.last_mut() {
*last = true;
}
self.push(JAVA_LINEBREAK, 2);
}
b'p' | b'P' => self.property(false)?,
b'1'..=b'9' => self.backreference(),
b'k' => self.named_backreference()?,
_ => return self.anchor(letter).map(|()| Some(false)),
}
Ok(Some(true))
}
fn anchor(&mut self, letter: u8) -> Result<(), &'static str> {
match letter {
b'A' => self.push(r"\A", 2),
b'z' => self.push(r"\z", 2),
b'Z' => self.push("$", 2),
b'b' | b'B' if self.byte(2) == Some(b'{') => {
return Err("Java's \\b{g} grapheme boundary isn't read");
}
b'b' | b'B' => {
self.boundary = true;
let text = match (self.lookaround_boundary, letter) {
(false, b'b') => r"(?-u:\b)",
(false, _) => r"(?-u:\B)",
(true, b'b') => WORD_BOUNDARY_LOOKAROUND,
(true, _) => NOT_WORD_BOUNDARY_LOOKAROUND,
};
self.push(text, 2);
}
b'G' => return Err("Java's \\G, the end of the last match, isn't read"),
b'X' => return Err("Java's \\X grapheme cluster isn't read"),
b'N' => return Err("Java's \\N{name} named character isn't read"),
_ => {
return Err(
"a backslash before a letter or digit Java's regex has no escape \
for, or one this dialect doesn't read",
);
}
}
Ok(())
}
fn space(&mut self, letter: u8) {
let set = if matches!(letter, b'h' | b'H') {
JAVA_H
} else {
JAVA_V
};
let caret = if letter.is_ascii_uppercase() { "^" } else { "" };
let class = format!("[{caret}{set}]");
self.push(&class, 2);
}
fn quote(&mut self) -> bool {
let text = &self.src[self.at + 2..];
let end = text.find("\\E").unwrap_or(text.len());
let quoted = &text[..end];
for c in quoted.chars() {
literal(c, &mut self.out);
}
let wrote = !quoted.is_empty();
self.at += 2 + end + if end < text.len() { 2 } else { 0 };
wrote
}
fn property(&mut self, in_class: bool) -> Result<(), &'static str> {
let negated = self.byte(1) == Some(b'P');
let (name, width) = if self.byte(2) == Some(b'{') {
let close = self.rest()[3..].find('}').ok_or("a \\p{ with no }")?;
(&self.rest()[3..3 + close], 4 + close)
} else {
match self.byte(2) {
Some(c) if c.is_ascii_alphabetic() => (&self.rest()[2..3], 3),
_ => return Err("a \\p with no name after it"),
}
};
let class = java_property(name, negated, in_class)?;
self.property = true;
self.push(&class, width);
Ok(())
}
fn backreference(&mut self) {
let digits = self.rest().as_bytes()[1..]
.iter()
.take_while(|d| d.is_ascii_digit())
.count();
let mut number = usize::from(self.rest().as_bytes()[1] - b'0');
let mut len = 1;
while len < digits {
let longer = number * 10 + usize::from(self.rest().as_bytes()[1 + len] - b'0');
if longer > self.groups {
break;
}
number = longer;
len += 1;
}
let text = format!(r"(?:\{number})");
self.backtrack = Some(BACKREFERENCE);
self.push(&text, 1 + len);
}
fn named_backreference(&mut self) -> Result<(), &'static str> {
if self.byte(2) != Some(b'<') {
return Err("Java's \\k needs a group name in <>");
}
let name = group_name(&self.rest()[3..])?;
let text = format!(r"(?:\k<{name}>)");
self.backtrack = Some(BACKREFERENCE);
self.push(&text, 4 + name.len());
Ok(())
}
fn class(&mut self) -> Result<(), &'static str> {
self.enter()?;
self.at += 1;
let negated = self.byte(0) == Some(b'^');
if negated {
self.at += 1;
}
self.out.push_str(if negated { "[^" } else { "[" });
let mut last = Item::Start;
loop {
let Some(b) = self.byte(0) else {
return Err("a [ with no ] to close it");
};
last = match b {
b']' if last != Item::Start => break,
b'[' if negated => {
return Err("a class nested in a negated class, which Java reads \
differently: write the negation inside the nested class");
}
b'[' => {
self.class()?;
Item::Set
}
b'&' if self.byte(1) == Some(b'&') => self.and(last, negated)?,
b'~' if self.byte(1) == Some(b'~') => {
return Err("~~ in a class, which the regex crate reads as symmetric \
difference: escape the ~");
}
b'-' if last != Item::Start && self.byte(1) != Some(b']') => {
return Err(
"a - in a class after a range, a class or &&, which Java and \
the regex crate read differently: escape it as \\-",
);
}
b'\\' => self.class_escape()?,
_ => {
let c = self.rest().chars().next().unwrap_or_default();
self.at += c.len_utf8();
self.class_char(c)?
}
};
}
self.depth -= 1;
self.push("]", 1);
Ok(())
}
fn quantified(&self, ahead: usize) -> bool {
matches!(self.byte(ahead), Some(b'*' | b'+' | b'?' | b'{'))
}
fn close_group(&mut self) -> Result<(), &'static str> {
self.depth = self.depth.saturating_sub(1);
let linebreak = self.linebreaks.pop().unwrap_or(false);
if linebreak && self.quantified(1) {
return Err(LINEBREAK_REPEATED);
}
if linebreak && let Some(outer) = self.linebreaks.last_mut() {
*outer = true;
}
self.push(")", 1);
Ok(())
}
const fn enter(&mut self) -> Result<(), &'static str> {
self.depth += 1;
if self.depth > NEST_LIMIT {
return Err(TOO_DEEP);
}
Ok(())
}
fn and(&mut self, last: Item, negated: bool) -> Result<Item, &'static str> {
if matches!(last, Item::Start | Item::And) || self.byte(2) == Some(b']') {
return Err("an && with no class on one side, which Java reads loosely");
}
if negated {
return Err("an && in a negated class, which Java reads differently");
}
self.push("&&", 2);
Ok(Item::And)
}
fn class_escape(&mut self) -> Result<Item, &'static str> {
if let Some((c, width)) = escaped_char(self.rest())? {
self.at += width;
return self.class_char(c);
}
let Some(letter) = self.byte(1) else {
return Err("a pattern can't end in a backslash");
};
match letter {
b'Q' => {
self.quote();
if self.byte(0) == Some(b'-') && self.byte(1) != Some(b']') {
return Err("a range from a \\Q...\\E quote, which isn't read");
}
return Ok(Item::Char);
}
b'E' => {
self.at += 2;
return Ok(Item::Char);
}
b'd' | b'D' | b'w' | b'W' | b's' | b'S' => {
let class = &self.rest()[..2];
self.push(class, 2);
}
b'h' | b'H' | b'v' | b'V' => self.space(letter),
b'p' | b'P' => self.property(true)?,
_ => {
return Err(
"an escape Java doesn't read in a class, such as \\R, \\Z, \\b or \
a backreference",
);
}
}
if self.byte(0) == Some(b'-') && self.byte(1) != Some(b']') {
return Err(
"a class escape such as \\v or \\h as a range end, which Java reads \
as a single character",
);
}
Ok(Item::Set)
}
fn class_char(&mut self, c: char) -> Result<Item, &'static str> {
literal(c, &mut self.out);
let next = match (self.byte(0), self.byte(1)) {
(Some(b'-'), Some(next)) if next != b']' => next,
_ => return Ok(Item::Char),
};
let end = match next {
b'-' => return Err("-- in a class, which the regex crate reads as set difference"),
b'[' => return Err("a - before a nested class, which Java reads as a literal"),
b'\\' => {
let Some((end, width)) = escaped_char(&self.rest()[1..])? else {
return Err(
"a class escape such as \\v or \\h as a range end, which Java \
reads as a single character",
);
};
self.at += 1 + width;
end
}
_ => {
let end = self.rest()[1..].chars().next().unwrap_or_default();
self.at += 1 + end.len_utf8();
end
}
};
self.out.push('-');
literal(end, &mut self.out);
Ok(Item::Range)
}
}
fn group_name(text: &str) -> Result<&str, &'static str> {
let len = text.bytes().take_while(u8::is_ascii_alphanumeric).count();
let name = &text[..len];
if !name.starts_with(|c: char| c.is_ascii_alphabetic())
|| text.as_bytes().get(len) != Some(&b'>')
{
return Err("a Java group name is an ASCII letter then letters and digits, closed by >");
}
Ok(name)
}
fn escaped_char(text: &str) -> Result<Option<(char, usize)>, &'static str> {
let b = text.as_bytes();
let Some(&letter) = b.get(1) else {
return Ok(None);
};
let simple = match letter {
b't' => '\t',
b'n' => '\n',
b'r' => '\r',
b'f' => '\u{c}',
b'a' => '\u{7}',
b'e' => '\u{1b}',
b'x' => return hex_escape(text).map(Some),
b'u' => return unicode_escape(text).map(Some),
b'0' => return octal_escape(b).map(Some),
b'c' => {
return match b.get(2) {
Some(&x) if x.is_ascii() => Ok(Some((char::from(x ^ 0x40), 3))),
_ => Err("Java's \\c needs an ASCII character after it"),
};
}
_ if letter.is_ascii_alphanumeric() => return Ok(None),
_ => {
let c = text[1..].chars().next().unwrap_or_default();
return Ok(Some((c, 1 + c.len_utf8())));
}
};
Ok(Some((simple, 2)))
}
fn hex_escape(text: &str) -> Result<(char, usize), &'static str> {
let b = text.as_bytes();
let (digits, width) = if b.get(2) == Some(&b'{') {
let close = text[3..].find('}').ok_or("a \\x{ with no }")?;
(&text[3..3 + close], 4 + close)
} else {
(text.get(2..4).unwrap_or_default(), 4)
};
let valid = !digits.is_empty() && digits.bytes().all(|d| d.is_ascii_hexdigit());
let value = if valid {
u32::from_str_radix(digits, 16).ok()
} else {
None
};
let c = value
.and_then(char::from_u32)
.ok_or("Java's \\x needs two hex digits, or hex digits naming a character in {}")?;
Ok((c, width))
}
fn unicode_escape(text: &str) -> Result<(char, usize), &'static str> {
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())
};
let first = unit(2).ok_or("Java's \\u needs four hex digits")?;
if let Some(c) = char::from_u32(first) {
return Ok((c, 6));
}
let low = text
.get(6..8)
.filter(|u| *u == "\\u")
.and_then(|_| unit(8))
.filter(|low| (0xDC00..=0xDFFF).contains(low));
match low {
Some(low) if (0xD800..=0xDBFF).contains(&first) => {
let c = char::from_u32(0x10000 + ((first - 0xD800) << 10) + (low - 0xDC00))
.ok_or("a \\u surrogate pair that names no character")?;
Ok((c, 12))
}
_ => Err("a \\u surrogate without its other half"),
}
}
fn octal_escape(b: &[u8]) -> Result<(char, usize), &'static str> {
let octal = |at: usize| b.get(at).filter(|d| (b'0'..=b'7').contains(*d)).copied();
let Some(first) = octal(2) else {
return Err("Java's \\0 needs an octal digit after it");
};
let mut value = u32::from(first - b'0');
let mut len = 1;
if let Some(second) = octal(3) {
value = value * 8 + u32::from(second - b'0');
len = 2;
if first <= b'3'
&& let Some(third) = octal(4)
{
value = value * 8 + u32::from(third - b'0');
len = 3;
}
}
let c = char::from_u32(value).unwrap_or_default();
Ok((c, 2 + len))
}
pub(super) fn literal(c: char, out: &mut String) {
if c.is_ascii_alphanumeric() || !c.is_ascii() {
out.push(c);
} else {
let _ = write!(out, "\\x{{{:X}}}", u32::from(c));
}
}
fn java_flag_refusal(flags: &[u8]) -> Option<&'static str> {
flags.iter().find_map(|f| match f {
b's' => None,
b'i' => Some(
"Java's (?i) folds ASCII alone: only a (?i) on its own at the start of the pattern \
is read, so move the flag there",
),
b'u' => Some("Java's (?u) folds case by Java's own Unicode rules, which aren't read"),
b'U' => Some(
"Java's (?U) makes the classes Unicode, where the regex crate's swaps greed: \
build without the Java dialect and write the classes as wanted",
),
b'd' => Some("Java's (?d) UNIX_LINES isn't read: drop it"),
b'm' => Some(
"Java's (?m) also holds ^ and $ at \\r, U+0085, U+2028 and U+2029: drop the m flag",
),
b'x' => Some("Java's (?x) isn't read: drop it and its comments"),
b'c' => Some("Java's (?c) canonical equivalence isn't read"),
_ => Some("a flag Java's regex doesn't have"),
})
}
fn java_property(name: &str, negated: bool, in_class: bool) -> Result<String, &'static str> {
let p = if negated { 'P' } else { 'p' };
if let Some((_, class)) = JAVA_POSIX.iter().find(|(java, _)| *java == name) {
let caret = if negated { "^" } else { "" };
return Ok(if in_class {
format!("[:{caret}{class}:]")
} else {
format!("[[:{caret}{class}:]]")
});
}
match name {
"javaLowerCase" => return Ok(format!("\\{p}{{Lowercase}}")),
"javaUpperCase" => return Ok(format!("\\{p}{{Uppercase}}")),
_ if name.starts_with("java") => return Err("this \\p{java...} class isn't read"),
_ if name.starts_with("In") || name.starts_with("blk=") || name.starts_with("block=") => {
return Err("Java's Unicode block classes, \\p{In...}, aren't read");
}
_ => {}
}
let found = match name.split_once('=') {
Some(("gc" | "general_category", value)) => category(value),
Some(("sc" | "script", value)) => script(value),
Some(_) => None,
None => match name.strip_prefix("Is") {
Some(base)
if JAVA_POSIX
.iter()
.any(|(java, _)| java.eq_ignore_ascii_case(base)) =>
{
return Err(
"Java's \\p{Is...} POSIX names are Unicode classes of Java's own, \
which aren't read: use the ASCII \\p{Alpha} form or a category",
);
}
Some(base) => category(base).or_else(|| script(base)),
None => category(name),
},
};
found
.map(|canonical| format!("\\{p}{{{canonical}}}"))
.ok_or("a \\p{...} name outside the categories and scripts the Java dialect reads")
}
fn category(name: &str) -> Option<&'static str> {
JAVA_CATEGORIES.iter().find(|c| **c == name).copied()
}
fn script(name: &str) -> Option<&'static str> {
JAVA_SCRIPTS
.iter()
.find(|s| s.eq_ignore_ascii_case(name))
.copied()
}