#![allow(
clippy::literal_string_with_formatting_args,
reason = "grok's %{NAME:field} reads as a format argument"
)]
use proptest::prelude::*;
use super::plan::Outcome;
use super::*;
use crate::parse::{Fields, Parsed, Parser};
const LOWERED: [&str; 45] = [
"%{IPV4:ip}:%{POSINT:port}",
"^%{WORD:verb} %{NOTSPACE:path} HTTP/%{NUMBER:v}$",
"%{IPORHOST:host} %{DATA:prog}: %{GREEDYDATA:msg}",
"^%{DATA:a} %{WORD:b}$",
"user=%{USERNAME:u} ip=%{IP:ip}",
"^%{INT:n} %{WORD:w}%{SPACE}",
"\\[%{HTTPDATE:t}\\] %{QS:q}",
"%{HTTPD_COMMONLOG}",
"%{WORD:a}(?: %{INT:n})? (?:-|%{NUMBER:b})",
"^[a-z]+=%{INT:n}",
"user=\\w+ id=\\d{2,4}(?:x)?",
"^%{WORD:k} +\\S+$",
"^%{WORD:k}\\s+%{NOTSPACE:v}$",
"^(?:%{INT},)+%{WORD:w}$",
"^%{WORD:a}(?: [a-z]+)*$",
"x(?:ab|a)+?y",
"^(?:[0-9]+,)*%{GREEDYDATA:rest}",
r"^\[%{WORD:w}] %{INT:n}$",
"%{WORD:a}%{WORD:b}",
"%{NUMBER:a}.%{INT:b}",
"^%{INT:n}%{SPACE}%{WORD:w}",
"%{SYSLOGTIMESTAMP:ts} %{WORD:h}",
"%{IP:ip}:%{INT:port}",
"^%{TIMESTAMP_ISO8601:t} %{WORD:w}",
"%{IPORHOST:h}:%{POSINT:p}",
r"%{NUMBER:n}\b",
r"(?:^%{WORD:a}:%{INT:b})",
r"\b%{INT:n}\b x",
r"(?:^%{INT:n}|x%{WORD:w})",
r"%{WORD:w}$|%{INT:n} ",
"%{GREEDYDATA:a} x%{INT:n}",
"%{NOTSPACE:a} %{INT:n}",
"%{DATA:a}: %{WORD:b}",
"(?<a>[a-z]+)=%{INT:n}",
"(?i)user=%{WORD:u}",
"(?i:err|warn) %{INT:n}",
"^(?i)%{INT:n}k",
"x[.]%{INT:n}",
"(?i)\u{e9}%{INT:n}",
"^(?i)%{MONTH:m} %{INT:d}",
"x%{INT:n}(?i)k",
"a(?i)b|c%{INT:n}",
"%{DATA:a}(?s)%{DATA:b}x",
"(?:^%{DATA:a} has) x",
"a}%{INT:n}",
];
const ONIG: [&str; 10] = [
r"^\<%{INT:pri}\>%{WORD:w}$",
"^%{WORD:a} %{GREEDYDATA:b}$",
r"id=\h{2,4} %{WORD:w}$",
r"^\<(?<pri>[0-9]+)\>(?<rest>.*)$",
r"(?:^%{WORD:a} %{INT:n})",
r"%{WORD:w}$\n%{WORD:v}",
"^%{WORD:w} (?m)%{GREEDYDATA:rest}",
"^{%{DATA:x}}$",
r"^(?<time>[^ ]*)\s+(?<severity>\w)\s+(?<component>[^ ]+)\s+\[(?<context>[^\]]+)]\s+(?<message>.*?) *(?<ms>(\d+))?(:?ms)?$",
r"^\<(?<pri>[0-9]+)\>(?<time>[^ ]* {1,2}[^ ]* [^ ]*) (?<host>[^ ]*) (?<ident>[a-zA-Z0-9_\/\.\-]*)(?:\[(?<pid>[0-9]+)\])?(?:[^\:]*\:)? *(?<message>.*)$",
];
const PCRE: [&str; 5] = [
r"^\<%{INT:pri}\>%{WORD:w}$",
r#"^{"id":%{INT:n},"tag":"(?<tag>[^"\>]+)"}"#,
r"(?<p>[\w[\]]+) %{INT:n}",
r"to=\<(?<to>[^\>\s]+)\>",
r#"^(?<k>[a-z]++)="(?<v>[^"]*+)" %{INT:n}"#,
];
static ONIG_BUILT: std::sync::LazyLock<Vec<Grok>> = std::sync::LazyLock::new(|| {
let onig = ONIG.iter().map(|p| (*p, Dialect::Oniguruma));
onig.chain(PCRE.iter().map(|p| (*p, Dialect::Pcre)))
.map(|(p, dialect)| {
Grok::builder("grok:o")
.pattern(p)
.dialect(dialect)
.strict(true)
.build()
.unwrap()
})
.collect()
});
fn grok(pattern: &str) -> Grok {
Grok::builder("grok:p").pattern(pattern).build().unwrap()
}
static BUILT: std::sync::LazyLock<Vec<Grok>> =
std::sync::LazyLock::new(|| LOWERED.iter().map(|p| grok(p)).collect());
fn regex_fields(g: &Grok, input: &[u8]) -> Option<Vec<(String, Vec<u8>)>> {
let mut out = Fields::new();
let parsed = g.parse_regex(input, &mut out).unwrap();
fields_of(&parsed, &out)
}
fn parse_fields(g: &Grok, input: &[u8]) -> Option<Vec<(String, Vec<u8>)>> {
let mut out = Fields::new();
let parsed = g.parse(input, &mut out).unwrap();
fields_of(&parsed, &out)
}
fn fields_of(parsed: &Parsed, out: &Fields<'_>) -> Option<Vec<(String, Vec<u8>)>> {
match parsed {
Parsed::NoMatch => None,
_ => Some(
out.as_slice()
.iter()
.map(|(n, v)| (n.clone(), v.bytes.to_vec()))
.collect(),
),
}
}
fn agrees(g: &Grok, input: &[u8]) -> Result<Option<bool>, TestCaseError> {
let (outcome, native) = g.native_outcome(input).expect("the pattern lowers");
let regex = regex_fields(g, input);
match outcome {
Outcome::Unsure => Ok(None),
Outcome::NoMatch => {
prop_assert_eq!(regex, None, "{:?}", String::from_utf8_lossy(input));
Ok(Some(true))
}
Outcome::Matched => {
prop_assert_eq!(regex, Some(native), "{:?}", String::from_utf8_lossy(input));
Ok(Some(true))
}
}
}
#[test]
fn patterns_lower_only_when_each_boundary_is_decided() {
for p in LOWERED {
let g = grok(p);
assert_eq!(g.blocked(), [None], "{p}");
assert_eq!(g.tier(), crate::tier::MatcherTier::Field, "{p}");
}
for (p, why) in [
(
"[a-z]{1,63}x",
"an unanchored pattern that starts with a run",
),
("\\b\\d+", "an unanchored pattern that starts with a run"),
("(?x)%{INT:n}", "regex syntax outside a reference"),
("(?:%{INT:n},)+", "a repeated group with a capture"),
] {
assert_eq!(grok(p).blocked(), [Some(why)], "{p}");
}
}
#[test]
fn known_lines_take_the_regex_answer() {
let g = grok("^%{DATA:a} %{WORD:b}$");
assert_eq!(
g.native_outcome(b"x y z"),
Some((
Outcome::Matched,
vec![("a".into(), b"x y".to_vec()), ("b".into(), b"z".to_vec())]
))
);
let mut out = Fields::new();
assert_eq!(g.parse(b"x y z", &mut out).unwrap(), Parsed::Done);
let got: Vec<_> = out
.as_slice()
.iter()
.map(|(n, v)| (n.as_str(), v.bytes.to_vec()))
.collect();
assert_eq!(got, [("a", b"x y".to_vec()), ("b", b"z".to_vec())]);
let g = grok("%{IPORHOST:host} %{DATA:prog}: %{GREEDYDATA:msg}");
assert_eq!(
g.native_outcome(b"10.1.2.3.4 p: m").map(|o| o.0),
Some(Outcome::Unsure)
);
let g = grok("%{HTTPD_COMMONLOG}");
let line = br#"10.0.0.1 - frank [26/Nov/2026:11:22:33 +1100] "GET /a.gif HTTP/1.0" 200 2326"#;
assert_eq!(g.native_outcome(line).map(|o| o.0), Some(Outcome::Matched));
assert_eq!(
g.native_outcome(line).map(|o| o.1),
Some(regex_fields(&g, line).unwrap())
);
let raw = br#"10.0.0.1 - - [26/Nov/2026:11:22:33 +1100] "\x16\x03" 400 -"#;
assert_eq!(
g.native_outcome(raw).map(|o| o.1),
Some(regex_fields(&g, raw).unwrap())
);
let g = grok("%{IPV4:ip}:%{POSINT:port}");
assert_eq!(
g.native_outcome(b"to 10.1.2.3:443 ok").map(|o| o.0),
Some(Outcome::Matched)
);
assert_eq!(
g.native_outcome(b"10.1.2.3:x").map(|o| o.0),
Some(Outcome::NoMatch)
);
}
fn pieces() -> Vec<&'static str> {
vec![
"10.1.2.3",
"1.2.3.4567",
"2026-11-26",
"T",
"10:00",
":30",
"Z",
"+11:00",
"+",
"USER=",
"user=",
"Err",
"WARN",
"k",
"K",
"\u{c9}",
"\u{e9}",
"Jan",
"{",
"}",
"a}",
" has",
"JAN",
"jan",
"5",
"::1",
"fe80::1",
":",
"443",
"0",
"80x",
" ",
" ",
"GET",
"/a/b",
"HTTP/",
"1.1",
"2",
"x",
"y",
"Nov 6 08:01:02",
"host.example.com",
"sshd[12]",
": ",
"msg",
"\n",
"user=",
"ip=",
"bob",
"é",
"-",
"[",
"]",
"26/Nov/2026:11:22:33 +1100",
"\"q\"",
"\"",
"\\",
"\t",
".",
"4",
".4",
"\r",
"\r\n",
"<",
">",
"<13>",
"1f",
"id=",
"Nov 6",
"{\"id\":7,\"tag\":\"x\"}",
"to=<a@b.c>",
]
}
proptest! {
#![proptest_config(ProptestConfig::with_cases(4096))]
#[test]
fn native_steps_agree_with_the_regex(
which in 0..LOWERED.len(),
body in prop::collection::vec(prop::sample::select(pieces()), 0..10),
) {
agrees(&BUILT[which], body.concat().as_bytes())?;
}
#[test]
fn other_dialects_steps_agree_with_the_regex(
which in 0..ONIG.len() + PCRE.len(),
body in prop::collection::vec(prop::sample::select(pieces()), 0..10),
) {
agrees(&ONIG_BUILT[which], body.concat().as_bytes())?;
}
}
#[test]
fn oniguruma_m_lets_dot_cross_a_newline() {
let g = &Grok::builder("grok:o")
.pattern("^%{WORD:w} (?m)%{GREEDYDATA:rest}")
.dialect(Dialect::Oniguruma)
.strict(true)
.build()
.unwrap();
let line = b"a b\nc";
let (outcome, fields) = g.native_outcome(line).unwrap();
assert_eq!(outcome, Outcome::Matched);
assert_eq!(fields[1].1, b"b\nc");
assert_eq!(Some(fields), regex_fields(g, line));
}
#[test]
fn oniguruma_anchors_are_line_anchors() {
let g = &ONIG_BUILT[0];
for (line, pri) in [
(&b"<13>up"[..], Some("13")),
(b"<13>up\n", Some("13")),
(b"<13>up\r\n", Some("13")),
(b"<13>up\r", Some("13")),
(b"junk\n<14>up", Some("14")),
(b"<13>up\n\n", Some("13")),
(b"<13>up\r\r", None),
(b"<13>up x", None),
] {
let (outcome, fields) = g.native_outcome(line).unwrap();
let got = (outcome == Outcome::Matched).then(|| fields[0].1.clone());
assert_eq!(got.as_deref(), pri.map(str::as_bytes), "{line:?}");
assert_eq!(
got,
regex_fields(g, line).map(|f| f[0].1.clone()),
"{line:?}"
);
}
}
proptest! {
#![proptest_config(ProptestConfig::with_cases(4096))]
#[test]
fn ambiguous_fields_agree_with_the_regex(
which in 18..LOWERED.len(),
body in prop::collection::vec(prop::sample::select(pieces()), 0..10),
) {
agrees(&BUILT[which], body.concat().as_bytes())?;
}
}
#[test]
fn an_ambiguous_field_takes_its_one_viable_end() {
for (p, line, field) in [
(
"%{IP:ip}:%{INT:port}",
&b"to 10.1.2.3:443 ok"[..],
"10.1.2.3",
),
(
"^%{TIMESTAMP_ISO8601:t} %{WORD:w}",
b"2026-11-26 10:00:00 INFO x",
"2026-11-26 10:00:00",
),
(
"%{SYSLOGTIMESTAMP:ts} %{WORD:h}",
b"Nov 6 08:01:02 host sshd",
"Nov 6 08:01:02",
),
(
"%{IPORHOST:h}:%{POSINT:p}",
b"example.com:443",
"example.com",
),
] {
let g = grok(p);
let (outcome, fields) = g.native_outcome(line).unwrap();
assert_eq!(outcome, Outcome::Matched, "{p}");
assert_eq!(fields[0].1, field.as_bytes(), "{p}");
assert_eq!(Some(fields), regex_fields(&g, line), "{p}");
}
let g = grok("%{IP:ip}:%{INT:port}");
let (outcome, fields) = g.native_outcome(b"fe80::1:443").unwrap();
assert_eq!(outcome, Outcome::Matched);
assert_eq!(Some(fields), regex_fields(&g, b"fe80::1:443"));
for (p, line) in [
(r"%{NUMBER:n}\b", &b"12.5x"[..]),
(r"%{NUMBER:n}$", b"12.5"),
] {
let g = grok(p);
let (outcome, fields) = g.native_outcome(line).unwrap();
assert_ne!(outcome, Outcome::NoMatch, "{p}");
if outcome == Outcome::Matched {
assert_eq!(Some(fields), regex_fields(&g, line), "{p}");
}
}
assert_eq!(
g.native_outcome(b"1::2:3:4").map(|o| o.0),
Some(Outcome::Unsure)
);
}
#[test]
fn folded_patterns_match_as_the_regex_does() {
for (p, line) in [
("^(?i)%{MONTH:m} %{INT:d}", &b"JAN 5"[..]),
("^(?i)%{MONTH:m} %{INT:d}", b"jan 5"),
("(?i)user=%{WORD:u}", b"USER=bob"),
("(?i:err|warn) %{INT:n}", b"WaRn 3"),
("(?i)\u{e9}%{INT:n}", "\u{c9}7".as_bytes()),
("a(?i)b|c%{INT:n}", b"C5"),
("x%{INT:n}(?i)k", b"x1K"),
("%{DATA:a}(?s)%{DATA:b}x", b"p\nqx"),
] {
let g = grok(p);
let (outcome, fields) = g.native_outcome(line).unwrap();
assert_eq!(outcome, Outcome::Matched, "{p} on {line:?}");
assert_eq!(Some(fields), regex_fields(&g, line), "{p} on {line:?}");
}
}
#[test]
fn a_flag_covers_only_what_follows_it_in_its_group() {
for (p, line) in [
("x%{INT:n}(?i)k", &b"X1k"[..]),
("(?:(?i)a)b", b"AB"),
("(?:(?i)a)[b]", b"AB"),
("%{DATA:a}(?s)%{DATA:b}x", b"p\nq\nx"),
] {
let g = grok(p);
assert_eq!(
regex_fields(&g, line).is_none(),
p != "%{DATA:a}(?s)%{DATA:b}x",
"{p}"
);
let (outcome, fields) = g.native_outcome(line).unwrap();
match outcome {
Outcome::Matched => assert_eq!(Some(fields), regex_fields(&g, line), "{p}"),
Outcome::NoMatch => assert_eq!(None, regex_fields(&g, line), "{p}"),
Outcome::Unsure => {}
}
}
}
#[test]
fn every_lowered_definition_agrees_on_lines_drawn_from_its_regex() {
use proptest::strategy::{Strategy, ValueTree};
use proptest::test_runner::{Config, RngAlgorithm, TestRng, TestRunner};
let lib = Library::default();
let mut names: Vec<&String> = lib.defs.keys().collect();
names.sort();
let mut runner = TestRunner::new_with_rng(
Config::default(),
TestRng::from_seed(RngAlgorithm::ChaCha, &[7; 32]),
);
let mut matched = 0;
for dialect in [Dialect::Rust, Dialect::Oniguruma] {
for name in &names {
let p = format!("%{{{name}}}");
let Ok(g) = Grok::builder("grok:d").pattern(&p).dialect(dialect).build() else {
continue;
};
if g.blocked()[0].is_some() {
continue;
}
let shape = expand(&p, &lib, dialect)
.unwrap()
.regex
.replace("(?m)", "")
.replace("\\b", "")
.replace(['^', '$'], "");
let Ok(lines) = proptest::string::string_regex(&shape) else {
continue;
};
for _ in 0..3 {
let line = lines.new_tree(&mut runner).unwrap().current();
let half: String = line.chars().take(line.chars().count() / 2).collect();
for input in [format!("x {line}"), format!("{line} y"), half, line] {
let (outcome, fields) = g.native_outcome(input.as_bytes()).unwrap();
let regex = regex_fields(&g, input.as_bytes());
assert_eq!(
parse_fields(&g, input.as_bytes()),
regex,
"{p} parses {input:?}"
);
match outcome {
Outcome::Matched => {
matched += 1;
assert_eq!(Some(fields), regex, "{p} on {input:?}");
}
Outcome::NoMatch => assert_eq!(None, regex, "{p} on {input:?}"),
Outcome::Unsure => {}
}
}
}
}
}
assert!(matched > 1_000, "only {matched} lines matched natively");
}
#[test]
fn every_date_format_lowers_and_agrees_with_the_regex() {
use proptest::strategy::{Strategy, ValueTree};
use proptest::test_runner::{Config, RngAlgorithm, TestRng, TestRunner};
let mut runner = TestRunner::new_with_rng(
Config::default(),
TestRng::from_seed(RngAlgorithm::ChaCha, &[11; 32]),
);
let mut matched = 0;
for format in [
"%Y-%m-%dT%H:%M:%S%.f%:z",
"%d/%b/%Y:%H:%M:%S %z",
"%b %e %H:%M:%S",
"%a, %d %b %Y %T %z",
"%Y%m%d%H%M%S",
"%m/%d/%y %I:%M:%S %p",
"%s.%f",
"%C%y-%j",
"%Y-%m-%dT%H:%M%:::z",
] {
for p in [
format!("%{{:ts:date({format})}}"),
format!("^%{{:ts:date({format})}} %{{WORD:w}}"),
] {
let g = grok(&p);
assert!(g.blocked()[0].is_none(), "{p}: {}", g.explain());
let lines =
proptest::string::string_regex(&super::date_pattern(format).unwrap()).unwrap();
for _ in 0..40 {
let line = format!("{} ok", lines.new_tree(&mut runner).unwrap().current());
let half: String = line.chars().take(line.chars().count() / 2).collect();
for input in [format!("x {line}"), half, line] {
let (outcome, fields) = g.native_outcome(input.as_bytes()).unwrap();
let regex = regex_fields(&g, input.as_bytes());
assert_eq!(
parse_fields(&g, input.as_bytes()),
regex,
"{p} parses {input:?}"
);
match outcome {
Outcome::Matched => {
matched += 1;
assert_eq!(Some(fields), regex, "{p} on {input:?}");
}
Outcome::NoMatch => assert_eq!(None, regex, "{p} on {input:?}"),
Outcome::Unsure => {}
}
}
}
}
}
assert!(matched > 500, "only {matched} lines matched natively");
}
#[test]
fn the_regex_decides_few_inputs() {
let lines: [&[u8]; 16] = [
b"10.1.2.3:443",
b"GET /a HTTP/1.1",
b"host sshd[12]: msg",
b"user=bob ip=::1",
b"12 word ",
b"[26/Nov/2026:11:22:33 +1100] \"q\"",
br#"10.0.0.1 - frank [26/Nov/2026:11:22:33 +1100] "GET /a HTTP/1.0" 200 2326"#,
b"a 1 -",
b"abc=12",
b"user=bob id=123x",
b"key value",
b"key\tvalue",
b"1,22,x",
b"go a bc",
b"xabay",
b"1,22,x",
];
for (p, line) in LOWERED
.iter()
.filter(|p| **p != "^%{DATA:a} %{WORD:b}$")
.zip(lines)
{
let g = grok(p);
assert_eq!(
g.native_outcome(line).map(|o| o.0),
Some(Outcome::Matched),
"{p}"
);
}
}
#[test]
fn strict_refuses_a_pattern_on_the_regex_and_explain_says_why() {
let refused = Grok::builder("grok:s")
.pattern("(?x)%{INT:n}")
.strict(true)
.build();
assert!(matches!(
refused,
Err(GrokBuildError::NotNative {
index: 0,
reason: "regex syntax outside a reference",
..
})
));
assert!(
Grok::builder("grok:s")
.pattern("%{IPV4:ip}:%{POSINT:p}")
.strict(true)
.build()
.is_ok()
);
let g = Grok::builder("grok:e")
.pattern("%{IPV4:ip}")
.pattern("x %{INT:n}")
.build()
.unwrap();
let text = g.explain();
assert!(
text.starts_with("0: lowers, but the list runs on the regex"),
"{text}"
);
assert!(text.contains("1: lowers"), "{text}");
let g = grok("(?x)%{INT:n}");
assert!(
g.explain()
.starts_with("0: regex: regex syntax outside a reference. Write the class"),
"{}",
g.explain()
);
assert!(
grok("%{IPV4:ip}")
.explain()
.starts_with("0: native steps, tier Field, about ")
);
}
#[test]
fn the_steps_never_read_a_pattern_or_a_line_differently_from_the_regex() {
for p in ["\\<%{WORD:a}\\>", "%{POSINT:n}\\>"] {
assert_eq!(
grok(p).blocked(),
[Some("an escape that isn't a literal")],
"{p}"
);
}
assert_eq!(grok("\\[%{INT:n}\\]").blocked(), [None]);
let rows: [(&str, &[u8]); 6] = [
("%{QS:q}", b"\"\xFF\""),
("%{IPV4:ip}:%{POSINT:port}", b"\xE4\xB8\xAD\x8010.1.2.3:443"),
("%{POSINT:n}:", b"\xC3\xA9\x8012:"),
("%{HOSTNAME:h}!", b"\xC3\xA9\x80foo!"),
("%{WINPATH:p}", b"C:\\a\xFFb"),
("^(?:%{NONNEGINT})?", b"\xBF"),
];
for (p, input) in rows {
let g = grok(p);
let mut out = Fields::new();
let parsed = g.parse(input, &mut out).unwrap();
let native: Option<Vec<(String, Vec<u8>)>> = (parsed != Parsed::NoMatch).then(|| {
out.as_slice()
.iter()
.map(|(n, v)| (n.clone(), v.bytes.to_vec()))
.collect()
});
assert_eq!(native, regex_fields(&g, input), "{p} on {input:?}");
}
assert_eq!(
grok("[a-z]{1,40}%{INT:n}").blocked(),
[Some("an unanchored pattern that starts with a run")]
);
}
#[test]
fn a_long_line_costs_the_steps_in_proportion_to_its_length() {
for p in [
"%{MAC:m}",
"%{DATA:a}%{WORD:b}",
"%{GREEDYDATA:a} x%{INT:n}",
] {
let g = grok(p);
let time = |n: usize| {
let line = vec![b'a'; n];
g.native_outcome(&line);
(0..5)
.map(|_| {
let t = std::time::Instant::now();
for _ in 0..3 {
g.native_outcome(&line);
}
t.elapsed()
})
.min()
.unwrap_or_default()
};
let (short, long) = (time(4_000), time(16_000));
assert!(
long < short * 10,
"{p}: 4x the line took {long:?} against {short:?}"
);
}
}
static LISTS: std::sync::LazyLock<Vec<Grok>> = std::sync::LazyLock::new(|| {
[
&["^%{IPV4:ip} %{WORD:w}", "^%{WORD:w} %{INT:n}"][..],
&["^%{INT:n}", "^%{WORD:w}", "^%{DATA:d}x"],
&[
"^%{IPORHOST:h} %{DATA:p}: %{GREEDYDATA:m}",
"^%{IPV4:ip}:%{POSINT:port}",
],
]
.iter()
.map(|ps| {
ps.iter()
.fold(Grok::builder("grok:l"), |b, p| b.pattern(*p))
.build()
.unwrap()
})
.collect()
});
proptest! {
#![proptest_config(ProptestConfig::with_cases(2048))]
#[test]
fn an_anchored_list_parses_as_the_regex_does(
which in 0..3_usize,
body in prop::collection::vec(prop::sample::select(pieces()), 0..8),
) {
let g = &LISTS[which];
prop_assert_eq!(g.tier(), crate::tier::MatcherTier::Field);
let input = body.concat();
let mut out = Fields::new();
let parsed = g.parse(input.as_bytes(), &mut out).unwrap();
let native: Option<Vec<(String, Vec<u8>)>> = (parsed != Parsed::NoMatch).then(|| {
out.as_slice().iter().map(|(n, v)| (n.clone(), v.bytes.to_vec())).collect()
});
prop_assert_eq!(native, regex_fields(g, input.as_bytes()), "{:?}", input);
}
}
#[test]
fn a_line_without_the_leading_literals_is_no_match_on_one_scan() {
let g = grok("user=%{USERNAME:u} ip=%{IP:ip}");
let mut out = Fields::new();
assert_eq!(g.parse(b"nothing here", &mut out).unwrap(), Parsed::NoMatch);
assert_eq!(regex_fields(&g, b"nothing here"), None);
assert_eq!(
g.parse(b"x user=bob ip=::1", &mut out).unwrap(),
Parsed::Done
);
}
#[test]
fn an_absent_optional_tail_is_decided_natively() {
for (p, line) in [
("%{WORD:a}(?: %{INT:n})?", &b"foo"[..]),
("%{IPV4:ip}(?::%{POSINT:port})?", b"10.1.2.3"),
("%{NUMBER:n}(?:ms)?", b"12"),
] {
let g = grok(p);
let (outcome, fields) = g.native_outcome(line).unwrap();
assert_eq!(outcome, Outcome::Matched, "{p}");
assert_eq!(Some(fields), regex_fields(&g, line), "{p}");
}
}
#[test]
#[ignore = "a report, not a check"]
fn report_the_library_lowering_share() {
let lib = Library::default();
let mut names: Vec<&String> = lib.defs.keys().collect();
names.sort();
let mut blockers = std::collections::BTreeMap::<&str, usize>::new();
let mut lowered = 0;
for name in &names {
match Grok::builder("grok:r")
.pattern(format!("%{{{name}}}"))
.build()
{
Ok(g) => match g.blocked()[0] {
None => {
lowered += 1;
}
Some(why) => {
*blockers.entry(why).or_default() += 1;
}
},
Err(_) => {
*blockers
.entry("does not build on the linear engine")
.or_default() += 1;
}
}
}
eprintln!("REPORT lowered {lowered} of {}", names.len());
for (why, n) in blockers {
eprintln!("REPORT {n:4} {why}");
}
}
#[test]
fn a_definition_with_groups_lowers_and_captures_as_the_regex_does() {
let mut lib = Library::default();
lib.add("PAIR", "(?<key>[a-z]+)=([0-9]+)(?: (?<unit>ms|s))?");
let g = Grok::builder("grok:g")
.library(lib)
.pattern("^%{PAIR}$")
.build()
.unwrap();
assert_eq!(g.blocked(), [None]);
for line in [&b"lat=12 ms"[..], b"lat=12", b"lat=x", b"lat=12 h"] {
let native = g.native_outcome(line).unwrap();
let regex = regex_fields(&g, line);
match native.0 {
Outcome::Matched => assert_eq!(Some(native.1), regex, "{line:?}"),
Outcome::NoMatch => assert_eq!(regex, None, "{line:?}"),
Outcome::Unsure => {}
}
}
assert_eq!(
g.native_outcome(b"lat=12 ms").map(|o| o.1),
Some(vec![
("key".into(), b"lat".to_vec()),
("unit".into(), b"ms".to_vec())
])
);
}
#[test]
fn an_optional_reference_is_tried_then_skipped() {
let g = grok("^%{INT:n}?:%{WORD:w}$");
assert_eq!(g.blocked(), [None]);
for line in [&b"12:ab"[..], b":ab", b"12ab", b"x:ab"] {
let (outcome, fields) = g.native_outcome(line).unwrap();
match outcome {
Outcome::Matched => assert_eq!(Some(fields), regex_fields(&g, line), "{line:?}"),
Outcome::NoMatch => assert_eq!(regex_fields(&g, line), None, "{line:?}"),
Outcome::Unsure => {}
}
}
assert_eq!(
g.native_outcome(b":ab").map(|o| o.0),
Some(Outcome::Matched)
);
assert_eq!(g.native_outcome(b"12:ab").map(|o| o.1.len()), Some(2));
}
#[test]
fn a_greedy_loop_takes_the_most_iterations_first() {
let g = grok("^(?:[0-9]+,)*%{GREEDYDATA:rest}");
assert_eq!(
g.native_outcome(b"1,22,x"),
Some((Outcome::Matched, vec![("rest".into(), b"x".to_vec())]))
);
let lazy = grok("^(?:[0-9]+,)*?%{GREEDYDATA:rest}");
assert_eq!(
lazy.native_outcome(b"1,22,x").map(|o| o.1),
Some(regex_fields(&lazy, b"1,22,x").unwrap())
);
}
#[test]
fn a_plan_counts_what_its_hit_runs() {
use super::plan::{Plan, Tail};
let lib = Library::default();
let terms = |p: &str| {
Plan::lower(p, &lib, Dialect::Rust, Span::Part)
.unwrap()
.terms()
};
let base = terms("^l");
let steps = terms(&format!("^{}", "[a-z]-".repeat(16)));
assert_eq!(base.steps, 1, "{base:?}");
assert_eq!(steps.steps - base.steps, 31, "{base:?} {steps:?}");
assert_eq!(terms("^%{TIMESTAMP_ISO8601:t} ").settled, 1);
assert_eq!(terms("^%{TIMESTAMP_ISO8601:t}[|]").settled, 0);
assert_eq!(terms("^[a-z ]+$").tail, Some(Tail::Class));
assert_eq!(terms("^.*$").tail, Some(Tail::Line), "a line run is memchr");
assert_eq!(
terms("^%{WORD:w} [FP]$").tail,
Some(Tail::Field("WORD")),
"a bounded run isn't a tail"
);
for p in [
"^%{TIMESTAMP_ISO8601:timestamp} (?<stream>stdout|stderr) (?<flag>[FP]) %{GREEDYDATA:message}$",
"^%{COMBINEDAPACHELOG}$",
"^%{WORD:k}=%{INT:v} %{NOTSPACE:rest}$",
] {
println!("{p}: {:?}", terms(p));
}
}
#[test]
fn every_stock_format_runs_compiled_code_that_agrees_with_the_regex() {
use proptest::strategy::{Strategy, ValueTree};
use proptest::test_runner::{Config, RngAlgorithm, TestRng, TestRunner};
let lib = Library::default();
let mut runner = TestRunner::new_with_rng(
Config::default(),
TestRng::from_seed(RngAlgorithm::ChaCha, &[13; 32]),
);
assert!(
super::stock::STOCK.len() > 100,
"{}",
super::stock::STOCK.len()
);
for &(pattern, _) in super::stock::STOCK {
let g = grok(pattern);
assert!(
g.explain()
.starts_with("0: compiled code, then native steps"),
"{}",
g.explain()
);
let shape = expand(pattern, &lib, Dialect::Rust)
.unwrap()
.regex
.replace("\\b", "")
.replace(['^', '$'], "");
let Ok(lines) = proptest::string::string_regex(&shape) else {
continue;
};
for _ in 0..3 {
let line = lines.new_tree(&mut runner).unwrap().current();
let half: String = line.chars().take(line.chars().count() / 2).collect();
for input in [format!("{line} y"), half, line] {
assert_eq!(
parse_fields(&g, input.as_bytes()),
regex_fields(&g, input.as_bytes()),
"{pattern} on {input:?}"
);
}
}
}
}
#[test]
fn a_list_captures_as_the_combined_regex_does() {
use proptest::strategy::{Strategy, ValueTree};
use proptest::test_runner::{Config, RngAlgorithm, TestRng, TestRunner};
use regex_automata::meta::Regex;
let lib = Library::default();
let mut runner = TestRunner::new_with_rng(
Config::default(),
TestRng::from_seed(RngAlgorithm::ChaCha, &[17; 32]),
);
for list in [
&["%{IPV4:ip} %{WORD:w}", "%{WORD:w} %{INT:n}"][..],
&["%{INT:n}x", "%{WORD:w}", "%{DATA:d}x"],
&[
"%{IPORHOST:h} %{DATA:p}: %{GREEDYDATA:m}",
"%{IPV4:ip}:%{POSINT:port}",
],
] {
let g = list
.iter()
.fold(Grok::builder("grok:l"), |b, p| b.pattern(*p))
.build()
.unwrap();
let expanded: Vec<_> = list
.iter()
.map(|p| expand(p, &lib, Dialect::Rust).unwrap())
.collect();
let combined = Regex::new_many(
&expanded
.iter()
.map(|e| e.regex.as_str())
.collect::<Vec<_>>(),
)
.unwrap();
let oracle = |input: &[u8]| {
let mut caps = combined.create_captures();
combined.search_captures(®ex_automata::Input::new(input), &mut caps);
let pid = caps.pattern()?;
let names: Vec<Option<std::sync::Arc<str>>> = combined
.group_info()
.pattern_names(pid)
.map(|n| n.map(Into::into))
.collect();
Some(
names
.iter()
.enumerate()
.filter_map(|(i, name)| {
let k: usize = name.as_ref()?.strip_prefix('g')?.parse().ok()?;
let span = caps.get_group(i)?;
Some((
expanded[pid.as_usize()].captures[k].field.clone(),
input[span.range()].to_vec(),
))
})
.collect::<Vec<_>>(),
)
};
for e in &expanded {
let lines = proptest::string::string_regex(&e.regex.replace("\\b", "")).unwrap();
for _ in 0..40 {
let line = lines.new_tree(&mut runner).unwrap().current();
let half: String = line.chars().take(line.chars().count() / 2).collect();
for input in [format!("x {line}"), half, line] {
assert_eq!(
regex_fields(&g, input.as_bytes()),
oracle(input.as_bytes()),
"{list:?} on {input:?}"
);
}
}
}
}
}
#[test]
fn a_first_try_budget_covers_matching_lines() {
use proptest::strategy::{Strategy, ValueTree};
use proptest::test_runner::{Config, RngAlgorithm, TestRng, TestRunner};
let lib = Library::default();
let mut names: Vec<&String> = lib.defs.keys().collect();
names.sort();
let mut runner = TestRunner::new_with_rng(
Config::default(),
TestRng::from_seed(RngAlgorithm::ChaCha, &[7; 32]),
);
let (mut lines, mut over) = (0_usize, Vec::new());
for name in &names {
let p = format!("^%{{{name}}}");
let Ok(g) = Grok::builder("grok:d").pattern(&p).build() else {
continue;
};
if g.blocked()[0].is_some() {
continue;
}
let shape = expand(&p, &lib, Dialect::Rust)
.unwrap()
.regex
.replace("(?m)", "")
.replace("\\b", "")
.replace(['^', '$'], "");
let Ok(drawn) = proptest::string::string_regex(&shape) else {
continue;
};
for _ in 0..8 {
let line = drawn.new_tree(&mut runner).unwrap().current();
for input in [format!("{line} y"), line] {
let (outcome, spent, budget) = g.first_try_units(input.as_bytes()).unwrap();
if outcome == Outcome::Matched {
lines += 1;
if spent > budget {
over.push(name.as_str());
}
}
}
}
}
assert!(lines > 3_000, "only {lines} lines matched");
over.dedup();
assert!(
over.len() <= 6,
"a first try's budget is short for {} definitions: {over:?}",
over.len()
);
}
const RETRIES: &str = "^%{DATA:a} %{DATA:b} %{DATA:c} %{INT:n}$";
fn words(bytes: usize) -> String {
"x ".repeat(bytes / 2)
}
#[test]
fn the_budgets_take_the_lines_they_are_for() {
use super::plan::{First, Located};
let matched = |first_fits| Located {
outcome: Outcome::Matched,
first_fits,
};
let g = grok(RETRIES);
assert_eq!(
g.first_and_located(b"alpha beta gamma 42").unwrap(),
(First::Matched, matched(true))
);
for bytes in [256, 1024, 4096] {
let long_hit = format!("{}5", words(bytes));
assert_eq!(
g.first_and_located(long_hit.as_bytes()).unwrap(),
(First::Spent, matched(false)),
"{bytes} bytes"
);
let miss = words(bytes);
assert_eq!(
g.first_and_located(miss.as_bytes()).unwrap().0,
First::Spent
);
}
assert_eq!(g.first_and_located(b"alpha").unwrap().0, First::Open);
let fields: Vec<String> = (0..24).map(|i| format!("%{{INT:n{i}}}")).collect();
let long_plan = grok(&format!("^{}$", fields.join("-")));
let line: Vec<String> = (0..24).map(|i| i.to_string()).collect();
assert_eq!(
long_plan
.first_and_located(line.join("-").as_bytes())
.unwrap(),
(First::Matched, matched(true))
);
let second = grok("^(?:%{DATA:a} %{DATA:b} %{DATA:c} %{INT:n}|%{GREEDYDATA:rest})$");
let (first, located) = second.first_and_located(words(1024).as_bytes()).unwrap();
assert_eq!((first, located.outcome), (First::Spent, Outcome::Unsure));
}
#[test]
fn two_first_tries_that_run_out_turn_the_first_try_off() {
let g = grok(RETRIES);
let miss = words(1024);
assert_eq!(parse_fields(&g, b"alpha beta gamma 42").unwrap().len(), 4);
assert!(g.tries_first());
assert_eq!(parse_fields(&g, miss.as_bytes()), None);
assert!(g.tries_first(), "one line that ran out leaves it on");
assert_eq!(parse_fields(&g, miss.as_bytes()), None);
assert!(!g.tries_first());
}
#[test]
fn a_line_past_a_first_trys_budget_does_not_turn_it_back_on() {
let g = grok(RETRIES);
let miss = words(1024);
let long_hit = format!("{}5", words(1024));
for _ in 0..2 {
assert_eq!(parse_fields(&g, miss.as_bytes()), None);
}
assert!(!g.tries_first());
for _ in 0..40 {
assert_eq!(
parse_fields(&g, long_hit.as_bytes()),
regex_fields(&g, long_hit.as_bytes())
);
}
assert!(!g.tries_first());
for _ in 0..20 {
parse_fields(&g, b"alpha beta gamma 42");
}
assert!(g.tries_first(), "lines a first try wins turn it back on");
}
#[test]
fn a_first_try_that_runs_out_on_a_matching_line_gives_the_regexs_fields() {
let long_hit = format!("{}5", words(1024));
let g = grok(RETRIES);
assert!(g.tries_first());
assert_eq!(
parse_fields(&g, long_hit.as_bytes()),
regex_fields(&g, long_hit.as_bytes())
);
let second = grok("^(?:%{DATA:a} %{DATA:b} %{DATA:c} %{INT:n}|%{GREEDYDATA:rest})$");
let line = words(1024);
for _ in 0..3 {
let fields = parse_fields(&second, line.as_bytes());
assert_eq!(fields, regex_fields(&second, line.as_bytes()));
assert_eq!(fields.unwrap()[0].0, "rest");
}
}
#[test]
fn a_stock_parser_on_lines_its_code_cant_settle_stops_trying_first() {
use proptest::strategy::{Strategy, ValueTree};
use proptest::test_runner::{Config, RngAlgorithm, TestRng, TestRunner};
let lib = Library::default();
let mut runner = TestRunner::new_with_rng(
Config::default(),
TestRng::from_seed(RngAlgorithm::ChaCha, &[7; 32]),
);
let mut case = None;
'patterns: for (p, _) in super::stock::STOCK {
let g = grok(p);
let shape = expand(p, &lib, Dialect::Rust)
.unwrap()
.regex
.replace(['^', '$'], "");
let Ok(drawn) = proptest::string::string_regex(&shape) else {
continue;
};
let (mut open, mut settled) = (None, None);
for _ in 0..64 {
let line = drawn.new_tree(&mut runner).unwrap().current();
if regex_fields(&g, line.as_bytes()).is_none() {
continue;
}
match g.stock_says(line.as_bytes()) {
Some(None) => open = open.or(Some(line)),
Some(Some(Parsed::Done)) if line.is_ascii() => settled = settled.or(Some(line)),
_ => {}
}
if let (Some(o), Some(s)) = (&open, &settled) {
case = Some((*p, o.clone(), s.clone()));
break 'patterns;
}
}
}
let (p, open, settled) = case.expect("a line some stock code can't settle");
let g = grok(p);
assert!(g.tries_first());
for _ in 0..64 {
assert_eq!(
parse_fields(&g, open.as_bytes()),
regex_fields(&g, open.as_bytes()),
"{p}"
);
}
assert!(!g.tries_first(), "{p} on {open:?}");
for _ in 0..64 {
parse_fields(&g, settled.as_bytes());
}
assert!(g.tries_first(), "{p} back on with {settled:?}");
}
const WHOLE: [&[&str]; 5] = [
&[
".*?^%{IPV4:addr}:%{PORT:port}$.*",
r".*?^\[%{IPV6:addr}\]:%{PORT:port}$.*",
".*?^%{IPV6:addr}%{SEP}%{PORT:port}$.*",
],
&["^%{DATA} %{DATA:host} %{DATA:kind} %{DATA}$"],
&[
".*?%{KIND}( %{NOTSPACE:op})? src=%{IP:src}( sport=%{NONNEGINT:sport})?.*",
"%{WORD:w}",
],
&[
"%{HDR}%{SPACE}%{WORD:host} %{GREEDYDATA:rest}",
"%{GREEDYDATA:all}",
],
&[
".*?=%{INT:n}",
"%{WORD:w}=.*",
"(?:in %{WORD:dir}|out %{WORD:dir})",
],
];
fn whole_aliases() -> Library {
let mut a = Library::empty();
a.add("SEP", "(?: port |[p#.])");
a.add("KIND", "(alpha|beta|gamma)");
a.add("HDR", "<%{NONNEGINT:pri}>%{VER}");
a.add("VER", r"\b(?:\d{1,2})\b");
a
}
fn whole(list: &[&str]) -> Grok {
list.iter()
.fold(Grok::builder("grok:w"), |b, p| b.pattern(*p))
.aliases(whole_aliases())
.dialect(Dialect::Oniguruma)
.span(Span::Whole)
.drop_empty(true)
.build()
.unwrap()
}
type Listed = Vec<(regex::bytes::Regex, Vec<Capture>)>;
fn first_listed(list: &[&str], aliases: &Library) -> Listed {
let mut lib = Library::default();
let owned: Vec<String> = list.iter().map(|p| (*p).to_owned()).collect();
super::layer_aliases(&owned, aliases, &mut lib)
.iter()
.map(|p| {
let e =
expand_as(p, &lib, Dialect::Oniguruma, Span::Whole, Possessive::Greedy).unwrap();
(regex::bytes::Regex::new(&e.regex).unwrap(), e.captures)
})
.collect()
}
static WHOLE_BUILT: std::sync::LazyLock<Vec<(Grok, Listed)>> = std::sync::LazyLock::new(|| {
WHOLE
.iter()
.map(|l| (whole(l), first_listed(l, &whole_aliases())))
.collect()
});
type Written = Vec<(String, Vec<u8>)>;
fn oracle_of(listed: &Listed, input: &[u8]) -> Option<(usize, Written)> {
listed.iter().enumerate().find_map(|(i, (re, captures))| {
let caps = re.captures(input)?;
let fields = re
.capture_names()
.enumerate()
.filter_map(|(g, name)| {
let k: usize = name?.strip_prefix('g')?.parse().ok()?;
let m = caps.get(g).filter(|m| !m.is_empty())?;
Some((captures[k].field.clone(), m.as_bytes().to_vec()))
})
.collect();
Some((i, fields))
})
}
fn indexed(g: &Grok, input: &[u8]) -> Option<(usize, Written)> {
let mut out = Fields::new();
let won = g.parse_indexed(input, &mut out).unwrap()?;
let fields = out
.as_slice()
.iter()
.map(|(n, v)| (n.clone(), v.bytes.to_vec()))
.collect();
Some((won, fields))
}
fn whole_pieces() -> Vec<&'static str> {
let mut p = pieces();
p.extend([
"src=", " sport=", "alpha", "gamma", " op", "p", "#", " port ", "in ", "out ", "=", "a=",
"<13>1", "\n\n",
]);
p
}
#[test]
fn whole_lists_lower_and_run_natively() {
for (list, (g, _)) in WHOLE.iter().zip(WHOLE_BUILT.iter()) {
assert_eq!(g.tier(), crate::tier::MatcherTier::Field, "{list:?}");
assert!(
g.blocked().iter().all(Option::is_none),
"{list:?}: {:?}",
g.blocked()
);
}
}
proptest! {
#![proptest_config(ProptestConfig::with_cases(4096))]
#[test]
fn a_whole_list_parses_as_the_first_listed_match(
which in 0..WHOLE.len(),
body in prop::collection::vec(prop::sample::select(whole_pieces()), 0..10),
) {
let (g, listed) = &WHOLE_BUILT[which];
let input = body.concat();
let want = oracle_of(listed, input.as_bytes());
prop_assert_eq!(&indexed(g, input.as_bytes()), &want, "{:?}", input);
let regex = regex_fields(g, input.as_bytes())
.map(|f| f.into_iter().filter(|(_, v)| !v.is_empty()).collect::<Vec<_>>());
prop_assert_eq!(regex, want.map(|(_, f)| f), "{:?}", input);
}
}
fn drawable(regex: &str) -> String {
regex
.replace(r"\A", "")
.replace(r"\z", "")
.replace(r"\b", "")
.replace(['^', '$'], "")
}
#[test]
fn whole_lists_agree_on_lines_drawn_from_their_regexes() {
use proptest::strategy::{Strategy, ValueTree};
use proptest::test_runner::{Config, RngAlgorithm, TestRng, TestRunner};
let mut runner = TestRunner::new_with_rng(
Config::default(),
TestRng::from_seed(RngAlgorithm::ChaCha, &[29; 32]),
);
let mut hits = 0;
for (list, (g, listed)) in WHOLE.iter().zip(WHOLE_BUILT.iter()) {
for (re, _) in listed {
let lines = proptest::string::string_regex(&drawable(re.as_str())).unwrap();
for _ in 0..64 {
let line = lines.new_tree(&mut runner).unwrap().current();
let half: String = line.chars().take(line.chars().count() / 2).collect();
for input in [format!("x {line}"), format!("{line}\nx"), half, line] {
let want = oracle_of(listed, input.as_bytes());
hits += usize::from(want.is_some());
assert_eq!(indexed(g, input.as_bytes()), want, "{list:?} on {input:?}");
}
}
}
}
assert!(hits > 1000, "{hits} drawn lines matched");
}
struct Row {
line: usize,
text: String,
source: String,
alias: Option<String>,
libdef: bool,
}
fn corpus(var: &str) -> Option<Vec<Row>> {
let text = std::env::var(var).ok()?;
Some(
text.lines()
.enumerate()
.filter(|(_, l)| !l.trim().is_empty())
.map(|(i, l)| {
let mut cols = l.splitn(3, '\t');
let text = cols.next().unwrap_or_default().to_owned();
let source = cols.next().unwrap_or_default().to_owned();
let tag = cols.next().unwrap_or_default();
Row {
line: i + 1,
text,
source,
alias: tag.strip_prefix("alias=").map(str::to_owned),
libdef: tag.starts_with("libdef="),
}
})
.collect(),
)
}
impl Row {
fn aliases(&self, rows: &[Self]) -> Library {
let mut a = Library::empty();
if !self.libdef {
for r in rows.iter().filter(|r| r.source == self.source) {
if let Some(name) = &r.alias {
a.add(name.clone(), r.text.clone());
}
}
}
a
}
}
const WHOLE_CORPUS: &str = "GRIPPO_GROK_WHOLE_CORPUS";
const LENIENT_CORPUS: &str = "GRIPPO_GROK_CORPUS";
const CORPUS_REFUSED: [(&str, usize); 5] = [
(WHOLE_CORPUS, 120),
(WHOLE_CORPUS, 129),
(WHOLE_CORPUS, 135),
(WHOLE_CORPUS, 140),
(WHOLE_CORPUS, 144),
];
fn corpus_builder(var: &str, row: &Row, rows: &[Row], backtrack: bool) -> GrokBuilder {
let b = Grok::builder("grok:c").dialect(Dialect::Oniguruma);
#[cfg(feature = "parse-backtracking")]
let b = if backtrack {
b.backtracking_pattern(row.text.clone())
} else {
b.pattern(row.text.clone())
};
#[cfg(not(feature = "parse-backtracking"))]
let b = {
let _ = backtrack;
b.pattern(row.text.clone())
};
if var == WHOLE_CORPUS {
b.aliases(row.aliases(rows))
.span(Span::Whole)
.drop_empty(true)
} else {
b.unknown(".+?")
}
}
fn lowered_on_the_default_span(row: &Row, rows: &[Row]) -> bool {
let mut lib = Library::default();
for (name, def) in &row.aliases(rows).defs {
lib.add(name.clone(), def.clone());
}
Grok::builder("grok:b")
.pattern(row.text.clone())
.library(lib)
.dialect(Dialect::Oniguruma)
.build()
.is_ok_and(|b| b.blocked()[0].is_none())
}
#[test]
fn every_corpus_row_builds_or_is_recorded() {
use proptest::strategy::{Strategy, ValueTree};
use proptest::test_runner::{Config, RngAlgorithm, TestRng, TestRunner};
let mut runner = TestRunner::new_with_rng(
Config::default(),
TestRng::from_seed(RngAlgorithm::ChaCha, &[31; 32]),
);
for var in [WHOLE_CORPUS, LENIENT_CORPUS] {
let Some(rows) = corpus(var) else {
eprintln!("{var} isn't set: no corpus to check");
continue;
};
let (mut lowered, mut before, mut hits) = (0, 0, 0);
for row in &rows {
let refused = CORPUS_REFUSED.contains(&(var, row.line));
before += usize::from(lowered_on_the_default_span(row, &rows));
let g = match corpus_builder(var, row, &rows, false).build() {
Ok(g) if !refused => g,
Ok(_) => panic!("{var} row {} builds: take it off the list", row.line),
Err(GrokBuildError::Regex(_)) if refused => {
#[cfg(feature = "parse-backtracking")]
corpus_builder(var, row, &rows, true).build().unwrap();
continue;
}
Err(e) => panic!("{var} row {}: {e}", row.line),
};
lowered += usize::from(g.blocked()[0].is_none());
let Ok(lines) = proptest::string::string_regex(&drawable(&g.regexes()[0])) else {
continue;
};
for _ in 0..8 {
let line = lines.new_tree(&mut runner).unwrap().current();
let half: String = line.chars().take(line.chars().count() / 2).collect();
for input in [format!("x {line}"), half, line] {
let mut out = Fields::new();
let parsed = g.parse(input.as_bytes(), &mut out).unwrap();
let got = fields_of(&parsed, &out);
hits += usize::from(got.is_some());
let regex = regex_fields(&g, input.as_bytes()).map(|f| {
let kept = |v: &Vec<u8>| var != WHOLE_CORPUS || !v.is_empty();
f.into_iter().filter(|(_, v)| kept(v)).collect::<Vec<_>>()
});
assert_eq!(got, regex, "{var} row {} on {input:?}", row.line);
}
}
}
eprintln!(
"REPORT {var}: {} rows, {lowered} lower, {before} lowered on the default span, {hits} drawn lines matched",
rows.len()
);
}
}
#[test]
fn every_whole_corpus_call_takes_the_first_listed_match() {
use proptest::strategy::{Strategy, ValueTree};
use proptest::test_runner::{Config, RngAlgorithm, TestRng, TestRunner};
let Some(rows) = corpus(WHOLE_CORPUS) else {
eprintln!("{WHOLE_CORPUS} isn't set: no corpus to check");
return;
};
let mut runner = TestRunner::new_with_rng(
Config::default(),
TestRng::from_seed(RngAlgorithm::ChaCha, &[37; 32]),
);
let mut sources: Vec<&str> = Vec::new();
for row in rows.iter().filter(|r| r.alias.is_none() && !r.libdef) {
if !sources.contains(&row.source.as_str()) {
sources.push(&row.source);
}
}
let (mut native, mut hits) = (0, 0);
for source in &sources {
let call: Vec<&Row> = rows
.iter()
.filter(|r| r.source == *source && r.alias.is_none() && !r.libdef)
.collect();
let list: Vec<&str> = call.iter().map(|r| r.text.as_str()).collect();
let aliases = call[0].aliases(&rows);
let g = list
.iter()
.fold(Grok::builder("grok:c"), |b, p| b.pattern(*p))
.aliases(aliases.clone())
.dialect(Dialect::Oniguruma)
.span(Span::Whole)
.drop_empty(true)
.build()
.unwrap();
native += usize::from(g.tier() == crate::tier::MatcherTier::Field);
let listed = first_listed(&list, &aliases);
for (re, _) in &listed {
let Ok(lines) = proptest::string::string_regex(&drawable(re.as_str())) else {
continue;
};
for _ in 0..16 {
let line = lines.new_tree(&mut runner).unwrap().current();
let half: String = line.chars().take(line.chars().count() / 2).collect();
for input in [format!("x\n{line}"), format!("{line}\n"), half, line] {
let want = oracle_of(&listed, input.as_bytes());
hits += usize::from(want.is_some());
assert_eq!(indexed(&g, input.as_bytes()), want, "{source} on {input:?}");
}
}
}
}
eprintln!(
"REPORT {WHOLE_CORPUS}: {} calls, {native} run on native steps, {hits} drawn lines matched",
sources.len()
);
}