use std::ops::Range;
use super::{Capture, Dialect, Grok, GrokBuildError, Library, expand};
use crate::parse::{FieldSink, ParseError, Parsed, Parser};
use crate::strmatch::Signature;
use crate::tier::MatcherTier;
#[doc(hidden)]
pub use memchr::{memchr, memmem};
pub const MAX_CAPTURES: usize = 64;
#[doc(hidden)]
pub const UNSET: (usize, usize) = (usize::MAX, usize::MAX);
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct Class {
pub ascii: u128,
pub other: bool,
pub line: bool,
}
#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
pub enum Op {
Literal(Vec<u8>),
Alt {
capture: Option<usize>,
literals: Vec<Vec<u8>>,
},
Field {
index: usize,
capture: Option<usize>,
alphabet: Class,
then_end: bool,
rest_nullable: bool,
},
Settle {
index: usize,
capture: Option<usize>,
follow: Class,
eoi: bool,
open: bool,
},
Span {
capture: Option<usize>,
class: Class,
min: usize,
max: Option<usize>,
},
GiveBack {
capture: Option<usize>,
class: Class,
min: usize,
max: Option<usize>,
lazy: bool,
},
Until {
capture: Option<usize>,
class: Class,
min: usize,
literal: Vec<u8>,
},
Optional(Vec<Self>),
Choice(Vec<Vec<Self>>),
Loop {
body: Vec<Self>,
min: usize,
max: Option<usize>,
lazy: bool,
},
Open(usize),
Close(usize),
End,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Steps {
Matched,
NoMatch,
Unsure,
}
pub fn ops(pattern: &str) -> Result<(Vec<Op>, Vec<Capture>), String> {
let library = Library::default();
let expanded = expand(pattern, &library, Dialect::Rust).map_err(|e| e.to_string())?;
if expanded.captures.len() > MAX_CAPTURES {
return Err(format!("more than {MAX_CAPTURES} captures"));
}
let plan = super::plan::Plan::lower(pattern, &library, Dialect::Rust, super::Span::Part)?;
let ops = plan.ops()?;
Ok((ops, expanded.captures))
}
fn with_caps<R>(n: usize, f: impl FnOnce(&mut [(usize, usize)]) -> R) -> R {
if n <= 8 {
f(&mut [UNSET; 8][..n])
} else if n <= 32 {
f(&mut [UNSET; 32][..n])
} else {
f(&mut [UNSET; MAX_CAPTURES][..n])
}
}
pub(super) fn run_steps<'a>(
steps: fn(&[u8], &mut [(usize, usize)]) -> Steps,
captures: &[Capture],
input: &'a [u8],
out: &mut dyn FieldSink<'a>,
) -> Option<Parsed> {
with_caps(captures.len(), |caps| match steps(input, caps) {
Steps::Matched => {
for (c, &(start, end)) in captures.iter().zip(caps.iter()) {
if start != usize::MAX
&& let Some(v) = c.value(&input[start..end])
{
out.field(&c.field, v);
}
}
Some(Parsed::Done)
}
Steps::NoMatch => Some(Parsed::NoMatch),
Steps::Unsure => None,
})
}
pub struct Compiled {
grok: Grok,
captures: Vec<Capture>,
steps: fn(&[u8], &mut [(usize, usize)]) -> Steps,
}
impl std::fmt::Debug for Compiled {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("Compiled")
.field("grok", &self.grok)
.finish_non_exhaustive()
}
}
impl Compiled {
#[doc(hidden)]
pub fn new(
name: &str,
pattern: &str,
steps: fn(&[u8], &mut [(usize, usize)]) -> Steps,
) -> Result<Self, GrokBuildError> {
let grok = Grok::builder(name).pattern(pattern).build()?;
let library = Library::default();
let expanded = expand(pattern, &library, Dialect::Rust)
.map_err(|source| GrokBuildError::Expand { index: 0, source })?;
Ok(Self {
grok,
captures: expanded.captures,
steps,
})
}
#[must_use]
pub fn steps(&self, input: &[u8]) -> Steps {
with_caps(self.captures.len(), |caps| (self.steps)(input, caps))
}
#[must_use]
pub const fn grok(&self) -> &Grok {
&self.grok
}
}
impl Parser for Compiled {
fn name(&self) -> &str {
self.grok.name()
}
fn tier(&self) -> MatcherTier {
self.grok.tier()
}
fn signature(&self) -> &Signature {
self.grok.signature()
}
fn parse<'a>(
&self,
input: &'a [u8],
out: &mut dyn FieldSink<'a>,
) -> Result<Parsed, ParseError> {
if let Some(parsed) = run_steps(self.steps, &self.captures, input, out) {
return Ok(parsed);
}
self.grok.parse(input, out)
}
}
#[doc(hidden)]
#[must_use]
pub fn settle(
index: usize,
h: &[u8],
at: usize,
follow: Class,
eoi: bool,
open: bool,
) -> Option<Result<usize, ()>> {
let field = crate::field::FIELDS.get(index)?;
if matches!((field.scan)(h, at), crate::field::Scan::NoMatch) {
return Some(Err(()));
}
let ends = super::ends::of(field)?;
let unsure = std::cell::Cell::new(false);
let viable = |p: usize| {
if open {
return true;
}
match h.get(p) {
None => eoi,
Some(&b) if b < 0x80 => (follow.ascii >> b) & 1 == 1,
Some(_) => {
unsure.set(unsure.get() || follow.other);
false
}
}
};
let mut budget = h.len().saturating_add(1).saturating_mul(64);
let end = ends.only(h, at, &mut budget, viable);
if unsure.get() {
return None;
}
match end {
super::ends::End::At(end) => Some(Ok(end)),
super::ends::End::Nowhere => Some(Err(())),
super::ends::End::Unsure | super::ends::End::Spent => None,
}
}
#[doc(hidden)]
#[must_use]
pub fn find(h: &[u8], from: usize, last: usize, literal: &[u8]) -> Option<usize> {
let p = from + memmem::find(h.get(from..)?, literal)?;
(p <= last).then_some(p)
}
#[doc(hidden)]
#[must_use]
pub const fn pair(range: Range<usize>) -> (usize, usize) {
(range.start, range.end)
}