use regex_automata::meta::Regex;
use super::{Fields, Parsed, Parser};
#[derive(Debug, thiserror::Error)]
#[error("both-paths: the regex does not compile: {0}")]
pub struct CheckError(#[from] Box<regex_automata::meta::BuildError>);
pub type Written = Vec<(String, Vec<u8>)>;
#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
pub enum Disagreement {
Fields {
input: Vec<u8>,
native: Option<Written>,
regex: Option<Written>,
},
Signature {
input: Vec<u8>,
},
}
impl std::fmt::Display for Disagreement {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
Self::Fields {
input,
native,
regex,
} => write!(
f,
"paths disagree on {:?}: native {native:?}, regex {regex:?}",
String::from_utf8_lossy(input)
),
Self::Signature { input } => write!(
f,
"the parser accepts {:?} but its signature rules it out",
String::from_utf8_lossy(input)
),
}
}
}
impl std::error::Error for Disagreement {}
pub fn check<'i, I>(
parser: &dyn Parser,
pattern: &str,
inputs: I,
) -> Result<Result<usize, Disagreement>, CheckError>
where
I: IntoIterator<Item = &'i [u8]>,
{
let re = Regex::new(pattern).map_err(|e| CheckError(Box::new(e)))?;
let mut caps = re.create_captures();
let mut agreed = 0;
for input in inputs {
let mut out = Fields::new();
let native = match parser.parse(input, &mut out) {
Ok(Parsed::Done | Parsed::Body { .. } | Parsed::Decoded(_)) => Some(sorted(
out.as_slice()
.iter()
.map(|(n, v)| (n.clone(), v.bytes.to_vec())),
)),
Ok(Parsed::NoMatch) | Err(_) => None,
};
if native.is_some() && !parser.signature().may_match(input) {
return Ok(Err(Disagreement::Signature {
input: input.to_vec(),
}));
}
re.captures(input, &mut caps);
let regex = caps.is_match().then(|| {
let names = re
.group_info()
.pattern_names(regex_automata::PatternID::ZERO);
sorted(names.enumerate().filter_map(|(i, name)| {
let span = caps.get_group(i)?;
Some((name?.to_owned(), input[span.range()].to_vec()))
}))
});
if native != regex {
return Ok(Err(Disagreement::Fields {
input: input.to_vec(),
native,
regex,
}));
}
agreed += 1;
}
Ok(Ok(agreed))
}
fn sorted(pairs: impl Iterator<Item = (String, Vec<u8>)>) -> Written {
let mut v: Written = pairs.collect();
v.sort();
v
}
#[cfg(test)]
mod tests {
use super::*;
use crate::parse::{FieldSink, FieldValue, Hint, ParseError};
use crate::strmatch::Signature;
use crate::tier::MatcherTier;
struct Pair {
sig: Signature,
loose: bool,
}
impl Parser for Pair {
fn name(&self) -> &'static str {
"pair"
}
fn tier(&self) -> MatcherTier {
MatcherTier::Field
}
fn signature(&self) -> &Signature {
&self.sig
}
fn parse<'a>(
&self,
input: &'a [u8],
out: &mut dyn FieldSink<'a>,
) -> Result<Parsed, ParseError> {
let Some(colon) = memchr::memchr(b':', input) else {
return Ok(Parsed::NoMatch);
};
let (a, b) = (&input[..colon], &input[colon + 1..]);
let digits = |s: &[u8]| !s.is_empty() && s.iter().all(u8::is_ascii_digit);
if !digits(a) || !(self.loose || digits(b)) {
return Ok(Parsed::NoMatch);
}
out.field("a", FieldValue::borrowed(a, Hint::Int));
out.field("b", FieldValue::borrowed(b, Hint::Int));
Ok(Parsed::Done)
}
}
const RE: &str = r"^(?P<a>[0-9]+):(?P<b>[0-9]+)$";
const INPUTS: [&[u8]; 6] = [b"1:2", b"10:20", b":2", b"1:", b"a:1", b"1:x"];
fn pair(loose: bool, sig: &str) -> Pair {
Pair {
sig: Signature::builder().all_of([sig]).build().unwrap(),
loose,
}
}
#[test]
fn an_exact_parser_agrees_on_every_input() {
assert_eq!(check(&pair(false, ":"), RE, INPUTS).unwrap(), Ok(6));
}
#[test]
fn a_loose_parser_is_caught_on_the_first_input_it_gets_wrong() {
let got = check(&pair(true, ":"), RE, INPUTS).unwrap().unwrap_err();
assert!(
matches!(&got, Disagreement::Fields { input, native: Some(_), regex: None } if input == b"1:")
);
}
#[test]
fn a_signature_that_rules_out_an_accepted_input_is_caught() {
let got = check(&pair(false, "::"), RE, INPUTS).unwrap().unwrap_err();
assert!(matches!(got, Disagreement::Signature { .. }));
}
#[test]
fn a_bad_regex_is_an_error() {
assert!(check(&pair(false, ":"), "(", INPUTS).is_err());
}
}