formualizer-eval 0.5.6

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
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
use super::super::utils::{ARG_NUM_LENIENT_ONE, ARG_NUM_LENIENT_TWO, coerce_num};
use crate::args::ArgSchema;
use crate::function::Function;
use crate::traits::{ArgumentHandle, CalcValue, FunctionContext};
use formualizer_common::{ExcelError, LiteralValue};
use formualizer_macros::func_caps;

#[derive(Debug)]
pub struct FactFn;
/// Returns the factorial of a non-negative integer.
///
/// `FACT` truncates fractional inputs toward zero before computing the factorial.
///
/// # Remarks
/// - Non-numeric values that cannot be coerced return `#VALUE!`.
/// - Negative inputs return `#NUM!`.
/// - Results above `170!` overflow Excel-compatible limits and return `#NUM!`.
///
/// # Examples
///
/// ```yaml,sandbox
/// title: "Basic factorial"
/// formula: "=FACT(5)"
/// expected: 120
/// ```
///
/// ```yaml,sandbox
/// title: "Fractional input is truncated"
/// formula: "=FACT(5.9)"
/// expected: 120
/// ```
///
/// ```yaml,sandbox
/// title: "Negative input returns numeric error"
/// formula: "=FACT(-1)"
/// expected: "#NUM!"
/// ```
///
/// ```yaml,docs
/// related:
///   - FACTDOUBLE
///   - GAMMALN
///   - COMBIN
/// faq:
///   - q: "Why does FACT(171) return #NUM!?"
///     a: "Excel-compatible factorial support is capped at 170!; larger values overflow and return #NUM!."
///   - q: "Does FACT round fractional inputs?"
///     a: "No. It truncates toward zero before computing the factorial."
/// ```
///
/// [formualizer-docgen:schema:start]
/// Name: FACT
/// Type: FactFn
/// Min args: 1
/// Max args: 1
/// Variadic: false
/// Signature: FACT(arg1: number@scalar)
/// Arg schema: arg1{kinds=number,required=true,shape=scalar,by_ref=false,coercion=NumberLenientText,max=None,repeating=None,default=false}
/// Caps: PURE
/// [formualizer-docgen:schema:end]
impl Function for FactFn {
    func_caps!(PURE);
    fn name(&self) -> &'static str {
        "FACT"
    }
    fn min_args(&self) -> usize {
        1
    }
    fn arg_schema(&self) -> &'static [ArgSchema] {
        &ARG_NUM_LENIENT_ONE[..]
    }
    fn eval<'a, 'b, 'c>(
        &self,
        args: &'c [ArgumentHandle<'a, 'b>],
        _: &dyn FunctionContext<'b>,
    ) -> Result<CalcValue<'b>, ExcelError> {
        let v = args[0].value()?.into_literal();
        let n = match v {
            LiteralValue::Error(e) => return Ok(CalcValue::Scalar(LiteralValue::Error(e))),
            other => coerce_num(&other)?,
        };

        // Excel truncates to integer
        let n = n.trunc() as i64;

        if n < 0 {
            return Ok(CalcValue::Scalar(
                LiteralValue::Error(ExcelError::new_num()),
            ));
        }

        // Factorial calculation (Excel supports up to 170!)
        if n > 170 {
            return Ok(CalcValue::Scalar(
                LiteralValue::Error(ExcelError::new_num()),
            ));
        }

        let mut result = 1.0_f64;
        for i in 2..=(n as u64) {
            result *= i as f64;
        }

        Ok(CalcValue::Scalar(LiteralValue::Number(result)))
    }
}

#[derive(Debug)]
pub struct GcdFn;
/// Returns the greatest common divisor of one or more integers.
///
/// `GCD` truncates each argument toward zero before calculating the divisor.
///
/// # Remarks
/// - Inputs must be between `0` and `9.99999999e9` after truncation, or `#NUM!` is returned.
/// - Negative values return `#NUM!`.
/// - Any argument error propagates immediately.
///
/// # Examples
///
/// ```yaml,sandbox
/// title: "Greatest common divisor of two numbers"
/// formula: "=GCD(24, 36)"
/// expected: 12
/// ```
///
/// ```yaml,sandbox
/// title: "Variadic and fractional arguments"
/// formula: "=GCD(18.9, 6, 30)"
/// expected: 6
/// ```
///
/// ```yaml,sandbox
/// title: "Negative values are invalid"
/// formula: "=GCD(-2, 4)"
/// expected: "#NUM!"
/// ```
///
/// ```yaml,docs
/// related:
///   - LCM
///   - MOD
///   - QUOTIENT
/// faq:
///   - q: "What happens to decimal inputs in GCD?"
///     a: "Each argument is truncated toward zero before the divisor is computed."
///   - q: "When does GCD return #NUM!?"
///     a: "Negative values or values outside the supported bound return #NUM!."
/// ```
///
/// [formualizer-docgen:schema:start]
/// Name: GCD
/// Type: GcdFn
/// Min args: 1
/// Max args: variadic
/// Variadic: true
/// Signature: GCD(arg1: number@scalar, arg2...: number@scalar)
/// Arg schema: arg1{kinds=number,required=true,shape=scalar,by_ref=false,coercion=NumberLenientText,max=None,repeating=None,default=false}; arg2{kinds=number,required=true,shape=scalar,by_ref=false,coercion=NumberLenientText,max=None,repeating=None,default=false}
/// Caps: PURE
/// [formualizer-docgen:schema:end]
impl Function for GcdFn {
    func_caps!(PURE);
    fn name(&self) -> &'static str {
        "GCD"
    }
    fn min_args(&self) -> usize {
        1
    }
    fn variadic(&self) -> bool {
        true
    }
    fn arg_schema(&self) -> &'static [ArgSchema] {
        &ARG_NUM_LENIENT_TWO[..]
    }
    fn eval<'a, 'b, 'c>(
        &self,
        args: &'c [ArgumentHandle<'a, 'b>],
        _: &dyn FunctionContext<'b>,
    ) -> Result<CalcValue<'b>, ExcelError> {
        fn gcd(a: u64, b: u64) -> u64 {
            if b == 0 { a } else { gcd(b, a % b) }
        }

        let mut result: Option<u64> = None;

        for arg in args {
            let v = arg.value()?.into_literal();
            let n = match v {
                LiteralValue::Error(e) => return Ok(CalcValue::Scalar(LiteralValue::Error(e))),
                other => coerce_num(&other)?,
            };

            // Excel truncates and requires non-negative
            let n = n.trunc();
            if !(0.0..=9.99999999e9).contains(&n) {
                return Ok(CalcValue::Scalar(
                    LiteralValue::Error(ExcelError::new_num()),
                ));
            }
            let n = n as u64;

            result = Some(match result {
                None => n,
                Some(r) => gcd(r, n),
            });
        }

        Ok(CalcValue::Scalar(LiteralValue::Number(
            result.unwrap_or(0) as f64
        )))
    }
}

#[derive(Debug)]
pub struct LcmFn;
/// Returns the least common multiple of one or more integers.
///
/// `LCM` truncates fractional arguments toward zero and combines values iteratively.
///
/// # Remarks
/// - Inputs must be non-negative and within the supported Excel-compatible range.
/// - If any input is `0`, the resulting least common multiple is `0`.
/// - Any argument error propagates immediately.
///
/// # Examples
///
/// ```yaml,sandbox
/// title: "Least common multiple for two integers"
/// formula: "=LCM(4, 6)"
/// expected: 12
/// ```
///
/// ```yaml,sandbox
/// title: "Fractional values are truncated"
/// formula: "=LCM(6.8, 8.2)"
/// expected: 24
/// ```
///
/// ```yaml,sandbox
/// title: "Negative values return numeric error"
/// formula: "=LCM(-3, 6)"
/// expected: "#NUM!"
/// ```
///
/// ```yaml,docs
/// related:
///   - GCD
///   - MOD
///   - MROUND
/// faq:
///   - q: "Why does LCM return 0 when one argument is 0?"
///     a: "LCM is defined as 0 if any truncated input is 0 in this implementation."
///   - q: "Are fractional inputs accepted?"
///     a: "Yes, but they are truncated toward zero before the LCM calculation."
/// ```
///
/// [formualizer-docgen:schema:start]
/// Name: LCM
/// Type: LcmFn
/// Min args: 1
/// Max args: variadic
/// Variadic: true
/// Signature: LCM(arg1: number@scalar, arg2...: number@scalar)
/// Arg schema: arg1{kinds=number,required=true,shape=scalar,by_ref=false,coercion=NumberLenientText,max=None,repeating=None,default=false}; arg2{kinds=number,required=true,shape=scalar,by_ref=false,coercion=NumberLenientText,max=None,repeating=None,default=false}
/// Caps: PURE
/// [formualizer-docgen:schema:end]
impl Function for LcmFn {
    func_caps!(PURE);
    fn name(&self) -> &'static str {
        "LCM"
    }
    fn min_args(&self) -> usize {
        1
    }
    fn variadic(&self) -> bool {
        true
    }
    fn arg_schema(&self) -> &'static [ArgSchema] {
        &ARG_NUM_LENIENT_TWO[..]
    }
    fn eval<'a, 'b, 'c>(
        &self,
        args: &'c [ArgumentHandle<'a, 'b>],
        _: &dyn FunctionContext<'b>,
    ) -> Result<CalcValue<'b>, ExcelError> {
        fn gcd(a: u64, b: u64) -> u64 {
            if b == 0 { a } else { gcd(b, a % b) }
        }
        fn lcm(a: u64, b: u64) -> u64 {
            if a == 0 || b == 0 {
                0
            } else {
                (a / gcd(a, b)) * b
            }
        }

        let mut result: Option<u64> = None;

        for arg in args {
            let v = arg.value()?.into_literal();
            let n = match v {
                LiteralValue::Error(e) => return Ok(CalcValue::Scalar(LiteralValue::Error(e))),
                other => coerce_num(&other)?,
            };

            let n = n.trunc();
            if !(0.0..=9.99999999e9).contains(&n) {
                return Ok(CalcValue::Scalar(
                    LiteralValue::Error(ExcelError::new_num()),
                ));
            }
            let n = n as u64;

            result = Some(match result {
                None => n,
                Some(r) => lcm(r, n),
            });
        }

        Ok(CalcValue::Scalar(LiteralValue::Number(
            result.unwrap_or(0) as f64
        )))
    }
}

#[derive(Debug)]
pub struct CombinFn;
/// Returns the number of combinations for selecting `k` items from `n`.
///
/// `COMBIN` evaluates `n` choose `k` using truncated integer inputs.
///
/// # Remarks
/// - Fractional inputs are truncated toward zero before evaluation.
/// - If `n < 0`, `k < 0`, or `k > n`, the function returns `#NUM!`.
/// - Argument errors propagate directly.
///
/// # Examples
///
/// ```yaml,sandbox
/// title: "Basic combinations"
/// formula: "=COMBIN(5, 2)"
/// expected: 10
/// ```
///
/// ```yaml,sandbox
/// title: "Fractional arguments are truncated"
/// formula: "=COMBIN(6.9, 3.2)"
/// expected: 20
/// ```
///
/// ```yaml,sandbox
/// title: "Invalid k returns numeric error"
/// formula: "=COMBIN(3, 5)"
/// expected: "#NUM!"
/// ```
///
/// ```yaml,docs
/// related:
///   - COMBINA
///   - PERMUT
///   - FACT
/// faq:
///   - q: "When does COMBIN return #NUM!?"
///     a: "It returns #NUM! if n or k is negative, or if k is greater than n after truncation."
///   - q: "Can COMBIN take non-integer values?"
///     a: "Yes, but both inputs are truncated toward zero before evaluation."
/// ```
///
/// [formualizer-docgen:schema:start]
/// Name: COMBIN
/// Type: CombinFn
/// Min args: 2
/// Max args: 2
/// Variadic: false
/// Signature: COMBIN(arg1: number@scalar, arg2: number@scalar)
/// Arg schema: arg1{kinds=number,required=true,shape=scalar,by_ref=false,coercion=NumberLenientText,max=None,repeating=None,default=false}; arg2{kinds=number,required=true,shape=scalar,by_ref=false,coercion=NumberLenientText,max=None,repeating=None,default=false}
/// Caps: PURE
/// [formualizer-docgen:schema:end]
impl Function for CombinFn {
    func_caps!(PURE);
    fn name(&self) -> &'static str {
        "COMBIN"
    }
    fn min_args(&self) -> usize {
        2
    }
    fn arg_schema(&self) -> &'static [ArgSchema] {
        &ARG_NUM_LENIENT_TWO[..]
    }
    fn eval<'a, 'b, 'c>(
        &self,
        args: &'c [ArgumentHandle<'a, 'b>],
        _: &dyn FunctionContext<'b>,
    ) -> Result<CalcValue<'b>, ExcelError> {
        // Check minimum required arguments
        if args.len() < 2 {
            return Ok(CalcValue::Scalar(LiteralValue::Error(
                ExcelError::new_value(),
            )));
        }

        let n_val = args[0].value()?.into_literal();
        let k_val = args[1].value()?.into_literal();

        let n = match n_val {
            LiteralValue::Error(e) => return Ok(CalcValue::Scalar(LiteralValue::Error(e))),
            other => coerce_num(&other)?,
        };
        let k = match k_val {
            LiteralValue::Error(e) => return Ok(CalcValue::Scalar(LiteralValue::Error(e))),
            other => coerce_num(&other)?,
        };

        let n = n.trunc() as i64;
        let k = k.trunc() as i64;

        if n < 0 || k < 0 || k > n {
            return Ok(CalcValue::Scalar(
                LiteralValue::Error(ExcelError::new_num()),
            ));
        }

        // Calculate C(n, k) = n! / (k! * (n-k)!)
        // Use the more efficient formula: C(n, k) = product of (n-i)/(i+1) for i in 0..k
        let k = k.min(n - k) as u64; // Use symmetry for efficiency
        let n = n as u64;

        let mut result = 1.0_f64;
        for i in 0..k {
            result = result * (n - i) as f64 / (i + 1) as f64;
        }

        Ok(CalcValue::Scalar(LiteralValue::Number(result.round())))
    }
}

#[derive(Debug)]
pub struct PermutFn;
/// Returns the number of permutations for selecting and ordering `k` items from `n`.
///
/// `PERMUT` computes `n!/(n-k)!` after truncating both inputs toward zero.
///
/// # Remarks
/// - Fractional inputs are truncated to integers.
/// - If `n < 0`, `k < 0`, or `k > n`, the function returns `#NUM!`.
/// - Argument errors propagate directly.
///
/// # Examples
///
/// ```yaml,sandbox
/// title: "Basic permutations"
/// formula: "=PERMUT(5, 2)"
/// expected: 20
/// ```
///
/// ```yaml,sandbox
/// title: "Fractional arguments are truncated"
/// formula: "=PERMUT(7.9, 3.1)"
/// expected: 210
/// ```
///
/// ```yaml,sandbox
/// title: "Out-of-range k returns numeric error"
/// formula: "=PERMUT(4, 6)"
/// expected: "#NUM!"
/// ```
///
/// ```yaml,docs
/// related:
///   - COMBIN
///   - FACT
///   - MULTINOMIAL
/// faq:
///   - q: "Why does PERMUT fail when k is larger than n?"
///     a: "Permutations require choosing at most n items, so k > n returns #NUM!."
///   - q: "How are decimal inputs handled?"
///     a: "PERMUT truncates n and k toward zero before computing n!/(n-k)!."
/// ```
///
/// [formualizer-docgen:schema:start]
/// Name: PERMUT
/// Type: PermutFn
/// Min args: 2
/// Max args: 2
/// Variadic: false
/// Signature: PERMUT(arg1: number@scalar, arg2: number@scalar)
/// Arg schema: arg1{kinds=number,required=true,shape=scalar,by_ref=false,coercion=NumberLenientText,max=None,repeating=None,default=false}; arg2{kinds=number,required=true,shape=scalar,by_ref=false,coercion=NumberLenientText,max=None,repeating=None,default=false}
/// Caps: PURE
/// [formualizer-docgen:schema:end]
impl Function for PermutFn {
    func_caps!(PURE);
    fn name(&self) -> &'static str {
        "PERMUT"
    }
    fn min_args(&self) -> usize {
        2
    }
    fn arg_schema(&self) -> &'static [ArgSchema] {
        &ARG_NUM_LENIENT_TWO[..]
    }
    fn eval<'a, 'b, 'c>(
        &self,
        args: &'c [ArgumentHandle<'a, 'b>],
        _: &dyn FunctionContext<'b>,
    ) -> Result<CalcValue<'b>, ExcelError> {
        // Check minimum required arguments
        if args.len() < 2 {
            return Ok(CalcValue::Scalar(LiteralValue::Error(
                ExcelError::new_value(),
            )));
        }

        let n_val = args[0].value()?.into_literal();
        let k_val = args[1].value()?.into_literal();

        let n = match n_val {
            LiteralValue::Error(e) => return Ok(CalcValue::Scalar(LiteralValue::Error(e))),
            other => coerce_num(&other)?,
        };
        let k = match k_val {
            LiteralValue::Error(e) => return Ok(CalcValue::Scalar(LiteralValue::Error(e))),
            other => coerce_num(&other)?,
        };

        let n = n.trunc() as i64;
        let k = k.trunc() as i64;

        if n < 0 || k < 0 || k > n {
            return Ok(CalcValue::Scalar(
                LiteralValue::Error(ExcelError::new_num()),
            ));
        }

        // P(n, k) = n! / (n-k)! = n * (n-1) * ... * (n-k+1)
        let mut result = 1.0_f64;
        for i in 0..k {
            result *= (n - i) as f64;
        }

        Ok(CalcValue::Scalar(LiteralValue::Number(result)))
    }
}

#[derive(Debug)]
pub struct FactDoubleFn;
/// Returns the double factorial of a number.
///
/// # Examples
///
/// ```excel
/// =FACTDOUBLE(7)
/// ```
///
/// ```yaml,sandbox
/// title: "Odd double factorial"
/// formula: '=FACTDOUBLE(7)'
/// expected: 105
/// ```
///
/// ```yaml,docs
/// related:
///   - FACT
///   - COMBIN
/// faq:
///   - q: "What does FACTDOUBLE do with 0 or -1?"
///     a: "It returns 1, matching spreadsheet double-factorial conventions."
/// ```
///
/// [formualizer-docgen:schema:start]
/// Name: FACTDOUBLE
/// Type: FactDoubleFn
/// Min args: 1
/// Max args: 1
/// Variadic: false
/// Signature: FACTDOUBLE(arg1: number@scalar)
/// Arg schema: arg1{kinds=number,required=true,shape=scalar,by_ref=false,coercion=NumberLenientText,max=None,repeating=None,default=false}
/// Caps: PURE
/// [formualizer-docgen:schema:end]
impl Function for FactDoubleFn {
    func_caps!(PURE);
    fn name(&self) -> &'static str {
        "FACTDOUBLE"
    }
    fn min_args(&self) -> usize {
        1
    }
    fn arg_schema(&self) -> &'static [ArgSchema] {
        &ARG_NUM_LENIENT_ONE[..]
    }
    fn eval<'a, 'b, 'c>(
        &self,
        args: &'c [ArgumentHandle<'a, 'b>],
        _: &dyn FunctionContext<'b>,
    ) -> Result<CalcValue<'b>, ExcelError> {
        let v = args[0].value()?.into_literal();
        let n = match v {
            LiteralValue::Error(e) => return Ok(CalcValue::Scalar(LiteralValue::Error(e))),
            other => coerce_num(&other)?,
        };
        let n = n.trunc() as i64;
        if n < -1 {
            return Ok(CalcValue::Scalar(
                LiteralValue::Error(ExcelError::new_num()),
            ));
        }
        if n <= 0 {
            return Ok(CalcValue::Scalar(LiteralValue::Number(1.0)));
        }
        let mut result = 1.0_f64;
        let mut i = n;
        while i > 0 {
            result *= i as f64;
            i -= 2;
        }
        Ok(CalcValue::Scalar(LiteralValue::Number(result)))
    }
}

#[derive(Debug)]
pub struct CombinaFn;
/// Returns the number of combinations with repetition.
///
/// # Examples
///
/// ```excel
/// =COMBINA(4,2)
/// ```
///
/// ```yaml,sandbox
/// title: "Choose with repetition"
/// formula: '=COMBINA(4,3)'
/// expected: 20
/// ```
///
/// ```yaml,docs
/// related:
///   - COMBIN
/// faq:
///   - q: "How is COMBINA different from COMBIN?"
///     a: "COMBINA counts selections where the same item can be chosen more than once."
/// ```
///
/// [formualizer-docgen:schema:start]
/// Name: COMBINA
/// Type: CombinaFn
/// Min args: 2
/// Max args: 2
/// Variadic: false
/// Signature: COMBINA(arg1: number@scalar, arg2: number@scalar)
/// Arg schema: arg1{kinds=number,required=true,shape=scalar,by_ref=false,coercion=NumberLenientText,max=None,repeating=None,default=false}; arg2{kinds=number,required=true,shape=scalar,by_ref=false,coercion=NumberLenientText,max=None,repeating=None,default=false}
/// Caps: PURE
/// [formualizer-docgen:schema:end]
impl Function for CombinaFn {
    func_caps!(PURE);
    fn name(&self) -> &'static str {
        "COMBINA"
    }
    fn min_args(&self) -> usize {
        2
    }
    fn arg_schema(&self) -> &'static [ArgSchema] {
        &ARG_NUM_LENIENT_TWO[..]
    }
    fn eval<'a, 'b, 'c>(
        &self,
        args: &'c [ArgumentHandle<'a, 'b>],
        _: &dyn FunctionContext<'b>,
    ) -> Result<CalcValue<'b>, ExcelError> {
        if args.len() < 2 {
            return Ok(CalcValue::Scalar(LiteralValue::Error(
                ExcelError::new_value(),
            )));
        }
        let n_val = args[0].value()?.into_literal();
        let k_val = args[1].value()?.into_literal();
        let n = match n_val {
            LiteralValue::Error(e) => return Ok(CalcValue::Scalar(LiteralValue::Error(e))),
            other => coerce_num(&other)?,
        };
        let k = match k_val {
            LiteralValue::Error(e) => return Ok(CalcValue::Scalar(LiteralValue::Error(e))),
            other => coerce_num(&other)?,
        };
        let n = n.trunc() as i64;
        let k = k.trunc() as i64;
        if n < 0 || k < 0 {
            return Ok(CalcValue::Scalar(
                LiteralValue::Error(ExcelError::new_num()),
            ));
        }
        if k == 0 {
            return Ok(CalcValue::Scalar(LiteralValue::Number(1.0)));
        }
        // COMBINA(n,k) = C(n+k-1, k)
        let nn = n + k - 1;
        let kk = k.min(nn - k) as u64;
        let nn = nn as u64;
        let mut result = 1.0_f64;
        for i in 0..kk {
            result = result * (nn - i) as f64 / (i + 1) as f64;
        }
        Ok(CalcValue::Scalar(LiteralValue::Number(result.round())))
    }
}

pub fn register_builtins() {
    use std::sync::Arc;
    crate::function_registry::register_function(Arc::new(FactFn));
    crate::function_registry::register_function(Arc::new(FactDoubleFn));
    crate::function_registry::register_function(Arc::new(GcdFn));
    crate::function_registry::register_function(Arc::new(LcmFn));
    crate::function_registry::register_function(Arc::new(CombinFn));
    crate::function_registry::register_function(Arc::new(CombinaFn));
    crate::function_registry::register_function(Arc::new(PermutFn));
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::test_workbook::TestWorkbook;
    use crate::traits::ArgumentHandle;
    use formualizer_parse::parser::{ASTNode, ASTNodeType};

    fn interp(wb: &TestWorkbook) -> crate::interpreter::Interpreter<'_> {
        wb.interpreter()
    }
    fn lit(v: LiteralValue) -> ASTNode {
        ASTNode::new(ASTNodeType::Literal(v), None)
    }

    #[test]
    fn fact_basic() {
        let wb = TestWorkbook::new().with_function(std::sync::Arc::new(FactFn));
        let ctx = interp(&wb);
        let n = lit(LiteralValue::Number(5.0));
        let f = ctx.context.get_function("", "FACT").unwrap();
        assert_eq!(
            f.dispatch(
                &[ArgumentHandle::new(&n, &ctx)],
                &ctx.function_context(None)
            )
            .unwrap()
            .into_literal(),
            LiteralValue::Number(120.0)
        );
    }

    #[test]
    fn fact_zero() {
        let wb = TestWorkbook::new().with_function(std::sync::Arc::new(FactFn));
        let ctx = interp(&wb);
        let n = lit(LiteralValue::Number(0.0));
        let f = ctx.context.get_function("", "FACT").unwrap();
        assert_eq!(
            f.dispatch(
                &[ArgumentHandle::new(&n, &ctx)],
                &ctx.function_context(None)
            )
            .unwrap()
            .into_literal(),
            LiteralValue::Number(1.0)
        );
    }

    #[test]
    fn gcd_basic() {
        let wb = TestWorkbook::new().with_function(std::sync::Arc::new(GcdFn));
        let ctx = interp(&wb);
        let a = lit(LiteralValue::Number(12.0));
        let b = lit(LiteralValue::Number(18.0));
        let f = ctx.context.get_function("", "GCD").unwrap();
        assert_eq!(
            f.dispatch(
                &[ArgumentHandle::new(&a, &ctx), ArgumentHandle::new(&b, &ctx)],
                &ctx.function_context(None)
            )
            .unwrap()
            .into_literal(),
            LiteralValue::Number(6.0)
        );
    }

    #[test]
    fn lcm_basic() {
        let wb = TestWorkbook::new().with_function(std::sync::Arc::new(LcmFn));
        let ctx = interp(&wb);
        let a = lit(LiteralValue::Number(4.0));
        let b = lit(LiteralValue::Number(6.0));
        let f = ctx.context.get_function("", "LCM").unwrap();
        assert_eq!(
            f.dispatch(
                &[ArgumentHandle::new(&a, &ctx), ArgumentHandle::new(&b, &ctx)],
                &ctx.function_context(None)
            )
            .unwrap()
            .into_literal(),
            LiteralValue::Number(12.0)
        );
    }

    #[test]
    fn combin_basic() {
        let wb = TestWorkbook::new().with_function(std::sync::Arc::new(CombinFn));
        let ctx = interp(&wb);
        let n = lit(LiteralValue::Number(5.0));
        let k = lit(LiteralValue::Number(2.0));
        let f = ctx.context.get_function("", "COMBIN").unwrap();
        assert_eq!(
            f.dispatch(
                &[ArgumentHandle::new(&n, &ctx), ArgumentHandle::new(&k, &ctx)],
                &ctx.function_context(None)
            )
            .unwrap()
            .into_literal(),
            LiteralValue::Number(10.0)
        );
    }

    #[test]
    fn permut_basic() {
        let wb = TestWorkbook::new().with_function(std::sync::Arc::new(PermutFn));
        let ctx = interp(&wb);
        let n = lit(LiteralValue::Number(5.0));
        let k = lit(LiteralValue::Number(2.0));
        let f = ctx.context.get_function("", "PERMUT").unwrap();
        assert_eq!(
            f.dispatch(
                &[ArgumentHandle::new(&n, &ctx), ArgumentHandle::new(&k, &ctx)],
                &ctx.function_context(None)
            )
            .unwrap()
            .into_literal(),
            LiteralValue::Number(20.0)
        );
    }
}