ferroxl 0.2.0

ferroxl: read and write Excel 2007 xlsx/xlsm files with an openpyxl-compatible API
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
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
//! Evaluating formulas, so a saved workbook carries values rather than blanks.
//!
//! # Why this is careful
//!
//! A wrong cached value is worse than a missing one. A missing `<v>` is visible -- a reader
//! knows it has to recalculate. A wrong one is silently believed, and the mistake surfaces days
//! later in a report nobody traces back to this library. So three rules hold throughout:
//!
//! - **Nothing is invented.** A formula this module cannot evaluate gets no `<v>` written at
//!   all, and is named in [`Recalculation::unresolved`] with the reason.
//! - **The caller can check first.** [`Recalculation`] is returned rather than side effects
//!   only, and [`supports`] answers "will you handle this?" without running anything.
//! - **Excel recomputes on open.** `recalculate` sets `calcPr/@fullCalcOnLoad`, so these values
//!   are a convenience for readers that are not Excel. A value this module gets wrong cannot
//!   survive being opened and saved by a human.
//!
//! # What is deliberately absent
//!
//! The functions that are hard to get right are missing rather than approximated:
//! `VLOOKUP`'s approximate match against unsorted data, `INDEX` returning a reference rather
//! than a value, `TEXT`'s format codes, date arithmetic across the 1900 leap-year bug, and
//! `SUMIF`'s wildcards. Each is a day of edge cases and a place to be subtly wrong, so a
//! formula using one is reported unresolved instead of being given a plausible number.

use crate::cell::cell::CellValue;
use std::collections::BTreeMap;

/// Every function this module can evaluate.
///
/// Kept in step with the dispatch table in `call_function`, and asserted against it by a test,
/// because a function that is listed but unimplemented would answer `supports` with a `yes` and
/// then produce nothing.
pub const SUPPORTED_FUNCTIONS: &[&str] = &[
    "ABS",
    "AND",
    "AVERAGE",
    "CHOOSE",
    "CONCAT",
    "CONCATENATE",
    "COUNT",
    "COUNTA",
    "COUNTIF",
    "COUNTIFS",
    "FALSE",
    "IF",
    "IFERROR",
    "INDEX",
    "INT",
    "ISBLANK",
    "ISERROR",
    "ISNUMBER",
    "ISTEXT",
    "LEFT",
    "LEN",
    "LOWER",
    "MATCH",
    "MAX",
    "MIN",
    "MOD",
    "NOT",
    "OR",
    "POWER",
    "PRODUCT",
    "RIGHT",
    "ROUND",
    "ROUNDDOWN",
    "ROUNDUP",
    "SIGN",
    "SQRT",
    "SUM",
    "SUMIF",
    "SUMIFS",
    "TRIM",
    "TRUE",
    "UPPER",
    "VLOOKUP",
    "XLOOKUP",
];

/// Whether this module can evaluate a formula naming `name`.
///
/// The check is on the name alone, so it cannot tell you a formula is safe -- only that no part
/// of it is unrecognised. A formula can still come back unresolved for a reference this module
/// could not read.
///
/// ```
/// assert!(ferroxl::formula::supports("SUM"));
/// assert!(!ferroxl::formula::supports("WEBSERVICE"));
/// ```
pub fn supports(name: &str) -> bool {
    let wanted = name.trim().to_uppercase();
    SUPPORTED_FUNCTIONS.contains(&wanted.as_str())
}

/// A formula that could not be evaluated, and why.
///
/// The reason is part of the contract: "unsupported function" and "circular reference" call for
/// different responses from the caller, and collapsing them into a failure count would throw
/// that away.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Unresolved {
    /// The cell holding the formula.
    pub sheet: String,
    /// Its coordinate.
    pub coordinate: String,
    /// The formula as written.
    pub formula: String,
    /// Why no value could be produced.
    pub reason: String,
}

/// What a recalculation produced.
#[derive(Debug, Clone, Default)]
pub struct Recalculation {
    /// Values written, keyed by sheet title then coordinate.
    ///
    /// Only cells that evaluated successfully appear, so the length of this map is the number of
    /// cached values in the saved file.
    pub computed: BTreeMap<String, BTreeMap<String, CellValue>>,
    /// Formulas left without a value, with the reason for each.
    pub unresolved: Vec<Unresolved>,
}

impl Recalculation {
    /// How many cells got a value.
    pub fn computed_count(&self) -> usize {
        self.computed.values().map(BTreeMap::len).sum()
    }

    /// Whether every formula in the workbook was evaluated.
    pub fn is_complete(&self) -> bool {
        self.unresolved.is_empty()
    }

    /// The reasons the evaluation stopped, deduplicated with a count for each.
    ///
    /// The useful summary when a workbook has four hundred formulas and one function is
    /// missing: four hundred messages saying the same thing is noise.
    pub fn reasons(&self) -> Vec<(String, usize)> {
        let mut counts: BTreeMap<&str, usize> = BTreeMap::new();
        for entry in &self.unresolved {
            *counts.entry(entry.reason.as_str()).or_default() += 1;
        }
        counts
            .into_iter()
            .map(|(reason, count)| (reason.to_string(), count))
            .collect()
    }
}

/// How a reference resolved.
enum Resolved {
    /// A single cell's value.
    Single(CellValue),
    /// A range's values, in reading order with its 2D dimensions.
    Range {
        values: Vec<CellValue>,
        cols: usize,
        rows: usize,
    },
}

/// Reads cells for the evaluator.
pub trait ValueSource {
    /// The value of one cell, or blank if it is empty or absent.
    fn cell(&self, sheet: &str, coordinate: &str) -> CellValue;

    /// The maximum row index on this sheet, used to clip whole-column references.
    fn max_row(&self, _sheet: &str) -> Option<u32> {
        None
    }
}

/// Evaluates `formula` as it would be evaluated in `sheet`.
///
/// `Ok(Some(_))` is a computed value. `Err` carries the reason nothing could be produced --
/// a malformed formula, an unrecognised function, an unreadable range -- and never a guess.
/// There is deliberately no `Ok(None)`: "no value" and "here is the value" should not be
/// adjacent options to mix up.
pub fn evaluate(
    formula: &str,
    sheet: &str,
    source: &dyn ValueSource,
) -> std::result::Result<CellValue, String> {
    let expression = formula.trim().trim_start_matches('=');
    let tokens = tokenize(expression).map_err(|reason| format!("cannot parse: {reason}"))?;
    let mut parser = Parser {
        tokens,
        position: 0,
    };
    let node = parser
        .parse_expression()
        .ok_or_else(|| "cannot parse: unexpected end of formula".to_string())?;
    if !parser.at_end() {
        return Err("cannot parse: trailing text after the formula".to_string());
    }
    eval(&node, sheet, source)
}

// ---------------------------------------------------------------------------------------
// Tokens
// ---------------------------------------------------------------------------------------

#[derive(Debug, Clone, PartialEq)]
enum Token {
    Number(f64),
    Text(String),
    /// `TRUE`, `FALSE`, or `#DIV/0!` and the rest.
    Word(String),
    /// A bare name that is not a literal: a function name or a reference.
    Name(String),
    Operator(String),
    OpenParen,
    CloseParen,
    Comma,
    Colon,
    Bang,
}

fn tokenize(input: &str) -> std::result::Result<Vec<Token>, String> {
    let chars: Vec<char> = input.chars().collect();
    let mut tokens = Vec::new();
    let mut at = 0usize;

    while at < chars.len() {
        let ch = chars[at];
        match ch {
            ' ' | '\t' | '\n' | '\r' => at += 1,
            '(' => {
                tokens.push(Token::OpenParen);
                at += 1;
            }
            ')' => {
                tokens.push(Token::CloseParen);
                at += 1;
            }
            ',' | ';' => {
                // Excel accepts either as an argument separator depending on locale.
                tokens.push(Token::Comma);
                at += 1;
            }
            ':' => {
                tokens.push(Token::Colon);
                at += 1;
            }
            '!' => {
                tokens.push(Token::Bang);
                at += 1;
            }
            '+' | '-' | '*' | '/' | '^' | '&' | '=' | '<' | '>' | '%' => {
                let start = at;
                at += 1;
                // `<>` and `<=` are one operator; `>=` likewise. `==` is *not* -- it is two
                // comparisons, so the second `=` is left for the next pass.
                let is_pair = match ch {
                    '<' | '>' => matches!(chars.get(at), Some('>') | Some('=')),
                    _ => false,
                };
                if is_pair {
                    at += 1;
                }
                tokens.push(Token::Operator(chars[start..at].iter().collect()));
            }
            '"' => {
                let mut text = String::new();
                at += 1;
                loop {
                    match chars.get(at) {
                        None => return Err("unterminated text".to_string()),
                        Some('"') => {
                            // A doubled quote is one literal quote, which is how Excel escapes it.
                            if chars.get(at + 1) == Some(&'"') {
                                text.push('"');
                                at += 2;
                            } else {
                                at += 1;
                                break;
                            }
                        }
                        Some(other) => {
                            text.push(*other);
                            at += 1;
                        }
                    }
                }
                tokens.push(Token::Text(text));
            }
            '\'' => {
                let mut sheet_name = String::new();
                at += 1;
                loop {
                    match chars.get(at) {
                        None => return Err("unterminated sheet name in formula".to_string()),
                        Some('\'') => {
                            if chars.get(at + 1) == Some(&'\'') {
                                sheet_name.push('\'');
                                at += 2;
                            } else {
                                at += 1;
                                break;
                            }
                        }
                        Some(other) => {
                            sheet_name.push(*other);
                            at += 1;
                        }
                    }
                }
                tokens.push(Token::Name(sheet_name));
            }
            '#' => {
                let start = at;
                while at < chars.len() && (chars[at].is_ascii_alphanumeric() || chars[at] == '!') {
                    at += 1;
                }
                let word: String = chars[start..at].iter().collect();
                if ERROR_CODES.contains(&word.to_uppercase().as_str()) {
                    tokens.push(Token::Word(word));
                } else {
                    return Err(format!("unknown error literal {word:?}"));
                }
            }
            _ if ch.is_ascii_digit()
                || (ch == '.' && chars.get(at + 1).is_some_and(|c| c.is_ascii_digit())) =>
            {
                let start = at;
                while at < chars.len() && (chars[at].is_ascii_digit() || chars[at] == '.') {
                    at += 1;
                }
                // Scientific notation, which Excel writes for very large and small numbers.
                if matches!(chars.get(at), Some('E') | Some('e')) {
                    let mut ahead = at + 1;
                    if matches!(chars.get(ahead), Some('+') | Some('-')) {
                        ahead += 1;
                    }
                    if chars.get(ahead).is_some_and(char::is_ascii_digit) {
                        at = ahead;
                        while at < chars.len() && chars[at].is_ascii_digit() {
                            at += 1;
                        }
                    }
                }
                let text: String = chars[start..at].iter().collect();
                let value = text
                    .parse::<f64>()
                    .map_err(|_| format!("cannot read the number {text:?}"))?;
                tokens.push(Token::Number(value));
            }
            _ if is_name_start(ch) => {
                let start = at;
                while at < chars.len() && is_name_part(chars[at]) {
                    at += 1;
                }
                let word: String = chars[start..at].iter().collect();
                // A `$` may lead or trail a reference, so it has to be consumed here rather
                // than being rejected as an unknown character.
                while at < chars.len() && chars[at] == '$' {
                    at += 1;
                }
                let upper = word.to_uppercase();
                if matches!(upper.as_str(), "TRUE" | "FALSE") {
                    tokens.push(Token::Word(upper));
                } else if crate::styles::named_style::builtin(&word).is_some()
                    && !looks_like_reference(&word)
                {
                    // `Good`, `Bad`, `Title` and the rest: a name, not a reference. They are not
                    // values, so evaluation reports them rather than resolving them to a style.
                    tokens.push(Token::Name(word));
                } else {
                    tokens.push(Token::Name(word));
                }
            }
            _ => return Err(format!("unexpected character {ch:?}")),
        }
    }
    Ok(tokens)
}

/// The seven values Excel treats as errors, so the tokenizer can read `#DIV/0!` as one.
const ERROR_CODES: [&str; 7] = [
    "#NULL!", "#DIV/0!", "#VALUE!", "#REF!", "#NAME?", "#NUM!", "#N/A",
];

fn is_name_start(ch: char) -> bool {
    ch.is_alphabetic() || ch == '_' || ch == '\\' || ch == '$'
}

fn is_name_part(ch: char) -> bool {
    ch.is_alphanumeric() || ch == '_' || ch == '.' || ch == '\\' || ch == '$'
}

/// Whether `word` is a bare column reference like `A` or `XFD`.
fn looks_like_column_reference(word: &str) -> bool {
    let letters: String = word.chars().filter(|c| *c != '$').collect();
    if letters.is_empty() || letters.len() > 3 {
        return false;
    }
    letters.chars().all(|c| c.is_ascii_alphabetic())
}

/// Whether `word` reads as `A1` rather than as a name.
///
/// `$` is stripped first so `$A$1` is a reference, and the digit test rejects `Good` while
/// accepting `XFD1048576`.
fn looks_like_reference(word: &str) -> bool {
    let letters: String = word.chars().filter(|c| *c != '$').collect();
    let mut chars = letters.chars();
    let Some(first) = chars.next() else {
        return false;
    };
    if !first.is_ascii_alphabetic() {
        return false;
    }
    if chars.clone().all(|c| c.is_ascii_alphabetic()) {
        return false;
    }
    chars.all(|c| c.is_ascii_alphanumeric())
}

// ---------------------------------------------------------------------------------------
// Syntax tree
// ---------------------------------------------------------------------------------------

#[derive(Debug, Clone, PartialEq)]
enum Node {
    Literal(CellValue),
    /// A cell or range reference, already split into an optional sheet and a body.
    Reference(Option<String>, String),
    Function(String, Vec<Node>),
    Unary(String, Box<Node>),
    Binary(String, Box<Node>, Box<Node>),
}

struct Parser {
    tokens: Vec<Token>,
    position: usize,
}

impl Parser {
    fn at_end(&self) -> bool {
        self.position >= self.tokens.len()
    }

    fn peek(&self) -> Option<&Token> {
        self.tokens.get(self.position)
    }

    fn take(&mut self) -> Option<Token> {
        let token = self.tokens.get(self.position).cloned();
        if token.is_some() {
            self.position += 1;
        }
        token
    }

    fn eat_operator(&mut self, wanted: &str) -> bool {
        if matches!(self.peek(), Some(Token::Operator(o)) if o == wanted) {
            self.position += 1;
            true
        } else {
            false
        }
    }

    /// Comparison, the loosest binding.
    fn parse_expression(&mut self) -> Option<Node> {
        let mut left = self.parse_concat()?;
        loop {
            let operator = match self.peek() {
                Some(Token::Operator(o))
                    if matches!(o.as_str(), "=" | "<>" | "<" | "<=" | ">" | ">=") =>
                {
                    o.clone()
                }
                _ => return Some(left),
            };
            self.position += 1;
            let right = self.parse_concat()?;
            left = Node::Binary(operator, Box::new(left), Box::new(right));
        }
    }

    fn parse_concat(&mut self) -> Option<Node> {
        let mut left = self.parse_additive()?;
        while self.eat_operator("&") {
            let right = self.parse_additive()?;
            left = Node::Binary("&".to_string(), Box::new(left), Box::new(right));
        }
        Some(left)
    }

    fn parse_additive(&mut self) -> Option<Node> {
        let mut left = self.parse_multiplicative()?;
        loop {
            let operator = match self.peek() {
                Some(Token::Operator(o)) if o == "+" || o == "-" => o.clone(),
                _ => return Some(left),
            };
            self.position += 1;
            let right = self.parse_multiplicative()?;
            left = Node::Binary(operator, Box::new(left), Box::new(right));
        }
    }

    fn parse_multiplicative(&mut self) -> Option<Node> {
        let mut left = self.parse_exponent()?;
        loop {
            let operator = match self.peek() {
                Some(Token::Operator(o)) if o == "*" || o == "/" => o.clone(),
                _ => return Some(left),
            };
            self.position += 1;
            let right = self.parse_exponent()?;
            left = Node::Binary(operator, Box::new(left), Box::new(right));
        }
    }

    fn parse_exponent(&mut self) -> Option<Node> {
        let mut left = self.parse_unary()?;
        // Left-associative, as Excel has it: `2^3^2` is 64, not 512.
        while self.eat_operator("^") {
            let right = self.parse_unary()?;
            left = Node::Binary("^".to_string(), Box::new(left), Box::new(right));
        }
        Some(left)
    }

    /// Unary minus binds *tighter* than `^` in Excel, which is why `-2^2` is 4 and not -4.
    fn parse_unary(&mut self) -> Option<Node> {
        if self.eat_operator("-") {
            let inner = self.parse_unary()?;
            return Some(Node::Unary("-".to_string(), Box::new(inner)));
        }
        if self.eat_operator("+") {
            return self.parse_unary();
        }
        self.parse_postfix()
    }

    fn parse_postfix(&mut self) -> Option<Node> {
        let mut node = self.parse_primary()?;
        // The percent sign is a postfix operator on whatever precedes it.
        while self.eat_operator("%") {
            node = Node::Unary("%".to_string(), Box::new(node));
        }
        Some(node)
    }

    fn parse_primary(&mut self) -> Option<Node> {
        match self.peek().cloned() {
            Some(Token::Number(value)) => {
                self.position += 1;
                Some(Node::Literal(CellValue::Number(value)))
            }
            Some(Token::Text(text)) => {
                self.position += 1;
                Some(Node::Literal(CellValue::Text(text)))
            }
            Some(Token::Word(word)) => {
                self.position += 1;
                match word.as_str() {
                    "TRUE" => Some(Node::Literal(CellValue::Bool(true))),
                    "FALSE" => Some(Node::Literal(CellValue::Bool(false))),
                    other => Some(Node::Literal(CellValue::Error(other.to_string()))),
                }
            }
            Some(Token::OpenParen) => {
                self.position += 1;
                let inner = self.parse_expression()?;
                if !matches!(self.take(), Some(Token::CloseParen)) {
                    return None;
                }
                Some(inner)
            }
            Some(Token::Name(name)) => {
                self.position += 1;
                self.parse_name(name)
            }
            _ => None,
        }
    }

    /// A name: a function call, a reference, or a sheet-qualified reference.
    fn parse_name(&mut self, name: String) -> Option<Node> {
        // A `(` right after the name makes it a call. Anything else is a reference.
        if matches!(self.peek(), Some(Token::OpenParen)) {
            self.position += 1;
            let mut arguments = Vec::new();
            if !matches!(self.peek(), Some(Token::CloseParen)) {
                loop {
                    arguments.push(self.parse_expression()?);
                    match self.peek() {
                        Some(Token::Comma) => {
                            self.position += 1;
                        }
                        _ => break,
                    }
                }
            }
            if !matches!(self.take(), Some(Token::CloseParen)) {
                return None;
            }
            return Some(Node::Function(name.to_uppercase(), arguments));
        }

        // `Sheet1!A1`, where the sheet may itself be quoted or reached through a path.
        let mut sheet = None;
        let mut body = name;
        while matches!(self.peek(), Some(Token::Bang)) {
            self.position += 1;
            let next = match self.take() {
                Some(Token::Name(second)) => second,
                Some(Token::Word(second)) => second,
                _ => return None,
            };
            sheet = Some(match sheet {
                Some(previous) => format!("{previous}!{body}"),
                None => body,
            });
            body = next;
        }

        // `A1:B2`, and the sheet-qualified form of the same.
        if matches!(self.peek(), Some(Token::Colon)) {
            self.position += 1;
            let second = match self.take() {
                Some(Token::Name(second)) => second,
                _ => return None,
            };
            let mut range = format!("{body}:{second}");
            // A whole-row or whole-column range names cells this module does not enumerate, so
            // it is reported rather than silently reading one row.
            if range.contains(':')
                && range
                    .split(':')
                    .any(|side| !looks_like_reference(side) && !looks_like_column_reference(side))
            {
                range.push(' ');
            }
            return Some(Node::Reference(sheet, range));
        }

        Some(Node::Reference(sheet, body))
    }
}

// ---------------------------------------------------------------------------------------
// Evaluation
// ---------------------------------------------------------------------------------------

/// Why a formula could not produce a value.
type Reason = String;

fn error_value(code: &str) -> CellValue {
    CellValue::Error(code.to_string())
}

/// What a referenced cell contributes as a *value*.
///
/// A cell holding a formula reads as blank. This module has no recalculation order, so
/// evaluating its dependency would mean inventing one; and returning the formula's text would be
/// worse still, since `=A1+1` would then try to add one to the string `"=1+1"`. Blank is
/// visible, and [`Workbook::recalculate`][crate::Workbook::recalculate] puts the value there once the order is known.
fn readable(value: CellValue) -> CellValue {
    match value {
        CellValue::Formula(_) => CellValue::None,
        other => other,
    }
}

fn is_error(value: &CellValue) -> bool {
    matches!(value, CellValue::Error(_))
}

fn eval(
    node: &Node,
    sheet: &str,
    source: &dyn ValueSource,
) -> std::result::Result<CellValue, Reason> {
    // An error anywhere propagates, and does so before the rest of the node is even looked at,
    // which is what makes `1/0+SUM(A1:A2)` yield `#DIV/0!` rather than something surprising.
    match node {
        Node::Literal(value) => Ok(value.clone()),
        Node::Reference(reference_sheet, body) => {
            let resolved = resolve(reference_sheet.as_deref().unwrap_or(sheet), body, source)?;
            match resolved {
                Resolved::Single(value) => Ok(readable(value)),
                // A range where a single value is needed takes the first cell, which is what
                // Excel's implicit intersection does for a one-row range.
                Resolved::Range { mut values, .. } => Ok(if values.is_empty() {
                    CellValue::None
                } else {
                    values.remove(0)
                }),
            }
        }
        Node::Unary(operator, inner) => {
            let value = eval(inner, sheet, source)?;
            unary(operator, value)
        }
        Node::Binary(operator, left, right) => {
            let a = eval(left, sheet, source)?;
            let b = eval(right, sheet, source)?;
            binary(operator, a, b)
        }
        Node::Function(name, arguments) => {
            if !supports(name) {
                return Err(format!("unsupported function {name}()"));
            }
            call_function(name, arguments, sheet, source)
        }
    }
}

/// Resolve a reference body against a sheet.
fn resolve(
    sheet: &str,
    body: &str,
    source: &dyn ValueSource,
) -> std::result::Result<Resolved, Reason> {
    let body = body.trim();
    let (start, end) = match body.split_once(':') {
        Some((start, end)) => (start, Some(end)),
        None => (body, None),
    };
    match end {
        None => {
            let start = normalise_reference(start)?;
            Ok(Resolved::Single(readable(source.cell(sheet, &start))))
        }
        Some(end) => {
            let start_clean: String = start.chars().filter(|c| *c != '$').collect();
            let end_clean: String = end.chars().filter(|c| *c != '$').collect();
            let (start_coord, end_coord) = if looks_like_column_reference(&start_clean)
                && looks_like_column_reference(&end_clean)
            {
                let max = source.max_row(sheet).unwrap_or(100).max(1);
                (
                    format!("{}1", start_clean.to_uppercase()),
                    format!("{}{max}", end_clean.to_uppercase()),
                )
            } else {
                (normalise_reference(start)?, normalise_reference(end)?)
            };

            let range = crate::worksheet::cell_range::CellRange::parse(&format!(
                "{start_coord}:{end_coord}"
            ))
            .map_err(|error| format!("cannot read the range {body:?}: {error}"))?;
            let (min_col, min_row, max_col, max_row) = range.bounds();
            let cols = (max_col - min_col + 1) as usize;
            let rows = (max_row - min_row + 1) as usize;
            let mut values = Vec::new();
            for coordinate in range.cells().map_err(|error| error.to_string())? {
                values.push(readable(source.cell(sheet, &coordinate)));
            }
            Ok(Resolved::Range { values, cols, rows })
        }
    }
}

/// Turn `a1` or `$A$1` into `A1`, the form the source is keyed by.
fn normalise_reference(text: &str) -> std::result::Result<String, Reason> {
    let cleaned: String = text.chars().filter(|c| *c != '$').collect();
    if !looks_like_reference(&cleaned) {
        return Err(format!("{text:?} is not a cell reference"));
    }
    Ok(cleaned.to_uppercase())
}

fn unary(operator: &str, value: CellValue) -> std::result::Result<CellValue, Reason> {
    if is_error(&value) {
        return Ok(value);
    }
    match operator {
        "%" => to_number(&value).map(|n| CellValue::Number(n / 100.0)),
        "-" => to_number(&value).map(|n| CellValue::Number(-n)),
        other => Err(format!("unknown operator {other}")),
    }
}

fn binary(
    operator: &str,
    left: CellValue,
    right: CellValue,
) -> std::result::Result<CellValue, Reason> {
    if let CellValue::Error(code) = &left {
        return Ok(error_value(code));
    }
    if let CellValue::Error(code) = &right {
        return Ok(error_value(code));
    }
    match operator {
        "&" => {
            // Concatenation renders a number the way Excel shows it, not as a raw float:
            // `1/3&""` is `0.333333333333333`, and a trailing `.0` never appears.
            Ok(CellValue::Text(format!(
                "{}{}",
                as_display(&left),
                as_display(&right)
            )))
        }
        "=" | "<>" | "<" | "<=" | ">" | ">=" => {
            let ordering = compare(&left, &right);
            let holds = match operator {
                "=" => ordering == std::cmp::Ordering::Equal,
                "<>" => ordering != std::cmp::Ordering::Equal,
                "<" => ordering == std::cmp::Ordering::Less,
                "<=" => ordering != std::cmp::Ordering::Greater,
                ">" => ordering == std::cmp::Ordering::Greater,
                _ => ordering != std::cmp::Ordering::Less,
            };
            Ok(CellValue::Bool(holds))
        }
        _ => {
            let a = to_number(&left)?;
            let b = to_number(&right)?;
            let value = match operator {
                "+" => a + b,
                "-" => a - b,
                "*" => a * b,
                "/" => {
                    if b == 0.0 {
                        return Ok(error_value("#DIV/0!"));
                    }
                    a / b
                }
                "^" => {
                    let result = a.powf(b);
                    if result.is_nan() {
                        return Ok(error_value("#NUM!"));
                    }
                    result
                }
                other => return Err(format!("unknown operator {other}")),
            };
            if value.is_infinite() {
                return Ok(error_value("#NUM!"));
            }
            Ok(CellValue::Number(value))
        }
    }
}

/// Excel's ordering across types: numbers before text before booleans.
fn rank(value: &CellValue) -> u8 {
    match value {
        CellValue::None => 0,
        CellValue::Number(_) => 1,
        CellValue::Text(_) => 2,
        CellValue::Bool(_) => 3,
        _ => 4,
    }
}

fn compare(left: &CellValue, right: &CellValue) -> std::cmp::Ordering {
    // A blank compares as zero against a number and as an empty string against text, which is
    // why `=A1=""` is true for an empty cell.
    let left = coerce_for_comparison(left);
    let right = coerce_for_comparison(right);
    match (&left, &right) {
        (CellValue::Number(a), CellValue::Number(b)) => {
            a.partial_cmp(b).unwrap_or(std::cmp::Ordering::Equal)
        }
        (CellValue::Text(a), CellValue::Text(b)) => {
            // Excel compares text case-insensitively.
            a.to_lowercase().cmp(&b.to_lowercase())
        }
        (CellValue::Bool(a), CellValue::Bool(b)) => a.cmp(b),
        _ => rank(&left).cmp(&rank(&right)),
    }
}

fn coerce_for_comparison(value: &CellValue) -> CellValue {
    match value {
        CellValue::None => CellValue::Number(0.0),
        other => other.clone(),
    }
}

/// Excel's coercion to a number, and the `#VALUE!` it produces when there is none.
fn to_number(value: &CellValue) -> std::result::Result<f64, Reason> {
    match value {
        CellValue::Number(v) => Ok(*v),
        CellValue::Bool(v) => Ok(if *v { 1.0 } else { 0.0 }),
        // A blank is zero in arithmetic, which is what makes `=A1+1` work on an empty cell.
        CellValue::None => Ok(0.0),
        CellValue::Text(text) => {
            let trimmed = text.trim();
            if trimmed.is_empty() {
                return Ok(0.0);
            }
            let cleaned = trimmed.replace(['$', ','], "");
            // Excel also reads a percentage and a date literal here; those are left out rather
            // than guessed at, and the caller sees `#VALUE!` as it would from a bad entry.
            cleaned
                .parse::<f64>()
                .map_err(|_| format!("#VALUE! cannot read {text:?} as a number"))
        }
        CellValue::DateTime(moment) => Ok(crate::date_time::to_excel(
            *moment,
            crate::date_time::BaseDate::Windows1900,
        )),
        CellValue::Date(day) => Ok(crate::date_time::date_to_excel(
            *day,
            crate::date_time::BaseDate::Windows1900,
        )),
        CellValue::Time(clock) => Ok(crate::date_time::time_to_days(*clock)),
        CellValue::Duration(span) => Ok(crate::date_time::timedelta_to_days(*span)),
        CellValue::Error(code) => Err(code.clone()),
        CellValue::Formula(_) => Err("#VALUE! a formula used as a value".to_string()),
    }
}

fn to_number_value(value: &CellValue) -> CellValue {
    match to_number(value) {
        Ok(number) => CellValue::Number(number),
        Err(code) => error_value(code.trim_start_matches("#VALUE! ")),
    }
}

/// The text a value renders as, for `&` and the text functions.
fn as_display(value: &CellValue) -> String {
    match value {
        CellValue::Text(text) => text.clone(),
        CellValue::Bool(v) => if *v { "TRUE" } else { "FALSE" }.to_string(),
        CellValue::None => String::new(),
        CellValue::Number(v) => format_number(*v),
        CellValue::DateTime(moment) => moment.format("%Y-%m-%d %H:%M:%S").to_string(),
        other => format!("{other:?}"),
    }
}

/// Render a number the way a spreadsheet cell shows it: no trailing `.0`, no float noise.
fn format_number(value: f64) -> String {
    if value == value.trunc() && value.abs() < 1e15 {
        return format!("{}", value as i64);
    }
    let mut text = format!("{value}");
    if text.contains('e') {
        text = format!("{value:.10}");
    }
    text
}

// ---------------------------------------------------------------------------------------
// Functions
// ---------------------------------------------------------------------------------------

/// The values a function argument evaluates to, ranges flattened and blanks kept.
///
/// Keeping blanks matters: `COUNT` and `SUM` treat a blank differently from a zero, and only one
/// of them can be right for any given function.
fn argument_values(
    arguments: &[Node],
    sheet: &str,
    source: &dyn ValueSource,
) -> std::result::Result<Vec<CellValue>, Reason> {
    let mut values = Vec::new();
    for argument in arguments {
        match argument {
            Node::Reference(reference_sheet, body) => {
                match resolve(reference_sheet.as_deref().unwrap_or(sheet), body, source)? {
                    Resolved::Single(value) => values.push(value),
                    Resolved::Range { values: range, .. } => values.extend(range),
                }
            }
            other => values.push(eval(other, sheet, source)?),
        }
    }
    Ok(values)
}

/// The numbers an aggregate should add, skipping blanks and text inside ranges.
///
/// `SUM(A1:A3)` ignores a text cell in the range but `SUM("x")` is `#VALUE!`, because a literal
/// was clearly meant as a number and a cell's contents were not.
fn aggregate_numbers(
    arguments: &[Node],
    sheet: &str,
    source: &dyn ValueSource,
) -> std::result::Result<Vec<f64>, Reason> {
    let mut numbers = Vec::new();
    for argument in arguments {
        match argument {
            Node::Reference(reference_sheet, body) => {
                let sheet = reference_sheet.as_deref().unwrap_or(sheet);
                match resolve(sheet, body, source)? {
                    Resolved::Single(value) => {
                        // A lone cell reference follows the range rule: blank and text are
                        // skipped rather than being an error.
                        if let CellValue::Number(number) = value {
                            numbers.push(number);
                        }
                    }
                    Resolved::Range { values, .. } => {
                        for value in values {
                            if let CellValue::Number(number) = value {
                                numbers.push(number);
                            }
                        }
                    }
                }
            }
            other => {
                let value = eval(other, sheet, source)?;
                numbers.push(to_number(&value)?);
            }
        }
    }
    Ok(numbers)
}

fn call_function(
    name: &str,
    arguments: &[Node],
    sheet: &str,
    source: &dyn ValueSource,
) -> std::result::Result<CellValue, Reason> {
    // The functions that need their arguments unevaluated -- IF and IFERROR -- are dispatched
    // before anything flattens them, so `IF(A1=0,"",1/A1)` does not divide by zero on the
    // branch it does not take.
    match name {
        "IF" => return call_if(arguments, sheet, source),
        "IFERROR" => return call_iferror(arguments, sheet, source),
        "AND" | "OR" => return call_and_or(name, arguments, sheet, source),
        "CHOOSE" => return call_choose(arguments, sheet, source),
        "INDEX" => return call_index(arguments, sheet, source),
        "MATCH" => return call_match(arguments, sheet, source),
        "VLOOKUP" => return call_vlookup(arguments, sheet, source),
        "XLOOKUP" => return call_xlookup(arguments, sheet, source),
        "SUMIF" => return call_sumif(arguments, sheet, source),
        "SUMIFS" => return call_sumifs(arguments, sheet, source),
        "COUNTIF" => return call_countif(arguments, sheet, source),
        "COUNTIFS" => return call_countifs(arguments, sheet, source),
        _ => {}
    }

    match name {
        "SUM" => {
            let numbers = aggregate_numbers(arguments, sheet, source)?;
            Ok(CellValue::Number(numbers.iter().sum()))
        }
        "PRODUCT" => {
            let numbers = aggregate_numbers(arguments, sheet, source)?;
            Ok(CellValue::Number(numbers.iter().product()))
        }
        "AVERAGE" => {
            let numbers = aggregate_numbers(arguments, sheet, source)?;
            if numbers.is_empty() {
                // Excel's answer for an empty average, which is not zero.
                return Ok(error_value("#DIV/0!"));
            }
            Ok(CellValue::Number(
                numbers.iter().sum::<f64>() / numbers.len() as f64,
            ))
        }
        "MIN" | "MAX" => {
            let numbers = aggregate_numbers(arguments, sheet, source)?;
            if numbers.is_empty() {
                return Ok(CellValue::Number(0.0));
            }
            let picked = if name == "MIN" {
                numbers.iter().copied().fold(f64::INFINITY, f64::min)
            } else {
                numbers.iter().copied().fold(f64::NEG_INFINITY, f64::max)
            };
            Ok(CellValue::Number(picked))
        }
        "COUNT" => {
            let values = argument_values(arguments, sheet, source)?;
            Ok(CellValue::Number(
                values
                    .iter()
                    .filter(|value| {
                        matches!(
                            value,
                            CellValue::Number(_) | CellValue::Bool(_) | CellValue::DateTime(_)
                        )
                    })
                    .count() as f64,
            ))
        }
        "COUNTA" => {
            let values = argument_values(arguments, sheet, source)?;
            Ok(CellValue::Number(
                values.iter().filter(|value| !value.is_empty()).count() as f64,
            ))
        }
        "ABS" | "INT" | "SIGN" | "SQRT" | "ROUND" | "ROUNDUP" | "ROUNDDOWN" | "MOD" | "POWER" => {
            let values = argument_values(arguments, sheet, source)?;
            if values.is_empty() {
                return Err(format!("{name}() needs an argument"));
            }
            let first = to_number_value(&values[0]);
            if is_error(&first) {
                return Ok(first);
            }
            let number = match first {
                CellValue::Number(n) => n,
                _ => 0.0,
            };
            match name {
                "ABS" => Ok(CellValue::Number(number.abs())),
                "INT" => Ok(CellValue::Number(number.floor())),
                "SIGN" => Ok(CellValue::Number(number.signum())),
                "SQRT" => {
                    if number < 0.0 {
                        return Ok(error_value("#NUM!"));
                    }
                    Ok(CellValue::Number(number.sqrt()))
                }
                "ROUND" | "ROUNDUP" | "ROUNDDOWN" => {
                    let places = match values.get(1) {
                        Some(value) => to_number(value)?,
                        // Excel's default is zero places, and rounding to zero places is the
                        // common case by far.
                        None => 0.0,
                    };
                    if is_error(&to_number_value(values.get(1).unwrap_or(&CellValue::None))) {
                        return Ok(to_number_value(values.get(1).unwrap_or(&CellValue::None)));
                    }
                    Ok(CellValue::Number(round(number, places, name)))
                }
                "MOD" => {
                    let divisor = match values.get(1) {
                        Some(value) => to_number(value)?,
                        None => return Err("MOD() needs a divisor".to_string()),
                    };
                    if divisor == 0.0 {
                        return Ok(error_value("#DIV/0!"));
                    }
                    // Excel's MOD follows the divisor's sign, unlike Rust's `%`.
                    Ok(CellValue::Number(
                        number - divisor * (number / divisor).floor(),
                    ))
                }
                "POWER" => {
                    let exponent = match values.get(1) {
                        Some(value) => to_number(value)?,
                        None => return Err("POWER() needs an exponent".to_string()),
                    };
                    let result = number.powf(exponent);
                    if result.is_nan() {
                        return Ok(error_value("#NUM!"));
                    }
                    Ok(CellValue::Number(result))
                }
                _ => unreachable!("the match above is exhaustive"),
            }
        }
        "CONCAT" | "CONCATENATE" => {
            let values = argument_values(arguments, sheet, source)?;
            if let Some(bad) = values.iter().find(|value| is_error(value)) {
                return Ok(bad.clone());
            }
            let mut text = String::new();
            for value in values {
                match value {
                    // A blank contributes nothing rather than a zero, which is what makes
                    // `CONCAT(A1:A3)` usable on a sparse column.
                    CellValue::None => {}
                    other => text.push_str(&as_display(&other)),
                }
            }
            Ok(CellValue::Text(text))
        }
        "LEFT" | "RIGHT" => {
            let values = argument_values(arguments, sheet, source)?;
            let text = as_display(values.first().unwrap_or(&CellValue::None));
            let count = match values.get(1) {
                Some(value) => to_number(value)?.max(0.0) as usize,
                None => 1,
            };
            let characters: Vec<char> = text.chars().collect();
            let taken: String = if name == "LEFT" {
                characters.iter().take(count).collect()
            } else {
                characters
                    .iter()
                    .skip(characters.len().saturating_sub(count))
                    .collect()
            };
            Ok(CellValue::Text(taken))
        }
        "LEN" => {
            let values = argument_values(arguments, sheet, source)?;
            let text = as_display(values.first().unwrap_or(&CellValue::None));
            // Excel counts characters, not bytes, so an emoji is one character.
            Ok(CellValue::Number(text.chars().count() as f64))
        }
        "TRIM" | "UPPER" | "LOWER" => {
            let values = argument_values(arguments, sheet, source)?;
            let text = as_display(values.first().unwrap_or(&CellValue::None));
            Ok(CellValue::Text(match name {
                // Excel's TRIM also collapses internal runs of spaces, not just the ends.
                "TRIM" => text.split_whitespace().collect::<Vec<_>>().join(" "),
                "UPPER" => text.to_uppercase(),
                _ => text.to_lowercase(),
            }))
        }
        "NOT" => {
            let values = argument_values(arguments, sheet, source)?;
            match to_bool(values.first().unwrap_or(&CellValue::None))? {
                Some(flag) => Ok(CellValue::Bool(!flag)),
                None => Ok(CellValue::Number(0.0)),
            }
        }
        "TRUE" => Ok(CellValue::Bool(true)),
        "FALSE" => Ok(CellValue::Bool(false)),
        "ISBLANK" => {
            let values = argument_values(arguments, sheet, source)?;
            let first = values.first().unwrap_or(&CellValue::None);
            Ok(CellValue::Bool(first.is_empty()))
        }
        "ISNUMBER" => {
            let values = argument_values(arguments, sheet, source)?;
            let first = values.first().unwrap_or(&CellValue::None);
            Ok(CellValue::Bool(matches!(first, CellValue::Number(_))))
        }
        "ISTEXT" => {
            let values = argument_values(arguments, sheet, source)?;
            let first = values.first().unwrap_or(&CellValue::None);
            Ok(CellValue::Bool(matches!(first, CellValue::Text(_))))
        }
        "ISERROR" => {
            let values = argument_values(arguments, sheet, source)?;
            let first = values.first().unwrap_or(&CellValue::None);
            Ok(CellValue::Bool(is_error(first)))
        }
        other => Err(format!("unsupported function {other}()")),
    }
}

fn resolve_range(
    node: &Node,
    sheet: &str,
    source: &dyn ValueSource,
) -> std::result::Result<(Vec<CellValue>, usize, usize), Reason> {
    match node {
        Node::Reference(ref_sheet, body) => {
            let target_sheet = ref_sheet.as_deref().unwrap_or(sheet);
            match resolve(target_sheet, body, source)? {
                Resolved::Single(val) => Ok((vec![val], 1, 1)),
                Resolved::Range { values, cols, rows } => Ok((values, cols, rows)),
            }
        }
        other => {
            let val = eval(other, sheet, source)?;
            Ok((vec![val], 1, 1))
        }
    }
}

fn values_equal(a: &CellValue, b: &CellValue) -> bool {
    match (a, b) {
        (CellValue::Number(x), CellValue::Number(y)) => (x - y).abs() < 1e-12,
        (CellValue::Text(x), CellValue::Text(y)) => x.eq_ignore_ascii_case(y),
        (CellValue::Bool(x), CellValue::Bool(y)) => x == y,
        (CellValue::None, CellValue::None) => true,
        (CellValue::Number(x), CellValue::Text(y)) | (CellValue::Text(y), CellValue::Number(x)) => {
            if let Ok(yn) = y.trim().parse::<f64>() {
                (x - yn).abs() < 1e-12
            } else {
                false
            }
        }
        _ => false,
    }
}

fn call_choose(
    arguments: &[Node],
    sheet: &str,
    source: &dyn ValueSource,
) -> std::result::Result<CellValue, Reason> {
    if arguments.len() < 2 {
        return Err("CHOOSE() needs an index and at least one choice".to_string());
    }
    let index_val = eval(&arguments[0], sheet, source)?;
    let index = to_number(&index_val)? as i64;
    if index < 1 || index as usize >= arguments.len() {
        return Ok(error_value("#VALUE!"));
    }
    eval(&arguments[index as usize], sheet, source)
}

fn call_index(
    arguments: &[Node],
    sheet: &str,
    source: &dyn ValueSource,
) -> std::result::Result<CellValue, Reason> {
    if arguments.len() < 2 {
        return Err("INDEX() needs at least a range and a row number".to_string());
    }
    let (values, cols, rows) = resolve_range(&arguments[0], sheet, source)?;
    let row_val = eval(&arguments[1], sheet, source)?;
    let row_num = to_number(&row_val)? as i64;
    let col_num = if arguments.len() >= 3 {
        let col_val = eval(&arguments[2], sheet, source)?;
        to_number(&col_val)? as i64
    } else if rows == 1 && cols > 1 {
        row_num
    } else {
        1
    };
    let actual_row = if rows == 1 && cols > 1 && arguments.len() < 3 {
        1
    } else {
        row_num
    };
    let actual_col = col_num;

    if actual_row < 1 || actual_row as usize > rows || actual_col < 1 || actual_col as usize > cols
    {
        return Ok(error_value("#REF!"));
    }
    let idx = (actual_row as usize - 1) * cols + (actual_col as usize - 1);
    Ok(values.get(idx).cloned().unwrap_or(CellValue::None))
}

fn call_match(
    arguments: &[Node],
    sheet: &str,
    source: &dyn ValueSource,
) -> std::result::Result<CellValue, Reason> {
    if arguments.len() < 2 {
        return Err("MATCH() needs a lookup value and lookup array".to_string());
    }
    let lookup_val = eval(&arguments[0], sheet, source)?;
    let (values, cols, rows) = resolve_range(&arguments[1], sheet, source)?;
    if cols > 1 && rows > 1 {
        return Ok(error_value("#N/A"));
    }
    let match_type = if arguments.len() >= 3 {
        let m_val = eval(&arguments[2], sheet, source)?;
        to_number(&m_val)? as i64
    } else {
        1
    };

    if match_type == 0 {
        for (idx, val) in values.iter().enumerate() {
            if values_equal(&lookup_val, val) {
                return Ok(CellValue::Number((idx + 1) as f64));
            }
        }
        Ok(error_value("#N/A"))
    } else if match_type == 1 {
        let mut last_match = None;
        let target = to_number(&lookup_val)?;
        for (idx, val) in values.iter().enumerate() {
            if let Ok(num) = to_number(val) {
                if num <= target {
                    last_match = Some(idx + 1);
                } else {
                    break;
                }
            }
        }
        match last_match {
            Some(idx) => Ok(CellValue::Number(idx as f64)),
            None => Ok(error_value("#N/A")),
        }
    } else if match_type == -1 {
        let mut last_match = None;
        let target = to_number(&lookup_val)?;
        for (idx, val) in values.iter().enumerate() {
            if let Ok(num) = to_number(val) {
                if num >= target {
                    last_match = Some(idx + 1);
                } else {
                    break;
                }
            }
        }
        match last_match {
            Some(idx) => Ok(CellValue::Number(idx as f64)),
            None => Ok(error_value("#N/A")),
        }
    } else {
        Ok(error_value("#N/A"))
    }
}

fn call_vlookup(
    arguments: &[Node],
    sheet: &str,
    source: &dyn ValueSource,
) -> std::result::Result<CellValue, Reason> {
    if arguments.len() < 3 {
        return Err("VLOOKUP() needs lookup_value, table_array, and col_index".to_string());
    }
    let lookup_val = eval(&arguments[0], sheet, source)?;
    let (values, cols, rows) = resolve_range(&arguments[1], sheet, source)?;
    let col_val = eval(&arguments[2], sheet, source)?;
    let col_index = to_number(&col_val)? as i64;
    if col_index < 1 || col_index as usize > cols {
        return Ok(error_value("#REF!"));
    }

    let approximate = if arguments.len() >= 4 {
        let flag_val = eval(&arguments[3], sheet, source)?;
        to_bool(&flag_val)?.unwrap_or(true)
    } else {
        true
    };

    let col_offset = col_index as usize - 1;
    if !approximate {
        // Exact match
        for r in 0..rows {
            let key = &values[r * cols];
            if values_equal(&lookup_val, key) {
                return Ok(values[r * cols + col_offset].clone());
            }
        }
        Ok(error_value("#N/A"))
    } else {
        let mut best_row = None;
        if let Ok(target) = to_number(&lookup_val) {
            for r in 0..rows {
                let key = &values[r * cols];
                if let Ok(k_num) = to_number(key) {
                    if k_num <= target {
                        best_row = Some(r);
                    } else {
                        break;
                    }
                }
            }
        } else {
            let target_str = as_display(&lookup_val).to_lowercase();
            for r in 0..rows {
                let key_str = as_display(&values[r * cols]).to_lowercase();
                if key_str.as_str() <= target_str.as_str() {
                    best_row = Some(r);
                } else {
                    break;
                }
            }
        }
        match best_row {
            Some(r) => Ok(values[r * cols + col_offset].clone()),
            None => Ok(error_value("#N/A")),
        }
    }
}

fn call_xlookup(
    arguments: &[Node],
    sheet: &str,
    source: &dyn ValueSource,
) -> std::result::Result<CellValue, Reason> {
    if arguments.len() < 3 {
        return Err("XLOOKUP() needs lookup_value, lookup_array, and return_array".to_string());
    }
    let lookup_val = eval(&arguments[0], sheet, source)?;
    let (lookup_values, _, _) = resolve_range(&arguments[1], sheet, source)?;
    let (return_values, _, _) = resolve_range(&arguments[2], sheet, source)?;
    if lookup_values.len() != return_values.len() {
        return Ok(error_value("#VALUE!"));
    }

    let match_mode = if arguments.len() >= 5 {
        let m_val = eval(&arguments[4], sheet, source)?;
        to_number(&m_val)? as i64
    } else {
        0
    };

    let mut found_index = None;
    if match_mode == 0 {
        for (i, val) in lookup_values.iter().enumerate() {
            if values_equal(&lookup_val, val) {
                found_index = Some(i);
                break;
            }
        }
    } else if match_mode == -1 {
        for (i, val) in lookup_values.iter().enumerate() {
            if values_equal(&lookup_val, val) {
                found_index = Some(i);
                break;
            }
        }
        if found_index.is_none() {
            if let Ok(target) = to_number(&lookup_val) {
                let mut best_diff = f64::INFINITY;
                for (i, val) in lookup_values.iter().enumerate() {
                    if let Ok(n) = to_number(val) {
                        if n < target && (target - n) < best_diff {
                            best_diff = target - n;
                            found_index = Some(i);
                        }
                    }
                }
            }
        }
    } else if match_mode == 1 {
        for (i, val) in lookup_values.iter().enumerate() {
            if values_equal(&lookup_val, val) {
                found_index = Some(i);
                break;
            }
        }
        if found_index.is_none() {
            if let Ok(target) = to_number(&lookup_val) {
                let mut best_diff = f64::INFINITY;
                for (i, val) in lookup_values.iter().enumerate() {
                    if let Ok(n) = to_number(val) {
                        if n > target && (n - target) < best_diff {
                            best_diff = n - target;
                            found_index = Some(i);
                        }
                    }
                }
            }
        }
    }

    match found_index {
        Some(i) => Ok(return_values[i].clone()),
        None => {
            if arguments.len() >= 4 {
                eval(&arguments[3], sheet, source)
            } else {
                Ok(error_value("#N/A"))
            }
        }
    }
}

fn matches_criteria(val: &CellValue, crit: &CellValue) -> bool {
    let crit_text = match crit {
        CellValue::Text(t) => t.trim(),
        CellValue::Number(n) => {
            return match val {
                CellValue::Number(vn) => (vn - n).abs() < 1e-12,
                _ => false,
            };
        }
        CellValue::Bool(b) => {
            return match val {
                CellValue::Bool(vb) => vb == b,
                _ => false,
            };
        }
        _ => return val.is_empty(),
    };

    if let Some(rest) = crit_text.strip_prefix(">=") {
        if let Ok(target) = rest.trim().parse::<f64>() {
            if let CellValue::Number(vn) = val {
                return *vn >= target;
            }
        }
        return false;
    }
    if let Some(rest) = crit_text.strip_prefix("<=") {
        if let Ok(target) = rest.trim().parse::<f64>() {
            if let CellValue::Number(vn) = val {
                return *vn <= target;
            }
        }
        return false;
    }
    if let Some(rest) = crit_text.strip_prefix("<>") {
        let rest = rest.trim();
        if let Ok(target) = rest.parse::<f64>() {
            return match val {
                CellValue::Number(vn) => (vn - target).abs() >= 1e-12,
                _ => true,
            };
        } else {
            return match val {
                CellValue::Text(vt) => !vt.eq_ignore_ascii_case(rest),
                _ => true,
            };
        }
    }
    if let Some(rest) = crit_text.strip_prefix('>') {
        if let Ok(target) = rest.trim().parse::<f64>() {
            if let CellValue::Number(vn) = val {
                return *vn > target;
            }
        }
        return false;
    }
    if let Some(rest) = crit_text.strip_prefix('<') {
        if let Ok(target) = rest.trim().parse::<f64>() {
            if let CellValue::Number(vn) = val {
                return *vn < target;
            }
        }
        return false;
    }
    if let Some(rest) = crit_text.strip_prefix('=') {
        let rest = rest.trim();
        if let Ok(target) = rest.parse::<f64>() {
            return match val {
                CellValue::Number(vn) => (vn - target).abs() < 1e-12,
                _ => false,
            };
        } else {
            return match val {
                CellValue::Text(vt) => vt.eq_ignore_ascii_case(rest),
                _ => false,
            };
        }
    }

    if let Ok(target) = crit_text.parse::<f64>() {
        match val {
            CellValue::Number(vn) => (vn - target).abs() < 1e-12,
            _ => false,
        }
    } else {
        match val {
            CellValue::Text(vt) => vt.eq_ignore_ascii_case(crit_text),
            _ => false,
        }
    }
}

fn call_sumif(
    arguments: &[Node],
    sheet: &str,
    source: &dyn ValueSource,
) -> std::result::Result<CellValue, Reason> {
    if arguments.len() < 2 {
        return Err("SUMIF() needs range and criteria".to_string());
    }
    let (range_values, _, _) = resolve_range(&arguments[0], sheet, source)?;
    let crit_val = eval(&arguments[1], sheet, source)?;
    let (sum_values, _, _) = if arguments.len() >= 3 {
        resolve_range(&arguments[2], sheet, source)?
    } else {
        (range_values.clone(), 1, 1)
    };

    let mut sum = 0.0;
    for (i, val) in range_values.iter().enumerate() {
        if matches_criteria(val, &crit_val) {
            if let Some(CellValue::Number(n)) = sum_values.get(i) {
                sum += n;
            }
        }
    }
    Ok(CellValue::Number(sum))
}

fn call_countif(
    arguments: &[Node],
    sheet: &str,
    source: &dyn ValueSource,
) -> std::result::Result<CellValue, Reason> {
    if arguments.len() < 2 {
        return Err("COUNTIF() needs range and criteria".to_string());
    }
    let (range_values, _, _) = resolve_range(&arguments[0], sheet, source)?;
    let crit_val = eval(&arguments[1], sheet, source)?;

    let count = range_values
        .iter()
        .filter(|val| matches_criteria(val, &crit_val))
        .count();
    Ok(CellValue::Number(count as f64))
}

fn call_sumifs(
    arguments: &[Node],
    sheet: &str,
    source: &dyn ValueSource,
) -> std::result::Result<CellValue, Reason> {
    if arguments.len() < 3 || !(arguments.len() - 1).is_multiple_of(2) {
        return Err(
            "SUMIFS() requires a sum range followed by pairs of criteria range and criteria"
                .to_string(),
        );
    }
    let (sum_values, _, _) = resolve_range(&arguments[0], sheet, source)?;
    let mut criteria_pairs = Vec::new();
    let mut idx = 1;
    while idx < arguments.len() {
        let (crit_range, _, _) = resolve_range(&arguments[idx], sheet, source)?;
        let crit_val = eval(&arguments[idx + 1], sheet, source)?;
        criteria_pairs.push((crit_range, crit_val));
        idx += 2;
    }

    let mut sum = 0.0;
    for (i, sum_val) in sum_values.iter().enumerate() {
        let mut all_match = true;
        for (crit_range, crit_val) in &criteria_pairs {
            if let Some(val) = crit_range.get(i) {
                if !matches_criteria(val, crit_val) {
                    all_match = false;
                    break;
                }
            } else {
                all_match = false;
                break;
            }
        }
        if all_match {
            if let CellValue::Number(n) = sum_val {
                sum += n;
            }
        }
    }
    Ok(CellValue::Number(sum))
}

fn call_countifs(
    arguments: &[Node],
    sheet: &str,
    source: &dyn ValueSource,
) -> std::result::Result<CellValue, Reason> {
    if arguments.len() < 2 || !arguments.len().is_multiple_of(2) {
        return Err("COUNTIFS() requires pairs of criteria range and criteria".to_string());
    }
    let mut criteria_pairs = Vec::new();
    let mut idx = 0;
    while idx < arguments.len() {
        let (crit_range, _, _) = resolve_range(&arguments[idx], sheet, source)?;
        let crit_val = eval(&arguments[idx + 1], sheet, source)?;
        criteria_pairs.push((crit_range, crit_val));
        idx += 2;
    }

    let first_len = criteria_pairs[0].0.len();
    let mut count = 0;
    for i in 0..first_len {
        let mut all_match = true;
        for (crit_range, crit_val) in &criteria_pairs {
            if let Some(val) = crit_range.get(i) {
                if !matches_criteria(val, crit_val) {
                    all_match = false;
                    break;
                }
            } else {
                all_match = false;
                break;
            }
        }
        if all_match {
            count += 1;
        }
    }
    Ok(CellValue::Number(count as f64))
}

/// Automatically prefix future functions with `_xlfn.` for OOXML compatibility.
pub fn prefix_future_functions(formula: &str) -> String {
    const FUTURE_FUNCTIONS: &[&str] = &[
        "XLOOKUP",
        "XMATCH",
        "SEQUENCE",
        "UNIQUE",
        "FILTER",
        "SORT",
        "SORTBY",
        "RANDARRAY",
        "SINGLE",
        "CONCAT",
        "TEXTJOIN",
        "IFS",
        "SWITCH",
        "MINIFS",
        "MAXIFS",
        "LET",
        "LAMBDA",
        "MAP",
        "REDUCE",
        "SCAN",
        "MAKEARRAY",
        "BYROW",
        "BYCOL",
        "ISOMITTED",
        "CHOOSEROWS",
        "CHOOSECOLS",
        "DROP",
        "TAKE",
        "EXPAND",
        "TOCOL",
        "TOROW",
        "WRAPROWS",
        "WRAPCOLS",
        "TEXTSPLIT",
        "TEXTBEFORE",
        "TEXTAFTER",
        "VSTACK",
        "HSTACK",
    ];

    let mut result = String::with_capacity(formula.len() + 16);
    let mut chars = formula.chars().peekable();
    let mut in_string = false;

    while let Some(ch) = chars.next() {
        if ch == '"' {
            in_string = !in_string;
            result.push(ch);
            continue;
        }
        if !in_string && (ch.is_alphabetic() || ch == '_') {
            let mut word = String::new();
            word.push(ch);
            while let Some(&next_ch) = chars.peek() {
                if next_ch.is_alphanumeric() || next_ch == '.' || next_ch == '_' {
                    if let Some(nc) = chars.next() {
                        word.push(nc);
                    }
                } else {
                    break;
                }
            }
            if chars.peek() == Some(&'(') {
                let upper = word.to_uppercase();
                if !upper.starts_with("_XLFN.") && FUTURE_FUNCTIONS.contains(&upper.as_str()) {
                    result.push_str("_xlfn.");
                }
            }
            result.push_str(&word);
        } else {
            result.push(ch);
        }
    }
    result
}

fn call_if(
    arguments: &[Node],
    sheet: &str,
    source: &dyn ValueSource,
) -> std::result::Result<CellValue, Reason> {
    let Some(condition) = arguments.first() else {
        return Err("IF() needs a condition".to_string());
    };
    let value = eval(condition, sheet, source)?;
    if is_error(&value) {
        // An error in the condition propagates; it is not a false.
        return Ok(value);
    }
    let flag = to_bool(&value)?;
    match flag {
        Some(true) => match arguments.get(1) {
            Some(branch) => eval(branch, sheet, source),
            // `IF(A1,)` is a zero-length string, not an error.
            None => Ok(CellValue::Text(String::new())),
        },
        Some(false) => match arguments.get(2) {
            Some(branch) => eval(branch, sheet, source),
            // Excel returns FALSE for a missing false-branch, not zero and not an empty string.
            None => Ok(CellValue::Bool(false)),
        },
        None => Ok(CellValue::Number(0.0)),
    }
}

fn call_iferror(
    arguments: &[Node],
    sheet: &str,
    source: &dyn ValueSource,
) -> std::result::Result<CellValue, Reason> {
    let Some(value_node) = arguments.first() else {
        return Err("IFERROR() needs a value".to_string());
    };
    match eval(value_node, sheet, source) {
        Ok(value) if is_error(&value) => match arguments.get(1) {
            Some(fallback) => eval(fallback, sheet, source),
            None => Ok(CellValue::Text(String::new())),
        },
        other => other,
    }
}

fn call_and_or(
    name: &str,
    arguments: &[Node],
    sheet: &str,
    source: &dyn ValueSource,
) -> std::result::Result<CellValue, Reason> {
    if arguments.is_empty() {
        return Err(format!("{name}() needs an argument"));
    }
    // AND needs "every value is true" and OR needs "some value is true", so both are tracked.
    // Folding them into one flag gets one of the two wrong, which is what happened first time.
    let mut any_true = false;
    let mut all_true = true;
    let mut seen = false;
    for argument in arguments {
        // A range contributes each of its values, so `AND(A1:A3)` checks three cells.
        let values = match argument {
            Node::Reference(reference_sheet, body) => {
                match resolve(reference_sheet.as_deref().unwrap_or(sheet), body, source)? {
                    Resolved::Single(value) => vec![value],
                    Resolved::Range { values, .. } => values,
                }
            }
            other => vec![eval(other, sheet, source)?],
        };
        for value in values {
            if is_error(&value) {
                return Ok(value);
            }
            if let CellValue::Text(text) = &value {
                // Text in a reference is ignored by AND and OR, matching Excel; a literal
                // `AND("x")` is still `#VALUE!`.
                if matches!(argument, Node::Reference(_, _)) {
                    continue;
                }
                return Err(format!("#VALUE! cannot read {text:?} as a condition"));
            }
            // A blank is not a condition: it neither satisfies nor breaks either, which is
            // what `seen` tracks.
            if let Some(flag) = to_bool(&value)? {
                seen = true;
                any_true |= flag;
                all_true &= flag;
            }
        }
    }
    if !seen {
        // Excel's AND() over nothing but blanks is TRUE, and OR() is FALSE.
        return Ok(CellValue::Bool(name == "AND"));
    }
    Ok(CellValue::Bool(if name == "AND" {
        all_true
    } else {
        any_true
    }))
}

/// Excel's coercion to a condition: `None` for a blank, which the callers treat as zero.
fn to_bool(value: &CellValue) -> std::result::Result<Option<bool>, Reason> {
    match value {
        CellValue::Bool(flag) => Ok(Some(*flag)),
        CellValue::Number(number) => Ok(Some(*number != 0.0)),
        CellValue::None => Ok(None),
        CellValue::Text(text) => Err(format!("#VALUE! cannot read {text:?} as a condition")),
        CellValue::Error(code) => Err(code.clone()),
        other => Err(format!("#VALUE! cannot use {other:?} as a condition")),
    }
}

/// Excel rounds half away from zero, which Rust's `round` does not do for negatives.
fn round(value: f64, places: f64, mode: &str) -> f64 {
    let factor = 10f64.powi(places as i32);
    let scaled = value * factor;
    let rounded = match mode {
        "ROUNDUP" => {
            if scaled >= 0.0 {
                scaled.ceil()
            } else {
                scaled.floor()
            }
        }
        "ROUNDDOWN" => {
            if scaled >= 0.0 {
                scaled.floor()
            } else {
                scaled.ceil()
            }
        }
        _ => {
            if scaled >= 0.0 {
                (scaled + 0.5).floor()
            } else {
                // Away from zero, so -2.5 rounds to -3 rather than -2.
                (scaled - 0.5).ceil()
            }
        }
    };
    rounded / factor
}

#[cfg(test)]
mod tests {
    use super::*;
    use std::collections::BTreeMap;

    /// A source backed by a map, so a test can write `A1=1` and read what the formula made of it.
    struct Map(BTreeMap<String, CellValue>);

    impl Map {
        fn new() -> Self {
            let mut cells = BTreeMap::new();
            for (coordinate, value) in [
                ("A1", CellValue::Number(1.0)),
                ("A2", CellValue::Number(2.0)),
                ("A3", CellValue::Number(3.0)),
                ("B1", CellValue::Text("hello".to_string())),
                ("B2", CellValue::Text("  padded  ".to_string())),
                ("C1", CellValue::Bool(true)),
                ("C2", CellValue::Bool(false)),
                ("A4", CellValue::Number(0.0)),
            ] {
                cells.insert(coordinate.to_string(), value);
            }
            Map(cells)
        }

        fn set(&mut self, coordinate: &str, value: CellValue) {
            self.0.insert(coordinate.to_string(), value);
        }
    }

    impl ValueSource for Map {
        fn cell(&self, _sheet: &str, coordinate: &str) -> CellValue {
            self.0.get(coordinate).cloned().unwrap_or(CellValue::None)
        }

        fn max_row(&self, _sheet: &str) -> Option<u32> {
            let mut max = 1u32;
            for coord in self.0.keys() {
                if let Ok((_col, row)) = crate::cell::utils::coordinate_from_string(coord) {
                    if row > max {
                        max = row;
                    }
                }
            }
            Some(max)
        }
    }

    fn value(formula: &str) -> CellValue {
        let source = Map::new();
        evaluate(formula, "Sheet1", &source).unwrap_or_else(|reason| panic!("{formula}: {reason}"))
    }

    /// The reason a formula could not be evaluated, if it could not be.
    fn reason(formula: &str) -> Option<String> {
        let source = Map::new();
        evaluate(formula, "Sheet1", &source).err()
    }

    fn number(formula: &str) -> f64 {
        match value(formula) {
            CellValue::Number(v) => v,
            other => panic!("{formula} gave {other:?}, not a number"),
        }
    }

    fn text(formula: &str) -> String {
        match value(formula) {
            CellValue::Text(v) => v,
            other => panic!("{formula} gave {other:?}, not text"),
        }
    }

    #[test]
    fn the_supported_list_has_no_names_the_dispatcher_lacks() {
        // A name listed but not implemented would answer `supports` with a yes and then
        // produce nothing, which is the one failure mode this list exists to prevent.
        for name in SUPPORTED_FUNCTIONS {
            let node = Node::Function(
                (*name).to_string(),
                vec![Node::Literal(CellValue::Number(1.0))],
            );
            let source = Map::new();
            let result = eval(&node, "Sheet1", &source);
            assert!(
                !matches!(result, Err(reason) if reason.starts_with("unsupported function")),
                "{name} is listed but the dispatcher refuses it"
            );
        }
        assert_eq!(SUPPORTED_FUNCTIONS.len(), 44, "the list grew or shrank");
    }

    #[test]
    fn arithmetic_follows_the_usual_precedence() {
        assert_eq!(number("=1+2*3"), 7.0);
        assert_eq!(number("=(1+2)*3"), 9.0);
        assert_eq!(number("=2^3^2"), 64.0, "Excel's ^ is left-associative");
    }

    #[test]
    fn unary_minus_binds_tighter_than_the_power() {
        // The classic Excel surprise: -2^2 is 4, because the minus applies to the 2 first.
        assert_eq!(number("=-2^2"), 4.0);
        assert_eq!(number("=-(2^2)"), -4.0);
    }

    #[test]
    fn percentages_and_blanks_behave_as_they_do_in_excel() {
        assert_eq!(number("=50%"), 0.5);
        assert_eq!(number("=E1+1"), 1.0, "a blank is zero in arithmetic");
        assert_eq!(number("=SUM(E1:E3)"), 0.0);
    }

    #[test]
    fn division_by_zero_is_an_error_rather_than_an_infinity() {
        assert!(matches!(value("=1/0"), CellValue::Error(code) if code == "#DIV/0!"));
    }

    #[test]
    fn an_error_anywhere_propagates() {
        assert!(matches!(value("=1/0+SUM(A1:A3)"), CellValue::Error(code) if code == "#DIV/0!"));
        assert!(matches!(value("=SUM(A1:A3)+1/0"), CellValue::Error(code) if code == "#DIV/0!"));
    }

    #[test]
    fn ranges_aggregate_over_their_cells() {
        assert_eq!(number("=SUM(A1:A3)"), 6.0);
        assert_eq!(number("=AVERAGE(A1:A3)"), 2.0);
        assert_eq!(number("=MIN(A1:A3)"), 1.0);
        assert_eq!(number("=MAX(A1:A3)"), 3.0);
        assert_eq!(number("=COUNT(A1:B3)"), 3.0, "text is not counted");
        // A1:B3 holds three numbers, two strings, and an empty B3.
        assert_eq!(
            number("=COUNTA(A1:B3)"),
            5.0,
            "COUNTA counts the text but not the blank"
        );
    }

    #[test]
    fn aggregating_an_empty_range_follows_excel() {
        // Not zero: Excel's AVERAGE of nothing is #DIV/0!.
        assert!(matches!(value("=AVERAGE(E1:E3)"), CellValue::Error(code) if code == "#DIV/0!"));
        assert_eq!(number("=SUM(E1:E3)"), 0.0);
        assert_eq!(number("=MIN(E1:E3)"), 0.0);
    }

    #[test]
    fn only_the_branch_if_takes_is_evaluated() {
        // Evaluating both branches is how an engine produces #DIV/0! for a formula Excel is
        // perfectly happy with. A3 is the cell holding the zero, and the division by it only
        // appears on the branch the formula does not take.
        assert_eq!(
            number("=IF(A4=0,0,1/A4)"),
            0.0,
            "the true branch avoids the division"
        );
        // The other way round: the false branch is the one that divides, and here it *is*
        // taken, so the error has to come through rather than being swallowed by laziness.
        assert!(
            matches!(value("=IF(A4<>0,0,1/A4)"), CellValue::Error(code) if code == "#DIV/0!"),
            "an error on the branch that is taken still propagates"
        );
        assert!(
            !matches!(value("=IF(A4=0,0,1/A4)"), CellValue::Error(_)),
            "the skipped branch must not raise #DIV/0!"
        );
        assert_eq!(
            number("=IF(A1=0,0,1/A1)"),
            1.0,
            "the other branch is taken normally"
        );
    }

    #[test]
    fn if_returns_false_when_the_else_branch_is_missing() {
        assert!(matches!(value("=IF(FALSE,1)"), CellValue::Bool(false)));
    }

    #[test]
    fn comparison_orders_types_with_numbers_first() {
        assert!(matches!(value("=1<\"a\""), CellValue::Bool(true)));
        assert!(matches!(value("=\"a\"<TRUE"), CellValue::Bool(true)));
        // Text compares case-insensitively.
        assert!(matches!(value("=\"ABC\"=\"abc\""), CellValue::Bool(true)));
        assert!(matches!(value("=\"a\"=\"b\""), CellValue::Bool(false)));
    }

    #[test]
    fn a_blank_compares_as_zero_against_a_number() {
        assert!(matches!(value("=E1=0"), CellValue::Bool(true)));
    }

    #[test]
    fn text_functions_behave() {
        assert_eq!(text("=UPPER(B1)"), "HELLO");
        assert_eq!(text("=LOWER(B1)"), "hello");
        assert_eq!(text("=LEFT(B1,2)"), "he");
        assert_eq!(text("=RIGHT(B1,3)"), "llo");
        assert_eq!(text("=LEFT(B1)"), "h");
        assert_eq!(number("=LEN(B1)"), 5.0);
        // TRIM collapses internal runs too, not just the ends.
        assert_eq!(text("=TRIM(B2)"), "padded");
    }

    #[test]
    fn concatenation_renders_numbers_the_way_a_cell_shows_them() {
        // A raw float would give `2.5` correctly but `2` as `2.0`, which is visible.
        assert_eq!(text("=1+1&\"\""), "2");
        assert_eq!(text("=\"n=\"&1&\"\" "), "n=1");
        assert_eq!(text("=A1&B1"), "1hello");
    }

    #[test]
    fn rounding_goes_away_from_zero_on_a_half() {
        assert_eq!(number("=ROUND(2.5)"), 3.0);
        assert_eq!(number("=ROUND(-2.5)"), -3.0, "Rust's round would say -2");
        assert_eq!(number("=ROUND(2.345,2)"), 2.35);
        assert_eq!(number("=ROUNDUP(2.1)"), 3.0);
        assert_eq!(number("=ROUNDDOWN(2.9)"), 2.0);
    }

    #[test]
    fn mod_follows_the_divisors_sign() {
        assert_eq!(number("=MOD(-3,2)"), 1.0);
        assert_eq!(number("=MOD(3,-2)"), -1.0);
        assert!(matches!(value("=MOD(1,0)"), CellValue::Error(code) if code == "#DIV/0!"));
    }

    #[test]
    fn iferror_replaces_an_error_and_leaves_everything_else_alone() {
        assert_eq!(number("=IFERROR(1/0,7)"), 7.0);
        assert_eq!(number("=IFERROR(1/2,7)"), 0.5);
    }

    #[test]
    fn and_or_and_not_read_conditions() {
        assert!(matches!(value("=AND(TRUE,TRUE)"), CellValue::Bool(true)));
        assert!(matches!(value("=AND(TRUE,FALSE)"), CellValue::Bool(false)));
        assert!(matches!(value("=OR(FALSE,TRUE)"), CellValue::Bool(true)));
        assert!(matches!(value("=NOT(TRUE)"), CellValue::Bool(false)));
        // A range contributes each cell.
        assert!(matches!(value("=AND(C1:C2)"), CellValue::Bool(false)));
    }

    #[test]
    fn an_unsupported_function_is_reported_rather_than_guessed_at() {
        // The whole reason this module can be trusted: a formula it does not understand gets
        // no value, not a plausible one.
        let source = Map::new();
        let result = evaluate("=WEBSERVICE(A1)", "Sheet1", &source);
        assert_eq!(
            result,
            Err("unsupported function WEBSERVICE()".to_string()),
            "WEBSERVICE must not produce a value"
        );
    }

    #[test]
    fn vlookup_and_xlookup_and_index_match() {
        let mut source = Map::new();
        // A1=10, B1=100; A2=20, B2=200; A3=30, B3=300
        source.set("A1", CellValue::Number(10.0));
        source.set("B1", CellValue::Number(100.0));
        source.set("A2", CellValue::Number(20.0));
        source.set("B2", CellValue::Number(200.0));
        source.set("A3", CellValue::Number(30.0));
        source.set("B3", CellValue::Number(300.0));

        assert_eq!(
            evaluate("=VLOOKUP(20, A1:B3, 2, FALSE)", "Sheet1", &source).unwrap(),
            CellValue::Number(200.0)
        );
        assert_eq!(
            evaluate("=XLOOKUP(30, A1:A3, B1:B3)", "Sheet1", &source).unwrap(),
            CellValue::Number(300.0)
        );
        assert_eq!(
            evaluate("=MATCH(20, A1:A3, 0)", "Sheet1", &source).unwrap(),
            CellValue::Number(2.0)
        );
        assert_eq!(
            evaluate("=INDEX(B1:B3, 2)", "Sheet1", &source).unwrap(),
            CellValue::Number(200.0)
        );
        assert_eq!(
            evaluate("=SUMIF(A1:A3, \">15\", B1:B3)", "Sheet1", &source).unwrap(),
            CellValue::Number(500.0)
        );
        assert_eq!(
            evaluate("=COUNTIF(A1:A3, \">15\")", "Sheet1", &source).unwrap(),
            CellValue::Number(2.0)
        );
        assert_eq!(
            evaluate("=CHOOSE(2, \"a\", \"b\", \"c\")", "Sheet1", &source).unwrap(),
            CellValue::Text("b".to_string())
        );
        assert_eq!(
            evaluate("=ISNUMBER(A1)", "Sheet1", &source).unwrap(),
            CellValue::Bool(true)
        );
        assert_eq!(
            evaluate("=ISTEXT(A1)", "Sheet1", &source).unwrap(),
            CellValue::Bool(false)
        );
    }

    #[test]
    fn a_sheet_qualified_reference_is_read() {
        let source = Map::new();
        let value = evaluate("=Other!A1", "Other", &source).expect("A1 on that sheet");
        assert_eq!(value, CellValue::Number(1.0));
    }

    #[test]
    fn absolute_references_are_accepted() {
        let source = Map::new();
        let value = evaluate("=SUM($A$1:$A$3)", "Sheet1", &source).expect("the range");
        assert_eq!(value, CellValue::Number(6.0));
    }

    #[test]
    fn text_is_parsed_with_doubled_quotes_inside_it() {
        assert_eq!(text("=\"say \"\"hi\"\"\""), "say \"hi\"");
    }

    #[test]
    fn a_formula_that_cannot_be_parsed_is_an_error_not_a_value() {
        let source = Map::new();
        assert!(evaluate("=1+", "Sheet1", &source).is_err());
        assert!(evaluate("=SUM(", "Sheet1", &source).is_err());
        assert!(evaluate("=1 1", "Sheet1", &source).is_err());
    }

    #[test]
    fn the_formula_may_be_written_with_or_without_its_leading_equals() {
        let source = Map::new();
        assert_eq!(
            evaluate("1+1", "Sheet1", &source).expect("no leading equals"),
            CellValue::Number(2.0)
        );
        assert_eq!(
            evaluate("=1+1", "Sheet1", &source).expect("a leading equals"),
            CellValue::Number(2.0)
        );
    }

    #[test]
    fn a_cell_reference_to_a_cell_holding_a_formula_is_not_followed() {
        // Reading it would need the recalculation order, which this module does not have. A
        // missing value is visible; a stale one is not.
        let mut source = Map::new();
        source.set("D1", CellValue::Formula("=1+1".to_string()));
        assert_eq!(
            evaluate("=D1", "Sheet1", &source).expect("the reference itself is fine"),
            CellValue::None,
            "a cell holding a formula reads as blank, not as its unevaluated text"
        );
    }

    #[test]
    fn scientific_notation_is_read() {
        assert_eq!(number("=1.5E2"), 150.0);
        assert!(reason("=1+").is_some());
    }

    #[test]
    fn functions_and_references_are_told_apart_by_the_bracket() {
        // `SUM` with no bracket is a name, and a name is not a value.
        let source = Map::new();
        assert!(
            evaluate("=SUM", "Sheet1", &source).is_err(),
            "a bare name is not a value"
        );
    }

    #[test]
    fn whole_column_reference_clips_to_used_range() {
        let mut source = Map::new();
        source.set("A1", CellValue::Number(10.0));
        source.set("A2", CellValue::Number(25.0));
        source.set("A3", CellValue::Number(15.0));
        let val = evaluate("=SUM(A:A)", "Sheet1", &source).unwrap();
        assert_eq!(val, CellValue::Number(50.0));
    }

    #[test]
    fn sumifs_and_countifs_evaluate_multi_criteria() {
        let mut source = Map::new();
        source.set("A1", CellValue::Text("Apple".into()));
        source.set("B1", CellValue::Number(10.0));
        source.set("C1", CellValue::Text("North".into()));

        source.set("A2", CellValue::Text("Banana".into()));
        source.set("B2", CellValue::Number(20.0));
        source.set("C2", CellValue::Text("South".into()));

        source.set("A3", CellValue::Text("Apple".into()));
        source.set("B3", CellValue::Number(30.0));
        source.set("C3", CellValue::Text("North".into()));

        let sum_res = evaluate(
            "=SUMIFS(B1:B3, A1:A3, \"Apple\", C1:C3, \"North\")",
            "Sheet1",
            &source,
        )
        .unwrap();
        assert_eq!(sum_res, CellValue::Number(40.0));

        let count_res = evaluate(
            "=COUNTIFS(A1:A3, \"Apple\", C1:C3, \"North\")",
            "Sheet1",
            &source,
        )
        .unwrap();
        assert_eq!(count_res, CellValue::Number(2.0));
    }

    #[test]
    fn quoted_and_unicode_sheet_names_resolve() {
        struct UnicodeSource;
        impl ValueSource for UnicodeSource {
            fn cell(&self, sheet: &str, coordinate: &str) -> CellValue {
                if sheet == "Master Cash Book (रोकड़ बही)" && coordinate == "K473" {
                    CellValue::Number(21600.0)
                } else {
                    CellValue::None
                }
            }
        }
        let source = UnicodeSource;
        let res = evaluate(
            "='Master Cash Book (रोकड़ बही)'!K473 + 100",
            "Sheet1",
            &source,
        )
        .unwrap();
        assert_eq!(res, CellValue::Number(21700.0));
    }

    #[test]
    fn recalculation_counts_and_reasons_are_reported() {
        let mut sheet = BTreeMap::new();
        sheet.insert("A1".to_string(), CellValue::Number(1.0));
        let mut computed = BTreeMap::new();
        computed.insert("Sheet1".to_string(), sheet);
        let report = Recalculation {
            computed,
            unresolved: vec![
                Unresolved {
                    sheet: "Sheet1".into(),
                    coordinate: "A2".into(),
                    formula: "=VLOOKUP(1,A:B,2)".into(),
                    reason: "unsupported function VLOOKUP()".into(),
                },
                Unresolved {
                    sheet: "Sheet1".into(),
                    coordinate: "A3".into(),
                    formula: "=XLOOKUP(1,A:B)".into(),
                    reason: "unsupported function VLOOKUP()".into(),
                },
            ],
        };
        assert_eq!(report.computed_count(), 1);
        assert!(!report.is_complete());
        assert_eq!(
            report.reasons(),
            vec![("unsupported function VLOOKUP()".to_string(), 2)]
        );
    }
}