grippo 0.2.2

Parse, match and scrub data faster and more efficiently.
Documentation
// Project:   grippo
// File:      src/expr/lex.rs
// Purpose:   Tokens of CEL text, with literal values decoded
// Language:  Rust
//
// License:   Apache-2.0
// Copyright: (c) 2026 HYPERI PTY LIMITED

//! Tokens of CEL text, read as cel's grammar (`CEL.g4`) reads them.

use std::borrow::Cow;
use std::ops::Range;

/// One token and the byte range of the text it was read from.
#[derive(Debug, Clone, PartialEq)]
pub(super) struct Token<'a> {
    pub(super) tok: Tok<'a>,
    pub(super) span: Range<usize>,
}

/// What a token is.
#[derive(Debug, Clone, PartialEq)]
pub(super) enum Tok<'a> {
    /// An identifier, or the text inside a backtick-quoted one.
    Ident(&'a str),
    /// A string literal's value.
    Str(Cow<'a, str>),
    /// A bytes literal, which no lowered form takes.
    Bytes,
    Int(i64),
    Uint(u64),
    Double(f64),
    OrOr,
    AndAnd,
    Not,
    EqEq,
    Ne,
    Lt,
    Le,
    Gt,
    Ge,
    Minus,
    Dot,
    Comma,
    LParen,
    RParen,
    LBracket,
    RBracket,
    Question,
    Colon,
    Plus,
    /// Any other operator or punctuation: `*`, `{` and the rest.
    Other,
}

/// Text cel's lexer rejects, and where.
#[derive(Debug, Clone, PartialEq, Eq)]
pub(super) struct LexError {
    pub(super) span: Range<usize>,
    pub(super) why: &'static str,
}

/// How [`tokens_with`] treats text cel's lexer rejects.
#[derive(Clone, Copy, PartialEq, Eq)]
pub(super) enum Mode {
    /// Return the first error, as cel does.
    Strict,
    /// Read the rejected span as one [`Tok::Other`] and go on, so no name
    /// inside a broken literal is read. A one-line literal ends at its line
    /// break and a lone backtick is one byte.
    Lenient,
}

/// Every token of `text`, or the first error.
pub(super) fn tokens(text: &str) -> Result<Vec<Token<'_>>, LexError> {
    tokens_with(text, Mode::Strict)
}

/// Every token of `text` under `mode`. [`Mode::Lenient`] never errors.
pub(super) fn tokens_with(text: &str, mode: Mode) -> Result<Vec<Token<'_>>, LexError> {
    let bytes = text.as_bytes();
    let mut out = Vec::new();
    let mut i = 0;
    while i < bytes.len() {
        let b = bytes[i];
        let start = i;
        if is_space(b) {
            i += 1;
            continue;
        }
        if bytes[i..].starts_with(b"//") {
            i = memchr::memchr(b'\n', &bytes[i..]).map_or(bytes.len(), |n| i + n);
            continue;
        }
        let step = if is_quote(b) {
            string(text, i, Quoting::Escaped, Kind::Text, mode)
        } else if b.is_ascii_digit()
            || (b == b'.' && bytes.get(i + 1).is_some_and(u8::is_ascii_digit))
        {
            number(text, i)
        } else if is_ident_start(b) {
            let mut end = i;
            while end < bytes.len() && is_ident_char(bytes[end]) {
                end += 1;
            }
            let word = &text[start..end];
            match bytes.get(end) {
                Some(&q) if is_quote(q) && LITERAL_PREFIXES.contains(&word) => {
                    let has = |c: u8| word.bytes().any(|w| w.eq_ignore_ascii_case(&c));
                    let quoting = if has(b'r') {
                        Quoting::Raw
                    } else {
                        Quoting::Escaped
                    };
                    let kind = if has(b'b') { Kind::Bytes } else { Kind::Text };
                    string(text, end, quoting, kind, mode)
                }
                _ => Ok((Tok::Ident(word), end)),
            }
        } else if b == b'`' {
            let body = bytes[i + 1..]
                .iter()
                .take_while(|c| is_escaped_ident_byte(**c))
                .count();
            if body == 0 || bytes.get(i + 1 + body) != Some(&b'`') {
                Err(LexError {
                    span: i..i + 1,
                    why: "a backtick that opens no quoted identifier",
                })
            } else {
                Ok((Tok::Ident(&text[start + 1..i + 1 + body]), i + body + 2))
            }
        } else {
            let (tok, n) = punct(&bytes[i..]);
            let n = if tok == Tok::Other {
                text[i..].chars().next().map_or(1, char::len_utf8)
            } else {
                n
            };
            Ok((tok, i + n))
        };
        let (tok, end) = match (step, mode) {
            (Ok(step), _) => step,
            (Err(e), Mode::Strict) => return Err(e),
            (Err(e), Mode::Lenient) => (Tok::Other, e.span.end.max(start + 1)),
        };
        i = end;
        out.push(Token {
            tok,
            span: start..i,
        });
    }
    Ok(out)
}

fn punct(rest: &[u8]) -> (Tok<'static>, usize) {
    match rest.get(..2).unwrap_or_default() {
        b"||" => return (Tok::OrOr, 2),
        b"&&" => return (Tok::AndAnd, 2),
        b"==" => return (Tok::EqEq, 2),
        b"!=" => return (Tok::Ne, 2),
        b"<=" => return (Tok::Le, 2),
        b">=" => return (Tok::Ge, 2),
        _ => {}
    }
    let tok = match rest.first() {
        Some(b'!') => Tok::Not,
        Some(b'<') => Tok::Lt,
        Some(b'>') => Tok::Gt,
        Some(b'-') => Tok::Minus,
        Some(b'.') => Tok::Dot,
        Some(b',') => Tok::Comma,
        Some(b'(') => Tok::LParen,
        Some(b')') => Tok::RParen,
        Some(b'[') => Tok::LBracket,
        Some(b']') => Tok::RBracket,
        Some(b'?') => Tok::Question,
        Some(b':') => Tok::Colon,
        Some(b'+') => Tok::Plus,
        _ => Tok::Other,
    };
    (tok, 1)
}

/// Whether a literal's backslashes are escapes.
#[derive(Clone, Copy, PartialEq, Eq)]
enum Quoting {
    Escaped,
    Raw,
}

/// Whether a literal is a string or bytes.
#[derive(Clone, Copy, PartialEq, Eq)]
enum Kind {
    Text,
    Bytes,
}

/// The literal whose opening quote is at `at`, and the index after it.
fn string(
    text: &str,
    at: usize,
    quoting: Quoting,
    kind: Kind,
    mode: Mode,
) -> Result<(Tok<'_>, usize), LexError> {
    let bytes = text.as_bytes();
    let quote = bytes[at];
    let triple = bytes[at..].starts_with(&[quote; 3]);
    let open = if triple { 3 } else { 1 };
    let body_start = at + open;
    let mut i = body_start;
    let mut escaped = false;
    let body_end = loop {
        let Some(&b) = bytes.get(i) else {
            if triple {
                // cel reads an unclosed `"""` as an empty literal, then a new
                // one opening at the third quote.
                let empty = if kind == Kind::Bytes {
                    Tok::Bytes
                } else {
                    Tok::Str(Cow::Borrowed(""))
                };
                return Ok((empty, at + 2));
            }
            return Err(LexError {
                span: at..bytes.len(),
                why: "a string literal with no closing quote",
            });
        };
        if triple && bytes[i..].starts_with(&[quote; 3]) || !triple && b == quote {
            break i;
        }
        if !triple && (b == b'\n' || b == b'\r') {
            return Err(LexError {
                span: at..i,
                why: "a line break inside a one-line string literal",
            });
        }
        if quoting == Quoting::Escaped && b == b'\\' {
            escaped = true;
            i += 2;
        } else {
            i += 1;
        }
    };
    let end = body_end + open;
    if kind == Kind::Bytes {
        return Ok((Tok::Bytes, end));
    }
    let body = &text[body_start..body_end.min(bytes.len())];
    if !escaped {
        return Ok((Tok::Str(Cow::Borrowed(body)), end));
    }
    match (unescape(body, body_start), mode) {
        (Ok(s), _) => Ok((Tok::Str(Cow::Owned(s)), end)),
        (Err(e), Mode::Strict) => Err(e),
        (Err(_), Mode::Lenient) => Ok((Tok::Other, end)),
    }
}

/// A string literal's body with CEL's escapes decoded.
fn unescape(body: &str, offset: usize) -> Result<String, LexError> {
    let mut out = String::with_capacity(body.len());
    let mut chars = body.char_indices();
    while let Some((at, c)) = chars.next() {
        if c != '\\' {
            out.push(c);
            continue;
        }
        let escaped = chars.clone().next().map_or(0, |(_, e)| e.len_utf8());
        let bad = |why| LexError {
            span: offset + at..offset + at + 1 + escaped,
            why,
        };
        let Some((_, e)) = chars.next() else {
            return Err(bad("a backslash at the end of a string literal"));
        };
        let simple = match e {
            '\\' => Some('\\'),
            '?' => Some('?'),
            '"' => Some('"'),
            '\'' => Some('\''),
            '`' => Some('`'),
            'a' => Some('\x07'),
            'b' => Some('\x08'),
            'f' => Some('\x0c'),
            'n' => Some('\n'),
            'r' => Some('\r'),
            't' => Some('\t'),
            'v' => Some('\x0b'),
            _ => None,
        };
        if let Some(s) = simple {
            out.push(s);
            continue;
        }
        let (digits, radix, mut value) = match e {
            'x' | 'X' => (2, 16, 0),
            'u' => (4, 16, 0),
            'U' => (8, 16, 0),
            '0'..='3' => (2, 8, e.to_digit(8).unwrap_or(0)),
            _ => return Err(bad("an escape CEL doesn't define")),
        };
        for _ in 0..digits {
            let Some(d) = chars.next().and_then(|(_, d)| d.to_digit(radix)) else {
                return Err(bad("an escape with too few digits"));
            };
            value = value * radix + d;
        }
        let Some(ch) = char::from_u32(value) else {
            return Err(bad("an escape naming no Unicode scalar value"));
        };
        out.push(ch);
    }
    Ok(out)
}

/// The number literal at `at` and the index after it.
fn number(text: &str, at: usize) -> Result<(Tok<'_>, usize), LexError> {
    let bytes = text.as_bytes();
    let bad = |end: usize, why| LexError { span: at..end, why };
    if bytes[at..].starts_with(b"0x") || bytes[at..].starts_with(b"0X") {
        let digits = bytes[at + 2..]
            .iter()
            .take_while(|b| b.is_ascii_hexdigit())
            .count();
        let end = at + 2 + digits;
        let v = u64::from_str_radix(&text[at + 2..end], 16)
            .map_err(|_| bad(end, "a hex literal with no digits or out of range"))?;
        return int_token(v, bytes.get(end), end)
            .ok_or_else(|| bad(end, "an int literal out of range"));
    }
    let digits = |mut i: usize| {
        while bytes.get(i).is_some_and(u8::is_ascii_digit) {
            i += 1;
        }
        i
    };
    let mut i = digits(at);
    let mut double = false;
    if bytes.get(i) == Some(&b'.') && bytes.get(i + 1).is_some_and(u8::is_ascii_digit) {
        double = true;
        i = digits(i + 1);
    }
    if matches!(bytes.get(i), Some(b'e' | b'E')) {
        let sign = usize::from(matches!(bytes.get(i + 1), Some(b'+' | b'-')));
        if bytes.get(i + 1 + sign).is_some_and(u8::is_ascii_digit) {
            double = true;
            i = digits(i + 1 + sign);
        }
    }
    if double {
        let v: f64 = text[at..i]
            .parse()
            .map_err(|_| bad(i, "a malformed double literal"))?;
        return Ok((Tok::Double(v), i));
    }
    let v: u64 = text[at..i]
        .parse()
        .map_err(|_| bad(i, "an int literal out of range"))?;
    int_token(v, bytes.get(i), i).ok_or_else(|| bad(i, "an int literal out of range"))
}

/// An int or, with a `u` suffix, a uint, and the index after it.
fn int_token(v: u64, next: Option<&u8>, end: usize) -> Option<(Tok<'static>, usize)> {
    if matches!(next, Some(b'u' | b'U')) {
        return Some((Tok::Uint(v), end + 1));
    }
    i64::try_from(v).ok().map(|n| (Tok::Int(n), end))
}

const fn is_quote(b: u8) -> bool {
    b == b'"' || b == b'\''
}

/// Whole names that open a literal when a quote follows directly: cel's
/// bytes prefix comes before its raw prefix.
const LITERAL_PREFIXES: &[&str] = &["r", "R", "b", "B", "br", "bR", "Br", "BR"];

/// Whitespace as cel reads it, vertical tab included.
const fn is_space(b: u8) -> bool {
    matches!(b, b' ' | b'\t' | b'\n' | b'\r' | b'\x0b' | b'\x0c')
}

const fn is_ident_start(b: u8) -> bool {
    b.is_ascii_alphabetic() || b == b'_'
}

const fn is_ident_char(b: u8) -> bool {
    b.is_ascii_alphanumeric() || b == b'_'
}

const fn is_escaped_ident_byte(b: u8) -> bool {
    b.is_ascii_alphanumeric() || matches!(b, b'_' | b'.' | b'-' | b'/' | b' ')
}