grippo 0.1.1

Parse, match and scrub data at scale.
Documentation
// Project:   grippo
// File:      src/parse/chain.rs
// Purpose:   The chain string: `syslog > cef > field("msg"):xml` read into hops
// Language:  Rust
//
// License:   Apache-2.0
// Copyright: (c) 2026 HYPERI PTY LIMITED

//! ```text
//! chain    = hop , { sep , hop } ;
//! sep      = ">" | "->" ;
//! hop      = [ selector , ":" ] , choice ;
//! selector = "each" | "field" , "(" , json-string , ")" ;
//! choice   = "auto" | "auto*" | parser | "(" , parser , { "," , parser } , ")" ;
//! parser   = format , [ ":" , instance ] ;
//! ```
//!
//! Whitespace may sit between tokens. A parser name is one token. `->` is
//! always the separator, so an instance name that ends in `-` needs a space
//! before `>`. Only the syntax is checked here: which hops may follow which
//! is [`super::ParsePlan::compile`]'s job, for the string and the list alike.

use thiserror::Error;

use super::config::{FormatChoice, HopConfig};

/// Format names a parser can't take: the chain's own words.
pub const RESERVED: [&str; 5] = ["auto", "each", "field", "raw", "reject"];

/// Why a string isn't a chain.
#[derive(Debug, Clone, PartialEq, Eq, Error)]
#[error("chain: {reason} at byte {offset}")]
pub struct ChainError {
    /// Byte offset into the string.
    pub offset: usize,
    /// What is wrong there.
    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;
        }
    }

    /// Skip spaces, then take `token` if it is next.
    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
    }

    /// Take the bytes `keep` accepts, given each byte and the one after it.
    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;
        }
        // Every kept byte is ASCII, so the slice is UTF-8.
        std::str::from_utf8(&text[start..self.at]).unwrap_or_default()
    }

    /// `[a-z][a-z0-9_]*`, or empty when the next byte starts none.
    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'_')
    }

    /// A JSON string, decoded.
    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",
        })
    }

    /// `format` or `format:instance`, with `auto` and `auto*` read as words.
    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(())
    }
}

/// Read a whole chain.
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)
}

/// Read one hop, as a list item writes it.
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)
}