mod literals;
mod numbers;
#[cfg(test)]
mod tests;
use crate::{Date, DateTime, ParseError, Position};
#[derive(Debug, Clone, PartialEq)]
pub(crate) enum Kind {
Identifier(String),
Integer(i64),
Float(f64),
String {
value: String,
quote: Quote,
end: Position,
},
Boolean(bool),
Undefined,
Null,
Date(Date),
DateTime(DateTime, u8),
Gt,
Lt,
Gte,
Lte,
Eq,
Ne,
EqualEqual,
StrictEqual,
StrictNe,
Plus,
Minus,
Multiply,
Divide,
Modulo,
AndAnd,
OrOr,
Bang,
AndOp(&'static str),
OrOp(&'static str),
NotOp(&'static str),
Lparen,
Rparen,
Lbracket,
Rbracket,
Lbrace,
Rbrace,
Colon,
DoubleColon,
Comma,
Semicolon,
Dot,
InOp(&'static str),
ContainsOp(&'static str),
IfKw,
ElseKw,
WhileKw,
FunctionName(String),
QualifiedFunctionName(String),
DurationUnit(&'static str),
FractionalNumber { whole: i64, fraction: String },
AgoOp,
FromOp,
NowOp,
NextOp,
LastOp,
Eof,
}
impl Kind {
#[cfg(test)]
pub(crate) fn name(&self) -> &'static str {
match self {
Kind::Identifier(_) => "identifier",
Kind::Integer(_) => "integer",
Kind::Float(_) => "float",
Kind::String { .. } => "string",
Kind::Boolean(_) => "boolean",
Kind::Undefined => "undefined",
Kind::Null => "null",
Kind::Date(_) => "date",
Kind::DateTime(..) => "datetime",
Kind::Gt => "gt",
Kind::Lt => "lt",
Kind::Gte => "gte",
Kind::Lte => "lte",
Kind::Eq => "eq",
Kind::Ne => "ne",
Kind::EqualEqual => "equal_equal",
Kind::StrictEqual => "strict_equal",
Kind::StrictNe => "strict_ne",
Kind::Plus => "plus",
Kind::Minus => "minus",
Kind::Multiply => "multiply",
Kind::Divide => "divide",
Kind::Modulo => "modulo",
Kind::AndAnd => "and_and",
Kind::OrOr => "or_or",
Kind::Bang => "bang",
Kind::AndOp(_) => "and_op",
Kind::OrOp(_) => "or_op",
Kind::NotOp(_) => "not_op",
Kind::Lparen => "lparen",
Kind::Rparen => "rparen",
Kind::Lbracket => "lbracket",
Kind::Rbracket => "rbracket",
Kind::Lbrace => "lbrace",
Kind::Rbrace => "rbrace",
Kind::Colon => "colon",
Kind::DoubleColon => "double_colon",
Kind::Comma => "comma",
Kind::Semicolon => "semicolon",
Kind::Dot => "dot",
Kind::InOp(_) => "in_op",
Kind::ContainsOp(_) => "contains_op",
Kind::IfKw => "if_kw",
Kind::ElseKw => "else_kw",
Kind::WhileKw => "while_kw",
Kind::FunctionName(_) => "function_name",
Kind::QualifiedFunctionName(_) => "qualified_function_name",
Kind::DurationUnit(_) => "duration_unit",
Kind::FractionalNumber { .. } => "fractional_number",
Kind::AgoOp => "ago_op",
Kind::FromOp => "from_op",
Kind::NowOp => "now_op",
Kind::NextOp => "next_op",
Kind::LastOp => "last_op",
Kind::Eof => "eof",
}
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) enum Quote {
Double,
Single,
}
#[derive(Debug, Clone, PartialEq)]
pub(crate) struct Token {
pub(crate) kind: Kind,
pub(crate) line: usize,
pub(crate) column: usize,
pub(crate) length: usize,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) struct Span {
pub(crate) start: Position,
pub(crate) end: Position,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub(crate) struct Refusal {
pub(crate) error: Box<ParseError>,
pub(crate) span: Span,
}
pub(crate) fn tokenize(source: &str) -> Result<Vec<Token>, Refusal> {
let mut scan = Scan {
source,
at: 0,
line: 1,
column: 1,
tokens: Vec::new(),
chain_end: 0,
kept: false,
};
scan.run()?;
Ok(scan.tokens)
}
struct Scan<'a> {
source: &'a str,
at: usize,
line: usize,
column: usize,
tokens: Vec<Token>,
chain_end: usize,
kept: bool,
}
fn reserved(word: &str) -> Option<Kind> {
Some(match word {
"true" => Kind::Boolean(true),
"false" => Kind::Boolean(false),
"undefined" => Kind::Undefined,
"null" => Kind::Null,
"AND" => Kind::AndOp("AND"),
"and" => Kind::AndOp("and"),
"OR" => Kind::OrOp("OR"),
"or" => Kind::OrOp("or"),
"NOT" => Kind::NotOp("NOT"),
"not" => Kind::NotOp("not"),
"IN" => Kind::InOp("IN"),
"in" => Kind::InOp("in"),
"CONTAINS" => Kind::ContainsOp("CONTAINS"),
"contains" => Kind::ContainsOp("contains"),
"if" => Kind::IfKw,
"else" => Kind::ElseKw,
"while" => Kind::WhileKw,
"ago" => Kind::AgoOp,
"from" => Kind::FromOp,
"now" => Kind::NowOp,
"next" => Kind::NextOp,
"last" => Kind::LastOp,
_ => return None,
})
}
fn punctuation(text: &str) -> Option<(Kind, usize)> {
type Spelling = (&'static str, fn() -> Kind);
const SPELLINGS: [Spelling; 28] = [
("===", || Kind::StrictEqual),
("!==", || Kind::StrictNe),
(">=", || Kind::Gte),
("<=", || Kind::Lte),
("==", || Kind::EqualEqual),
("!=", || Kind::Ne),
("&&", || Kind::AndAnd),
("||", || Kind::OrOr),
("::", || Kind::DoubleColon),
(">", || Kind::Gt),
("<", || Kind::Lt),
("=", || Kind::Eq),
("!", || Kind::Bang),
("+", || Kind::Plus),
("-", || Kind::Minus),
("*", || Kind::Multiply),
("/", || Kind::Divide),
("%", || Kind::Modulo),
("(", || Kind::Lparen),
(")", || Kind::Rparen),
("[", || Kind::Lbracket),
("]", || Kind::Rbracket),
("{", || Kind::Lbrace),
("}", || Kind::Rbrace),
(":", || Kind::Colon),
(",", || Kind::Comma),
(";", || Kind::Semicolon),
(".", || Kind::Dot),
];
SPELLINGS
.iter()
.find(|(spelling, _)| text.starts_with(spelling))
.map(|(spelling, kind)| (kind(), spelling.len()))
}
fn is_word_start(byte: u8) -> bool {
byte.is_ascii_alphabetic() || byte == b'_'
}
fn is_word_byte(byte: u8) -> bool {
byte.is_ascii_alphanumeric() || byte == b'_'
}
fn word_length(text: &str) -> usize {
text.bytes().take_while(|byte| is_word_byte(*byte)).count()
}
impl<'a> Scan<'a> {
fn run(&mut self) -> Result<(), Refusal> {
while let Some(char) = self.rest().chars().next() {
match char {
' ' | '\t' => {
self.at += 1;
self.column += 1;
}
'\n' => {
self.at += 1;
self.line += 1;
self.column = 1;
}
'\r' => self.at += 1,
'0'..='9' => self.number()?,
'a'..='z' | 'A'..='Z' | '_' => self.word(),
'"' => self.string(Quote::Double)?,
'\'' => self.string(Quote::Single)?,
'#' => self.date()?,
_ => self.operator(char)?,
}
}
self.tokens.push(Token {
kind: Kind::Eof,
line: self.line,
column: self.column,
length: 0,
});
Ok(())
}
fn rest(&self) -> &'a str {
self.source.get(self.at..).unwrap_or_default()
}
fn from(&self, offset: usize) -> &'a str {
self.source.get(offset..).unwrap_or_default()
}
fn since(&self, start: usize) -> &'a str {
self.source.get(start..self.at).unwrap_or_default()
}
fn emit(&mut self, kind: Kind, length: usize) {
self.tokens.push(Token {
kind,
line: self.line,
column: self.column,
length,
});
self.column += length;
}
fn refuse(&self, reason: &str, message: String, end: Position) -> Refusal {
let start = self.position();
Refusal {
error: Box::new(ParseError::new(reason, message).with_position(start)),
span: Span { start, end },
}
}
fn position(&self) -> Position {
Position {
line: self.line,
column: self.column,
}
}
fn call_follows(&self, offset: usize) -> bool {
self.from(offset)
.trim_start_matches([' ', '\t', '\n', '\r'])
.starts_with('(')
}
fn word(&mut self) {
let start = self.at;
let length = word_length(self.rest());
self.at += length;
let name = self.since(start);
let mut after_dot = self.rest().bytes();
let dotted = after_dot.next() == Some(b'.') && after_dot.next().is_some_and(is_word_start);
if start >= self.chain_end && dotted {
return self.dotted(name);
}
let kind = match reserved(name) {
Some(kind) => kind,
None if self.call_follows(self.at) => Kind::FunctionName(name.to_owned()),
None => Kind::Identifier(name.to_owned()),
};
self.emit(kind, length);
}
fn dotted(&mut self, name: &str) {
let mut end = self.at;
loop {
let mut ahead = self.from(end).bytes();
if ahead.next() != Some(b'.') || !ahead.next().is_some_and(is_word_start) {
break;
}
end += 1 + word_length(self.from(end + 1));
}
if self.call_follows(end) {
let length = name.len() + (end - self.at);
let whole = self
.source
.get(self.at - name.len()..end)
.unwrap_or_default();
self.at = end;
return self.emit(Kind::QualifiedFunctionName(whole.to_owned()), length);
}
self.chain_end = end;
let kind = reserved(name).unwrap_or_else(|| Kind::Identifier(name.to_owned()));
self.emit(kind, name.len());
}
fn operator(&mut self, char: char) -> Result<(), Refusal> {
match punctuation(self.rest()) {
Some((kind, length)) => {
self.at += length;
self.emit(kind, length);
Ok(())
}
None => Err(self.refuse(
"unexpected_character",
format!("Unexpected character '{char}'"),
Position {
line: self.line,
column: self.column + 1,
},
)),
}
}
}