Skip to main content

formula_lang/
value.rs

1//! Runtime values and Excel's coercion rules.
2//!
3//! The four rules that make spreadsheet arithmetic feel like spreadsheet
4//! arithmetic, all here:
5//!
6//! 1. **Arithmetic coerces.** Booleans are 1/0, numeric text parses,
7//!    empty is 0, everything else is `#VALUE!`.
8//! 2. **Comparisons rank types.** Number < Text < Boolean; `"1" = 1` is
9//!    FALSE (no cross-type coercion); text compares case-insensitively;
10//!    empty coerces to the other side's zero value.
11//! 3. **Concatenation stringifies** through an Excel-approximating
12//!    General format (15 significant digits, `E+NN` exponents).
13//! 4. **Errors dominate.** Any error operand propagates before coercion
14//!    is attempted.
15
16use crate::error::ExcelError;
17use alloc::format;
18use alloc::string::{String, ToString};
19
20/// A runtime value — the evaluator's currency.
21#[derive(Debug, Clone, PartialEq)]
22pub enum Value {
23    /// A 64-bit float. Non-finite values never escape evaluation: any
24    /// operation producing inf/NaN folds to
25    /// [`ExcelError::Num`](ExcelError::Num).
26    Number(f64),
27    /// Text (owned; this is the only allocating variant).
28    Text(String),
29    /// A logical value.
30    Boolean(bool),
31    /// An error **stored as data** — a cell that holds `#REF!`, or a range
32    /// element. Operators convert this to the hard
33    /// [`FormulaError::Eval`](crate::FormulaError::Eval) channel on first
34    /// use; `ISERROR` and friends inspect it directly.
35    Error(ExcelError),
36    /// An empty cell.
37    Empty,
38}
39
40impl Value {
41    /// Excel-flavored type name: `"number"`, `"text"`, `"logical"`,
42    /// `"error"`, `"empty"`.
43    #[must_use]
44    pub const fn typename(&self) -> &'static str {
45        match self {
46            Self::Number(_) => "number",
47            Self::Text(_) => "text",
48            Self::Boolean(_) => "logical",
49            Self::Error(_) => "error",
50            Self::Empty => "empty",
51        }
52    }
53
54    /// True when this is [`Value::Error`].
55    #[must_use]
56    pub const fn is_error(&self) -> bool {
57        matches!(self, Self::Error(_))
58    }
59}
60
61/// Coerces a value to a number under Excel arithmetic rules.
62///
63/// `Number` → itself · `Boolean` → 1/0 · `Text` → trimmed `f64` parse
64/// (never boolean text — `="TRUE"+0` is `#VALUE!`) · `Empty` → 0 ·
65/// `Error` → itself. Failures are [`ExcelError::Value`].
66pub(crate) fn coerce_number(v: &Value) -> Result<f64, ExcelError> {
67    match v {
68        Value::Number(n) => Ok(*n),
69        Value::Boolean(b) => Ok(if *b { 1.0 } else { 0.0 }),
70        Value::Text(s) => match s.trim().parse::<f64>() {
71            Ok(n) => Ok(n),
72            Err(_) => Err(ExcelError::Value),
73        },
74        Value::Empty => Ok(0.0),
75        Value::Error(e) => Err(*e),
76    }
77}
78
79/// Coerces a value to text under concatenation rules: numbers render in
80/// General format, `TRUE`/`FALSE` upper-case, empty → `""`, error →
81/// propagates.
82pub(crate) fn coerce_text(v: &Value) -> Result<String, ExcelError> {
83    match v {
84        Value::Number(n) => Ok(number_to_text(*n)),
85        Value::Text(s) => Ok(s.clone()),
86        Value::Boolean(b) => Ok(if *b { "TRUE" } else { "FALSE" }.to_string()),
87        Value::Empty => Ok(String::new()),
88        Value::Error(e) => Err(*e),
89    }
90}
91
92/// Coerces a value to a logical under `IF`/`AND`/`OR` rules: `Number` →
93/// `n != 0` · `Text` → `"true"`/`"false"` case-insensitive, else `#VALUE!`
94/// · `Empty` → `FALSE` · `Error` → propagates.
95pub(crate) fn coerce_bool(v: &Value) -> Result<bool, ExcelError> {
96    match v {
97        Value::Boolean(b) => Ok(*b),
98        Value::Number(n) => Ok(*n != 0.0),
99        Value::Text(s) => {
100            if s.eq_ignore_ascii_case("TRUE") {
101                Ok(true)
102            } else if s.eq_ignore_ascii_case("FALSE") {
103                Ok(false)
104            } else {
105                Err(ExcelError::Value)
106            }
107        }
108        Value::Empty => Ok(false),
109        Value::Error(e) => Err(*e),
110    }
111}
112
113/// The comparison type rank: Number < Text < Boolean. Errors never reach
114/// here (propagated first).
115fn type_rank(v: &Value) -> u8 {
116    match v {
117        Value::Number(_) => 0,
118        Value::Text(_) => 1,
119        Value::Boolean(_) => 2,
120        // Empty is substituted away before ranking.
121        Value::Empty | Value::Error(_) => u8::MAX,
122    }
123}
124
125/// Excel's empty-cell substitution: comparing against an empty yields the
126/// other side's zero value (`A1 = 0`, `A1 = ""`, `A1 = FALSE` all TRUE for
127/// an empty A1).
128fn empty_substitute(other: &Value) -> Value {
129    match other {
130        Value::Number(_) => Value::Number(0.0),
131        Value::Text(_) => Value::Text(String::new()),
132        Value::Boolean(_) => Value::Boolean(false),
133        _ => Value::Number(0.0),
134    }
135}
136
137/// Excel comparison: returns `Ordering` with the type ladder
138/// Number < Text < Boolean, case-insensitive text order, and empty-cell
139/// substitution. Errors must be propagated by the caller.
140pub(crate) fn compare(a: &Value, b: &Value) -> Result<core::cmp::Ordering, ExcelError> {
141    use core::cmp::Ordering;
142    match (a, b) {
143        (Value::Empty, Value::Empty) => Ok(Ordering::Equal),
144        (Value::Empty, _) => compare(&empty_substitute(b), b),
145        (_, Value::Empty) => compare(a, &empty_substitute(a)),
146        (Value::Error(e), _) | (_, Value::Error(e)) => Err(*e),
147        (Value::Number(x), Value::Number(y)) => Ok(x.partial_cmp(y).unwrap_or(Ordering::Equal)),
148        (Value::Text(x), Value::Text(y)) => Ok(compare_text(x, y)),
149        (Value::Boolean(x), Value::Boolean(y)) => Ok(x.cmp(y)),
150        // Cross-type: no coercion — rank decides.
151        _ => Ok(type_rank(a).cmp(&type_rank(b))),
152    }
153}
154
155/// Case-insensitive text ordering. ASCII folds exactly; non-ASCII folds by
156/// simple `char::to_lowercase` (locale-collation exactness is out of scope
157/// for the core and documented).
158fn compare_text(x: &str, y: &str) -> core::cmp::Ordering {
159    let mut xi = x.chars().flat_map(char::to_lowercase);
160    let mut yi = y.chars().flat_map(char::to_lowercase);
161    loop {
162        match (xi.next(), yi.next()) {
163            (None, None) => return core::cmp::Ordering::Equal,
164            (None, Some(_)) => return core::cmp::Ordering::Less,
165            (Some(_), None) => return core::cmp::Ordering::Greater,
166            (Some(cx), Some(cy)) => match cx.cmp(&cy) {
167                core::cmp::Ordering::Equal => continue,
168                ord => return ord,
169            },
170        }
171    }
172}
173
174/// Renders a number in an Excel-approximating **General** format:
175/// 15 significant digits, trailing zeros stripped, exponent notation
176/// (`1E+20`, `1.5E-07`) outside `[1e-4, 1e11)`. This is what `&`, `TEXT`
177/// General, and `CONCATENATE` use.
178///
179/// Deterministic and std-free — no platform float formatting beyond
180/// `core::fmt`'s shortest round-trip digits.
181#[must_use]
182pub fn number_to_text(n: f64) -> String {
183    if n.is_nan() {
184        return ExcelError::Num.literal().to_string();
185    }
186    if n.is_infinite() {
187        return if n > 0.0 { "1E+999" } else { "-1E+999" }.to_string();
188    }
189    if n == 0.0 {
190        return "0".to_string();
191    }
192    let a = n.abs();
193    if (1e-4..1e11).contains(&a) {
194        // Decimal, 15 significant digits, trailing zeros stripped.
195        let sci = format!("{:.14e}", a); // d.ddddddddddddde±x
196        let (mantissa, exp) = split_sci(&sci);
197        let digits: String = mantissa.chars().filter(|c| *c != '.').collect();
198        let exp: i32 = exp.parse().unwrap_or(0);
199        let mut out = String::new();
200        if n < 0.0 {
201            out.push('-');
202        }
203        if exp >= 0 {
204            let ip = exp as usize + 1;
205            let ip = ip.min(digits.len().max(1));
206            out.push_str(&digits[..ip]);
207            let frac = digits[ip..].trim_end_matches('0');
208            if !frac.is_empty() {
209                out.push('.');
210                out.push_str(frac);
211            }
212        } else {
213            out.push_str("0.");
214            for _ in 0..(-exp - 1) {
215                out.push('0');
216            }
217            out.push_str(digits.trim_end_matches('0'));
218        }
219        out
220    } else {
221        // Exponent notation: 15 significant digits, `E±NN` (two-digit min).
222        let neg = n < 0.0;
223        let sci = format!("{:.14e}", a); // d.ddddddddddddddd±x — 15 sig
224        let (mantissa, exp) = split_sci(&sci);
225        let exp: i32 = exp.parse().unwrap_or(0);
226        let mut out = String::new();
227        if neg {
228            out.push('-');
229        }
230        out.push_str(mantissa.trim_end_matches('0').trim_end_matches('.'));
231        out.push('E');
232        if exp < 0 {
233            out.push('-');
234        } else {
235            out.push('+');
236        }
237        let ea = exp.abs();
238        if ea < 10 {
239            out.push('0');
240        }
241        let _ = core::fmt::Write::write_fmt(&mut out, format_args!("{ea}"));
242        out
243    }
244}
245
246/// Splits `core::fmt`'s `{:e}`/`{:.14e}` output (`"3.00000000000000e-1"`)
247/// into mantissa and exponent-number strings.
248fn split_sci(sci: &str) -> (&str, &str) {
249    match sci.split_once('e') {
250        Some((m, e)) => (m, e),
251        None => (sci, "0"),
252    }
253}
254
255#[cfg(test)]
256mod tests {
257    // Test harness: assertions legitimately panic; the lib target's
258    // non-test paths remain lint-clean.
259    #![allow(
260        clippy::unwrap_used,
261        clippy::expect_used,
262        clippy::panic,
263        clippy::indexing_slicing
264    )]
265
266    use super::*;
267
268    #[test]
269    fn general_format_decimal() {
270        assert_eq!(number_to_text(0.0), "0");
271        assert_eq!(number_to_text(1.0), "1");
272        assert_eq!(number_to_text(-1.5), "-1.5");
273        // 15 significant digits — the Excel display rule.
274        assert_eq!(number_to_text(0.1 + 0.2), "0.3");
275        assert_eq!(number_to_text(1.0 / 3.0), "0.333333333333333");
276        assert_eq!(number_to_text(123456789.125), "123456789.125");
277        assert_eq!(number_to_text(0.0001), "0.0001");
278        assert_eq!(number_to_text(-0.0001), "-0.0001");
279        assert_eq!(number_to_text(1.5e10), "15000000000");
280    }
281
282    #[test]
283    fn general_format_exponent() {
284        assert_eq!(number_to_text(1e11), "1E+11");
285        assert_eq!(number_to_text(1e20), "1E+20");
286        assert_eq!(number_to_text(1.5e-5), "1.5E-05");
287        assert_eq!(number_to_text(1e-7), "1E-07");
288        assert_eq!(number_to_text(-2.5e13), "-2.5E+13");
289        assert_eq!(number_to_text(6.02e23), "6.02E+23");
290        assert_eq!(number_to_text(f64::INFINITY), "1E+999");
291        assert_eq!(number_to_text(f64::NEG_INFINITY), "-1E+999");
292        assert_eq!(number_to_text(f64::NAN), "#NUM!");
293    }
294
295    #[test]
296    fn coercions() {
297        assert_eq!(coerce_number(&Value::Boolean(true)), Ok(1.0));
298        assert_eq!(coerce_number(&Value::Empty), Ok(0.0));
299        assert_eq!(coerce_number(&Value::Text(" 3.5 ".into())), Ok(3.5));
300        assert_eq!(
301            coerce_number(&Value::Text("TRUE".into())),
302            Err(ExcelError::Value)
303        );
304        assert_eq!(
305            coerce_number(&Value::Text("x".into())),
306            Err(ExcelError::Value)
307        );
308        assert_eq!(
309            coerce_number(&Value::Error(ExcelError::NA)),
310            Err(ExcelError::NA)
311        );
312        assert_eq!(coerce_bool(&Value::Number(2.0)), Ok(true));
313        assert_eq!(coerce_bool(&Value::Text("false".into())), Ok(false));
314        assert_eq!(
315            coerce_bool(&Value::Text("yes".into())),
316            Err(ExcelError::Value)
317        );
318        assert_eq!(coerce_text(&Value::Empty), Ok(String::new()));
319        assert_eq!(coerce_text(&Value::Boolean(false)), Ok("FALSE".into()));
320    }
321
322    #[test]
323    fn comparison_ladder() {
324        use core::cmp::Ordering::*;
325        assert_eq!(
326            compare(&Value::Number(1.0), &Value::Text("a".into())),
327            Ok(Less)
328        );
329        assert_eq!(
330            compare(&Value::Text("z".into()), &Value::Boolean(false)),
331            Ok(Less)
332        );
333        assert_eq!(
334            compare(&Value::Boolean(false), &Value::Boolean(true)),
335            Ok(Less)
336        );
337        // Cross-type equality is FALSE (never coerced).
338        assert_eq!(
339            compare(&Value::Number(1.0), &Value::Text("1".into())),
340            Ok(Less)
341        );
342        // Case-insensitive text.
343        assert_eq!(
344            compare(&Value::Text("ABC".into()), &Value::Text("abc".into())),
345            Ok(Equal)
346        );
347        // Empty substitutes.
348        assert_eq!(compare(&Value::Empty, &Value::Number(0.0)), Ok(Equal));
349        assert_eq!(compare(&Value::Empty, &Value::Text("".into())), Ok(Equal));
350        assert_eq!(compare(&Value::Empty, &Value::Boolean(false)), Ok(Equal));
351        assert_eq!(compare(&Value::Empty, &Value::Number(1.0)), Ok(Less));
352        // Errors propagate.
353        assert_eq!(
354            compare(&Value::Error(ExcelError::Ref), &Value::Number(1.0)),
355            Err(ExcelError::Ref)
356        );
357    }
358}