use alloc::boxed::Box;
use alloc::string::{String, ToString};
use alloc::vec::Vec;
use core::fmt;
use core::mem;
pub const MAX_COL: u32 = 16_384;
pub const MAX_ROW: u32 = 1_048_576;
#[derive(Debug, Clone, PartialEq)]
pub enum Expr {
Number(f64),
Text(String),
Boolean(bool),
Error(crate::error::ExcelError),
CellRef {
col: u32,
row: u32,
col_abs: bool,
row_abs: bool,
},
Range {
start: CellRef,
end: CellRef,
},
Unary {
op: UnaryOp,
expr: Box<Expr>,
},
Binary {
op: BinaryOp,
left: Box<Expr>,
right: Box<Expr>,
},
Function {
name: String,
args: Vec<Expr>,
},
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub struct CellRef {
pub col: u32,
pub row: u32,
pub col_abs: bool,
pub row_abs: bool,
}
impl CellRef {
#[must_use]
pub const fn new(col: u32, row: u32) -> Self {
Self {
col,
row,
col_abs: false,
row_abs: false,
}
}
#[must_use]
pub const fn in_grid(&self) -> bool {
self.col >= 1 && self.col <= MAX_COL && self.row >= 1 && self.row <= MAX_ROW
}
}
impl fmt::Display for CellRef {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
if self.col_abs {
f.write_str("$")?;
}
write!(f, "{}", col_name(self.col))?;
if self.row_abs {
f.write_str("$")?;
}
write!(f, "{}", self.row)
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum BinaryOp {
Add,
Sub,
Mul,
Div,
Pow,
Concat,
Eq,
Ne,
Lt,
Gt,
Le,
Ge,
}
impl BinaryOp {
#[must_use]
pub const fn binding_power(self) -> (usize, usize) {
match self {
Self::Eq | Self::Ne | Self::Lt | Self::Gt | Self::Le | Self::Ge => (10, 11),
Self::Concat => (20, 21),
Self::Add | Self::Sub => (30, 31),
Self::Mul | Self::Div => (40, 41),
Self::Pow => (50, 50),
}
}
#[must_use]
pub const fn symbol(self) -> &'static str {
match self {
Self::Add => "+",
Self::Sub => "-",
Self::Mul => "*",
Self::Div => "/",
Self::Pow => "^",
Self::Concat => "&",
Self::Eq => "=",
Self::Ne => "<>",
Self::Lt => "<",
Self::Gt => ">",
Self::Le => "<=",
Self::Ge => ">=",
}
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum UnaryOp {
Neg,
Pos,
Percent,
}
impl UnaryOp {
#[must_use]
pub const fn binding_power(self) -> usize {
match self {
Self::Neg | Self::Pos => 60,
Self::Percent => 70,
}
}
#[must_use]
pub const fn symbol(self) -> &'static str {
match self {
Self::Neg => "-",
Self::Pos => "+",
Self::Percent => "%",
}
}
#[must_use]
pub const fn is_prefix(self) -> bool {
!matches!(self, Self::Percent)
}
}
#[must_use]
pub fn normalize_range(start: &CellRef, end: &CellRef) -> (u32, u32, u32, u32) {
(
start.col.min(end.col),
start.row.min(end.row),
start.col.max(end.col),
start.row.max(end.row),
)
}
#[must_use]
pub fn is_omitted_arg(expr: &Expr) -> bool {
matches!(expr, Expr::Error(crate::error::ExcelError::Null))
}
#[must_use]
pub fn col_name(col: u32) -> String {
if col == 0 {
return "?".to_string();
}
let mut rev = Vec::new();
let mut n = col;
while n > 0 {
rev.push(b'A' + ((n - 1) % 26) as u8);
n = (n - 1) / 26;
}
let mut s = String::with_capacity(rev.len());
while let Some(byte) = rev.pop() {
s.push(byte as char);
}
s
}
#[must_use]
pub fn col_number(letters: &str) -> Option<u32> {
if letters.is_empty() || !letters.bytes().all(|b| b.is_ascii_alphabetic()) {
return None;
}
let mut col: u32 = 0;
for b in letters.bytes() {
col = col * 26 + u32::from(b.to_ascii_uppercase() - b'A' + 1);
}
if col <= MAX_COL {
Some(col)
} else {
None
}
}
impl Drop for Expr {
fn drop(&mut self) {
if trivial_shell(self) {
return;
}
let mut stack: Vec<Expr> = Vec::new();
stack.push(mem::replace(self, Expr::Number(0.0)));
while let Some(mut node) = stack.pop() {
match &mut node {
Expr::Binary { left, right, .. } => {
let r = mem::replace(right.as_mut(), Expr::Number(0.0));
let l = mem::replace(left.as_mut(), Expr::Number(0.0));
stack.push(r);
stack.push(l);
}
Expr::Unary { expr, .. } => {
stack.push(mem::replace(expr.as_mut(), Expr::Number(0.0)));
}
Expr::Function { args, .. } => {
for a in args.iter_mut() {
stack.push(mem::replace(a, Expr::Number(0.0)));
}
}
_ => {}
}
drop(node);
}
}
}
fn trivial_shell(e: &Expr) -> bool {
match e {
Expr::Number(_)
| Expr::Text(_)
| Expr::Boolean(_)
| Expr::Error(_)
| Expr::CellRef { .. }
| Expr::Range { .. } => true,
Expr::Binary { left, right, .. } => {
matches!(**left, Expr::Number(_)) && matches!(**right, Expr::Number(_))
}
Expr::Unary { expr, .. } => matches!(**expr, Expr::Number(_)),
Expr::Function { args, .. } => args.iter().all(|a| matches!(a, Expr::Number(_))),
}
}
#[cfg(test)]
mod tests {
#![allow(
clippy::unwrap_used,
clippy::expect_used,
clippy::panic,
clippy::indexing_slicing
)]
use super::*;
use crate::error::ExcelError;
use alloc::string::ToString;
#[test]
fn col_name_roundtrip() {
for col in [1u32, 2, 26, 27, 28, 52, 703, 16_384] {
assert_eq!(col_number(&col_name(col)), Some(col), "col {col}");
}
assert_eq!(col_name(1), "A");
assert_eq!(col_name(26), "Z");
assert_eq!(col_name(27), "AA");
assert_eq!(col_name(28), "AB");
assert_eq!(col_name(702), "ZZ");
assert_eq!(col_name(703), "AAA");
assert_eq!(col_name(16_384), "XFD");
assert_eq!(col_name(0), "?");
}
#[test]
fn col_number_rejects() {
assert_eq!(col_number(""), None);
assert_eq!(col_number("A1"), None);
assert_eq!(col_number("XFE"), None); assert_eq!(col_number("Ä"), None);
assert_eq!(col_number("ABCD"), None); }
#[test]
fn cellref_display_with_anchors() {
assert_eq!(CellRef::new(1, 1).to_string(), "A1");
assert_eq!(
CellRef {
col: 2,
row: 3,
col_abs: true,
row_abs: false
}
.to_string(),
"$B3"
);
assert_eq!(
CellRef {
col: 2,
row: 3,
col_abs: false,
row_abs: true
}
.to_string(),
"B$3"
);
assert_eq!(
CellRef {
col: 16384,
row: 1_048_576,
col_abs: true,
row_abs: true
}
.to_string(),
"$XFD$1048576"
);
}
#[test]
fn in_grid_bounds() {
assert!(CellRef::new(1, 1).in_grid());
assert!(CellRef::new(16_384, 1_048_576).in_grid());
assert!(!CellRef::new(0, 1).in_grid());
assert!(!CellRef::new(16_385, 1).in_grid());
assert!(!CellRef::new(1, 0).in_grid());
assert!(!CellRef::new(1, 1_048_577).in_grid());
}
#[test]
fn normalize_range_orders_corners() {
let a = CellRef::new(1, 1);
let b = CellRef::new(2, 2);
assert_eq!(normalize_range(&b, &a), (1, 1, 2, 2));
assert_eq!(normalize_range(&a, &b), (1, 1, 2, 2));
}
#[test]
fn binding_power_ladder() {
assert!(BinaryOp::Eq.binding_power().0 < BinaryOp::Concat.binding_power().0);
assert!(BinaryOp::Concat.binding_power().0 < BinaryOp::Add.binding_power().0);
assert!(BinaryOp::Add.binding_power().0 < BinaryOp::Mul.binding_power().0);
assert!(BinaryOp::Mul.binding_power().0 < BinaryOp::Pow.binding_power().0);
assert_eq!(
BinaryOp::Pow.binding_power().0,
BinaryOp::Pow.binding_power().1
);
assert!(BinaryOp::Add.binding_power().1 > BinaryOp::Add.binding_power().0);
assert!(BinaryOp::Pow.binding_power().0 < UnaryOp::Neg.binding_power());
assert!(UnaryOp::Neg.binding_power() < UnaryOp::Percent.binding_power());
assert!(UnaryOp::Neg.is_prefix());
assert!(!UnaryOp::Percent.is_prefix());
}
#[test]
fn omitted_marker_only_null() {
assert!(is_omitted_arg(&Expr::Error(ExcelError::Null)));
assert!(!is_omitted_arg(&Expr::Error(ExcelError::NA)));
assert!(!is_omitted_arg(&Expr::Number(0.0)));
assert!(!is_omitted_arg(&Expr::Text(alloc::string::String::new())));
}
#[test]
fn op_symbols() {
assert_eq!(BinaryOp::Ne.symbol(), "<>");
assert_eq!(BinaryOp::Ge.symbol(), ">=");
assert_eq!(UnaryOp::Percent.symbol(), "%");
}
#[test]
fn iterative_drop_handles_deep_and_stringy_trees() {
let mut e = Expr::Number(0.0);
for _ in 0..20_000 {
e = Expr::Binary {
op: BinaryOp::Concat,
left: Box::new(e),
right: Box::new(Expr::Text(alloc::string::String::from("x"))),
};
}
drop(e); let mut f = Expr::Function {
name: alloc::string::String::from("SUM"),
args: alloc::vec::Vec::new(),
};
for _ in 0..5_000 {
f = Expr::Function {
name: alloc::string::String::from("SUM"),
args: alloc::vec![f, Expr::Number(1.0)],
};
}
drop(f);
}
}