formualizer-eval 0.9.3

High-performance Arrow-backed Excel formula engine with dependency graph and incremental recalculation
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
use super::super::utils::{ARG_RANGE_NUM_LENIENT_ONE, coerce_num};
use super::{AggregateArgument, resolve_aggregate_argument};
use crate::args::ArgSchema;
use crate::function::Function;
use crate::function_contract::FunctionDependencyContract;
use crate::traits::{ArgumentHandle, FunctionContext};
use arrow_array::Array;
use formualizer_common::{ExcelError, LiteralValue};
use formualizer_macros::func_caps;

#[derive(Debug)]
pub struct MinFn; // MIN(...)
/// Returns the smallest numeric value from one or more arguments.
///
/// `MIN` scans scalar values and ranges, considering only values that can be treated as numbers.
///
/// # Remarks
/// - Errors in any scalar argument or range cell propagate immediately.
/// - In ranges, non-numeric cells are ignored.
/// - Scalar text is included only when it can be coerced to a number.
/// - If no numeric value is found, `MIN` returns `0`.
///
/// # Examples
///
/// ```yaml,sandbox
/// title: "Minimum in a numeric range"
/// grid:
///   A1: 8
///   A2: -2
///   A3: 5
/// formula: "=MIN(A1:A3)"
/// expected: -2
/// ```
///
/// ```yaml,sandbox
/// title: "Coercible scalar text participates"
/// formula: "=MIN(10, \"3\", 7)"
/// expected: 3
/// ```
///
/// ```yaml,sandbox
/// title: "No numeric values returns zero"
/// formula: "=MIN(\"x\")"
/// expected: 0
/// ```
///
/// ```yaml,docs
/// related:
///   - MAX
///   - SMALL
///   - LARGE
///   - MINIFS
/// faq:
///   - q: "Why can MIN return 0 even when no numbers are present?"
///     a: "If nothing numeric is found after coercion/scan, MIN falls back to 0."
///   - q: "Do errors in referenced ranges get ignored?"
///     a: "No. Any encountered range or scalar error is propagated."
/// ```
///
/// [formualizer-docgen:schema:start]
/// Name: MIN
/// Type: MinFn
/// Min args: 1
/// Max args: variadic
/// Variadic: true
/// Signature: MIN(arg1...: number@range)
/// Arg schema: arg1{kinds=number,required=true,shape=range,by_ref=false,coercion=NumberLenientText,max=None,repeating=None,default=false}
/// Caps: PURE, REDUCTION, NUMERIC_ONLY
/// [formualizer-docgen:schema:end]
impl Function for MinFn {
    fn propagate_format(
        &self,
        result: &crate::traits::CalcValue<'_>,
    ) -> Option<crate::format::FormatId> {
        result.format_id()
    }

    func_caps!(PURE, REDUCTION, NUMERIC_ONLY);
    fn name(&self) -> &'static str {
        "MIN"
    }
    fn min_args(&self) -> usize {
        1
    }
    fn variadic(&self) -> bool {
        true
    }
    fn dependency_contract(&self, arity: usize) -> Option<FunctionDependencyContract> {
        FunctionDependencyContract::static_reduction(arity, self.min_args())
    }
    fn arg_schema(&self) -> &'static [ArgSchema] {
        &ARG_RANGE_NUM_LENIENT_ONE[..]
    }
    fn eval<'a, 'b, 'c>(
        &self,
        args: &'c [ArgumentHandle<'a, 'b>],
        ctx: &dyn FunctionContext<'b>,
    ) -> Result<crate::traits::CalcValue<'b>, ExcelError> {
        let mut mv: Option<f64> = None;
        let mut mv_format = None;
        for a in args {
            let argument_format = a.value()?.format_id();
            match resolve_aggregate_argument(a, ctx)? {
                AggregateArgument::Range(view) => {
                    // Propagate errors from range first
                    for res in view.errors_slices() {
                        let (_, _, err_cols) = res?;
                        for col in err_cols {
                            if col.null_count() < col.len() {
                                for i in 0..col.len() {
                                    if !col.is_null(i) {
                                        return Ok(crate::traits::CalcValue::Scalar(
                                            LiteralValue::Error(ExcelError::new(
                                                crate::arrow_store::unmap_error_code(col.value(i)),
                                            )),
                                        ));
                                    }
                                }
                            }
                        }
                    }

                    for res in view.numbers_slices() {
                        let (_, _, num_cols) = res?;
                        for col in num_cols {
                            if let Some(n) = arrow::compute::kernels::aggregate::min(col.as_ref())
                                && mv.is_none_or(|current| n < current)
                            {
                                mv = Some(n);
                                mv_format =
                                    (view.dims() == (1, 1)).then_some(argument_format).flatten();
                            }
                        }
                    }
                }
                AggregateArgument::ReferenceError(e) => {
                    return Ok(crate::traits::CalcValue::Scalar(LiteralValue::Error(e)));
                }
                AggregateArgument::Scalar(v) => match v {
                    LiteralValue::Error(e) => {
                        return Ok(crate::traits::CalcValue::Scalar(LiteralValue::Error(e)));
                    }
                    other => {
                        if let Ok(n) = coerce_num(&other)
                            && mv.is_none_or(|current| n < current)
                        {
                            mv = Some(n);
                            mv_format = argument_format;
                        }
                    }
                },
            }
        }
        Ok(
            crate::traits::CalcValue::Scalar(super::super::utils::aggregate_result(
                mv.unwrap_or(0.0),
            ))
            .with_format(mv_format),
        )
    }
}

#[derive(Debug)]
pub struct MaxFn; // MAX(...)
/// Returns the largest numeric value from one or more arguments.
///
/// `MAX` scans scalar values and ranges, considering only values that can be treated as numbers.
///
/// # Remarks
/// - Errors in any scalar argument or range cell propagate immediately.
/// - In ranges, non-numeric cells are ignored.
/// - Scalar text is included only when it can be coerced to a number.
/// - If no numeric value is found, `MAX` returns `0`.
///
/// # Examples
///
/// ```yaml,sandbox
/// title: "Maximum in a numeric range"
/// grid:
///   A1: 5
///   A2: 9
///   A3: 1
/// formula: "=MAX(A1:A3)"
/// expected: 9
/// ```
///
/// ```yaml,sandbox
/// title: "Scalar text can be coerced"
/// formula: "=MAX(2, \"11\", 4)"
/// expected: 11
/// ```
///
/// ```yaml,sandbox
/// title: "No numeric values returns zero"
/// formula: "=MAX(\"x\")"
/// expected: 0
/// ```
///
/// ```yaml,docs
/// related:
///   - MIN
///   - LARGE
///   - SMALL
///   - MAXIFS
/// faq:
///   - q: "Why can MAX return 0 for non-numeric input sets?"
///     a: "When no numeric values are found, MAX returns 0 by design."
///   - q: "Does MAX evaluate scalar text arguments?"
///     a: "Yes, but only when scalar text can be coerced to a numeric value."
/// ```
///
/// [formualizer-docgen:schema:start]
/// Name: MAX
/// Type: MaxFn
/// Min args: 1
/// Max args: variadic
/// Variadic: true
/// Signature: MAX(arg1...: number@range)
/// Arg schema: arg1{kinds=number,required=true,shape=range,by_ref=false,coercion=NumberLenientText,max=None,repeating=None,default=false}
/// Caps: PURE, REDUCTION, NUMERIC_ONLY
/// [formualizer-docgen:schema:end]
impl Function for MaxFn {
    fn propagate_format(
        &self,
        result: &crate::traits::CalcValue<'_>,
    ) -> Option<crate::format::FormatId> {
        result.format_id()
    }

    func_caps!(PURE, REDUCTION, NUMERIC_ONLY);
    fn name(&self) -> &'static str {
        "MAX"
    }
    fn min_args(&self) -> usize {
        1
    }
    fn variadic(&self) -> bool {
        true
    }
    fn dependency_contract(&self, arity: usize) -> Option<FunctionDependencyContract> {
        FunctionDependencyContract::static_reduction(arity, self.min_args())
    }
    fn arg_schema(&self) -> &'static [ArgSchema] {
        &ARG_RANGE_NUM_LENIENT_ONE[..]
    }
    fn eval<'a, 'b, 'c>(
        &self,
        args: &'c [ArgumentHandle<'a, 'b>],
        ctx: &dyn FunctionContext<'b>,
    ) -> Result<crate::traits::CalcValue<'b>, ExcelError> {
        let mut mv: Option<f64> = None;
        let mut mv_format = None;
        for a in args {
            let argument_format = a.value()?.format_id();
            match resolve_aggregate_argument(a, ctx)? {
                AggregateArgument::Range(view) => {
                    // Propagate errors from range first
                    for res in view.errors_slices() {
                        let (_, _, err_cols) = res?;
                        for col in err_cols {
                            if col.null_count() < col.len() {
                                for i in 0..col.len() {
                                    if !col.is_null(i) {
                                        return Ok(crate::traits::CalcValue::Scalar(
                                            LiteralValue::Error(ExcelError::new(
                                                crate::arrow_store::unmap_error_code(col.value(i)),
                                            )),
                                        ));
                                    }
                                }
                            }
                        }
                    }

                    for res in view.numbers_slices() {
                        let (_, _, num_cols) = res?;
                        for col in num_cols {
                            if let Some(n) = arrow::compute::kernels::aggregate::max(col.as_ref())
                                && mv.is_none_or(|current| n > current)
                            {
                                mv = Some(n);
                                mv_format =
                                    (view.dims() == (1, 1)).then_some(argument_format).flatten();
                            }
                        }
                    }
                }
                AggregateArgument::ReferenceError(e) => {
                    return Ok(crate::traits::CalcValue::Scalar(LiteralValue::Error(e)));
                }
                AggregateArgument::Scalar(v) => match v {
                    LiteralValue::Error(e) => {
                        return Ok(crate::traits::CalcValue::Scalar(LiteralValue::Error(e)));
                    }
                    other => {
                        if let Ok(n) = coerce_num(&other)
                            && mv.is_none_or(|current| n > current)
                        {
                            mv = Some(n);
                            mv_format = argument_format;
                        }
                    }
                },
            }
        }
        Ok(
            crate::traits::CalcValue::Scalar(super::super::utils::aggregate_result(
                mv.unwrap_or(0.0),
            ))
            .with_format(mv_format),
        )
    }
}

pub fn register_builtins() {
    use std::sync::Arc;
    crate::function_registry::register_builtin(Arc::new(MinFn));
    crate::function_registry::register_builtin(Arc::new(MaxFn));
}

#[cfg(test)]
mod tests_min_max {
    use super::*;
    use crate::test_workbook::TestWorkbook;
    use crate::traits::ArgumentHandle;
    use formualizer_common::LiteralValue;
    use formualizer_parse::parser::{ASTNode, ASTNodeType};
    fn interp(wb: &TestWorkbook) -> crate::interpreter::Interpreter<'_> {
        wb.interpreter()
    }

    #[test]
    fn min_basic_array_and_scalar() {
        let wb = TestWorkbook::new().with_function(std::sync::Arc::new(MinFn));
        let ctx = interp(&wb);
        let arr = ASTNode::new(
            ASTNodeType::Literal(LiteralValue::Array(vec![vec![
                LiteralValue::Int(5),
                LiteralValue::Int(2),
                LiteralValue::Int(9),
            ]])),
            None,
        );
        let extra = ASTNode::new(ASTNodeType::Literal(LiteralValue::Int(1)), None);
        let f = ctx.context.get_function("", "MIN").unwrap();
        let out = f
            .dispatch(
                &[
                    ArgumentHandle::new(&arr, &ctx),
                    ArgumentHandle::new(&extra, &ctx),
                ],
                &ctx.function_context(None),
            )
            .unwrap()
            .into_literal();
        assert_eq!(out, LiteralValue::Number(1.0));
    }

    #[test]
    fn max_basic_with_text_ignored() {
        let wb = TestWorkbook::new().with_function(std::sync::Arc::new(MaxFn));
        let ctx = interp(&wb);
        let arr = ASTNode::new(
            ASTNodeType::Literal(LiteralValue::Array(vec![vec![
                LiteralValue::Int(5),
                LiteralValue::Text("x".into()),
                LiteralValue::Int(9),
            ]])),
            None,
        );
        let f = ctx.context.get_function("", "MAX").unwrap();
        let out = f
            .dispatch(
                &[ArgumentHandle::new(&arr, &ctx)],
                &ctx.function_context(None),
            )
            .unwrap()
            .into_literal();
        assert_eq!(out, LiteralValue::Number(9.0));
    }

    #[test]
    fn min_error_propagates() {
        let wb = TestWorkbook::new().with_function(std::sync::Arc::new(MinFn));
        let ctx = interp(&wb);
        let err = ASTNode::new(
            ASTNodeType::Literal(LiteralValue::Error(ExcelError::new_na())),
            None,
        );
        let one = ASTNode::new(ASTNodeType::Literal(LiteralValue::Int(1)), None);
        let f = ctx.context.get_function("", "MIN").unwrap();
        let out = f
            .dispatch(
                &[
                    ArgumentHandle::new(&err, &ctx),
                    ArgumentHandle::new(&one, &ctx),
                ],
                &ctx.function_context(None),
            )
            .unwrap()
            .into_literal();
        match out {
            LiteralValue::Error(e) => assert_eq!(e, "#N/A"),
            v => panic!("expected error got {v:?}"),
        }
    }

    #[test]
    fn max_error_propagates() {
        let wb = TestWorkbook::new().with_function(std::sync::Arc::new(MaxFn));
        let ctx = interp(&wb);
        let err = ASTNode::new(
            ASTNodeType::Literal(LiteralValue::Error(ExcelError::from_error_string(
                "#DIV/0!",
            ))),
            None,
        );
        let one = ASTNode::new(ASTNodeType::Literal(LiteralValue::Int(1)), None);
        let f = ctx.context.get_function("", "MAX").unwrap();
        let out = f
            .dispatch(
                &[
                    ArgumentHandle::new(&one, &ctx),
                    ArgumentHandle::new(&err, &ctx),
                ],
                &ctx.function_context(None),
            )
            .unwrap()
            .into_literal();
        match out {
            LiteralValue::Error(e) => assert_eq!(e, "#DIV/0!"),
            v => panic!("expected error got {v:?}"),
        }
    }
}