pub const WILDCARD_ROW: u32 = u32::MAX;
#[derive(Debug, Clone, PartialEq)]
pub enum Token {
Number(f64),
CellRef(String, u32),
Function(String),
Direction(DirectionKind),
Plus,
Minus,
Star,
Slash,
LParen,
RParen,
Comma,
Colon,
}
#[derive(Debug, Clone, Copy, PartialEq)]
pub enum DirectionKind {
Left,
Right,
Above,
Below,
}
pub fn tokenize(input: &str) -> Option<Vec<Token>> {
let s = input.trim();
let s = if s.starts_with('=') || s.starts_with('@') {
&s[1..]
} else {
s
};
let chars: Vec<char> = s.chars().collect();
let len = chars.len();
let mut tokens = Vec::new();
let mut i = 0;
while i < len {
let ch = chars[i];
if ch.is_whitespace() {
i += 1;
continue;
}
if ch.is_ascii_digit() || (ch == '.' && i + 1 < len && chars[i + 1].is_ascii_digit()) {
let start = i;
while i < len && (chars[i].is_ascii_digit() || chars[i] == '.') {
i += 1;
}
let num_str: String = chars[start..i].iter().collect();
tokens.push(Token::Number(num_str.parse().ok()?));
continue;
}
if ch.is_ascii_alphabetic() || ch == '?' {
let start = i;
while i < len
&& (chars[i].is_ascii_alphanumeric() || chars[i] == '?' || chars[i] == '_')
{
i += 1;
}
let word: String = chars[start..i].iter().collect();
let upper = word.to_uppercase();
match upper.as_str() {
"LEFT" => {
tokens.push(Token::Direction(DirectionKind::Left));
continue;
}
"RIGHT" => {
tokens.push(Token::Direction(DirectionKind::Right));
continue;
}
"ABOVE" => {
tokens.push(Token::Direction(DirectionKind::Above));
continue;
}
"BELOW" => {
tokens.push(Token::Direction(DirectionKind::Below));
continue;
}
_ => {}
}
if i >= len || chars[i] != '(' {
let col_len = if upper.starts_with('?') {
1
} else {
upper
.chars()
.take_while(|c| c.is_ascii_alphabetic())
.count()
};
if col_len > 0 && col_len < upper.len() {
let col: String = upper.chars().take(col_len).collect();
let rest: String = upper.chars().skip(col_len).collect();
let valid_col = col == "?" || col.chars().all(|c| c.is_ascii_alphabetic());
if valid_col && (rest.chars().all(|c| c.is_ascii_digit()) || rest == "?") {
let row = if rest == "?" {
Some(WILDCARD_ROW)
} else {
match rest.parse::<u32>() {
Ok(0) => None,
Ok(n) => Some(n),
Err(_) => None,
}
};
if let Some(row) = row {
tokens.push(Token::CellRef(col, row));
continue;
}
}
}
}
tokens.push(Token::Function(upper));
continue;
}
match ch {
'+' => tokens.push(Token::Plus),
'-' => tokens.push(Token::Minus),
'*' => tokens.push(Token::Star),
'/' => tokens.push(Token::Slash),
'(' => tokens.push(Token::LParen),
')' => tokens.push(Token::RParen),
',' => tokens.push(Token::Comma),
':' => tokens.push(Token::Colon),
_ => return None,
}
i += 1;
}
Some(tokens)
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_simple_number() {
let tokens = tokenize("=123").unwrap();
assert_eq!(tokens, vec![Token::Number(123.0)]);
}
#[test]
fn test_cell_ref() {
let tokens = tokenize("=A1+B3").unwrap();
assert_eq!(
tokens,
vec![
Token::CellRef("A".into(), 1),
Token::Plus,
Token::CellRef("B".into(), 3),
]
);
}
#[test]
fn test_function_call() {
let tokens = tokenize("=SUM(A1:B5)").unwrap();
assert_eq!(
tokens,
vec![
Token::Function("SUM".into()),
Token::LParen,
Token::CellRef("A".into(), 1),
Token::Colon,
Token::CellRef("B".into(), 5),
Token::RParen,
]
);
}
#[test]
fn test_direction() {
let tokens = tokenize("=sum(left)").unwrap();
assert_eq!(
tokens,
vec![
Token::Function("SUM".into()),
Token::LParen,
Token::Direction(DirectionKind::Left),
Token::RParen,
]
);
}
#[test]
fn test_complex_formula() {
let tokens = tokenize("=a1+(b3-3)*2+sum(a1:b5,avg(c3,e5-3))").unwrap();
assert!(tokens.len() > 10);
assert_eq!(tokens[0], Token::CellRef("A".into(), 1));
assert_eq!(tokens[1], Token::Plus);
}
#[test]
fn test_wildcard() {
let tokens = tokenize("=SUM(?1:?3)").unwrap();
assert_eq!(
tokens,
vec![
Token::Function("SUM".into()),
Token::LParen,
Token::CellRef("?".into(), 1),
Token::Colon,
Token::CellRef("?".into(), 3),
Token::RParen,
]
);
}
#[test]
fn test_at_prefix() {
let tokens = tokenize("@SUM(A1:A5)").unwrap();
assert_eq!(tokens[0], Token::Function("SUM".into()));
}
}