Your browser sucks, JavaScript disabled! Gunnar's console needs JavaScript and WebAssembly. Git over SSH on port 2222 does not.

nordisk/kleene

crates/kleene-gql/src/lexer.rs

//! Tokens of a GQL query (from the parked openCypher lexer; `<>` is "not equal").

use crate::error::{GqlError, Result};

/// A token and where it starts in the query (bytes).
#[derive(Clone, Debug, PartialEq)]
pub(crate) struct Token {
    pub kind: Tok,
    pub start: usize,
}

/// The kinds of token.
#[derive(Clone, Debug, PartialEq)]
pub(crate) enum Tok {
    /// A name or keyword (keywords are told apart by the parser, case-insensitively).
    Ident(String),
    /// A name in back-quotes: never a keyword.
    Quoted(String),
    /// An unsigned integer (decimal, `0x` hex or `0o` octal).
    Int(u64),
    /// `$name`: a query parameter, its value given when the query runs.
    Param(String),
    /// A string literal (its value read again from the text: [`string_at`]).
    Str,
    /// A number with a fraction or exponent (its value: [`float_at`]).
    Float,
    LParen,
    RParen,
    LBracket,
    RBracket,
    LBrace,
    RBrace,
    Comma,
    Dot,
    DotDot,
    Colon,
    Semi,
    Plus,
    Minus,
    Star,
    Slash,
    Percent,
    Pipe,
    /// `||`: string concatenation.
    Concat,
    Eq,
    Ne,
    Lt,
    Gt,
    Le,
    Ge,
    Eof,
}

fn err(pos: usize, msg: impl Into<String>) -> GqlError {
    GqlError::Syntax {
        pos,
        msg: msg.into(),
    }
}

/// Split `text` into tokens; the last is [`Tok::Eof`].
pub(crate) fn lex(text: &str) -> Result<Vec<Token>> {
    let b = text.as_bytes();
    let mut out = Vec::new();
    let mut i = 0;
    while i < b.len() {
        let c = b[i];
        if c.is_ascii_whitespace() {
            i += 1;
            continue;
        }
        if c == b'/' && b.get(i + 1) == Some(&b'/') {
            while i < b.len() && b[i] != b'\n' {
                i += 1;
            }
            continue;
        }
        if c == b'/' && b.get(i + 1) == Some(&b'*') {
            let start = i;
            i += 2;
            loop {
                if i + 1 >= b.len() {
                    return Err(err(start, "unclosed comment"));
                }
                if b[i] == b'*' && b[i + 1] == b'/' {
                    i += 2;
                    break;
                }
                i += 1;
            }
            continue;
        }
        let start = i;
        let kind = if c.is_ascii_alphabetic() || c == b'_' || c >= 0x80 {
            while i < b.len() && (b[i].is_ascii_alphanumeric() || b[i] == b'_' || b[i] >= 0x80) {
                i += 1;
            }
            Tok::Ident(text[start..i].to_string())
        } else if c == b'`' {
            i += 1;
            let mut s = String::new();
            loop {
                match b.get(i) {
                    None => return Err(err(start, "unclosed back-quoted name")),
                    Some(b'`') if b.get(i + 1) == Some(&b'`') => {
                        s.push('`');
                        i += 2;
                    }
                    Some(b'`') => {
                        i += 1;
                        break;
                    }
                    Some(_) => {
                        let ch = text[i..].chars().next().unwrap_or('\0');
                        s.push(ch);
                        i += ch.len_utf8();
                    }
                }
            }
            Tok::Quoted(s)
        } else if c.is_ascii_digit() || (c == b'.' && b.get(i + 1).is_some_and(u8::is_ascii_digit))
        {
            number(text, &mut i)?
        } else if c == b'$' {
            i += 1;
            let s = i;
            while i < b.len() && (b[i].is_ascii_alphanumeric() || b[i] == b'_' || b[i] >= 0x80) {
                i += 1;
            }
            if s == i || b[s].is_ascii_digit() {
                return Err(err(start, "a parameter is `$` and a name"));
            }
            Tok::Param(text[s..i].to_string())
        } else if c == b'\'' || c == b'"' {
            skip_string(text, &mut i)?;
            Tok::Str
        } else {
            let two = b.get(i + 1).copied();
            let (k, n) = match (c, two) {
                (b'.', Some(b'.')) => (Tok::DotDot, 2),
                (b'<', Some(b'>')) => (Tok::Ne, 2),
                (b'<', Some(b'=')) => (Tok::Le, 2),
                (b'>', Some(b'=')) => (Tok::Ge, 2),
                (b'(', _) => (Tok::LParen, 1),
                (b')', _) => (Tok::RParen, 1),
                (b'[', _) => (Tok::LBracket, 1),
                (b']', _) => (Tok::RBracket, 1),
                (b'{', _) => (Tok::LBrace, 1),
                (b'}', _) => (Tok::RBrace, 1),
                (b',', _) => (Tok::Comma, 1),
                (b'.', _) => (Tok::Dot, 1),
                (b':', _) => (Tok::Colon, 1),
                (b';', _) => (Tok::Semi, 1),
                (b'+', _) => (Tok::Plus, 1),
                (b'-', _) => (Tok::Minus, 1),
                (b'*', _) => (Tok::Star, 1),
                (b'/', _) => (Tok::Slash, 1),
                (b'%', _) => (Tok::Percent, 1),
                (b'|', Some(b'|')) => (Tok::Concat, 2),
                (b'|', _) => (Tok::Pipe, 1),
                (b'=', _) => (Tok::Eq, 1),
                (b'<', _) => (Tok::Lt, 1),
                (b'>', _) => (Tok::Gt, 1),
                (b'!', Some(b'=')) => return Err(err(i, "`!=` is not GQL; write `<>`")),
                _ => {
                    let ch = text[i..].chars().next().unwrap_or('?');
                    return Err(err(i, format!("unexpected character {ch:?}")));
                }
            };
            i += n;
            k
        };
        out.push(Token { kind, start });
    }
    out.push(Token {
        kind: Tok::Eof,
        start: b.len(),
    });
    Ok(out)
}

fn number(text: &str, i: &mut usize) -> Result<Tok> {
    let b = text.as_bytes();
    let start = *i;
    if b[start] == b'0' && matches!(b.get(start + 1), Some(b'x' | b'X' | b'o' | b'O')) {
        let radix = if matches!(b[start + 1], b'x' | b'X') {
            16
        } else {
            8
        };
        *i += 2;
        let s = *i;
        while *i < b.len() && (b[*i] as char).is_digit(radix) {
            *i += 1;
        }
        return u64::from_str_radix(&text[s..*i], radix)
            .map(Tok::Int)
            .map_err(|_| err(start, "integer out of range"));
    }
    let mut float = false;
    while *i < b.len() && b[*i].is_ascii_digit() {
        *i += 1;
    }
    // `1..3` is two integers around `..`; `1.5` is a float.
    if *i < b.len() && b[*i] == b'.' && b.get(*i + 1).is_some_and(u8::is_ascii_digit) {
        float = true;
        *i += 1;
        while *i < b.len() && b[*i].is_ascii_digit() {
            *i += 1;
        }
    }
    if *i < b.len() && matches!(b[*i], b'e' | b'E') {
        let mut j = *i + 1;
        if j < b.len() && matches!(b[j], b'+' | b'-') {
            j += 1;
        }
        if j < b.len() && b[j].is_ascii_digit() {
            float = true;
            *i = j;
            while *i < b.len() && b[*i].is_ascii_digit() {
                *i += 1;
            }
        }
    }
    if float {
        return Ok(Tok::Float);
    }
    text[start..*i]
        .parse::<u64>()
        .map(Tok::Int)
        .map_err(|_| err(start, "integer out of range"))
}

fn skip_string(text: &str, i: &mut usize) -> Result<()> {
    let b = text.as_bytes();
    let start = *i;
    let q = b[start];
    *i += 1;
    loop {
        let Some(&c) = b.get(*i) else {
            return Err(err(start, "unclosed string"));
        };
        if c == q {
            *i += 1;
            // a doubled quote is the quote itself
            if b.get(*i) == Some(&q) {
                *i += 1;
                continue;
            }
            return Ok(());
        }
        *i += if c == b'\\' { 2 } else { 1 };
    }
}

/// The value of the string literal at `start`: GQL's escapes `\\`, `\'`, `\"`, `` \` ``,
/// `\t` `\b` `\n` `\r` `\f`, `\uXXXX` and `\UXXXXXX` (hex), and a doubled quote.
pub(crate) fn string_at(text: &str, start: usize) -> Result<String> {
    let b = text.as_bytes();
    let q = b[start];
    let mut out = String::new();
    let mut i = start + 1;
    loop {
        let Some(c) = text[i..].chars().next() else {
            return Err(err(start, "unclosed string"));
        };
        let at = i;
        i += c.len_utf8();
        if c as u32 == q as u32 {
            if b.get(i) == Some(&q) {
                out.push(c);
                i += 1;
                continue;
            }
            return Ok(out);
        }
        if c != '\\' {
            out.push(c);
            continue;
        }
        let Some(e) = text[i..].chars().next() else {
            return Err(err(start, "unclosed string"));
        };
        i += e.len_utf8();
        let hex = |i: &mut usize, n: usize| -> Result<char> {
            let h = text
                .get(*i..*i + n)
                .filter(|h| h.bytes().all(|d| d.is_ascii_hexdigit()))
                .ok_or_else(|| err(at, format!("`\\{e}` takes {n} hex digits")))?;
            *i += n;
            u32::from_str_radix(h, 16)
                .ok()
                .and_then(char::from_u32)
                .ok_or_else(|| err(at, format!("`\\{e}{h}` is not a character")))
        };
        out.push(match e {
            '\\' | '\'' | '"' | '`' => e,
            't' => '\t',
            'b' => '\u{8}',
            'n' => '\n',
            'r' => '\r',
            'f' => '\u{c}',
            'u' => hex(&mut i, 4)?,
            'U' => hex(&mut i, 6)?,
            _ => return Err(err(at, format!("unknown escape `\\{e}`"))),
        });
    }
}

/// The value of the number with a fraction or exponent at `start`.
pub(crate) fn float_at(text: &str, start: usize) -> Result<f64> {
    let mut i = start;
    number(text, &mut i)?;
    text[start..i]
        .parse::<f64>()
        .map_err(|_| err(start, "not a number"))
}

#[cfg(test)]
mod tests {
    use super::*;

    fn kinds(s: &str) -> Vec<Tok> {
        lex(s).unwrap().into_iter().map(|t| t.kind).collect()
    }

    #[test]
    fn arrows_quantifiers_and_numbers() {
        assert_eq!(
            kinds("(a)<-[:T*1..2]-(b)-[:U]->{1,} 0x1F 0o17 7 1.5e2"),
            vec![
                Tok::LParen,
                Tok::Ident("a".into()),
                Tok::RParen,
                Tok::Lt,
                Tok::Minus,
                Tok::LBracket,
                Tok::Colon,
                Tok::Ident("T".into()),
                Tok::Star,
                Tok::Int(1),
                Tok::DotDot,
                Tok::Int(2),
                Tok::RBracket,
                Tok::Minus,
                Tok::LParen,
                Tok::Ident("b".into()),
                Tok::RParen,
                Tok::Minus,
                Tok::LBracket,
                Tok::Colon,
                Tok::Ident("U".into()),
                Tok::RBracket,
                Tok::Minus,
                Tok::Gt,
                Tok::LBrace,
                Tok::Int(1),
                Tok::Comma,
                Tok::RBrace,
                Tok::Int(31),
                Tok::Int(15),
                Tok::Int(7),
                Tok::Float,
                Tok::Eof
            ]
        );
    }

    #[test]
    fn strings_names_comments() {
        assert_eq!(
            kinds("'it\\'s' \"x\" `a b` // c\n /* d */ <> <= >="),
            vec![
                Tok::Str,
                Tok::Str,
                Tok::Quoted("a b".into()),
                Tok::Ne,
                Tok::Le,
                Tok::Ge,
                Tok::Eof
            ]
        );
        assert!(lex("a != b").is_err());
        assert!(lex("/* open").is_err());
    }
}