1#[derive(Debug, Clone, PartialEq)]
5pub enum Expr {
6 Number(f64),
8 String(String),
10 Bool(bool),
12 Error(String),
14 Missing,
16 CellRef(CellReference),
18 Range {
20 start: CellReference,
21 end: CellReference,
22 },
23 Function { name: String, args: Vec<Expr> },
25 BinaryOp {
27 op: BinaryOperator,
28 left: Box<Expr>,
29 right: Box<Expr>,
30 },
31 UnaryOp {
33 op: UnaryOperator,
34 operand: Box<Expr>,
35 },
36 Paren(Box<Expr>),
38}
39
40impl Expr {
41 pub(crate) fn structural_metrics(&self) -> (u64, u64, u64) {
47 let mut nodes = 0_u64;
48 let mut max_depth = 0_u64;
49 let mut max_binary_chain = 0_u64;
50 let mut stack = MetricStack::new(self);
51 stack.push((self, 1_u64, 0_u64));
52
53 while let Some((expr, depth, parent_binary_chain)) = stack.pop() {
54 nodes = nodes.saturating_add(1);
55 max_depth = max_depth.max(depth);
56 match expr {
57 Self::Function { args, .. } => {
58 for arg in args.iter().rev() {
59 stack.push((arg, depth.saturating_add(1), 0));
60 }
61 }
62 Self::BinaryOp { left, right, .. } => {
63 let chain = parent_binary_chain.saturating_add(1);
64 max_binary_chain = max_binary_chain.max(chain);
65 stack.push((right, depth, 0));
66 stack.push((left, depth, chain));
67 }
68 Self::UnaryOp { operand, .. } | Self::Paren(operand) => {
69 stack.push((operand, depth.saturating_add(1), 0));
70 }
71 _ => {}
72 }
73 }
74
75 (nodes, max_depth, max_binary_chain)
76 }
77}
78
79struct MetricStack<'a> {
82 inline: [(&'a Expr, u64, u64); MetricStack::INLINE],
83 len: usize,
84 spill: Vec<(&'a Expr, u64, u64)>,
85}
86
87impl<'a> MetricStack<'a> {
88 const INLINE: usize = 16;
89
90 fn new(filler: &'a Expr) -> Self {
91 Self {
92 inline: [(filler, 0, 0); Self::INLINE],
93 len: 0,
94 spill: Vec::new(),
95 }
96 }
97
98 fn push(&mut self, entry: (&'a Expr, u64, u64)) {
99 if self.spill.is_empty() && self.len < Self::INLINE {
100 self.inline[self.len] = entry;
101 self.len += 1;
102 } else {
103 self.spill.push(entry);
104 }
105 }
106
107 fn pop(&mut self) -> Option<(&'a Expr, u64, u64)> {
108 if let Some(entry) = self.spill.pop() {
109 return Some(entry);
110 }
111 if self.len == 0 {
112 return None;
113 }
114 self.len -= 1;
115 Some(self.inline[self.len])
116 }
117}
118
119#[derive(Debug, Clone, PartialEq)]
121pub struct CellReference {
122 pub col: String,
124 pub row: u32,
126 pub abs_col: bool,
128 pub abs_row: bool,
130 pub sheet: Option<String>,
132}
133
134#[derive(Debug, Clone, Copy, PartialEq, Eq)]
136pub enum BinaryOperator {
137 Add,
139 Sub,
141 Mul,
143 Div,
145 Pow,
147 Concat,
149 Eq,
151 Ne,
153 Lt,
155 Le,
157 Gt,
159 Ge,
161}
162
163#[derive(Debug, Clone, Copy, PartialEq, Eq)]
165pub enum UnaryOperator {
166 Neg,
168 Pos,
170 Percent,
172}