use regex_automata::meta::Regex;
use regex_automata::util::primitives::NonMaxUsize;
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::OnceLock;
use std::sync::atomic::{AtomicI32, Ordering};
use super::Expanded;
#[cfg(feature = "parse-backtracking")]
use super::backtrack::Backtracking;
use super::backtrack::{Hit, Pattern};
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, Render, Span, define_unknown, expand_as,
has_possessive, inline_definitions, layer_aliases, unmark,
};
use crate::cost::{Cost, Line, REFERENCE_BYTES};
use crate::field::Edge;
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>>>,
checks: Vec<Checks>,
#[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);
}
}
const fn reads_as_regex(plan: &Plan, input: &[u8]) -> bool {
if plan.ascii_lines() {
input.is_ascii()
} else {
std::str::from_utf8(input).is_ok()
}
}
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,
readings: Readings,
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(
"pattern {index}: {reason}. Leave atomic_number off, or opt the pattern into backtracking"
)]
Atomic {
index: usize,
reason: &'static str,
},
#[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,
readings: Readings::default(),
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 validate(mut self, validate: bool) -> Self {
self.readings.validate = validate;
self
}
#[must_use]
pub const fn wide_ipv6_zone(mut self, wide: bool) -> Self {
self.readings.wide_zone = wide;
self
}
#[must_use]
pub const fn atomic_number(mut self, atomic: bool) -> Self {
self.readings.atomic_number = atomic;
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.readings.any()
&& 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();
option_fields(&mut library, self.readings);
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_with(p, &library, self.dialect, span, self.readings.atomic_number))
.collect();
let atomic = reads_atomic(
self.readings.atomic_number,
self.dialect,
&patterns,
&library,
span,
)?;
let unproven = |index: usize| {
lowered[index].is_err()
&& (atomic[index] || has_possessive(&patterns[index], self.dialect))
};
let expansion = Expansion {
patterns: &patterns,
library: &library,
dialect: self.dialect,
span,
atomic: &atomic,
unproven: &unproven,
};
#[cfg(feature = "parse-backtracking")]
let opted = |i: usize| self.backtrack.contains(&i);
#[cfg(not(feature = "parse-backtracking"))]
let opted = |_: usize| false;
let (expanded, rendered) = expansion.all(&opted)?;
let (linear, slow) = split(&expanded, &opted, &unproven);
if let Some(&index) = linear.iter().find(|&&i| unproven(i)) {
let reason = lowered[index].as_ref().err().copied().unwrap_or_default();
return Err(if has_possessive(&patterns[index], self.dialect) {
GrokBuildError::Possessive { index, reason }
} else {
GrokBuildError::Atomic { index, reason }
});
}
let regexes: Vec<&str> = linear.iter().map(|&i| expanded[i].regex.as_str()).collect();
let (regex, each) = list_regexes(®exes)?;
let groups = capture_groups(®ex, &linear, &expanded);
let limit = share(&linear, &expanded, slow.len());
#[cfg(feature = "parse-backtracking")]
let backtracking =
Backtracking::new(&slow, &rendered, limit).map_err(GrokBuildError::Backtracking)?;
let checks = Checks::each(®ex, &linear, &expanded, rendered, limit);
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();
report_blocked(&self.name, self.strict, &blocked)?;
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,
checks,
#[cfg(feature = "parse-backtracking")]
backtracking,
signature,
each,
native,
blocked,
regexes: regexes_owned,
stock,
compilable,
shadow,
on_field,
on_regex,
})
}
}
#[derive(Debug, Clone, Copy, Default)]
struct Readings {
validate: bool,
wide_zone: bool,
atomic_number: bool,
}
impl Readings {
const fn any(self) -> bool {
self.validate || self.wide_zone || self.atomic_number
}
}
fn option_fields(library: &mut Library, readings: Readings) {
use crate::field::{CHECKED, Field, WIDE_ZONE, WIDE_ZONE_CHECKED};
let (validate, wide_zone) = (readings.validate, readings.wide_zone);
let tables: [(bool, &[Field]); 3] = [
(validate, &CHECKED),
(wide_zone, &WIDE_ZONE),
(validate && wide_zone, &WIDE_ZONE_CHECKED),
];
for (on, table) in tables {
if on {
for f in table {
library.add(f.name, f.regex);
}
}
}
}
struct Expansion<'e> {
patterns: &'e [String],
library: &'e Library,
dialect: Dialect,
span: Span,
atomic: &'e [bool],
unproven: &'e dyn Fn(usize) -> bool,
}
impl Expansion<'_> {
fn all(
&self,
opted: &dyn Fn(usize) -> bool,
) -> Result<(Vec<Expanded>, Vec<Option<Expanded>>), GrokBuildError> {
let expanded = (0..self.patterns.len())
.map(|i| self.of(i, Render::Groups))
.collect::<Result<Vec<Expanded>, GrokBuildError>>()?;
let rendered = (0..self.patterns.len())
.map(|i| {
(!expanded[i].edges.is_empty() || opted(i))
.then(|| self.of(i, Render::Lookarounds))
.transpose()
})
.collect::<Result<Vec<Option<Expanded>>, GrokBuildError>>()?;
Ok((expanded, rendered))
}
fn of(&self, index: usize, render: Render) -> Result<Expanded, GrokBuildError> {
let unproven = (self.unproven)(index);
let possessive = if unproven {
Possessive::Kept
} else {
Possessive::Greedy
};
let kept = self.atomic[index] && unproven;
expand_as(
&self.patterns[index],
self.library,
self.dialect,
self.span,
possessive,
kept,
render,
)
.map_err(|source| GrokBuildError::Expand {
index,
source: unmark(source),
})
}
}
fn reads_atomic(
on: bool,
dialect: Dialect,
patterns: &[String],
library: &Library,
span: Span,
) -> Result<Vec<bool>, GrokBuildError> {
if !on {
return Ok(vec![false; patterns.len()]);
}
patterns
.iter()
.enumerate()
.map(|(index, p)| {
let expand = |atomic| {
expand_as(
p,
library,
dialect,
span,
Possessive::Greedy,
atomic,
Render::Groups,
)
.map_err(|source| GrokBuildError::Expand {
index,
source: unmark(source),
})
};
Ok(expand(true)?.regex != expand(false)?.regex)
})
.collect()
}
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))
}
fn share(linear: &[usize], expanded: &[Expanded], slow: usize) -> usize {
let edged = linear
.iter()
.filter(|&&i| !expanded[i].edges.is_empty())
.count();
RECORD_BACKTRACKS / (edged + slow).max(1)
}
fn split(
expanded: &[Expanded],
opted: &dyn Fn(usize) -> bool,
unproven: &dyn Fn(usize) -> bool,
) -> (Vec<usize>, Vec<usize>) {
let (slow, linear): (Vec<usize>, Vec<usize>) = (0..expanded.len())
.partition(|&i| opted(i) && (unproven(i) || Regex::new(&expanded[i].regex).is_err()));
(linear, slow)
}
fn capture_groups(
regex: &Regex,
linear: &[usize],
expanded: &[Expanded],
) -> Vec<Vec<Option<Capture>>> {
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()
}
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() {
#[cfg(test)]
REGEX_FIRST.with(|n| n.set(n.get() + 1));
self.tier(tally, Tier::Regex);
return self.regex_won(input, out);
}
}
self.parse_fast(input, out, tally, false)
.map(|(won, _)| won)
}
fn parse_fast<'a>(
&self,
input: &'a [u8],
out: &mut dyn FieldSink<'a>,
tally: &mut Tally<'_>,
timed: bool,
) -> Result<(Option<usize>, Option<f32>), 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, None));
}
Some(_) => {
native.score(if on { Went::First } else { Went::Probed });
self.tier(tally, Tier::Field);
return Ok((Some(0), None));
}
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 Native::reads_as_regex(&native.plans[0], input) => {
native.score(Went::First);
self.tier(tally, Tier::Field);
native.write(0, &steps, input, out);
return Ok((Some(0), None));
}
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, None));
};
if !spent && Native::reads_as_regex(&native.plans[pid], input) {
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), None));
}
}
native.score(missed);
self.tier(tally, Tier::Regex);
return self.regex_timed(input, out, timed);
}
#[cfg(feature = "parse-backtracking")]
if self.backtracking.is_some() && !self.signature.may_match(input) {
self.tier(tally, Tier::Regex);
return Ok((None, Some(0.0)));
}
self.tier(tally, Tier::Regex);
self.regex_timed(input, out, timed)
}
fn regex_timed<'a>(
&self,
input: &'a [u8],
out: &mut dyn FieldSink<'a>,
timed: bool,
) -> Result<(Option<usize>, Option<f32>), ParseError> {
let clock = timed.then(Clock::now);
let won = self.regex_won(input, out)?;
Ok((won, Some(clock.map_or(0.0, |c| c.ns()))))
}
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, by_regex) = self.parse_fast(input, &mut by_steps, tally, true)?;
let steps_ns = clock.ns();
let (regex_ns, agreed) = if let Some(regex_ns) = by_regex {
(regex_ns, true)
} else {
let mut by_regex = Fields::new();
let clock = Clock::now();
let regex = self.regex_won(input, &mut by_regex)?;
let regex_ns = clock.ns();
let agreed = agree(&parsed(won), &by_steps, &parsed(regex), &by_regex);
(regex_ns, agreed)
};
shadow.record(steps_ns, regex_ns, agreed);
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 shadow_state(&self) -> Option<(u32, bool)> {
self.shadow.as_ref().map(|s| (s.samples(), s.regex_first()))
}
#[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();
if !Native::reads_as_regex(&native.plans[0], input) {
return Some((Outcome::Unsure, 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 native_units(&self, input: &[u8]) -> Option<(Outcome, usize, usize)> {
Some(self.native.as_ref()?.plans[0].run_units(input))
}
#[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)
}
fn regex_won<'a>(
&self,
input: &'a [u8],
out: &mut dyn FieldSink<'a>,
) -> Result<Option<usize>, ParseError> {
let answer = self.linear_answer(input)?;
#[cfg(feature = "parse-backtracking")]
if let Some(hit) = self
.backtracking
.as_ref()
.map(|b| b.search(input, answer.as_ref().map(|a| a.place(self))))
.transpose()?
.flatten()
{
let linear = answer.as_ref().map(|a| a.place(self));
if linear.is_none_or(|first| (hit.start, hit.index) < first) {
hit.write(input, out);
return Ok(Some(hit.index));
}
}
match answer {
None => Ok(None),
Some(Answer::Fancy(hit)) => {
hit.write(input, out);
Ok(Some(hit.index))
}
Some(Answer::Slots { pid, shape, slots }) => {
for (i, capture) in self.groups[pid.as_usize()].iter().enumerate() {
if let (Some(c), Some(span)) = (capture, group_span(Some(shape), &slots, i))
&& let Some(v) = c.value(&input[span])
{
out.field(&c.field, v);
}
}
Ok(Some(self.checks[pid.as_usize()].index))
}
}
}
fn linear_answer<'g, 'a>(
&'g self,
input: &'a [u8],
) -> Result<Option<Answer<'g, 'a>>, ParseError> {
let search = Input::new(input);
let (pid, 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(&search, &mut slots);
(pid, pid.map(|pid| (&self.regex, pid)), slots)
} else if let Some(m) = self.regex.search(&search) {
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 (Some(pid), Some(shape)) = (pid, shape) else {
return Ok(None);
};
if self.keeps(pid.as_usize(), Some(shape), &slots, input) {
return Ok(Some(Answer::Slots { pid, shape, slots }));
}
let start = group_span(Some(shape), &slots, 0).map_or(0, |m| m.start);
self.refused(input, start)
}
fn keeps(
&self,
pid: usize,
shape: Option<(&Regex, PatternID)>,
slots: &[Option<NonMaxUsize>],
input: &[u8],
) -> bool {
let c = &self.checks[pid];
c.groups.is_empty()
|| (!c.repeated
&& c.groups.iter().all(|&(g, edge)| {
group_span(shape, slots, g).is_none_or(|s| edge.holds(input, s.start))
}))
}
fn refused<'g, 'a>(
&'g self,
input: &'a [u8],
from: usize,
) -> Result<Option<Answer<'g, 'a>>, ParseError> {
let mut best: Option<Answer<'g, 'a>> = None;
for (q, c) in self.checks.iter().enumerate() {
let found = if c.groups.is_empty() {
let one = self.each.get(q).unwrap_or(&self.regex);
let mut slots = super::scratch::slots(one.group_info().slot_len());
let at = Input::new(input).range(from..);
one.search_slots(&at, &mut slots).map(|own| Answer::Slots {
pid: PatternID::new_unchecked(q),
shape: (one, own),
slots,
})
} else {
c.fancy()?.search_from(input, from)?.map(Answer::Fancy)
};
let Some(found) = found else { continue };
if best.as_ref().is_none_or(|b| found.start() < b.start()) {
let first = found.start() == from;
best = Some(found);
if first {
break;
}
}
}
Ok(best)
}
}
const RECORD_BACKTRACKS: usize = 1_000_000;
#[cfg(test)]
thread_local! {
pub(super) static REGEX_FIRST: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
}
enum Answer<'g, 'a> {
Slots {
pid: PatternID,
shape: (&'g Regex, PatternID),
slots: super::scratch::Lease<Option<NonMaxUsize>>,
},
Fancy(Hit<'g, 'a>),
}
impl Answer<'_, '_> {
fn start(&self) -> usize {
match self {
Self::Slots { shape, slots, .. } => {
group_span(Some(*shape), slots, 0).map_or(0, |m| m.start)
}
Self::Fancy(hit) => hit.start,
}
}
#[cfg(feature = "parse-backtracking")]
fn place(&self, grok: &Grok) -> (usize, usize) {
match self {
Self::Slots { pid, .. } => (self.start(), grok.checks[pid.as_usize()].index),
Self::Fancy(hit) => (hit.start, hit.index),
}
}
}
struct Checks {
index: usize,
groups: Vec<(usize, Edge)>,
repeated: bool,
rendered: Option<Expanded>,
limit: usize,
fancy: OnceLock<Result<Pattern, String>>,
}
impl Checks {
fn each(
regex: &Regex,
linear: &[usize],
expanded: &[Expanded],
mut rendered: Vec<Option<Expanded>>,
limit: usize,
) -> Vec<Self> {
linear
.iter()
.enumerate()
.map(|(pid, &i)| Self::new(regex, pid, i, &expanded[i], rendered[i].take(), limit))
.collect()
}
fn new(
regex: &Regex,
pid: usize,
index: usize,
expanded: &Expanded,
rendered: Option<Expanded>,
limit: usize,
) -> Self {
let names: Vec<Option<&str>> = regex
.group_info()
.pattern_names(PatternID::new_unchecked(pid))
.collect();
let groups: Vec<(usize, Edge)> = expanded
.edges
.iter()
.enumerate()
.filter_map(|(k, &edge)| {
let name = format!("e{k}");
let g = names.iter().position(|n| *n == Some(name.as_str()))?;
Some((g, edge))
})
.collect();
let repeated = !groups.is_empty()
&& regex_syntax::parse(&expanded.regex).is_ok_and(|hir| {
let at: Vec<usize> = groups.iter().map(|&(g, _)| g).collect();
repeats_an_edge(&hir, &at, false)
});
Self {
index,
groups,
repeated,
rendered,
limit,
fancy: OnceLock::new(),
}
}
fn fancy(&self) -> Result<&Pattern, ParseError> {
let built = self.fancy.get_or_init(|| {
let e = self
.rendered
.as_ref()
.ok_or_else(|| "a pattern with no lookaround reading".to_owned())?;
Pattern::new(self.index, &e.regex, &e.captures, self.limit).map_err(|e| e.to_string())
});
built
.as_ref()
.map_err(|e| ParseError::Other(e.clone().into()))
}
}
fn repeats_an_edge(hir: ®ex_syntax::hir::Hir, edges: &[usize], inside: bool) -> bool {
use regex_syntax::hir::HirKind;
match hir.kind() {
HirKind::Capture(c) => {
(inside && usize::try_from(c.index).is_ok_and(|i| edges.contains(&i)))
|| repeats_an_edge(&c.sub, edges, inside)
}
HirKind::Repetition(r) => repeats_an_edge(&r.sub, edges, inside || r.max != Some(1)),
HirKind::Concat(subs) | HirKind::Alternation(subs) => {
subs.iter().any(|h| repeats_an_edge(h, edges, inside))
}
HirKind::Empty | HirKind::Literal(_) | HirKind::Class(_) | HirKind::Look(_) => false,
}
}
fn group_span(
shape: Option<(&Regex, PatternID)>,
slots: &[Option<regex_automata::util::primitives::NonMaxUsize>],
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())
}
fn report_blocked(
name: &str,
strict: bool,
blocked: &[Option<&'static str>],
) -> Result<(), GrokBuildError> {
for (index, reason) in blocked.iter().enumerate() {
if let Some(reason) = *reason {
if strict {
return Err(GrokBuildError::NotNative {
index,
reason,
hint: hint(reason),
});
}
summarise(name, index, reason);
}
}
Ok(())
}
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 number the next step could make give back digits" => {
"Put a literal between them that a number can't hold, or opt the pattern into backtracking"
}
"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,
})
}