use std::ops::Range;
use regex_syntax::hir::{Class, ClassUnicode, Hir, HirKind};
use super::Library;
use super::ends::{self, End, Ends};
use crate::field::{FIELDS, Field, Scan};
use crate::kernel::ByteClass;
type Set = ClassUnicode;
#[derive(Debug)]
struct Chars {
ascii: u128,
class: ByteClass,
line: bool,
set: Set,
}
impl Chars {
fn new(set: Set) -> Self {
let mut ascii = 0_u128;
for r in set.ranges() {
for c in u32::from(r.start())..=u32::from(r.end()).min(0x7F) {
ascii |= 1 << c;
}
}
let line = set == all_but_newline();
Self {
ascii,
class: ByteClass::new(ascii),
line,
set,
}
}
fn has(&self, c: char) -> bool {
if c.is_ascii() {
self.ascii >> u32::from(c) & 1 == 1
} else {
contains(&self.set, c)
}
}
fn run(&self, h: &[u8]) -> usize {
if self.line {
return memchr::memchr(b'\n', h).unwrap_or(h.len());
}
let mut at = 0;
loop {
at += self.class.run(h.get(at..).unwrap_or_default());
match char_at(h, at) {
Some((c, w)) if !c.is_ascii() && contains(&self.set, c) => at += w,
_ => return at,
}
}
}
}
const DATA: &str = ".*?";
const STEP: usize = 16;
const WORK_PER_BYTE: usize = 64;
const WORK_PER_STEP: usize = 4;
const FIRST_PER_BYTE: usize = 2;
const FIRST_PER_STEP: usize = 2;
const FIRST_SPARE: usize = 16;
const SIZE_CAP: usize = 256;
const MAX_DEPTH: usize = 32;
const MAX_LEADING_RUN: usize = 16;
#[derive(Debug)]
struct Ambiguous {
ends: &'static Ends,
follow: Chars,
eoi: bool,
open: bool,
}
#[derive(Debug, Clone, Copy)]
enum Look {
Word,
Start,
StartLine,
End,
EndLine,
}
#[derive(Debug)]
enum Step {
Literal(Vec<u8>),
Look(Look),
Field {
field: &'static Field,
capture: Option<usize>,
alphabet: Box<Chars>,
rest_nullable: bool,
then_end: bool,
ambiguous: Option<Box<Ambiguous>>,
},
Run {
capture: Option<usize>,
class: Box<Chars>,
min: usize,
max: Option<usize>,
lazy: bool,
possessive: bool,
next: Box<Chars>,
skip: Option<Box<ByteClass>>,
next_nullable: bool,
next_eoi: bool,
},
Choice(Vec<Vec<Self>>),
Loop {
body: Vec<Self>,
min: usize,
max: Option<usize>,
lazy: bool,
},
Open(usize),
Close(usize),
End,
LineEnd,
}
#[derive(Debug)]
#[cfg_attr(
not(test),
expect(dead_code, reason = "the every-start scan is test-only")
)]
pub(super) struct Plan {
anchored: bool,
lines: bool,
lead: Option<Set>,
steps: Vec<Step>,
size: usize,
slots: usize,
}
#[derive(Debug, PartialEq, Eq)]
pub(super) enum First {
Matched,
Open,
Spent,
}
#[derive(Debug, PartialEq, Eq)]
pub(super) struct Located {
pub(super) outcome: Outcome,
pub(super) first_fits: bool,
}
#[derive(Debug, Default, PartialEq, Eq)]
pub(super) struct Terms {
pub(super) steps: usize,
pub(super) fields: Vec<&'static str>,
pub(super) settled: usize,
pub(super) tail: Option<Tail>,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(super) enum Tail {
Line,
Class,
Field(&'static str),
}
fn tally(steps: &[Step], times: usize, t: &mut Terms) {
for step in steps {
t.steps += times;
match step {
Step::Field {
field, ambiguous, ..
} => {
t.fields.extend(std::iter::repeat_n(field.name, times));
if ambiguous.is_some() {
t.settled += times;
}
t.tail = Some(Tail::Field(field.name));
}
Step::Run {
class, max: None, ..
} => t.tail = Some(if class.line { Tail::Line } else { Tail::Class }),
Step::Choice(branches) => {
if let Some(first) = branches.first() {
tally(first, times, t);
}
}
Step::Loop { body, min, .. } => tally(body, times * min, t),
_ => {}
}
}
}
fn count(steps: &[Step], times: usize, n: &mut usize) {
for step in steps {
*n = n.saturating_add(times).min(SIZE_CAP);
if *n == SIZE_CAP {
return;
}
match step {
Step::Choice(branches) => {
if let Some(first) = branches.first() {
count(first, times, n);
}
}
Step::Loop { body, min, .. } => count(body, times.saturating_mul(*min), n),
_ => {}
}
}
}
#[derive(Debug, PartialEq, Eq)]
pub(super) enum Outcome {
Matched,
NoMatch,
Unsure,
}
struct Lowerer<'l> {
library: &'l Library,
captures: usize,
stack: Vec<String>,
dialect: super::Dialect,
fold: bool,
dotall: bool,
}
impl Plan {
pub(super) fn lower(
pattern: &str,
library: &Library,
dialect: super::Dialect,
span: super::Span,
) -> Result<Self, &'static str> {
let onig = dialect == super::Dialect::Oniguruma;
let whole = span == super::Span::Whole;
let pattern = &*super::as_rust(pattern, dialect, super::Possessive::Kept);
let mut l = Lowerer {
library,
captures: 0,
stack: Vec::new(),
dialect,
fold: false,
dotall: whole,
};
let (pattern, fold) = fold_prefix(pattern);
l.fold = fold;
let (body, anchored, end) = if whole {
(pattern, true, true)
} else {
let (body, anchored) = pattern
.strip_prefix('^')
.map_or((pattern, false), |rest| (rest, true));
match body.strip_suffix('$') {
Some(rest) if !rest.ends_with('\\') => (rest, anchored, true),
_ => (body, anchored, false),
}
};
let (mut branches, rest) = l.alternation(body)?;
if !rest.is_empty() {
return Err("an unbalanced parenthesis");
}
if !whole && (anchored || end) && branches.len() > 1 {
return Err("an anchor beside a top-level alternation");
}
let mut steps = if branches.len() == 1 {
branches.pop().unwrap_or_default()
} else {
vec![Step::Choice(branches)]
};
if end {
steps.push(if onig && !whole {
Step::LineEnd
} else {
Step::End
});
}
if steps.is_empty() {
return Err("an empty pattern");
}
let lead = match steps.iter().find(|s| !matches!(s, Step::Open(_))) {
Some(Step::Run {
class, max: None, ..
}) if !anchored => Some(class.set.clone()),
_ => None,
};
let starts_at_line = matches!(
steps.iter().find(|s| !matches!(s, Step::Open(_))),
Some(Step::Look(Look::Start | Look::StartLine))
);
let first = steps
.iter()
.find(|s| !matches!(s, Step::Open(_) | Step::Look(_)));
let long = |max: &Option<usize>| max.is_none_or(|m| m > MAX_LEADING_RUN);
if !anchored
&& !starts_at_line
&& lead.is_none()
&& matches!(first, Some(Step::Run { max, .. }) if long(max))
{
return Err("an unanchored pattern that starts with a run");
}
check(&mut steps, &Follow::nothing())?;
let slots = if opens(&steps) { l.captures } else { 0 };
let mut size = 0;
count(&steps, 1, &mut size);
Ok(Self {
anchored,
lines: onig && !whole,
lead,
steps,
size,
slots,
})
}
pub(super) const fn starts_at_zero(&self) -> bool {
self.anchored && !self.lines
}
pub(super) fn terms(&self) -> Terms {
let mut t = Terms::default();
tally(&self.steps, 1, &mut t);
t
}
pub(super) fn run_at(
&self,
h: &[u8],
at: usize,
caps: &mut Vec<(usize, Range<usize>)>,
) -> Located {
let budget = self.located(h);
let (outcome, left, _) = self.run_within(h, at, caps, budget);
Located {
outcome,
first_fits: at == 0 && budget - left <= self.first(h),
}
}
pub(super) fn first_try(&self, h: &[u8], caps: &mut Vec<(usize, Range<usize>)>) -> First {
match self.run_within(h, 0, caps, self.first(h)) {
(Outcome::Matched, ..) => First::Matched,
(_, _, true) => First::Spent,
_ => First::Open,
}
}
const fn located(&self, h: &[u8]) -> usize {
h.len()
.saturating_add(1)
.saturating_mul(WORK_PER_BYTE)
.saturating_add(self.size * WORK_PER_STEP * STEP)
}
const fn first(&self, h: &[u8]) -> usize {
h.len()
.saturating_mul(FIRST_PER_BYTE)
.saturating_add((self.size * FIRST_PER_STEP + FIRST_SPARE) * STEP)
}
#[cfg(test)]
pub(super) fn first_try_units(&self, h: &[u8]) -> (Outcome, usize, usize) {
let whole = 1 << 40;
let (outcome, left, _) = self.run_within(h, 0, &mut Vec::new(), whole);
(outcome, whole - left, self.first(h))
}
fn run_within(
&self,
h: &[u8],
at: usize,
caps: &mut Vec<(usize, Range<usize>)>,
budget: usize,
) -> (Outcome, usize, bool) {
let mut ctx = Ctx {
h,
caps,
opens: vec![0; self.slots],
budget,
spent: false,
};
ctx.caps.clear();
let outcome = seq(&self.steps, None, at, &mut ctx);
if outcome == Outcome::Matched {
ctx.caps.sort_by_key(|(i, _)| *i);
}
(outcome, ctx.budget, ctx.spent)
}
#[cfg(test)]
pub(super) fn run(&self, h: &[u8], caps: &mut Vec<(usize, Range<usize>)>) -> Outcome {
let mut ctx = Ctx {
h,
caps,
opens: vec![0; self.slots],
budget: self.located(h),
spent: false,
};
let last = if self.anchored { 0 } else { h.len() };
let line_starts = (self.anchored && self.lines)
.then(|| {
h.iter()
.enumerate()
.filter(|&(_, &b)| b == b'\n')
.map(|(i, _)| i + 1)
})
.into_iter()
.flatten();
for at in (0..=last).chain(line_starts) {
if let Some(lead) = &self.lead
&& char_before(h, at).is_some_and(|(c, _)| contains(lead, c))
{
continue;
}
ctx.caps.clear();
match seq(&self.steps, None, at, &mut ctx) {
Outcome::NoMatch => {}
Outcome::Matched => {
ctx.caps.sort_by_key(|(i, _)| *i);
return Outcome::Matched;
}
Outcome::Unsure => return Outcome::Unsure,
}
}
Outcome::NoMatch
}
}
impl Lowerer<'_> {
const fn onig(&self) -> bool {
matches!(self.dialect, super::Dialect::Oniguruma)
}
const fn pcre(&self) -> bool {
matches!(self.dialect, super::Dialect::Pcre)
}
fn alternation<'t>(
&mut self,
mut text: &'t str,
) -> Result<(Vec<Vec<Step>>, &'t str), &'static str> {
let mut branches = Vec::new();
loop {
let (steps, rest) = self.sequence(text)?;
branches.push(steps);
match rest.strip_prefix('|') {
Some(after) => text = after,
None => return Ok((branches, rest)),
}
}
}
fn group<'t>(&mut self, rest: &'t str) -> Result<Option<(Vec<Step>, &'t str)>, &'static str> {
let opened = if let Some(after) = rest.strip_prefix("(?:") {
(None, after, None)
} else if let Some(after) = rest.strip_prefix("(?i:") {
(None, after, Some(Flag::Fold))
} else if let Some(after) = rest.strip_prefix("(?s:").filter(|_| !self.onig()) {
(None, after, Some(Flag::Dotall))
} else if let Some((_, after)) = super::named_group(rest) {
self.captures += 1;
(Some(self.captures - 1), after, None)
} else if rest.starts_with('(') && !rest.starts_with("(?") {
(None, &rest[1..], None)
} else {
return Ok(None);
};
let (capture, after, flag) = opened;
let outer = (self.fold, self.dotall);
self.fold |= flag == Some(Flag::Fold);
self.dotall |= flag == Some(Flag::Dotall);
let lowered = self.alternation(after);
(self.fold, self.dotall) = outer;
let (mut branches, tail) = lowered?;
if let Some(c) = capture {
let inner = if branches.len() == 1 {
branches.pop().unwrap_or_default()
} else {
vec![Step::Choice(branches)]
};
let mut wrapped = vec![Step::Open(c)];
wrapped.extend(inner);
wrapped.push(Step::Close(c));
branches = vec![wrapped];
}
let tail = tail.strip_prefix(')').ok_or("an unclosed group")?;
let group = if branches.len() == 1 {
branches.pop().unwrap_or_default()
} else {
vec![Step::Choice(branches)]
};
repeated(group, tail).map(Some)
}
fn sequence<'t>(&mut self, mut rest: &'t str) -> Result<(Vec<Step>, &'t str), &'static str> {
let mut steps = Vec::new();
let mut literal = Vec::new();
let mut fold_from = self.fold.then_some(0);
while let Some(c) = rest.chars().next() {
if c == '|' || c == ')' {
break;
}
if let Some((flag, len)) = inline_flag(rest, self.onig()) {
flush(&mut literal, &mut steps);
match flag {
Flag::Fold => {
fold_from.get_or_insert(steps.len());
self.fold = true;
}
Flag::Dotall => self.dotall = true,
}
rest = &rest[len..];
continue;
}
if let Some(after) = rest.strip_prefix("%{") {
let end = after.find('}').ok_or("an unclosed reference")?;
flush(&mut literal, &mut steps);
let mark = steps.len();
self.reference(&after[..end], &mut steps)?;
let inner = steps.split_off(mark);
let (inner, after) = repeated(inner, &after[end + 1..])?;
steps.extend(inner);
rest = after;
continue;
}
if rest.starts_with('(') {
flush(&mut literal, &mut steps);
}
if let Some((group, after)) = self.group(rest)? {
steps.extend(group);
rest = after;
continue;
}
if let Some((class, after)) = raw_class(rest, self.onig(), self.fold, self.dotall)? {
flush(&mut literal, &mut steps);
let (step, after) = quantified(&class, after, self.pcre())?;
steps.push(step);
rest = after;
continue;
}
let look = match c {
'\\' if rest.starts_with("\\b") => Some((Look::Word, 2)),
'^' => Some((
if self.onig() {
Look::StartLine
} else {
Look::Start
},
1,
)),
'$' => Some((
if self.onig() {
Look::EndLine
} else {
Look::End
},
1,
)),
_ => None,
};
if let Some((look, len)) = look {
flush(&mut literal, &mut steps);
steps.push(Step::Look(look));
rest = &rest[len..];
continue;
}
if c == '\\' {
let next = rest[1..].chars().next().ok_or("a trailing backslash")?;
let byte = match next {
'n' => b'\n',
't' => b'\t',
'r' => b'\r',
'<' if self.onig() => b'<',
'>' if self.onig() => b'>',
n if n.is_ascii() && regex_syntax::is_escapeable_character(n) => {
u8::try_from(n).unwrap_or_else(|_| unreachable!("invariant: ASCII"))
}
_ => return Err("an escape that isn't a literal"),
};
literal.push(byte);
rest = &rest[1 + next.len_utf8()..];
continue;
}
if c == '{' && self.onig() && super::interval(rest).is_none() {
literal.push(b'{');
rest = &rest[1..];
continue;
}
if "+*?{".contains(c) {
let last = std::str::from_utf8(&literal)
.ok()
.and_then(|l| l.chars().next_back())
.ok_or("a quantifier after a reference or group")?;
literal.truncate(literal.len() - last.len_utf8());
flush(&mut literal, &mut steps);
let class = if self.fold {
fold_class(last)?
} else {
ClassUnicode::new([regex_syntax::hir::ClassUnicodeRange::new(last, last)])
};
let (step, after) = quantified(&class, rest, self.pcre())?;
steps.push(step);
rest = after;
continue;
}
if ".[(?*+{".contains(c) {
return Err("regex syntax outside a reference");
}
let mut buf = [0; 4];
literal.extend_from_slice(c.encode_utf8(&mut buf).as_bytes());
rest = &rest[c.len_utf8()..];
}
flush(&mut literal, &mut steps);
if let Some(from) = fold_from {
let folded = fold_literals(steps.split_off(from))?;
steps.extend(folded);
}
Ok((steps, rest))
}
fn reference(&mut self, inner: &str, steps: &mut Vec<Step>) -> Result<(), &'static str> {
let mut parts = inner.splitn(3, ':');
let mut name = parts.next().unwrap_or_default();
let capture = parts.next().filter(|f| !f.is_empty()).map(|_| {
self.captures += 1;
self.captures - 1
});
let generated;
let mut def = match parts.next().and_then(super::date_format) {
Some(format) if name.is_empty() => {
generated =
super::date_pattern(format).map_err(|_| "a date format with no matcher")?;
generated.as_str()
}
_ => self.library.get(name).ok_or("an unknown name")?,
};
for _ in 0..MAX_DEPTH {
match def.strip_prefix("%{").and_then(|d| d.strip_suffix('}')) {
Some(n) if !n.contains(['%', '}', ':']) => {
name = n;
def = self.library.get(n).ok_or("an unknown name")?;
}
_ => break,
}
}
if def == DATA {
let class = if self.dotall {
anything()
} else {
all_but_newline()
};
steps.push(run(capture, &class, 0, None, true));
return Ok(());
}
if let Some(f) = FIELDS.iter().find(|f| {
f.name == name
&& f.regex == def
&& (!self.fold || unchanged_by("i", f.regex))
&& (!self.dotall || unchanged_by("s", f.regex))
}) {
steps.push(field_step(f, capture)?);
return Ok(());
}
if self.stack.iter().any(|s| s == name) || self.stack.len() == MAX_DEPTH {
return Err("a definition that refers to itself");
}
self.stack.push(name.to_owned());
let (mut branches, rest) = self.alternation(def)?;
self.stack.pop();
if !rest.is_empty() {
return Err("an unbalanced parenthesis in a definition");
}
if let Some(c) = capture {
steps.push(Step::Open(c));
}
if branches.len() == 1 {
steps.append(&mut branches[0]);
} else {
steps.push(Step::Choice(branches));
}
if let Some(c) = capture {
steps.push(Step::Close(c));
}
Ok(())
}
}
fn fold_prefix(pattern: &str) -> (&str, bool) {
pattern
.strip_prefix("(?i)")
.map_or((pattern, false), |rest| (rest, true))
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum Flag {
Fold,
Dotall,
}
fn inline_flag(rest: &str, onig: bool) -> Option<(Flag, usize)> {
if rest.starts_with("(?i)") {
Some((Flag::Fold, 4))
} else if rest.starts_with(if onig { "(?m)" } else { "(?s)" }) {
Some((Flag::Dotall, 4))
} else {
None
}
}
fn unchanged_by(flag: &str, regex: &str) -> bool {
let flagged = regex_syntax::parse(&format!("(?{flag}:{regex})"));
flagged.is_ok() && flagged == regex_syntax::parse(&format!("(?:{regex})"))
}
fn fold_class(c: char) -> Result<ClassUnicode, &'static str> {
let hir = regex_syntax::parse(&format!(
"(?i){}",
regex_syntax::escape(c.encode_utf8(&mut [0; 4]))
))
.map_err(|_| "a character that doesn't fold")?;
match hir.into_kind() {
HirKind::Class(Class::Unicode(class)) => Ok(class),
_ => Ok(ClassUnicode::new([
regex_syntax::hir::ClassUnicodeRange::new(c, c),
])),
}
}
fn fold_literals(steps: Vec<Step>) -> Result<Vec<Step>, &'static str> {
let mut out = Vec::with_capacity(steps.len());
for step in steps {
let Step::Literal(bytes) = step else {
out.push(step);
continue;
};
let text = std::str::from_utf8(&bytes).map_err(|_| "a literal that isn't UTF-8")?;
let mut plain = Vec::new();
for c in text.chars() {
let class = fold_class(c)?;
if class.ranges().len() == 1 && class.ranges()[0].start() == class.ranges()[0].end() {
plain.extend_from_slice(c.encode_utf8(&mut [0; 4]).as_bytes());
} else {
flush(&mut plain, &mut out);
out.push(run(None, &class, 1, Some(1), false));
}
}
flush(&mut plain, &mut out);
}
Ok(out)
}
fn raw_class(
rest: &str,
onig: bool,
fold: bool,
dotall: bool,
) -> Result<Option<(ClassUnicode, &str)>, &'static str> {
if onig && rest.starts_with("\\h") {
let hex = regex_syntax::parse("[0-9A-Fa-f]").map_err(|_| "a class that doesn't parse")?;
if let HirKind::Class(Class::Unicode(c)) = hex.into_kind() {
return Ok(Some((c, &rest[2..])));
}
}
let len = if rest.starts_with('.') {
1
} else if rest.len() >= 2 && rest.starts_with('\\') && "dswDSW".contains(&rest[1..2]) {
2
} else if rest.starts_with('[') {
class_end(rest).ok_or("an unclosed class")?
} else {
return Ok(None);
};
let flags = match (fold, dotall) {
(true, true) => "(?is)",
(true, false) => "(?i)",
(false, true) => "(?s)",
(false, false) => "",
};
let text = format!("{flags}{}", &rest[..len]);
let hir = regex_syntax::parse(&text).map_err(|_| "a class that doesn't parse")?;
match hir.into_kind() {
HirKind::Class(Class::Unicode(c)) => Ok(Some((c, &rest[len..]))),
HirKind::Literal(l) => {
let mut chars = std::str::from_utf8(&l.0).unwrap_or_default().chars();
match (chars.next(), chars.next()) {
(Some(c), None) => Ok(Some((
ClassUnicode::new([regex_syntax::hir::ClassUnicodeRange::new(c, c)]),
&rest[len..],
))),
_ => Err("a class that isn't one character"),
}
}
_ => Err("a class that isn't one character"),
}
}
fn class_end(rest: &str) -> Option<usize> {
let b = rest.as_bytes();
let mut i = 1;
if b.get(i) == Some(&b'^') {
i += 1;
}
if b.get(i) == Some(&b']') {
i += 1;
}
let mut depth = 1;
while i < b.len() {
match b[i] {
b'\\' => i += 1,
b'[' if b.get(i + 1) == Some(&b':') => {
i += rest[i..].find(":]")? + 1;
}
b'[' => depth += 1,
b']' => {
depth -= 1;
if depth == 0 {
return Some(i + 1);
}
}
_ => {}
}
i += 1;
}
None
}
struct Quant<'t> {
min: usize,
max: Option<usize>,
lazy: bool,
possessive: bool,
rest: &'t str,
}
fn quantifier(rest: &str) -> Result<Option<Quant<'_>>, &'static str> {
let (min, max, rest) = match rest.chars().next() {
Some('+') => (1, None, &rest[1..]),
Some('*') => (0, None, &rest[1..]),
Some('?') => (0, Some(1), &rest[1..]),
Some('{') => {
let end = rest.find('}').ok_or("an unclosed repetition")?;
let inner = &rest[1..end];
let num = |t: &str| {
t.parse::<usize>()
.map_err(|_| "a repetition that isn't counts")
};
let (min, max) = match inner.split_once(',') {
None => (num(inner)?, Some(num(inner)?)),
Some((lo, "")) => (num(lo)?, None),
Some((lo, hi)) => (num(lo)?, Some(num(hi)?)),
};
(min, max, &rest[end + 1..])
}
_ => return Ok(None),
};
let (lazy, possessive) = (rest.starts_with('?'), rest.starts_with('+'));
Ok(Some(Quant {
min,
max,
lazy,
possessive,
rest: if lazy || possessive { &rest[1..] } else { rest },
}))
}
fn quantified<'t>(
class: &ClassUnicode,
rest: &'t str,
pcre: bool,
) -> Result<(Step, &'t str), &'static str> {
let Some(q) = quantifier(rest)? else {
return Ok((run(None, class, 1, Some(1), false), rest));
};
if q.possessive && !pcre {
return Err("a possessive repetition");
}
let mut step = run(None, class, q.min, q.max, q.lazy);
if let Step::Run { possessive, .. } = &mut step {
*possessive = q.possessive;
}
Ok((step, q.rest))
}
fn repeated(mut inner: Vec<Step>, rest: &str) -> Result<(Vec<Step>, &str), &'static str> {
Ok(match quantifier(rest)? {
None => (inner, rest),
Some(Quant {
possessive: true, ..
}) => return Err("a possessive repetition"),
Some(Quant {
min: 0,
max: Some(1),
lazy: false,
rest,
..
}) => (
vec![Step::Choice(vec![std::mem::take(&mut inner), Vec::new()])],
rest,
),
Some(Quant {
min,
max,
lazy,
rest,
..
}) => (
vec![Step::Loop {
body: inner,
min,
max,
lazy,
}],
rest,
),
})
}
fn field_step(f: &'static Field, capture: Option<usize>) -> Result<Step, &'static str> {
let hir = regex_syntax::parse(f.regex).map_err(|_| "a field regex that doesn't parse")?;
if let HirKind::Repetition(r) = hir.kind()
&& let HirKind::Class(Class::Unicode(class)) = r.sub.kind()
{
let min = usize::try_from(r.min).map_err(|_| "a repetition too long")?;
let max = r
.max
.map(usize::try_from)
.transpose()
.map_err(|_| "a repetition too long")?;
return Ok(run(capture, class, min, max, !r.greedy));
}
let mut alphabet = Set::empty();
add_alphabet(&hir, &mut alphabet);
Ok(Step::Field {
field: f,
capture,
alphabet: Box::new(Chars::new(alphabet)),
rest_nullable: false,
then_end: false,
ambiguous: None,
})
}
fn run(
capture: Option<usize>,
class: &ClassUnicode,
min: usize,
max: Option<usize>,
lazy: bool,
) -> Step {
Step::Run {
capture,
class: Box::new(Chars::new(class.clone())),
min,
max,
lazy,
possessive: false,
next: Box::new(Chars::new(Set::empty())),
skip: None,
next_nullable: false,
next_eoi: false,
}
}
fn all_but_newline() -> ClassUnicode {
let mut c = ClassUnicode::new([regex_syntax::hir::ClassUnicodeRange::new('\n', '\n')]);
c.negate();
c
}
fn flush(literal: &mut Vec<u8>, steps: &mut Vec<Step>) {
if !literal.is_empty() {
steps.push(Step::Literal(std::mem::take(literal)));
}
}
#[derive(Clone)]
#[expect(
clippy::struct_excessive_bools,
reason = "four facts about what follows, each read alone"
)]
struct Follow {
first: Set,
nullable: bool,
end: bool,
eoi: bool,
partly: bool,
}
impl Follow {
fn nothing() -> Self {
Self {
first: Set::empty(),
nullable: true,
end: false,
eoi: true,
partly: false,
}
}
fn after(&self, mut first: Set, nullable: bool) -> Self {
if nullable {
first.union(&self.first);
}
Self {
first,
nullable: nullable && self.nullable,
end: false,
eoi: nullable && self.eoi,
partly: nullable && self.partly,
}
}
}
fn check(steps: &mut [Step], after: &Follow) -> Result<Follow, &'static str> {
let mut f = after.clone();
for step in steps.iter_mut().rev() {
f = match step {
Step::Open(_) | Step::Close(_) => f,
Step::Look(_) => Follow {
first: anything(),
nullable: false,
end: false,
eoi: true,
partly: false,
},
Step::Literal(l) => {
let mut first = Set::empty();
if let Some(c) = std::str::from_utf8(l).ok().and_then(|t| t.chars().next()) {
first.push(regex_syntax::hir::ClassUnicodeRange::new(c, c));
}
f.after(first, false)
}
Step::LineEnd => {
let mut first = Set::empty();
first.push(regex_syntax::hir::ClassUnicodeRange::new('\n', '\n'));
first.push(regex_syntax::hir::ClassUnicodeRange::new('\r', '\r'));
Follow {
first,
nullable: false,
end: false,
eoi: true,
partly: false,
}
}
Step::End => Follow {
first: Set::empty(),
nullable: false,
end: true,
eoi: true,
partly: false,
},
Step::Field {
field,
alphabet,
rest_nullable,
then_end,
ambiguous,
..
} => {
*rest_nullable = f.nullable;
*then_end = f.end;
let mut overlap = alphabet.set.clone();
overlap.intersect(&f.first);
let moves = !f.nullable || f.partly;
*ambiguous = if moves && !overlap.ranges().is_empty() {
let ends =
ends::of(field).ok_or("a field that can end where the next step starts")?;
Some(Box::new(Ambiguous {
ends,
follow: Chars::new(f.first.clone()),
eoi: f.eoi,
open: f.nullable,
}))
} else {
None
};
let hir = regex_syntax::parse(field.regex)
.map_err(|_| "a field regex that doesn't parse")?;
let mut first = Set::empty();
let nullable = add_first(&hir, &mut first);
f.after(first, nullable)
}
Step::Run {
class,
min,
max,
lazy,
possessive,
next,
skip,
next_nullable,
next_eoi,
..
} => {
if *possessive {
let mut back = class.set.clone();
back.intersect(&f.first);
let always = f.nullable && !f.partly;
if !always && (f.nullable || !back.ranges().is_empty()) {
return Err("a possessive repetition that could give characters back");
}
}
**next = Chars::new(f.first.clone());
*skip = (*lazy && max.is_none() && !f.nullable)
.then(|| Box::new(ByteClass::new(class.ascii & !next.ascii)));
*next_nullable = f.nullable;
*next_eoi = f.eoi;
f.after(class.set.clone(), *min == 0)
}
Step::Choice(branches) => {
let mut union = Follow {
first: Set::empty(),
nullable: false,
end: true,
eoi: false,
partly: false,
};
for b in branches.iter_mut() {
let bf = check(b, &f)?;
union.first.union(&bf.first);
union.nullable |= bf.nullable;
union.end &= bf.end;
union.eoi |= bf.eoi;
union.partly |= bf.partly;
}
union
}
Step::Loop { body, min, .. } => {
if captures(body) {
return Err("a repeated group with a capture");
}
let own = check(body, &Follow::nothing())?;
if own.nullable {
return Err("a repeated group that can match nothing");
}
let mut inside = f.clone();
inside.first.union(&own.first);
inside.end = false;
inside.partly |= f.nullable && *min >= 2;
check(body, &inside)?;
f.after(own.first, *min == 0)
}
};
}
Ok(f)
}
fn captures(steps: &[Step]) -> bool {
steps.iter().any(|s| match s {
Step::Field { capture, .. } | Step::Run { capture, .. } => capture.is_some(),
Step::Open(_) | Step::Close(_) => true,
Step::Choice(bs) => bs.iter().any(|b| captures(b)),
Step::Loop { body, .. } => captures(body),
Step::Literal(_) | Step::Look(_) | Step::End | Step::LineEnd => false,
})
}
impl Plan {
pub(super) fn ops(&self) -> Result<Vec<super::spec::Op>, &'static str> {
if !self.starts_at_zero() {
return Err("a pattern that doesn't start with ^");
}
convert(&self.steps, &[])
}
}
fn convert(steps: &[Step], tail: &[&Step]) -> Result<Vec<super::spec::Op>, &'static str> {
use super::spec::Op;
let mut ops = Vec::with_capacity(steps.len());
let mut k = 0;
while k < steps.len() {
let (capture, step, width) = match (&steps[k], steps.get(k + 2)) {
(Step::Open(c), Some(Step::Close(d))) if c == d => (Some(*c), &steps[k + 1], 3),
(Step::Open(c), _) => {
ops.push(Op::Open(*c));
k += 1;
continue;
}
(Step::Close(c), _) => {
ops.push(Op::Close(*c));
k += 1;
continue;
}
(step, _) => (None, step, 1),
};
let rest: Vec<&Step> = steps[k + width..]
.iter()
.chain(tail.iter().copied())
.collect();
if let Step::Choice(branches) = step
&& let [taken, empty] = branches.as_slice()
&& empty.is_empty()
{
ops.push(optional(taken, capture, &rest)?);
} else if let Step::Choice(branches) = step
&& op(step, capture, None).is_err()
{
let mut each = Vec::with_capacity(branches.len());
for b in branches {
each.push(convert(b, &rest)?);
}
if let Some(c) = capture {
ops.push(Op::Open(c));
}
ops.push(Op::Choice(each));
if let Some(c) = capture {
ops.push(Op::Close(c));
}
} else {
let next = rest
.iter()
.copied()
.find(|s| !matches!(s, Step::Open(_) | Step::Close(_)));
match (capture, step) {
(Some(c), Step::Literal(_) | Step::End) => {
ops.push(Op::Open(c));
ops.push(op(step, None, next)?);
ops.push(Op::Close(c));
}
_ => ops.push(op(step, capture, next)?),
}
}
k += width;
}
Ok(ops)
}
fn optional(
taken: &[Step],
group: Option<usize>,
rest: &[&Step],
) -> Result<super::spec::Op, &'static str> {
if group.is_some() {
return Err("a named optional group");
}
Ok(super::spec::Op::Optional(convert(taken, rest)?))
}
fn op(
step: &Step,
group: Option<usize>,
next: Option<&Step>,
) -> Result<super::spec::Op, &'static str> {
use super::spec::Op;
let pick = |own: Option<usize>| match (own, group) {
(Some(_), Some(_)) => Err("a field inside a named group"),
(own, group) => Ok(own.or(group)),
};
Ok(match step {
Step::Literal(l) if group.is_none() => Op::Literal(l.clone()),
Step::End if group.is_none() => Op::End,
Step::Field {
field,
capture,
alphabet,
rest_nullable,
then_end,
ambiguous: None,
} => Op::Field {
index: FIELDS
.iter()
.position(|f| std::ptr::eq(f, *field))
.ok_or("a field not in the table")?,
capture: pick(*capture)?,
alphabet: class_of(alphabet),
then_end: *then_end,
rest_nullable: *rest_nullable,
},
Step::Field {
field,
capture,
ambiguous: Some(a),
..
} => Op::Settle {
index: FIELDS
.iter()
.position(|f| std::ptr::eq(f, *field))
.ok_or("a field not in the table")?,
capture: pick(*capture)?,
follow: class_of(&a.follow),
eoi: a.eoi,
open: a.open,
},
Step::Run {
capture,
class,
min,
max,
lazy: false,
next: follow,
..
} => {
let c = class_of(class);
if c.line && (*min > 1 || max.is_some()) {
return Err("a counted run of any character");
}
let mut overlap = class.set.clone();
overlap.intersect(&follow.set);
if *max != Some(*min) && !overlap.ranges().is_empty() {
Op::GiveBack {
capture: pick(*capture)?,
class: c,
min: *min,
max: *max,
lazy: false,
}
} else {
Op::Span {
capture: pick(*capture)?,
class: c,
min: *min,
max: *max,
}
}
}
Step::Run {
capture,
class,
min,
max: None,
lazy: true,
..
} if *min <= 1 => match next {
Some(Step::Literal(l)) if !l.is_empty() => Op::Until {
capture: pick(*capture)?,
class: class_of(class),
min: *min,
literal: l.clone(),
},
_ => Op::GiveBack {
capture: pick(*capture)?,
class: class_of(class),
min: *min,
max: None,
lazy: true,
},
},
Step::Choice(branches) => {
let mut literals = Vec::with_capacity(branches.len());
for b in branches {
match b.as_slice() {
[Step::Literal(l)] if !l.is_empty() => literals.push(l.clone()),
_ => return Err("a choice that isn't between literals"),
}
}
let prefix = literals.iter().enumerate().any(|(i, a)| {
literals
.iter()
.enumerate()
.any(|(j, b)| i != j && b.starts_with(a))
});
if prefix {
return Err("a choice where one literal starts another");
}
Op::Alt {
capture: group,
literals,
}
}
Step::Look(_) => return Err("a zero-width check such as \\b"),
Step::Loop {
body,
min,
max,
lazy,
} if group.is_none() => {
let tail: Vec<&Step> = next.into_iter().collect();
let body = convert(body, &tail)?;
if body.iter().any(|o| {
matches!(
o,
Op::Choice(_) | Op::Optional(_) | Op::GiveBack { .. } | Op::Loop { .. }
)
}) {
return Err("a repeated group of choices");
}
Op::Loop {
body,
min: *min,
max: *max,
lazy: *lazy,
}
}
Step::Loop { .. } => return Err("a repeated group"),
Step::Literal(_) | Step::End => return Err("a literal or end inside a named group"),
_ => return Err("a step outside the compiled subset"),
})
}
fn class_of(chars: &Chars) -> super::spec::Class {
super::spec::Class {
ascii: chars.ascii,
other: chars.set.ranges().last().is_some_and(|r| r.end() > '\x7f'),
line: chars.line,
}
}
fn opens(steps: &[Step]) -> bool {
steps.iter().any(|s| match s {
Step::Open(_) => true,
Step::Choice(bs) => bs.iter().any(|b| opens(b)),
Step::Loop { body, .. } => opens(body),
_ => false,
})
}
enum Cont<'a> {
Steps {
steps: &'a [Step],
next: Option<&'a Self>,
},
Again {
body: &'a [Step],
min: usize,
max: Option<usize>,
lazy: bool,
n: usize,
start: usize,
next: Option<&'a Self>,
},
}
fn resume(cont: Option<&Cont<'_>>, i: usize, ctx: &mut Ctx<'_, '_>) -> Outcome {
match cont {
None => Outcome::Matched,
Some(Cont::Steps { steps, next }) => seq(steps, *next, i, ctx),
Some(&Cont::Again {
body,
min,
max,
lazy,
n,
start,
next,
}) => repeat(body, (min, max, lazy), n, start, i, next, ctx),
}
}
fn repeat(
body: &[Step],
(min, max, lazy): (usize, Option<usize>, bool),
n: usize,
start: usize,
i: usize,
next: Option<&Cont<'_>>,
ctx: &mut Ctx<'_, '_>,
) -> Outcome {
let empty = n > 0 && i == start;
let more = !empty && max.is_none_or(|m| n < m);
let stop = n >= min || empty;
for go_on in if lazy { [false, true] } else { [true, false] } {
let mark = ctx.caps.len();
let out = if go_on {
if !more {
continue;
}
let again = Cont::Again {
body,
min,
max,
lazy,
n: n + 1,
start: i,
next,
};
seq(body, Some(&again), i, ctx)
} else {
if !stop {
continue;
}
resume(next, i, ctx)
};
match out {
Outcome::NoMatch => ctx.caps.truncate(mark),
done => return done,
}
}
Outcome::NoMatch
}
struct Ctx<'h, 'c> {
h: &'h [u8],
caps: &'c mut Vec<(usize, Range<usize>)>,
opens: Vec<usize>,
budget: usize,
spent: bool,
}
const fn charge(ctx: &mut Ctx<'_, '_>, n: usize) -> bool {
if let Some(left) = ctx.budget.checked_sub(n) {
ctx.budget = left;
true
} else {
ctx.spent = true;
false
}
}
fn seq(steps: &[Step], cont: Option<&Cont<'_>>, mut i: usize, ctx: &mut Ctx<'_, '_>) -> Outcome {
let h = ctx.h;
for (k, step) in steps.iter().enumerate() {
if !charge(ctx, STEP) {
return Outcome::Unsure;
}
match step {
Step::Literal(l) => {
if !h[i..].starts_with(l) {
return Outcome::NoMatch;
}
i += l.len();
}
Step::Open(c) => ctx.opens[*c] = i,
Step::Look(look) => {
if !holds(*look, h, i) {
return Outcome::NoMatch;
}
}
Step::Close(c) => ctx.caps.push((*c, ctx.opens[*c]..i)),
Step::LineEnd => {
let line_end = |j: usize| j == h.len() || h[j] == b'\n';
let terminator = [&b"\r\n"[..], b"\n", b"\r"]
.iter()
.any(|t| h[i..].starts_with(t) && line_end(i + t.len()));
if !(line_end(i) || terminator) {
return Outcome::NoMatch;
}
}
Step::End => {
if i != h.len() {
return Outcome::NoMatch;
}
}
Step::Field {
field,
capture,
alphabet,
rest_nullable,
then_end,
ambiguous,
} => {
if let Some(a) = ambiguous {
let viable =
|p: usize| a.open || char_at(h, p).map_or(a.eoi, |(c, _)| a.follow.has(c));
match a.ends.only(h, i, &mut ctx.budget, viable) {
End::At(end) => {
if let Some(c) = capture {
ctx.caps.push((*c, i..end));
}
i = end;
continue;
}
End::Nowhere => return Outcome::NoMatch,
End::Unsure => return Outcome::Unsure,
End::Spent => {
ctx.spent = true;
return Outcome::Unsure;
}
}
}
let end = match (field.scan)(h, i) {
Scan::Defer => return Outcome::Unsure,
Scan::NoMatch => {
let read = alphabet.run(&h[i..]);
return if charge(ctx, read) {
Outcome::NoMatch
} else {
Outcome::Unsure
};
}
Scan::Match(end) => end,
};
if !charge(ctx, end - i) {
return Outcome::Unsure;
}
if *then_end {
if end != h.len() {
let read = alphabet.run(&h[i..]);
let run = i + read;
return if !charge(ctx, read) {
Outcome::Unsure
} else if run < h.len() {
Outcome::NoMatch
} else {
Outcome::Unsure
};
}
} else if !*rest_nullable && char_at(h, end).is_some_and(|(c, _)| alphabet.has(c)) {
return Outcome::Unsure;
}
if let Some(c) = capture {
ctx.caps.push((*c, i..end));
}
i = end;
}
Step::Choice(branches) => {
let after = Cont::Steps {
steps: &steps[k + 1..],
next: cont,
};
for b in branches {
let mark = ctx.caps.len();
match seq(b, Some(&after), i, ctx) {
Outcome::NoMatch => ctx.caps.truncate(mark),
done => return done,
}
}
return Outcome::NoMatch;
}
Step::Loop {
body,
min,
max,
lazy,
} => {
let after = Cont::Steps {
steps: &steps[k + 1..],
next: cont,
};
return repeat(body, (*min, *max, *lazy), 0, i, i, Some(&after), ctx);
}
Step::Run { .. } => return run_class_step(step, &steps[k + 1..], cont, i, ctx),
}
}
resume(cont, i, ctx)
}
fn run_class_step(
step: &Step,
rest: &[Step],
cont: Option<&Cont<'_>>,
i: usize,
ctx: &mut Ctx<'_, '_>,
) -> Outcome {
let Step::Run {
capture,
class,
min,
max,
lazy,
next,
skip,
next_nullable,
next_eoi,
..
} = step
else {
unreachable!("invariant: seq hands run_class_step only a run step");
};
let h = ctx.h;
let viable =
|end: usize| *next_nullable || char_at(h, end).map_or(*next_eoi, |(c, _)| next.has(c));
let (mut at, mut taken) = (i, 0);
if *lazy {
loop {
if let Some(skip) = skip {
let from = at;
at += skip.run(h.get(at..).unwrap_or_default());
taken += at - from;
if !charge(ctx, at - from) {
return Outcome::Unsure;
}
}
if !charge(ctx, STEP) {
return Outcome::Unsure;
}
if taken >= *min
&& viable(at)
&& let Some(done) = take_end(rest, cont, *capture, i..at, ctx)
{
return done;
}
match run_step(h, at, class, taken, *max) {
Some(w) => (at, taken) = (at + w, taken + 1),
None => return Outcome::NoMatch,
}
}
}
if max.is_none() && *min <= 1 {
at += class.run(&h[i..]);
if !charge(ctx, at - i + 1) {
return Outcome::Unsure;
}
loop {
if (at > i || *min == 0)
&& viable(at)
&& let Some(done) = take_end(rest, cont, *capture, i..at, ctx)
{
return done;
}
if at == i {
return Outcome::NoMatch;
}
at = char_start_before(h, at);
}
}
while let Some(w) = run_step(h, at, class, taken, *max) {
(at, taken) = (at + w, taken + 1);
}
if !charge(ctx, taken + 1) {
return Outcome::Unsure;
}
while taken >= *min {
if viable(at)
&& let Some(done) = take_end(rest, cont, *capture, i..at, ctx)
{
return done;
}
if taken == 0 {
break;
}
at = char_start_before(h, at);
taken -= 1;
}
Outcome::NoMatch
}
fn run_step(h: &[u8], at: usize, class: &Chars, count: usize, max: Option<usize>) -> Option<usize> {
if max == Some(count) {
return None;
}
let (c, w) = char_at(h, at)?;
class.has(c).then_some(w)
}
const fn char_start_before(h: &[u8], at: usize) -> usize {
let mut start = at - 1;
while start > 0 && h[start] & 0xC0 == 0x80 {
start -= 1;
}
start
}
fn take_end(
rest: &[Step],
cont: Option<&Cont<'_>>,
capture: Option<usize>,
span: Range<usize>,
ctx: &mut Ctx<'_, '_>,
) -> Option<Outcome> {
let mark = ctx.caps.len();
let end = span.end;
if let Some(c) = capture {
ctx.caps.push((c, span));
}
match seq(rest, cont, end, ctx) {
Outcome::NoMatch => {
ctx.caps.truncate(mark);
None
}
done => Some(done),
}
}
fn anything() -> Set {
Set::new([regex_syntax::hir::ClassUnicodeRange::new('\0', char::MAX)])
}
fn holds(look: Look, h: &[u8], i: usize) -> bool {
static WORD: std::sync::LazyLock<Chars> =
std::sync::LazyLock::new(|| match regex_syntax::parse(r"\w").map(Hir::into_kind) {
Ok(HirKind::Class(Class::Unicode(c))) => Chars::new(c),
_ => unreachable!("invariant: \\w is a Unicode class"),
});
let word = |c: Option<(char, usize)>| c.is_some_and(|(c, _)| WORD.has(c));
match look {
Look::Word => word(char_before(h, i)) != word(char_at(h, i)),
Look::Start => i == 0,
Look::StartLine => i == 0 || h[i - 1] == b'\n',
Look::End => i == h.len(),
Look::EndLine => i == h.len() || h[i] == b'\n',
}
}
fn char_before(h: &[u8], i: usize) -> Option<(char, usize)> {
if i == 0 {
return None;
}
char_at(h, char_start_before(h, i))
}
fn char_at(h: &[u8], at: usize) -> Option<(char, usize)> {
let rest = h.get(at..)?;
let width = match *rest.first()? {
b if b < 0x80 => return Some((char::from(b), 1)),
b if b >= 0xF0 => 4,
b if b >= 0xE0 => 3,
_ => 2,
};
let c = std::str::from_utf8(rest.get(..width)?)
.ok()?
.chars()
.next()?;
Some((c, width))
}
fn add_alphabet(hir: &Hir, out: &mut Set) {
match hir.kind() {
HirKind::Literal(l) => add_literal(&l.0, out, false),
HirKind::Class(c) => add_class(c, out),
HirKind::Repetition(r) => add_alphabet(&r.sub, out),
HirKind::Capture(c) => add_alphabet(&c.sub, out),
HirKind::Concat(hs) | HirKind::Alternation(hs) => {
for h in hs {
add_alphabet(h, out);
}
}
HirKind::Empty | HirKind::Look(_) => {}
}
}
fn add_first(hir: &Hir, out: &mut Set) -> bool {
match hir.kind() {
HirKind::Empty | HirKind::Look(_) => true,
HirKind::Literal(l) => {
add_literal(&l.0, out, true);
l.0.is_empty()
}
HirKind::Class(c) => {
add_class(c, out);
false
}
HirKind::Repetition(r) => add_first(&r.sub, out) || r.min == 0,
HirKind::Capture(c) => add_first(&c.sub, out),
HirKind::Concat(hs) => hs.iter().all(|h| add_first(h, out)),
HirKind::Alternation(hs) => {
let mut nullable = false;
for h in hs {
nullable |= add_first(h, out);
}
nullable
}
}
}
fn add_literal(bytes: &[u8], out: &mut Set, first_only: bool) {
use regex_syntax::hir::ClassUnicodeRange as R;
match std::str::from_utf8(bytes) {
Ok(t) => {
for c in t.chars().take(if first_only { 1 } else { usize::MAX }) {
out.push(R::new(c, c));
}
}
Err(_) => out.push(R::new('\u{80}', char::MAX)),
}
}
fn add_class(class: &Class, out: &mut Set) {
use regex_syntax::hir::ClassUnicodeRange as R;
match class {
Class::Unicode(c) => out.union(c),
Class::Bytes(c) => {
for r in c.ranges() {
if r.end() < 0x80 {
out.push(R::new(char::from(r.start()), char::from(r.end())));
} else {
out.push(R::new(char::from(r.start().min(0x7F)), char::MAX));
}
}
}
}
}
fn contains(set: &Set, c: char) -> bool {
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()
}