use thiserror::Error;
use super::config::{FormatChoice, HopConfig};
pub const RESERVED: [&str; 5] = ["auto", "each", "field", "raw", "reject"];
#[derive(Debug, Clone, PartialEq, Eq, Error)]
#[error("chain: {reason} at byte {offset}")]
pub struct ChainError {
pub offset: usize,
pub reason: &'static str,
}
struct Cursor<'t> {
text: &'t [u8],
at: usize,
}
impl<'t> Cursor<'t> {
const fn fail<T>(&self, reason: &'static str) -> Result<T, ChainError> {
Err(ChainError {
offset: self.at,
reason,
})
}
fn peek(&self) -> Option<u8> {
self.text.get(self.at).copied()
}
fn skip_spaces(&mut self) {
while self.peek().is_some_and(|b| b.is_ascii_whitespace()) {
self.at += 1;
}
}
fn eat(&mut self, token: &str) -> bool {
self.skip_spaces();
let found = self.text[self.at..].starts_with(token.as_bytes());
if found {
self.at += token.len();
}
found
}
fn take(&mut self, keep: impl Fn(u8, Option<u8>) -> bool) -> &'t str {
let text: &'t [u8] = self.text;
let start = self.at;
while let Some(b) = self.peek()
&& keep(b, self.text.get(self.at + 1).copied())
{
self.at += 1;
}
std::str::from_utf8(&text[start..self.at]).unwrap_or_default()
}
fn word(&mut self) -> &'t str {
self.skip_spaces();
if !self.peek().is_some_and(|b| b.is_ascii_lowercase()) {
return "";
}
self.take(|b, _| b.is_ascii_lowercase() || b.is_ascii_digit() || b == b'_')
}
fn string(&mut self) -> Result<String, ChainError> {
self.skip_spaces();
let start = self.at;
if self.peek() != Some(b'"') {
return self.fail("expected a quoted field name");
}
self.at += 1;
loop {
match self.peek() {
None => return self.fail("the field name has no closing quote"),
Some(b'\\') => self.at += 2,
Some(b'"') => break,
Some(_) => self.at += 1,
}
}
self.at += 1;
let quoted = self.text.get(start..self.at).unwrap_or_default();
serde_json::from_slice(quoted).map_err(|_| ChainError {
offset: start,
reason: "the field name isn't a JSON string",
})
}
fn choice_word(&mut self) -> Result<FormatChoice, ChainError> {
self.skip_spaces();
let start = self.at;
let format = self.word();
if format.is_empty() {
return self.fail("expected a parser name");
}
if format == "auto" {
return match self.peek() {
Some(b'*') => {
self.at += 1;
Ok(FormatChoice::AutoStar)
}
Some(b':') => self.fail("auto takes no instance name"),
_ => Ok(FormatChoice::Auto),
};
}
if RESERVED.contains(&format) {
self.at = start;
return self.fail("a reserved word where a parser name belongs");
}
if self.peek() != Some(b':') {
return Ok(FormatChoice::Named(vec![format.to_owned()]));
}
self.at += 1;
let instance = self.take(|b, next| match b {
b'-' => next != Some(b'>'),
_ => b.is_ascii_lowercase() || b.is_ascii_digit() || matches!(b, b'_' | b'.'),
});
if instance.is_empty() {
return self.fail("expected an instance name after `:`");
}
let name = format!("{format}:{instance}");
Ok(FormatChoice::Named(vec![name]))
}
fn choice(&mut self) -> Result<FormatChoice, ChainError> {
if !self.eat("(") {
return self.choice_word();
}
let mut names = Vec::new();
loop {
self.skip_spaces();
let at = self.at;
match self.choice_word()? {
FormatChoice::Named(mut one) => names.append(&mut one),
FormatChoice::Auto | FormatChoice::AutoStar => {
self.at = at;
return self.fail("auto can't sit in a list: name the parsers, or write auto");
}
}
if self.eat(")") {
return Ok(FormatChoice::Named(names));
}
if !self.eat(",") {
return self.fail("expected `,` or `)`");
}
}
}
fn hop(&mut self) -> Result<HopConfig, ChainError> {
self.skip_spaces();
let start = self.at;
let (field, each) = match self.word() {
"each" => (None, true),
"field" => {
if !self.eat("(") {
return self.fail("expected `(` after field");
}
let name = self.string()?;
if !self.eat(")") {
return self.fail("expected `)` after the field name");
}
(Some(name), false)
}
_ => {
self.at = start;
(None, false)
}
};
if (each || field.is_some()) && !self.eat(":") {
return self.fail("expected `:` after the selector");
}
Ok(HopConfig {
field,
each,
..HopConfig::new(self.choice()?)
})
}
fn end(&mut self) -> Result<(), ChainError> {
self.skip_spaces();
if self.at < self.text.len() {
return self.fail("expected `>` or the end of the chain");
}
Ok(())
}
}
pub fn chain(text: &str) -> Result<Vec<HopConfig>, ChainError> {
let mut cursor = Cursor {
text: text.as_bytes(),
at: 0,
};
let mut hops = vec![cursor.hop()?];
while cursor.eat("->") || cursor.eat(">") {
hops.push(cursor.hop()?);
}
cursor.end()?;
Ok(hops)
}
pub fn hop(text: &str) -> Result<HopConfig, ChainError> {
let mut cursor = Cursor {
text: text.as_bytes(),
at: 0,
};
let hop = cursor.hop()?;
cursor.end()?;
Ok(hop)
}