use crate::coordinate::{CellRef, Range};
use crate::error::{CellError, Error, Result};
#[derive(Debug, Clone, PartialEq)]
#[non_exhaustive]
pub enum Expr {
Number(f64),
Text(String),
Bool(bool),
Error(CellError),
Range {
sheet: Option<String>,
range: Range,
anchors: Anchors,
},
Name(String),
Missing,
Unary(UnaryOp, Box<Self>),
Binary(BinaryOp, Box<Self>, Box<Self>),
Call {
name: String,
args: Vec<Self>,
},
Array(Vec<Vec<Self>>),
Structured(Structured),
Apply {
callee: Box<Self>,
args: Vec<Self>,
},
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
#[expect(
clippy::struct_excessive_bools,
reason = "four independent `$` signs, one per part of the reference"
)]
pub struct Anchors {
pub start_col: bool,
pub start_row: bool,
pub end_col: bool,
pub end_row: bool,
}
impl Anchors {
fn of(left: &str, right: &str) -> Self {
let part = |text: &str| {
let col_abs = text.starts_with('$');
let body = text.trim_start_matches('$');
let letters: String = body.chars().take_while(char::is_ascii_alphabetic).collect();
let rest = &body[letters.len()..];
let row_abs = rest.starts_with('$');
let digits = rest.trim_start_matches('$');
let col = crate::Col::from_letters(&letters)
.ok()
.map(crate::Col::index);
let row = digits.parse::<u32>().ok();
if letters.is_empty() {
(false, col_abs || row_abs, col, row)
} else {
(col_abs, row_abs, col, row)
}
};
let (c1, r1, col1, row1) = part(left);
let (c2, r2, col2, row2) = part(right);
let (start_col, end_col) = if col1 > col2 { (c2, c1) } else { (c1, c2) };
let (start_row, end_row) = if row1 > row2 { (r2, r1) } else { (r1, r2) };
Self {
start_col,
start_row,
end_col,
end_row,
}
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Structured {
pub table: Option<String>,
pub part: TablePart,
pub columns: Option<(String, Option<String>)>,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum TablePart {
#[default]
Data,
All,
Headers,
Totals,
HeadersData,
DataTotals,
ThisRow,
}
impl TablePart {
fn with(self, other: Self) -> Self {
match (self, other) {
(Self::Headers, Self::Data) | (Self::Data, Self::Headers) => Self::HeadersData,
(Self::Totals, Self::Data) | (Self::Data, Self::Totals) => Self::DataTotals,
(Self::Headers, Self::Totals) | (Self::Totals, Self::Headers) => Self::All,
_ => other,
}
}
fn parse(name: &str) -> Option<Self> {
Some(match name.to_ascii_lowercase().as_str() {
"all" => Self::All,
"data" => Self::Data,
"headers" => Self::Headers,
"totals" => Self::Totals,
"this row" => Self::ThisRow,
_ => return None,
})
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum UnaryOp {
Neg,
Plus,
Percent,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum BinaryOp {
Add,
Sub,
Mul,
Div,
Pow,
Concat,
Eq,
Ne,
Lt,
Le,
Gt,
Ge,
Intersect,
Union,
Span,
}
pub fn parse(formula: &str) -> Result<Expr> {
let text = formula.strip_prefix('=').unwrap_or(formula);
let tokens = lex(text)?;
let mut p = Parser {
tokens,
at: 0,
comma_separates: false,
depth: 0,
};
let expr = p.expr(0)?;
match p.peek() {
Tok::Eof => Ok(expr),
other => Err(Error::InvalidFormula(format!("unexpected {other:?}"))),
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum Op {
Plus,
Minus,
Star,
Slash,
Caret,
Amp,
Eq,
Ne,
Lt,
Le,
Gt,
Ge,
Percent,
Colon,
Comma,
Semi,
LParen,
RParen,
LBrace,
RBrace,
}
#[derive(Debug, Clone, PartialEq)]
enum Tok {
Num(f64),
Str(String),
Err(CellError),
Ident {
sheet: Option<String>,
text: String,
},
Structured(Structured),
Op(Op),
Eof,
}
#[derive(Debug, Clone, PartialEq)]
struct Lexed {
tok: Tok,
spaced: bool,
}
fn lex(s: &str) -> Result<Vec<Lexed>> {
let c: Vec<char> = s.chars().collect();
let mut out = Vec::new();
let mut i = 0;
let mut spaced = false;
while i < c.len() {
let ch = c[i];
if ch.is_whitespace() {
spaced = true;
i += 1;
continue;
}
let tok = match ch {
'"' => Tok::Str(lex_quoted(&c, &mut i, '"', "unterminated string")?),
'#' => lex_error(&c, &mut i)?,
'0'..='9' | '.' => lex_number(&c, &mut i)?,
'\'' => lex_quoted_sheet(&c, &mut i)?,
'[' if brackets_hold_an_index(&c, i) => lex_workbook_ref(&c, &mut i)?,
'[' => lex_structured(&c, &mut i, None)?,
c0 if is_name_char(c0) => {
let text = take_name(&c, &mut i);
if c.get(i) == Some(&'[') {
lex_structured(&c, &mut i, Some(text))?
}
else if c.get(i) == Some(&'!') {
i += 1;
Tok::Ident {
sheet: Some(text),
text: take_name(&c, &mut i),
}
} else {
Tok::Ident { sheet: None, text }
}
}
_ => Tok::Op(lex_op(&c, &mut i)?),
};
out.push(Lexed { tok, spaced });
spaced = false;
}
out.push(Lexed {
tok: Tok::Eof,
spaced,
});
Ok(out)
}
fn lex_quoted(c: &[char], i: &mut usize, quote: char, unterminated: &str) -> Result<String> {
let mut text = String::new();
*i += 1;
loop {
let Some(&ch) = c.get(*i) else {
return Err(Error::InvalidFormula(unterminated.into()));
};
*i += 1;
if ch == quote {
if c.get(*i) == Some("e) {
text.push(quote);
*i += 1;
continue;
}
return Ok(text);
}
text.push(ch);
}
}
fn lex_error(c: &[char], i: &mut usize) -> Result<Tok> {
let rest: String = c[*i..].iter().collect();
let found = ERROR_LITERALS
.iter()
.find(|lit| rest.starts_with(**lit))
.ok_or_else(|| Error::InvalidFormula(format!("unknown error literal {rest}")))?;
*i += found.chars().count();
CellError::parse(found)
.map(Tok::Err)
.ok_or_else(|| Error::InvalidFormula((*found).to_owned()))
}
fn lex_number(c: &[char], i: &mut usize) -> Result<Tok> {
let start = *i;
while *i < c.len() && (c[*i].is_ascii_digit() || c[*i] == '.') {
*i += 1;
}
if let Some(&e) = c.get(*i)
&& (e == 'e' || e == 'E')
{
let mut j = *i + 1;
if matches!(c.get(j), Some('+' | '-')) {
j += 1;
}
if c.get(j).is_some_and(char::is_ascii_digit) {
*i = j;
while *i < c.len() && c[*i].is_ascii_digit() {
*i += 1;
}
}
}
let text: String = c[start..*i].iter().collect();
text.parse()
.map(Tok::Num)
.map_err(|_| Error::InvalidFormula(format!("bad number {text}")))
}
fn lex_quoted_sheet(c: &[char], i: &mut usize) -> Result<Tok> {
let name = lex_quoted(c, i, '\'', "unterminated sheet name")?;
expect_bang(c, i, "sheet name", &name)?;
Ok(Tok::Ident {
sheet: Some(name),
text: take_name(c, i),
})
}
fn brackets_hold_an_index(c: &[char], i: usize) -> bool {
let Some(close) = c[i..].iter().position(|&ch| ch == ']') else {
return false;
};
close > 1 && c[i + 1..i + close].iter().all(char::is_ascii_digit)
}
fn lex_structured(c: &[char], i: &mut usize, table: Option<String>) -> Result<Tok> {
let body = take_brackets(c, i)?;
let mut out = Structured {
table,
part: TablePart::Data,
columns: None,
};
let mut part: Option<TablePart> = None;
let mut columns: Vec<String> = Vec::new();
let mut spans = false;
let mut this_row = false;
let mut at = 0;
while at < body.len() {
match body[at] {
',' | ']' => at += 1,
':' => {
spans = true;
at += 1;
}
'@' => {
this_row = true;
at += 1;
}
'[' => {
let mut inner = at;
let text = take_brackets(&body, &mut inner)?;
at = inner;
read_item(&text.iter().collect::<String>(), &mut part, &mut columns);
}
_ => {
let start = at;
while at < body.len() && !matches!(body[at], ',' | ':' | ']') {
at += 1;
}
read_item(
&body[start..at].iter().collect::<String>(),
&mut part,
&mut columns,
);
}
}
}
out.part = if this_row {
TablePart::ThisRow
} else {
part.unwrap_or(TablePart::Data)
};
let mut names = columns.into_iter();
if let Some(first) = names.next() {
out.columns = Some((first, spans.then(|| names.next()).flatten()));
}
Ok(Tok::Structured(out))
}
fn read_item(text: &str, part: &mut Option<TablePart>, columns: &mut Vec<String>) {
let text = text.trim();
if let Some(name) = text.strip_prefix('#') {
if let Some(found) = TablePart::parse(name) {
*part = Some(part.map_or(found, |had| had.with(found)));
}
return;
}
let name = text.strip_prefix('@').unwrap_or(text);
if !name.is_empty() {
columns.push(name.to_owned());
}
}
fn take_brackets(c: &[char], i: &mut usize) -> Result<Vec<char>> {
let mut depth = 0usize;
let mut out = Vec::new();
while *i < c.len() {
let ch = c[*i];
*i += 1;
match ch {
'\'' => {
if let Some(&next) = c.get(*i) {
out.push(next);
*i += 1;
}
}
'[' => {
depth += 1;
if depth > 1 {
out.push(ch);
}
}
']' => {
depth -= 1;
if depth == 0 {
return Ok(out);
}
out.push(ch);
}
_ => out.push(ch),
}
}
Err(Error::InvalidFormula(
"unterminated structured reference".into(),
))
}
fn lex_workbook_ref(c: &[char], i: &mut usize) -> Result<Tok> {
let Some(close) = c[*i..].iter().position(|&ch| ch == ']') else {
return Err(Error::InvalidFormula("unterminated workbook index".into()));
};
let mut name: String = c[*i..=*i + close].iter().collect();
*i += close + 1;
name.push_str(&take_name(c, i));
expect_bang(c, i, "workbook reference", &name)?;
Ok(Tok::Ident {
sheet: Some(name),
text: take_name(c, i),
})
}
fn expect_bang(c: &[char], i: &mut usize, what: &str, name: &str) -> Result<()> {
if c.get(*i) != Some(&'!') {
return Err(Error::InvalidFormula(format!(
"{what} {name:?} is not followed by '!'"
)));
}
*i += 1;
Ok(())
}
fn lex_op(c: &[char], i: &mut usize) -> Result<Op> {
let two: String = c[*i..(*i + 2).min(c.len())].iter().collect();
if let Some(op) = match two.as_str() {
"<=" => Some(Op::Le),
">=" => Some(Op::Ge),
"<>" => Some(Op::Ne),
_ => None,
} {
*i += 2;
return Ok(op);
}
let ch = c[*i];
let op = match ch {
'+' => Op::Plus,
'-' => Op::Minus,
'*' => Op::Star,
'/' => Op::Slash,
'^' => Op::Caret,
'&' => Op::Amp,
'=' => Op::Eq,
'<' => Op::Lt,
'>' => Op::Gt,
'%' => Op::Percent,
':' => Op::Colon,
',' => Op::Comma,
';' => Op::Semi,
'(' => Op::LParen,
')' => Op::RParen,
'{' => Op::LBrace,
'}' => Op::RBrace,
_ => {
return Err(Error::InvalidFormula(format!(
"unexpected character {ch:?}"
)));
}
};
*i += 1;
Ok(op)
}
const ERROR_LITERALS: [&str; 8] = [
"#DIV/0!", "#VALUE!", "#NAME?", "#NULL!", "#CALC!", "#REF!", "#NUM!", "#N/A",
];
fn is_name_char(c: char) -> bool {
c.is_alphanumeric() || matches!(c, '_' | '.' | '$' | '\\')
}
fn take_name(c: &[char], i: &mut usize) -> String {
let start = *i;
while *i < c.len() && is_name_char(c[*i]) {
*i += 1;
}
c[start..*i].iter().collect()
}
struct Parser {
tokens: Vec<Lexed>,
at: usize,
comma_separates: bool,
depth: u32,
}
const fn lbp(op: Op) -> u8 {
match op {
Op::Colon => 90,
Op::Comma => 70,
Op::Percent => 50,
Op::Caret => 40,
Op::Star | Op::Slash => 30,
Op::Plus | Op::Minus => 20,
Op::Amp => 10,
Op::Eq | Op::Ne | Op::Lt | Op::Le | Op::Gt | Op::Ge => 5,
_ => 0,
}
}
const INTERSECT_BP: u8 = 80;
const MAX_DEPTH: u32 = 256;
const UNARY_BP: u8 = 60;
impl Parser {
fn peek(&self) -> &Tok {
self.tokens.get(self.at).map_or(&Tok::Eof, |l| &l.tok)
}
fn peek_at(&self, offset: usize) -> &Tok {
self.tokens
.get(self.at + offset)
.map_or(&Tok::Eof, |l| &l.tok)
}
fn spaced(&self) -> bool {
self.tokens.get(self.at).is_some_and(|l| l.spaced)
}
fn next(&mut self) -> Tok {
let tok = self.peek().clone();
self.at += 1;
tok
}
fn eat(&mut self, op: Op) -> bool {
if *self.peek() == Tok::Op(op) {
self.at += 1;
return true;
}
false
}
fn expect(&mut self, op: Op) -> Result<()> {
if self.eat(op) {
return Ok(());
}
Err(Error::InvalidFormula(format!(
"expected {op:?}, found {:?}",
self.peek()
)))
}
fn grouped<T>(
&mut self,
separates: bool,
body: impl FnOnce(&mut Self) -> Result<T>,
) -> Result<T> {
let outer = std::mem::replace(&mut self.comma_separates, separates);
let out = body(self);
self.comma_separates = outer;
out
}
fn expr(&mut self, min_bp: u8) -> Result<Expr> {
self.depth += 1;
if self.depth > MAX_DEPTH {
return Err(Error::InvalidFormula("nested too deeply".into()));
}
let mut lhs = self.operand()?;
while *self.peek() == Tok::Op(Op::LParen) && !self.spaced() {
self.at += 1;
let args = self.arguments()?;
lhs = Expr::Apply {
callee: Box::new(lhs),
args,
};
}
loop {
if INTERSECT_BP > min_bp && self.spaced() && self.starts_operand() {
let rhs = self.expr(INTERSECT_BP)?;
lhs = Expr::Binary(BinaryOp::Intersect, Box::new(lhs), Box::new(rhs));
continue;
}
let Tok::Op(op) = *self.peek() else { break };
if op == Op::Comma && self.comma_separates {
break;
}
let bp = lbp(op);
if bp == 0 || bp <= min_bp {
break;
}
self.at += 1;
if op == Op::Percent {
lhs = Expr::Unary(UnaryOp::Percent, Box::new(lhs));
continue;
}
let binary = match op {
Op::Plus => BinaryOp::Add,
Op::Minus => BinaryOp::Sub,
Op::Star => BinaryOp::Mul,
Op::Slash => BinaryOp::Div,
Op::Caret => BinaryOp::Pow,
Op::Amp => BinaryOp::Concat,
Op::Eq => BinaryOp::Eq,
Op::Ne => BinaryOp::Ne,
Op::Lt => BinaryOp::Lt,
Op::Le => BinaryOp::Le,
Op::Gt => BinaryOp::Gt,
Op::Ge => BinaryOp::Ge,
Op::Comma => BinaryOp::Union,
Op::Colon => BinaryOp::Span,
_ => break,
};
let rhs = self.expr(bp)?;
lhs = Expr::Binary(binary, Box::new(lhs), Box::new(rhs));
}
self.depth -= 1;
Ok(lhs)
}
fn starts_operand(&self) -> bool {
matches!(
self.peek(),
Tok::Num(_)
| Tok::Str(_)
| Tok::Err(_)
| Tok::Ident { .. }
| Tok::Op(Op::LParen | Op::LBrace)
)
}
fn operand(&mut self) -> Result<Expr> {
match self.next() {
Tok::Num(n) => {
if *self.peek() == Tok::Op(Op::Colon)
&& let Tok::Num(end) = *self.peek_at(1)
&& let Ok(range) = Range::parse(&format!("{n}:{end}"))
{
self.at += 2;
return Ok(Expr::Range {
sheet: None,
range,
anchors: Anchors::default(),
});
}
Ok(Expr::Number(n))
}
Tok::Str(s) => Ok(Expr::Text(s)),
Tok::Err(e) => Ok(Expr::Error(e)),
Tok::Op(Op::Minus) => Ok(Expr::Unary(UnaryOp::Neg, Box::new(self.expr(UNARY_BP)?))),
Tok::Op(Op::Plus) => Ok(Expr::Unary(UnaryOp::Plus, Box::new(self.expr(UNARY_BP)?))),
Tok::Op(Op::LParen) => {
let inner = self.grouped(false, |p| p.expr(0))?;
self.expect(Op::RParen)?;
Ok(inner)
}
Tok::Op(Op::LBrace) => self.array(),
Tok::Ident { sheet, text } => self.ident(sheet, text),
Tok::Structured(reference) => Ok(Expr::Structured(reference)),
other => Err(Error::InvalidFormula(format!(
"expected a value, found {other:?}"
))),
}
}
fn array(&mut self) -> Result<Expr> {
let mut rows = vec![Vec::new()];
loop {
let last = rows.len() - 1;
rows[last].push(self.grouped(true, |p| p.expr(0))?);
if self.eat(Op::Comma) {
continue;
}
if self.eat(Op::Semi) {
rows.push(Vec::new());
continue;
}
self.expect(Op::RBrace)?;
break;
}
if rows.iter().any(|r| r.len() != rows[0].len()) {
return Err(Error::InvalidFormula("array rows differ in length".into()));
}
Ok(Expr::Array(rows))
}
fn arguments(&mut self) -> Result<Vec<Expr>> {
let mut args = Vec::new();
if self.eat(Op::RParen) {
return Ok(args);
}
loop {
args.push(if matches!(self.peek(), Tok::Op(Op::Comma | Op::RParen)) {
Expr::Missing
} else {
self.grouped(true, |p| p.expr(0))?
});
if self.eat(Op::Comma) {
continue;
}
self.expect(Op::RParen)?;
break;
}
Ok(args)
}
fn ident(&mut self, sheet: Option<String>, text: String) -> Result<Expr> {
if *self.peek() == Tok::Op(Op::LParen) && !self.spaced() {
self.at += 1;
let name = function_name(&text);
let args = self.arguments()?;
return Ok(Expr::Call { name, args });
}
if sheet.is_none() {
match text.to_uppercase().as_str() {
"TRUE" => return Ok(Expr::Bool(true)),
"FALSE" => return Ok(Expr::Bool(false)),
_ => {}
}
}
if *self.peek() == Tok::Op(Op::Colon) {
let right = match self.peek_at(1).clone() {
Tok::Ident { text, .. } => Some(text),
Tok::Num(n) if n.fract() == 0.0 && n >= 0.0 => Some(format!("{n}")),
_ => None,
};
if let Some(right) = right
&& let Ok(range) = Range::parse(&format!("{text}:{right}"))
{
self.at += 2;
let anchors = Anchors::of(&text, &right);
return Ok(Expr::Range {
sheet,
range,
anchors,
});
}
}
if let Ok(cell) = CellRef::parse(&text) {
return Ok(Expr::Range {
sheet,
range: Range::new(cell, cell),
anchors: Anchors::of(&text, &text),
});
}
Ok(match sheet {
Some(s) => Expr::Name(format!("{s}!{text}")),
None => Expr::Name(text),
})
}
}
fn function_name(text: &str) -> String {
let mut name = text.to_uppercase();
for prefix in ["_XLFN.", "_XLWS."] {
if let Some(rest) = name.strip_prefix(prefix) {
name = rest.to_owned();
}
}
name
}
#[cfg(test)]
mod tests {
use super::{BinaryOp, Expr, UnaryOp, parse};
fn show(e: &Expr) -> String {
match e {
Expr::Number(n) => format!("{n}"),
Expr::Text(t) => format!("{t:?}"),
Expr::Bool(b) => if *b { "TRUE" } else { "FALSE" }.to_owned(),
Expr::Error(err) => err.as_str().to_owned(),
Expr::Structured(r) => format!(
"{}[{:?}{:?}]",
r.table.as_deref().unwrap_or(""),
r.part,
r.columns
),
Expr::Range { sheet, range, .. } => match sheet {
Some(s) => format!("{s}!{range}"),
None => range.to_string(),
},
Expr::Name(n) => n.clone(),
Expr::Missing => "_".to_owned(),
Expr::Unary(op, x) => {
let op = match op {
UnaryOp::Neg => "-",
UnaryOp::Plus => "+",
UnaryOp::Percent => "%",
};
format!("({op} {})", show(x))
}
Expr::Binary(op, a, b) => {
let op = match op {
BinaryOp::Add => "+",
BinaryOp::Sub => "-",
BinaryOp::Mul => "*",
BinaryOp::Div => "/",
BinaryOp::Pow => "^",
BinaryOp::Concat => "&",
BinaryOp::Eq => "=",
BinaryOp::Ne => "<>",
BinaryOp::Lt => "<",
BinaryOp::Le => "<=",
BinaryOp::Gt => ">",
BinaryOp::Ge => ">=",
BinaryOp::Intersect => "isect",
BinaryOp::Union => "union",
BinaryOp::Span => "span",
};
format!("({op} {} {})", show(a), show(b))
}
Expr::Apply { callee, args } => {
let args: Vec<String> = args.iter().map(show).collect();
format!("(apply {} {})", show(callee), args.join(" "))
}
Expr::Call { name, args } => {
let args: Vec<String> = args.iter().map(show).collect();
if args.is_empty() {
format!("({name})")
} else {
format!("({name} {})", args.join(" "))
}
}
Expr::Array(rows) => {
let rows: Vec<String> = rows
.iter()
.map(|r| r.iter().map(show).collect::<Vec<_>>().join(" "))
.collect();
format!("{{{}}}", rows.join("; "))
}
}
}
#[track_caller]
fn shows(formula: &str, expected: &str) {
let tree = parse(formula).unwrap_or_else(|e| panic!("{formula:?} must parse: {e}"));
assert_eq!(show(&tree), expected, "{formula}");
}
#[test]
fn literals() {
shows("=1", "1");
shows("1.5", "1.5");
shows(".5", "0.5");
shows("1E3", "1000");
shows("1.5e-2", "0.015");
shows(r#""a""b""#, r#""a\"b""#);
shows(r#""""#, r#""""#);
shows("TRUE", "TRUE");
shows("false", "FALSE");
shows("#N/A", "#N/A");
shows("#DIV/0!", "#DIV/0!");
}
#[test]
fn references() {
shows("A1", "A1:A1");
shows("$A$1", "A1:A1");
shows("A1:B2", "A1:B2");
shows("$B$4:$D$9", "B4:D9");
shows("A:A", "A1:A1048576");
shows("2:3", "A2:XFD3");
shows("Sheet1!A1", "Sheet1!A1:A1");
shows("'Лист 1'!A1:B2", "Лист 1!A1:B2");
shows("Sheet1!A1:B2", "Sheet1!A1:B2");
shows("myName", "myName");
shows("Sheet1!myName", "Sheet1!myName");
}
#[test]
fn anchors_follow_the_part_they_were_written_on() {
use super::Anchors;
let anchors = |text: &str| match parse(text).unwrap() {
Expr::Range { anchors, .. } => anchors,
other => panic!("{text} parsed as {other:?}"),
};
let all = Anchors {
start_col: true,
start_row: true,
end_col: true,
end_row: true,
};
assert_eq!(anchors("$A$1"), all);
assert_eq!(anchors("A1"), Anchors::default());
assert_eq!(
anchors("$B4:D$9"),
Anchors {
start_col: true,
end_row: true,
..Anchors::default()
}
);
assert_eq!(
anchors("$D9:B4"),
Anchors {
end_col: true,
..Anchors::default()
}
);
assert_eq!(
anchors("$A:B"),
Anchors {
start_col: true,
..Anchors::default()
}
);
assert_eq!(
anchors("$2:3"),
Anchors {
start_row: true,
..Anchors::default()
}
);
}
#[test]
fn precedence_follows_excel() {
shows("1+2*3", "(+ 1 (* 2 3))");
shows("(1+2)*3", "(* (+ 1 2) 3)");
shows("-2^2", "(^ (- 2) 2)");
shows("2^3^2", "(^ (^ 2 3) 2)");
shows("1&2=3", "(= (& 1 2) 3)");
shows("1<=2", "(<= 1 2)");
shows("5%", "(% 5)");
shows("1+2%", "(+ 1 (% 2))");
shows("-A1", "(- A1:A1)");
shows("1--2", "(- 1 (- 2))");
}
#[test]
fn calls() {
shows("SUM(A1:A3)", "(SUM A1:A3)");
shows("sum(1,2)", "(SUM 1 2)");
shows("NOW()", "(NOW)");
shows("IF(A1,,0)", "(IF A1:A1 _ 0)");
shows("IF(A1>0,\"y\",\"n\")", "(IF (> A1:A1 0) \"y\" \"n\")");
shows("SUM(SUM(1),2)", "(SUM (SUM 1) 2)");
shows("LOG10(100)", "(LOG10 100)");
shows("_xlfn.IFERROR(1,2)", "(IFERROR 1 2)");
shows("_xlfn._xlws.FILTER(A1:A2,B1:B2)", "(FILTER A1:A2 B1:B2)");
}
#[test]
fn arrays_and_reference_operators() {
shows("{1,2;3,4}", "{1 2; 3 4}");
shows("{1;2}", "{1; 2}");
shows("A1:B5 A3:D3", "(isect A1:B5 A3:D3)");
shows("SUM((A1,B2))", "(SUM (union A1:A1 B2:B2))");
shows("SUM(A1,B2)", "(SUM A1:A1 B2:B2)");
}
#[test]
fn a_stray_bracket_in_a_structured_reference_ends() {
let _ = parse("[Q[]]");
let _ = parse("Sales[[a]]]");
}
#[test]
fn rejects_broken_formulas() {
for bad in [
r#""unterminated"#,
"1+",
"(1",
"SUM(1",
"1 @ 2",
"#WHAT!",
"{1,2;3}",
"'sheet'A1",
] {
assert!(parse(bad).is_err(), "{bad:?} must not parse");
}
}
}