formula_lang/resolver.rs
1//! The cell-value abstraction — the boundary that keeps this crate a pure
2//! evaluator.
3//!
4//! `formula-lang` never stores spreadsheet data. Host engines implement
5//! [`CellResolver`] (a sheet model, a sparse map, a test fixture) and hand
6//! it to [`evaluate`](crate::evaluate). Two ready-made implementations are
7//! included: [`EmptyResolver`] and [`MapResolver`].
8//!
9//! # Range layout contract
10//!
11//! [`CellResolver::get_range`] returns values **row-major**, suitable for
12//! indexing as `vec[(r - top) * width + (c - left)]` with `width = right -
13//! left + 1`. The lookup functions (`VLOOKUP`, `HLOOKUP`, `INDEX`,
14//! `MATCH`, `OFFSET`) rely on this layout. Out-of-grid coordinates inside a
15//! requested range are `Value::Empty`.
16
17use crate::ast::normalize_range;
18use crate::value::Value;
19use alloc::collections::BTreeMap;
20use alloc::string::ToString;
21use alloc::vec::Vec;
22
23/// Resolves cell coordinates to values. Coordinates are 1-based; `None`
24/// from [`get`](CellResolver::get) means "no such cell / empty".
25pub trait CellResolver {
26 /// The scalar value of one cell, or `None` when the cell is empty or
27 /// outside the modeled grid.
28 fn get(&self, col: u32, row: u32) -> Option<Value>;
29
30 /// The values of a rectangular region, **row-major**. `start` and
31 /// `end` corners may arrive in either order (the evaluator normalizes
32 /// before calling, but implementations should not rely on that).
33 ///
34 /// The default implementation derives the rectangle from repeated
35 /// [`get`](CellResolver::get) calls — correct for any resolver, but
36 /// engines with bulk access should override for speed.
37 fn get_range(&self, start: (u32, u32), end: (u32, u32)) -> Vec<Value> {
38 let (c0, r0, c1, r1) = normalize_range(
39 &crate::ast::CellRef::new(start.0, start.1),
40 &crate::ast::CellRef::new(end.0, end.1),
41 );
42 let mut out = Vec::new();
43 for row in r0..=r1 {
44 for col in c0..=c1 {
45 out.push(self.get(col, row).unwrap_or(Value::Empty));
46 }
47 }
48 out
49 }
50}
51
52/// A resolver where every cell is empty. Useful as the null engine in
53/// tests and as the default of host pipelines.
54#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
55pub struct EmptyResolver;
56
57impl CellResolver for EmptyResolver {
58 fn get(&self, _col: u32, _row: u32) -> Option<Value> {
59 None
60 }
61}
62
63/// A sparse `BTreeMap`-backed resolver — the workhorse for tests, docs,
64/// and small host models.
65#[derive(Debug, Clone, Default, PartialEq)]
66pub struct MapResolver {
67 cells: BTreeMap<(u32, u32), Value>,
68}
69
70impl MapResolver {
71 /// An empty map.
72 #[must_use]
73 pub fn new() -> Self {
74 Self::default()
75 }
76
77 /// Sets one cell (1-based coordinates).
78 pub fn set(&mut self, col: u32, row: u32, value: Value) {
79 self.cells.insert((col, row), value);
80 }
81
82 /// Convenience: sets one cell to a number.
83 pub fn set_num(&mut self, col: u32, row: u32, n: f64) {
84 self.set(col, row, Value::Number(n));
85 }
86
87 /// Convenience: sets one cell to text.
88 pub fn set_text(&mut self, col: u32, row: u32, s: &str) {
89 self.set(col, row, Value::Text(s.to_string()));
90 }
91
92 /// Number of populated cells.
93 #[must_use]
94 pub fn len(&self) -> usize {
95 self.cells.len()
96 }
97
98 /// True when no cells are set.
99 #[must_use]
100 pub fn is_empty(&self) -> bool {
101 self.cells.is_empty()
102 }
103}
104
105impl CellResolver for MapResolver {
106 fn get(&self, col: u32, row: u32) -> Option<Value> {
107 self.cells.get(&(col, row)).cloned()
108 }
109
110 fn get_range(&self, start: (u32, u32), end: (u32, u32)) -> Vec<Value> {
111 let (c0, r0, c1, r1) = normalize_range(
112 &crate::ast::CellRef::new(start.0, start.1),
113 &crate::ast::CellRef::new(end.0, end.1),
114 );
115 let mut out = Vec::new();
116 for row in r0..=r1 {
117 for col in c0..=c1 {
118 out.push(self.cells.get(&(col, row)).cloned().unwrap_or(Value::Empty));
119 }
120 }
121 out
122 }
123}