use regex_syntax::hir::{ClassUnicode, ClassUnicodeRange};
use thiserror::Error;
use crate::field::FIELDS;
use crate::grok::{Grok, GrokBuildError, Library};
use crate::parse::Hint;
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Chars(ClassUnicode);
impl Chars {
#[must_use]
pub fn of(chars: &str) -> Self {
Self(ClassUnicode::new(
chars.chars().map(|c| ClassUnicodeRange::new(c, c)),
))
}
#[must_use]
pub fn range(first: char, last: char) -> Self {
Self(ClassUnicode::new([ClassUnicodeRange::new(first, last)]))
}
#[must_use]
pub fn but(chars: &str) -> Self {
let mut set = Self::of(chars);
set.0.negate();
set
}
#[must_use]
pub fn or(mut self, other: &Self) -> Self {
self.0.union(&other.0);
self
}
}
#[derive(Debug, Clone)]
pub struct Part {
node: Node,
name: Option<String>,
hint: Hint,
misuse: Option<&'static str>,
}
#[derive(Debug, Clone)]
enum Node {
Literal(String),
Field(String),
Run {
chars: Chars,
min: usize,
max: Option<usize>,
},
Until(Option<String>),
OneOf(Vec<String>),
Seq(Vec<Part>),
Or(Vec<Part>),
Optional(Box<Part>),
Start,
End,
}
const fn part(node: Node) -> Part {
Part {
node,
name: None,
hint: Hint::Text,
misuse: None,
}
}
#[must_use]
pub fn literal(text: impl Into<String>) -> Part {
part(Node::Literal(text.into()))
}
#[must_use]
pub fn field(name: impl Into<String>) -> Part {
part(Node::Field(name.into()))
}
#[must_use]
pub const fn run(chars: Chars) -> Part {
part(Node::Run {
chars,
min: 1,
max: None,
})
}
#[must_use]
pub fn until(literal: impl Into<String>) -> Part {
part(Node::Until(Some(literal.into())))
}
#[must_use]
pub const fn until_next() -> Part {
part(Node::Until(None))
}
#[must_use]
pub fn one_of<I>(literals: I) -> Part
where
I: IntoIterator,
I::Item: Into<String>,
{
part(Node::OneOf(literals.into_iter().map(Into::into).collect()))
}
#[must_use]
pub const fn start() -> Part {
part(Node::Start)
}
#[must_use]
pub const fn end() -> Part {
part(Node::End)
}
impl Part {
#[must_use]
pub fn then(self, next: Self) -> Self {
let mut parts = self.members(Join::Seq);
parts.extend(next.members(Join::Seq));
part(Node::Seq(parts))
}
#[must_use]
pub fn or(self, other: Self) -> Self {
let mut parts = self.members(Join::Or);
parts.extend(other.members(Join::Or));
part(Node::Or(parts))
}
#[must_use]
pub fn optional(self) -> Self {
part(Node::Optional(Box::new(self)))
}
#[must_use]
pub fn named(mut self, name: impl Into<String>) -> Self {
self.name = Some(name.into());
self
}
#[must_use]
pub const fn typed(mut self, hint: Hint) -> Self {
self.hint = hint;
self
}
#[must_use]
pub const fn at_least(mut self, count: usize) -> Self {
match &mut self.node {
Node::Run { min, .. } => *min = count,
_ => self.misuse = Some("at_least on a part that isn't a run"),
}
self
}
#[must_use]
pub const fn at_most(mut self, count: usize) -> Self {
match &mut self.node {
Node::Run { max, .. } => *max = Some(count),
_ => self.misuse = Some("at_most on a part that isn't a run"),
}
self
}
pub fn build(&self, name: impl Into<String>) -> Result<Grok, ComposeError> {
let mut speller = Speller {
aliases: Library::empty(),
count: 0,
};
let mut pattern = String::new();
speller.part(self, &mut pattern)?;
if pattern.is_empty() {
return Err(ComposeError::Shape("a part that matches nothing"));
}
Ok(Grok::builder(name)
.pattern(pattern)
.aliases(speller.aliases)
.build()?)
}
fn plain(&self) -> bool {
self.name.is_none() && self.hint == Hint::Text && self.misuse.is_none()
}
fn members(mut self, kind: Join) -> Vec<Self> {
if self.plain() {
match (&mut self.node, kind) {
(Node::Seq(parts), Join::Seq) | (Node::Or(parts), Join::Or) => {
return std::mem::take(parts);
}
_ => {}
}
}
vec![self]
}
}
#[derive(Debug, Clone, Copy)]
enum Join {
Seq,
Or,
}
#[derive(Debug, Error)]
#[non_exhaustive]
pub enum ComposeError {
#[error("no field scanner is named {0:?}")]
UnknownField(String),
#[error("{0:?} can't be a field name")]
Name(String),
#[error("{0}")]
Shape(&'static str),
#[error(transparent)]
Build(#[from] GrokBuildError),
}
struct Speller {
aliases: Library,
count: usize,
}
impl Speller {
fn part(&mut self, p: &Part, out: &mut String) -> Result<(), ComposeError> {
if let Some(misuse) = p.misuse {
return Err(ComposeError::Shape(misuse));
}
let capture = match &p.name {
Some(name) => Some((checked(name)?, suffix(p.hint)?)),
None if p.hint == Hint::Text => None,
None => return Err(ComposeError::Shape("a hint with no name")),
};
match (&p.node, capture) {
(Node::Field(name), capture) => scanner(name, capture, out),
(Node::Until(literal), capture) => lazy_until(literal.as_deref(), capture, out),
(Node::Start | Node::End, Some(_)) => Err(ComposeError::Shape("a name on an anchor")),
(node, None) => self.node(node, out),
(node, Some(capture)) => {
let mut definition = String::new();
self.node(node, &mut definition)?;
let alias = format!("_{}", self.count);
self.count += 1;
reference(&alias, Some(capture), out);
self.aliases.add(alias, definition);
Ok(())
}
}
}
fn node(&mut self, node: &Node, out: &mut String) -> Result<(), ComposeError> {
match node {
Node::Field(name) => scanner(name, None, out)?,
Node::Until(literal) => lazy_until(literal.as_deref(), None, out)?,
Node::Literal(text) => out.push_str(®ex_syntax::escape(text)),
Node::Run { chars, min, max } => {
class(chars, out)?;
quantifier(*min, *max, out)?;
}
Node::OneOf(literals) => {
if literals.is_empty() {
return Err(ComposeError::Shape("one_of with no literals"));
}
out.push_str("(?:");
for (i, literal) in literals.iter().enumerate() {
if i > 0 {
out.push('|');
}
out.push_str(®ex_syntax::escape(literal));
}
out.push(')');
}
Node::Seq(parts) => {
for p in parts {
self.part(p, out)?;
}
}
Node::Or(parts) => {
out.push_str("(?:");
for (i, p) in parts.iter().enumerate() {
if i > 0 {
out.push('|');
}
self.part(p, out)?;
}
out.push(')');
}
Node::Optional(inner) => {
out.push_str("(?:");
self.part(inner, out)?;
out.push_str(")?");
}
Node::Start => out.push('^'),
Node::End => out.push('$'),
}
Ok(())
}
}
type Capture<'p> = (&'p str, Option<&'static str>);
fn scanner(name: &str, capture: Option<Capture<'_>>, out: &mut String) -> Result<(), ComposeError> {
if !FIELDS.iter().any(|f| f.name == name) {
return Err(ComposeError::UnknownField(name.to_owned()));
}
reference(name, capture, out);
Ok(())
}
fn lazy_until(
literal: Option<&str>,
capture: Option<Capture<'_>>,
out: &mut String,
) -> Result<(), ComposeError> {
if literal == Some("") {
return Err(ComposeError::Shape("an until with an empty literal"));
}
reference("DATA", capture, out);
if let Some(literal) = literal {
out.push_str(®ex_syntax::escape(literal));
}
Ok(())
}
fn reference(name: &str, capture: Option<Capture<'_>>, out: &mut String) {
out.push_str("%{");
out.push_str(name);
if let Some((field, suffix)) = capture {
out.push(':');
out.push_str(field);
if let Some(suffix) = suffix {
out.push(':');
out.push_str(suffix);
}
}
out.push('}');
}
fn checked(name: &str) -> Result<&str, ComposeError> {
let bad = |c: char| c.is_control() || matches!(c, ':' | '{' | '}' | '=' | '%');
if name.is_empty() || name.contains(bad) {
return Err(ComposeError::Name(name.to_owned()));
}
Ok(name)
}
const fn suffix(hint: Hint) -> Result<Option<&'static str>, ComposeError> {
match hint {
Hint::Text => Ok(None),
Hint::Int => Ok(Some("int")),
Hint::Float => Ok(Some("float")),
Hint::Bool => Ok(Some("boolean")),
_ => Err(ComposeError::Shape(
"a hint grok can't write: only Text, Int, Float and Bool",
)),
}
}
fn class(chars: &Chars, out: &mut String) -> Result<(), ComposeError> {
use std::fmt::Write as _;
let ranges = chars.0.ranges();
if ranges.is_empty() {
return Err(ComposeError::Shape("a run of an empty set"));
}
out.push('[');
for r in ranges {
let (first, last) = (u32::from(r.start()), u32::from(r.end()));
let _ = if first == last {
write!(out, "\\x{{{first:X}}}")
} else {
write!(out, "\\x{{{first:X}}}-\\x{{{last:X}}}")
};
}
out.push(']');
Ok(())
}
fn quantifier(min: usize, max: Option<usize>, out: &mut String) -> Result<(), ComposeError> {
use std::fmt::Write as _;
let _ = match (min, max) {
(_, Some(0)) => return Err(ComposeError::Shape("a run of at most 0")),
(min, Some(max)) if max < min => {
return Err(ComposeError::Shape(
"a run whose at_most is below its at_least",
));
}
(1, Some(1)) => Ok(()),
(0, Some(1)) => out.write_char('?'),
(0, None) => out.write_char('*'),
(1, None) => out.write_char('+'),
(min, None) => write!(out, "{{{min},}}"),
(min, Some(max)) if min == max => write!(out, "{{{min}}}"),
(min, Some(max)) => write!(out, "{{{min},{max}}}"),
};
Ok(())
}
#[cfg(test)]
mod tests;