use regex_automata::meta::Regex;
use regex_automata::{Anchored, Input, PatternID};
use regex_syntax::hir::Look;
use regex_syntax::hir::literal::{ExtractKind, Extractor};
use std::fmt::Write as _;
use std::num::NonZeroU32;
use std::ops::Range;
use std::sync::atomic::{AtomicI32, Ordering};
#[cfg(feature = "parse-backtracking")]
use super::Expanded;
#[cfg(feature = "parse-backtracking")]
use super::backtrack::Backtracking;
use super::plan::{First, Outcome, Plan, Tail, Terms};
use super::shadow::{Clock, Shadow, agree};
use super::spec::{Steps, run_steps};
use super::{
Capture, Dialect, GrokError, Library, Possessive, Span, define_unknown, expand_as,
has_possessive, inline_definitions, layer_aliases, unmark,
};
use crate::cost::{Cost, Line, REFERENCE_BYTES};
use crate::parse::{Counter, counter};
use crate::parse::{FieldSink, FieldValue, Fields, ParseError, Parsed, Parser, SinkMark};
use crate::strmatch::Signature;
use crate::tier::MatcherTier;
const MAX_PREFIXES: usize = 64;
pub struct Grok {
name: String,
drop_empty: bool,
regex: Regex,
groups: Vec<Vec<Option<Capture>>>,
#[cfg(feature = "parse-backtracking")]
linear: Vec<usize>,
#[cfg(feature = "parse-backtracking")]
backtracking: Option<Backtracking>,
signature: Signature,
each: Vec<Regex>,
native: Option<Native>,
blocked: Vec<Option<&'static str>>,
regexes: Vec<String>,
stock: Option<StepsFn>,
compilable: bool,
shadow: Option<Shadow>,
on_field: Counter,
on_regex: Counter,
}
struct Native {
plans: Vec<Plan>,
at_start: bool,
captures: Vec<Vec<Capture>>,
score: AtomicI32,
}
const SCORE_MAX: i32 = 32;
const SCORE_HIT: i32 = 4;
const SCORE_SPENT: i32 = 16;
const PROBE_EVERY: u32 = 16;
fn probe_due() -> bool {
thread_local! {
static LINES: std::cell::Cell<u32> = const { std::cell::Cell::new(0) };
}
LINES.with(|lines| {
let next = lines.get().wrapping_add(1);
lines.set(next);
next % PROBE_EVERY == 0
})
}
#[derive(Clone, Copy)]
enum Went {
First,
Other,
Spent,
Probed,
}
impl Native {
fn tries_first(&self) -> bool {
self.score.load(Ordering::Relaxed) > 0
}
fn score(&self, went: Went) {
let now = self.score.load(Ordering::Relaxed);
let next = match went {
Went::First => (now + SCORE_HIT).min(SCORE_MAX),
Went::Other => (now - 1).max(-SCORE_MAX),
Went::Spent => (now - SCORE_SPENT).max(-SCORE_MAX),
Went::Probed => SCORE_MAX,
};
if next != now {
self.score.store(next, Ordering::Relaxed);
}
}
fn write<'a>(
&self,
pid: usize,
steps: &[(usize, Range<usize>)],
input: &'a [u8],
out: &mut dyn FieldSink<'a>,
) {
let captures = &self.captures[pid];
for (i, span) in steps {
let c = &captures[*i];
if let Some(v) = c.value(&input[span.clone()]) {
out.field(&c.field, v);
}
}
}
}
type StepsFn = fn(&[u8], &mut [(usize, usize)]) -> Steps;
impl std::fmt::Debug for Grok {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("Grok")
.field("name", &self.name)
.field("patterns", &self.groups.len())
.finish_non_exhaustive()
}
}
#[derive(Debug, Clone)]
pub struct GrokBuilder {
name: String,
patterns: Vec<String>,
library: Option<Library>,
aliases: Library,
unknown: Option<String>,
dialect: Dialect,
span: Span,
drop_empty: bool,
strict: bool,
shadow: Option<NonZeroU32>,
#[cfg(feature = "parse-backtracking")]
backtrack: Vec<usize>,
}
#[derive(Debug, thiserror::Error)]
#[non_exhaustive]
pub enum GrokBuildError {
#[error("pattern {index}: {source}")]
Expand {
index: usize,
source: GrokError,
},
#[error("the expanded patterns don't compile: {0}")]
Regex(Box<regex_automata::meta::BuildError>),
#[cfg(feature = "parse-backtracking")]
#[error("a backtracking pattern doesn't compile: {0}")]
Backtracking(Box<fancy_regex::Error>),
#[error("a grok parser needs at least one pattern")]
Empty,
#[error("pattern {index} runs on the regex: {reason}. {hint}")]
NotNative {
index: usize,
reason: &'static str,
hint: &'static str,
},
#[error(
"pattern {index}: {reason}. Write the greedy repeat if that's meant, or opt the pattern into backtracking"
)]
Possessive {
index: usize,
reason: &'static str,
},
}
impl Grok {
#[must_use]
pub fn builder(name: impl Into<String>) -> GrokBuilder {
GrokBuilder {
name: name.into(),
patterns: Vec::new(),
library: None,
aliases: Library::empty(),
unknown: None,
dialect: Dialect::Rust,
span: Span::Part,
drop_empty: false,
strict: false,
shadow: None,
#[cfg(feature = "parse-backtracking")]
backtrack: Vec::new(),
}
}
}
impl GrokBuilder {
#[must_use]
pub fn pattern(mut self, pattern: impl Into<String>) -> Self {
self.patterns.push(pattern.into());
self
}
#[cfg(feature = "parse-backtracking")]
#[must_use]
pub fn backtracking_pattern(mut self, pattern: impl Into<String>) -> Self {
self.backtrack.push(self.patterns.len());
self.patterns.push(pattern.into());
self
}
#[must_use]
pub fn library(mut self, library: Library) -> Self {
self.library = Some(library);
self
}
#[must_use]
pub const fn strict(mut self, strict: bool) -> Self {
self.strict = strict;
self
}
#[must_use]
pub const fn shadow(mut self, every: NonZeroU32) -> Self {
self.shadow = Some(every);
self
}
#[must_use]
pub const fn dialect(mut self, dialect: Dialect) -> Self {
self.dialect = dialect;
self
}
#[must_use]
pub const fn span(mut self, span: Span) -> Self {
self.span = span;
self
}
#[must_use]
pub fn aliases(mut self, aliases: Library) -> Self {
self.aliases = aliases;
self
}
#[must_use]
pub fn unknown(mut self, definition: impl Into<String>) -> Self {
self.unknown = Some(definition.into());
self
}
#[must_use]
pub const fn drop_empty(mut self, drop: bool) -> Self {
self.drop_empty = drop;
self
}
pub fn build(self) -> Result<Grok, GrokBuildError> {
if self.patterns.is_empty() {
return Err(GrokBuildError::Empty);
}
let lone_on_stock = self.library.is_none()
&& self.aliases.defs.is_empty()
&& self.dialect == Dialect::Rust
&& self.span == Span::Part
&& self.patterns.len() == 1;
let stock = lone_on_stock
.then(|| {
super::stock::STOCK
.iter()
.find(|(p, _)| *p == self.patterns[0])
})
.flatten()
.map(|&(_, steps)| steps);
let mut library = self.library.unwrap_or_default();
let patterns: Vec<String> = layer_aliases(&self.patterns, &self.aliases, &mut library)
.iter()
.map(|p| inline_definitions(p, &mut library))
.collect();
if let Some(definition) = &self.unknown {
define_unknown(&patterns, &mut library, definition);
}
let span = self.span;
let lowered: Vec<Result<Plan, &'static str>> = patterns
.iter()
.map(|p| Plan::lower(p, &library, self.dialect, span))
.collect();
let unproven = |index: usize| {
lowered[index].is_err() && has_possessive(&patterns[index], self.dialect)
};
let expanded = patterns
.iter()
.enumerate()
.map(|(index, p)| {
let possessive = if unproven(index) {
Possessive::Kept
} else {
Possessive::Greedy
};
expand_as(p, &library, self.dialect, span, possessive).map_err(|source| {
GrokBuildError::Expand {
index,
source: unmark(source),
}
})
})
.collect::<Result<Vec<_>, _>>()?;
#[cfg(feature = "parse-backtracking")]
let (linear, backtracking) = split(&expanded, &self.backtrack, &unproven)?;
#[cfg(not(feature = "parse-backtracking"))]
let linear: Vec<usize> = (0..expanded.len()).collect();
if let Some(&index) = linear.iter().find(|&&i| unproven(i)) {
let reason = lowered[index].as_ref().err().copied().unwrap_or_default();
return Err(GrokBuildError::Possessive { index, reason });
}
let regexes: Vec<&str> = linear.iter().map(|&i| expanded[i].regex.as_str()).collect();
let (regex, each) = list_regexes(®exes)?;
let groups = linear
.iter()
.map(|&i| &expanded[i])
.enumerate()
.map(|(pid, e)| {
regex
.group_info()
.pattern_names(PatternID::new_unchecked(pid))
.map(|name| {
let i: usize = name?.strip_prefix('g')?.parse().ok()?;
e.captures.get(i).cloned()
})
.collect()
})
.collect();
let all: Vec<&str> = expanded.iter().map(|e| e.regex.as_str()).collect();
let signature = signature(&all);
let blocked: Vec<Option<&'static str>> =
lowered.iter().map(|l| l.as_ref().err().copied()).collect();
for (index, reason) in blocked.iter().enumerate() {
if let Some(reason) = *reason {
if self.strict {
return Err(GrokBuildError::NotNative {
index,
reason,
hint: hint(reason),
});
}
summarise(&self.name, index, reason);
}
}
let ordered = lowered.len() == 1
|| span == Span::Whole
|| self.patterns.iter().all(|p| p.starts_with('^'));
let regexes_owned = expanded.iter().map(|e| e.regex.clone()).collect();
let labels = |tier: &str| [("parser", self.name.clone()), ("tier", tier.to_owned())];
let on_field = counter("parse_tier_total", &labels("field"));
#[cfg(feature = "parse-backtracking")]
let slow = backtracking.is_some();
#[cfg(not(feature = "parse-backtracking"))]
let slow = false;
let on_regex = counter(
"parse_tier_total",
&labels(if slow { "backtracking" } else { "regex" }),
);
let compilable = lone_on_stock
&& !self.drop_empty
&& self.unknown.is_none()
&& stock.is_none()
&& expanded[0].captures.len() <= super::spec::MAX_CAPTURES
&& lowered[0].as_ref().is_ok_and(|p| p.ops().is_ok());
let native = (ordered && !slow && lowered.iter().all(Result::is_ok)).then(|| Native {
at_start: lowered.iter().flatten().all(Plan::starts_at_zero),
plans: lowered.into_iter().flatten().collect(),
captures: expanded.into_iter().map(|e| e.captures).collect(),
score: AtomicI32::new(SCORE_MAX),
});
let stock = stock.filter(|_| native.is_some());
let compilable = compilable && native.is_some();
if compilable {
suggest_compiling(&self.name);
}
let shadow = self.shadow.filter(|_| native.is_some()).map(|every| {
Shadow::new(
every,
counter(
"parse_shadow_disagree_total",
&[("parser", self.name.clone())],
),
)
});
Ok(Grok {
name: self.name,
drop_empty: self.drop_empty,
regex,
groups,
#[cfg(feature = "parse-backtracking")]
linear,
#[cfg(feature = "parse-backtracking")]
backtracking,
signature,
each,
native,
blocked,
regexes: regexes_owned,
stock,
compilable,
shadow,
on_field,
on_regex,
})
}
}
fn list_regexes(regexes: &[&str]) -> Result<(Regex, Vec<Regex>), GrokBuildError> {
let each = if regexes.len() > 1 {
regexes
.iter()
.map(|r| Regex::new(r).map_err(|e| GrokBuildError::Regex(Box::new(e))))
.collect::<Result<Vec<_>, GrokBuildError>>()?
} else {
Vec::new()
};
let cache = (2 << 20_usize).max(regexes.len() * (64 << 10));
let nfa = (10 << 20_usize)
.max(regexes.len() * (128 << 10))
.min(256 << 20);
let regex = regex_automata::meta::Builder::new()
.configure(
regex_automata::meta::Config::new()
.hybrid_cache_capacity(cache)
.nfa_size_limit(Some(nfa)),
)
.build_many(regexes)
.map_err(|e| GrokBuildError::Regex(Box::new(e)))?;
Ok((regex, each))
}
#[cfg(feature = "parse-backtracking")]
fn split(
expanded: &[Expanded],
opted: &[usize],
unproven: &dyn Fn(usize) -> bool,
) -> Result<(Vec<usize>, Option<Backtracking>), GrokBuildError> {
let (slow, linear): (Vec<usize>, Vec<usize>) = (0..expanded.len()).partition(|i| {
opted.contains(i) && (unproven(*i) || Regex::new(&expanded[*i].regex).is_err())
});
if slow.is_empty() {
return Ok((linear, None));
}
let patterns = slow
.iter()
.map(|&i| {
(
i,
expanded[i].regex.as_str(),
expanded[i].captures.as_slice(),
)
})
.collect();
let backtracking = Backtracking::new(patterns).map_err(GrokBuildError::Backtracking)?;
Ok((linear, Some(backtracking)))
}
fn signature(regexes: &[&str]) -> Signature {
let mut literals: Vec<Vec<u8>> = Vec::new();
let mut from_start = true;
let mut extractor = Extractor::new();
extractor.kind(ExtractKind::Prefix);
for re in regexes {
let Ok(hir) = regex_syntax::parse(re) else {
return Signature::builder()
.build()
.unwrap_or_else(|_| unreachable!("invariant: no literal"));
};
from_start &= hir.properties().look_set_prefix().contains(Look::Start);
let seq = extractor.extract(&hir);
match seq.literals() {
Some(lits) if !lits.is_empty() && lits.iter().all(|l| !l.is_empty()) => {
literals.extend(lits.iter().map(|l| l.as_bytes().to_vec()));
}
_ => literals.clear(),
}
if literals.is_empty() || literals.len() > MAX_PREFIXES {
literals.clear();
break;
}
}
let builder = Signature::builder();
let builder = if literals.is_empty() {
builder
} else if from_start {
builder.anchored(literals)
} else {
builder.any_of(literals)
};
builder
.build()
.unwrap_or_else(|_| unreachable!("invariant: literals are non-empty"))
}
impl Parser for Grok {
fn name(&self) -> &str {
&self.name
}
fn tier(&self) -> MatcherTier {
#[cfg(feature = "parse-backtracking")]
if self.backtracking.is_some() {
return MatcherTier::Backtracking;
}
if self.native.is_some() {
MatcherTier::Field
} else {
MatcherTier::Regex
}
}
fn signature(&self) -> &Signature {
&self.signature
}
fn hands_on_body(&self) -> bool {
false
}
fn cost(&self) -> Option<Cost> {
let Some(native) = self.native.as_ref() else {
#[cfg(feature = "parse-backtracking")]
if self.backtracking.is_some() {
return None;
}
let [groups] = self.groups.as_slice() else {
return None;
};
return regex_priced(groups.len());
};
let [plan] = native.plans.as_slice() else {
return None;
};
priced(&plan.terms(), native.at_start)
}
fn parse<'a>(
&self,
input: &'a [u8],
out: &mut dyn FieldSink<'a>,
) -> Result<Parsed, ParseError> {
self.run(input, out, &mut Tally::Now).map(parsed)
}
fn parse_counted<'a>(
&self,
input: &'a [u8],
out: &mut dyn FieldSink<'a>,
counts: &mut crate::parse::ParserCounts,
) -> Result<Parsed, ParseError> {
self.run(input, out, &mut Tally::Held(counts)).map(parsed)
}
}
const fn parsed(won: Option<usize>) -> Parsed {
match won {
Some(_) => Parsed::Done,
None => Parsed::NoMatch,
}
}
struct NonEmpty<'s, 'a>(&'s mut dyn FieldSink<'a>);
impl<'a> FieldSink<'a> for NonEmpty<'_, 'a> {
fn field(&mut self, name: &str, value: FieldValue<'a>) {
if !value.bytes.is_empty() {
self.0.field(name, value);
}
}
fn body_field(&mut self, name: &str, value: FieldValue<'a>) {
if !value.bytes.is_empty() {
self.0.body_field(name, value);
}
}
fn push_prefix(&mut self, prefix: &str) {
self.0.push_prefix(prefix);
}
fn pop_prefix(&mut self) {
self.0.pop_prefix();
}
fn mark(&self) -> SinkMark {
self.0.mark()
}
fn rollback(&mut self, mark: SinkMark) {
self.0.rollback(mark);
}
}
#[derive(Clone, Copy)]
enum Tier {
Field,
Regex,
}
enum Tally<'c> {
Now,
Held(&'c mut crate::parse::ParserCounts),
}
impl Grok {
#[cfg_attr(
not(feature = "metrics"),
allow(clippy::missing_const_for_fn, reason = "the body is the counter add")
)]
fn tier(&self, tally: &mut Tally<'_>, tier: Tier) {
let counter = match tier {
Tier::Field => &self.on_field,
Tier::Regex => &self.on_regex,
};
match tally {
Tally::Now => counter.increment(1),
#[cfg(feature = "metrics")]
Tally::Held(counts) => counts.add(tier as usize, counter, 1),
#[cfg(not(feature = "metrics"))]
Tally::Held(counts) => {
let _ = counts;
}
}
}
fn run<'a>(
&self,
input: &'a [u8],
out: &mut dyn FieldSink<'a>,
tally: &mut Tally<'_>,
) -> Result<Option<usize>, ParseError> {
if self.drop_empty {
return self.run_into(input, &mut NonEmpty(out), tally);
}
self.run_into(input, out, tally)
}
fn run_into<'a>(
&self,
input: &'a [u8],
out: &mut dyn FieldSink<'a>,
tally: &mut Tally<'_>,
) -> Result<Option<usize>, ParseError> {
if let Some(shadow) = &self.shadow {
if shadow.sample() {
return self.parse_shadowed(shadow, input, out, tally);
}
if shadow.regex_first() {
self.tier(tally, Tier::Regex);
return self.regex_won(input, out);
}
}
self.parse_fast(input, out, tally)
}
fn parse_fast<'a>(
&self,
input: &'a [u8],
out: &mut dyn FieldSink<'a>,
tally: &mut Tally<'_>,
) -> Result<Option<usize>, ParseError> {
if let Some(native) = &self.native {
let mut tried = false;
let on = native.tries_first();
if let Some(code) = self.stock
&& (on || probe_due())
{
match run_steps(code, &native.captures[0], input, out) {
Some(Parsed::NoMatch) => {
native.score(Went::Other);
self.tier(tally, Tier::Field);
return Ok(None);
}
Some(_) => {
native.score(if on { Went::First } else { Went::Probed });
self.tier(tally, Tier::Field);
return Ok(Some(0));
}
None => tried = true,
}
}
let mut steps = super::scratch::steps();
let first = !tried && native.plans.len() == 1 && native.tries_first();
let mut spent = false;
if first {
match native.plans[0].first_try(input, &mut steps) {
First::Matched if std::str::from_utf8(input).is_ok() => {
native.score(Went::First);
self.tier(tally, Tier::Field);
native.write(0, &steps, input, out);
return Ok(Some(0));
}
First::Spent => spent = true,
First::Matched | First::Open => {}
}
}
let missed = if spent { Went::Spent } else { Went::Other };
let found = if native.at_start {
let anchored = Input::new(input).anchored(Anchored::Yes);
let half = self.regex.search_half(&anchored);
half.map(|h| (h.pattern().as_usize(), 0))
} else {
let m = self.regex.search(&Input::new(input));
m.map(|m| (m.pattern().as_usize(), m.start()))
};
let Some((pid, start)) = found else {
native.score(missed);
self.tier(tally, Tier::Field);
return Ok(None);
};
if !spent && std::str::from_utf8(input).is_ok() {
let located = native.plans[pid].run_at(input, start, &mut steps);
if located.outcome == Outcome::Matched {
if self.stock.is_none() && located.first_fits {
native.score(Went::First);
} else if tried || !located.first_fits {
native.score(Went::Other);
}
self.tier(tally, Tier::Field);
native.write(pid, &steps, input, out);
return Ok(Some(pid));
}
}
native.score(missed);
self.tier(tally, Tier::Regex);
return self.regex_won(input, out);
}
#[cfg(feature = "parse-backtracking")]
if self.backtracking.is_some() && !self.signature.may_match(input) {
self.tier(tally, Tier::Regex);
return Ok(None);
}
self.tier(tally, Tier::Regex);
self.regex_won(input, out)
}
fn parse_shadowed<'a>(
&self,
shadow: &Shadow,
input: &'a [u8],
out: &mut dyn FieldSink<'a>,
tally: &mut Tally<'_>,
) -> Result<Option<usize>, ParseError> {
let mut by_steps = Fields::new();
let clock = Clock::now();
let won = self.parse_fast(input, &mut by_steps, tally)?;
let steps_ns = clock.ns();
let mut by_regex = Fields::new();
let clock = Clock::now();
let regex = self.regex_won(input, &mut by_regex)?;
shadow.record(
steps_ns,
clock.ns(),
agree(&parsed(won), &by_steps, &parsed(regex), &by_regex),
);
for (name, value) in by_steps.as_slice() {
out.field(name, value.clone());
}
Ok(won)
}
pub fn parse_indexed<'a>(
&self,
input: &'a [u8],
out: &mut dyn FieldSink<'a>,
) -> Result<Option<usize>, ParseError> {
self.run(input, out, &mut Tally::Now)
}
}
impl Grok {
#[must_use]
pub fn explain(&self) -> String {
let mut out = String::new();
for (i, (blocked, regex)) in self.blocked.iter().zip(&self.regexes).enumerate() {
#[cfg(feature = "parse-backtracking")]
if self.backtracking.as_ref().is_some_and(|b| b.holds(i)) {
let _ = writeln!(
out,
"{i}: backtracking: the linear engine refuses it\n {regex}"
);
continue;
}
let plan = match blocked {
None if self.native.is_some() => {
let first = if self.stock.is_some() { "compiled code, then " } else { "" };
let steps = self.cost().map_or_else(
|| "native steps".to_owned(),
|c| {
format!(
"native steps, tier Field, about {:.0} ns a hit and {:.0} ns a miss at {REFERENCE_BYTES} B",
c.label(),
c.miss.ns(REFERENCE_BYTES)
)
},
);
let up = if self.compilable { "; grok! compiles it to code" } else { "" };
format!("{first}{steps}{up}")
}
None => "lowers, but the list runs on the regex: a list lowers when it is one pattern, all start with ^, or each matches the whole line".to_owned(),
Some(reason) => {
let price = self.cost().map_or_else(String::new, |c| {
format!(". About {:.0} ns a hit at {REFERENCE_BYTES} B", c.label())
});
format!("regex: {reason}. {}{price}", hint(reason))
}
};
let _ = writeln!(out, "{i}: {plan}\n {regex}");
}
out
}
#[must_use]
pub fn blocked(&self) -> &[Option<&'static str>] {
&self.blocked
}
#[cfg(test)]
pub(super) fn tries_first(&self) -> bool {
self.native.as_ref().is_some_and(Native::tries_first)
}
#[cfg(test)]
pub(super) fn native_outcome(&self, input: &[u8]) -> Option<(Outcome, Vec<(String, Vec<u8>)>)> {
let native = self.native.as_ref()?;
let mut steps = Vec::new();
let outcome = native.plans[0].run(input, &mut steps);
let fields = steps
.iter()
.map(|(i, span)| {
(
native.captures[0][*i].field.clone(),
input[span.clone()].to_vec(),
)
})
.collect();
Some((outcome, fields))
}
#[cfg(test)]
#[allow(
clippy::option_option,
reason = "no stock code and code that can't say are both answers"
)]
pub(super) fn stock_says(&self, input: &[u8]) -> Option<Option<Parsed>> {
let native = self.native.as_ref()?;
let code = self.stock?;
Some(run_steps(
code,
&native.captures[0],
input,
&mut crate::parse::Fields::new(),
))
}
#[cfg(test)]
pub(super) fn first_and_located(&self, input: &[u8]) -> Option<(First, super::plan::Located)> {
let plan = &self.native.as_ref()?.plans[0];
let mut caps = Vec::new();
Some((
plan.first_try(input, &mut caps),
plan.run_at(input, 0, &mut caps),
))
}
#[cfg(test)]
pub(super) fn first_try_units(&self, input: &[u8]) -> Option<(Outcome, usize, usize)> {
Some(self.native.as_ref()?.plans[0].first_try_units(input))
}
#[cfg(test)]
pub(super) fn regexes(&self) -> &[String] {
&self.regexes
}
#[cfg(test)]
pub(super) fn parse_regex<'a>(
&self,
input: &'a [u8],
out: &mut dyn FieldSink<'a>,
) -> Result<Parsed, ParseError> {
self.regex_won(input, out).map(parsed)
}
#[cfg_attr(
not(feature = "parse-backtracking"),
allow(
clippy::unnecessary_wraps,
reason = "only a backtracking search can fail"
)
)]
fn regex_won<'a>(
&self,
input: &'a [u8],
out: &mut dyn FieldSink<'a>,
) -> Result<Option<usize>, ParseError> {
let (pid_of, shape, slots) = if self.each.is_empty() {
let mut slots = super::scratch::slots(self.regex.group_info().slot_len());
let pid = self.regex.search_slots(&Input::new(input), &mut slots);
(pid, pid.map(|pid| (&self.regex, pid)), slots)
} else if let Some(m) = self.regex.search(&Input::new(input)) {
let one = &self.each[m.pattern().as_usize()];
let mut slots = super::scratch::slots(one.group_info().slot_len());
let at = Input::new(input).range(m.start()..).anchored(Anchored::Yes);
let own = one.search_slots(&at, &mut slots);
(Some(m.pattern()), own.map(|own| (one, own)), slots)
} else {
(None, None, super::scratch::slots(0))
};
let group = |i: usize| -> Option<Range<usize>> {
let (regex, pid) = shape?;
let (start, end) = regex.group_info().slots(pid, i)?;
Some(slots.get(start).copied()??.get()..slots.get(end).copied()??.get())
};
#[cfg(feature = "parse-backtracking")]
if let Some(hit) = self
.backtracking
.as_ref()
.map(|b| b.search(input))
.transpose()?
.flatten()
{
let linear = group(0)
.zip(pid_of)
.map(|(m, pid)| (m.start, self.linear[pid.as_usize()]));
if linear.is_none_or(|first| (hit.start, hit.index) < first) {
hit.write(input, out);
return Ok(Some(hit.index));
}
}
let Some(pid) = pid_of else {
return Ok(None);
};
for (i, capture) in self.groups[pid.as_usize()].iter().enumerate() {
if let (Some(c), Some(span)) = (capture, group(i))
&& let Some(v) = c.value(&input[span])
{
out.field(&c.field, v);
}
}
#[cfg(feature = "parse-backtracking")]
let pid = self.linear[pid.as_usize()];
#[cfg(not(feature = "parse-backtracking"))]
let pid = pid.as_usize();
Ok(Some(pid))
}
}
fn hint(reason: &str) -> &'static str {
match reason {
"a field that can end where the next step starts" => {
"Put a literal between them that the first field can't hold, or use a field that stops there"
}
"regex syntax outside a reference" | "an escape that isn't a literal" => {
"Write the class or repetition as a grok field such as %{NOTSPACE} or %{DATA}"
}
"a repeated group" => "Repeat a field instead of a group, or keep it on the regex",
"an unanchored pattern that starts with a run" => {
"Anchor it with ^, or start it with a literal or a field"
}
_ => "Keep it on the regex, or split the pattern",
}
}
#[cfg_attr(
not(feature = "tracing"),
allow(
unused_variables,
clippy::missing_const_for_fn,
reason = "the body is the tracing call"
)
)]
fn summarise(parser: &str, index: usize, reason: &'static str) {
#[cfg(feature = "tracing")]
{
use std::sync::atomic::{AtomicUsize, Ordering};
static TOLD: AtomicUsize = AtomicUsize::new(0);
if TOLD.fetch_add(1, Ordering::Relaxed) < 10 {
tracing::warn!(
parser,
pattern = index,
blocked = reason,
hint = hint(reason),
"grok pattern runs on the regex"
);
} else {
tracing::debug!(
parser,
pattern = index,
blocked = reason,
"grok pattern runs on the regex"
);
}
}
}
#[cfg_attr(
not(feature = "tracing"),
allow(
unused_variables,
clippy::missing_const_for_fn,
reason = "the body is the tracing call"
)
)]
fn suggest_compiling(parser: &str) {
#[cfg(feature = "tracing")]
{
use std::sync::atomic::{AtomicBool, Ordering};
static TOLD: AtomicBool = AtomicBool::new(false);
if TOLD.swap(true, Ordering::Relaxed) {
tracing::debug!(parser, "grok pattern could be compiled with grok!");
} else {
tracing::warn!(
parser,
"grok pattern could be compiled with grok!, which skips the step interpreter"
);
}
}
}
const REGEX_RATE_PER_GROUP: f32 = 0.8;
fn regex_priced(groups: usize) -> Option<Cost> {
use crate::cost::of;
let (meta, dfa) = (of("meta_captures")?, of("lazy_dfa_find")?);
#[allow(clippy::cast_precision_loss, reason = "a group count far below 2^24")]
let scale = REGEX_RATE_PER_GROUP * (groups as f32 + 1.0);
Some(Cost {
hit: Line {
fixed_ns: meta.hit.fixed_ns,
ns_per_byte: meta.hit.ns_per_byte * scale,
},
miss: dfa.miss,
})
}
const BASE_STEPS: usize = 1;
const STEPS_ROW_EXTRA: f32 = 31.0;
fn priced(t: &Terms, at_start: bool) -> Option<Cost> {
use crate::cost::of;
let (base, steps) = (of("grok.base")?, of("grok.steps")?);
let (settled, unsettled, run) = (of("grok.settled")?, of("grok.unsettled")?, of("grok.run")?);
let per_step = ((steps.hit.fixed_ns - base.hit.fixed_ns) / STEPS_ROW_EXTRA).max(0.0);
let settle = (settled.hit.fixed_ns - unsettled.hit.fixed_ns).max(0.0);
#[allow(
clippy::cast_precision_loss,
reason = "step and field counts are far below 2^24"
)]
let mut fixed = (t.steps.saturating_sub(BASE_STEPS) as f32).mul_add(
per_step,
(t.settled as f32).mul_add(settle, base.hit.fixed_ns),
);
for c in t.fields.iter().filter_map(|f| of(&format!("field.{f}"))) {
fixed += c.hit.fixed_ns;
}
let tail = match t.tail {
None => 0.0,
Some(Tail::Line) => of("memchr")?.hit.ns_per_byte,
Some(Tail::Class) => run.hit.ns_per_byte,
Some(Tail::Field(f)) => of(&format!("field.{f}")).map_or(0.0, |c| c.hit.ns_per_byte),
};
let per_byte = base.hit.ns_per_byte + tail;
let miss = if at_start {
base.miss
} else {
let dfa = of("lazy_dfa_find")?.miss;
Line {
fixed_ns: base.miss.fixed_ns + dfa.fixed_ns,
ns_per_byte: dfa.ns_per_byte,
}
};
Some(Cost {
hit: Line {
fixed_ns: fixed,
ns_per_byte: per_byte,
},
miss,
})
}