formualizer-parse 2.0.0

High-performance Excel/OpenFormula tokenizer + parser with a stable AST surface
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
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
#[cfg(test)]
mod tests {
    use crate::FormulaDialect;
    use crate::tokenizer::Tokenizer;
    use formualizer_common::{ExcelError, LiteralValue};

    use crate::parser::{ASTNode, ASTNodeType, Parser, ParserError, ReferenceType};
    use crate::parser::{CollectPolicy, RefView};

    // Helper function to parse a formula
    fn parse_formula(formula: &str) -> Result<ASTNode, ParserError> {
        let tokenizer = Tokenizer::new(formula).map_err(|e| ParserError {
            message: e.to_string(),
            position: Some(e.pos),
        })?;
        let mut parser = Parser::new(tokenizer.items, false);
        parser.parse()
    }

    fn parse_formula_with_dialect(
        formula: &str,
        dialect: FormulaDialect,
    ) -> Result<ASTNode, ParserError> {
        let tokenizer = Tokenizer::new_with_dialect(formula, dialect).map_err(|e| ParserError {
            message: e.to_string(),
            position: Some(e.pos),
        })?;
        let mut parser = Parser::new_with_dialect(tokenizer.items, false, dialect);
        parser.parse()
    }

    #[test]
    fn parser_rejects_best_effort_invalid_spans() {
        let tokenizer = Tokenizer::new_best_effort("=A1+)");
        let mut parser = Parser::new(tokenizer.items, false);
        let err = parser.parse().unwrap_err();
        assert!(err.message.contains("Unexpected"));
    }

    #[test]
    fn parser_accepts_lowercase_error_literals() {
        let ast = parse_formula("=#ref!").expect("parse lowercase error literal");
        match ast.node_type {
            ASTNodeType::Literal(LiteralValue::Error(e)) => {
                assert_eq!(e.kind, ExcelError::new_ref().kind)
            }
            other => panic!("expected error literal, got {other:?}"),
        }
    }

    #[test]
    fn parser_accepts_sheet_prefixed_lowercase_error_literal() {
        // Sheet-qualified error literals collapse to the bare error literal,
        // preserving the error kind (here `#ref!` -> ExcelError::Ref).
        let ast = parse_formula("=source!#ref!").expect("parse sheet-prefixed lowercase");
        match ast.node_type {
            ASTNodeType::Literal(LiteralValue::Error(e)) => {
                assert_eq!(e.kind, ExcelError::new_ref().kind);
            }
            other => panic!("expected error literal, got {other:?}"),
        }
    }

    mod sheet_qualified_errors {
        use super::parse_formula;
        use crate::parser::{ASTNode, ASTNodeType, Parser};
        use crate::tokenizer::Tokenizer;
        use formualizer_common::{ExcelErrorKind, LiteralValue};

        fn parse_span(formula: &str) -> Result<ASTNode, crate::parser::ParserError> {
            crate::parser::parse(formula)
        }

        fn assert_error_kind(formula: &str, expected: ExcelErrorKind) {
            for (label, ast) in [
                ("classic", parse_formula(formula).expect("classic parse")),
                ("span", parse_span(formula).expect("span parse")),
            ] {
                match ast.node_type {
                    ASTNodeType::Literal(LiteralValue::Error(e)) => {
                        assert_eq!(e.kind, expected, "{label} parser kind for {formula:?}");
                    }
                    other => panic!(
                        "{label} parser: expected error literal for {formula:?}, got {other:?}"
                    ),
                }
            }
        }

        #[test]
        fn test_sheet_qualified_ref_error() {
            assert_error_kind("=Sheet1!#REF!", ExcelErrorKind::Ref);
        }

        #[test]
        fn test_quoted_sheet_qualified_ref_error() {
            assert_error_kind("='My Sheet'!#REF!", ExcelErrorKind::Ref);
        }

        #[test]
        fn test_sheet_qualified_div_error() {
            assert_error_kind("=Sheet1!#DIV/0!", ExcelErrorKind::Div);
        }

        #[test]
        fn test_sheet_qualified_value_error() {
            assert_error_kind("=Sheet1!#VALUE!", ExcelErrorKind::Value);
        }

        #[test]
        fn test_sheet_qualified_name_error() {
            assert_error_kind("=Sheet1!#NAME?", ExcelErrorKind::Name);
        }

        #[test]
        fn test_sheet_qualified_lowercase() {
            assert_error_kind("=sheet1!#ref!", ExcelErrorKind::Ref);
        }

        #[test]
        fn test_external_sheet_qualified_error() {
            assert_error_kind("=[1]Sheet1!#REF!", ExcelErrorKind::Ref);
        }

        #[test]
        fn negative_unknown_error_code_with_sheet_prefix() {
            // Classic and span parsers must both reject unknown error codes.
            assert!(
                parse_formula("=Sheet1!#BOGUS!").is_err(),
                "classic parser should reject unknown error code"
            );
            assert!(
                parse_span("=Sheet1!#BOGUS!").is_err(),
                "span parser should reject unknown error code"
            );
        }

        #[test]
        fn negative_empty_sheet_prefix() {
            assert!(
                parse_formula("=!#REF!").is_err(),
                "classic parser should reject empty sheet prefix"
            );
            assert!(
                parse_span("=!#REF!").is_err(),
                "span parser should reject empty sheet prefix"
            );
        }

        #[test]
        fn negative_trailing_garbage_after_error() {
            assert!(
                parse_formula("=#REF!Sheet1").is_err(),
                "classic parser should reject trailing garbage after error literal"
            );
            assert!(
                parse_span("=#REF!Sheet1").is_err(),
                "span parser should reject trailing garbage after error literal"
            );
        }

        #[test]
        fn regression_ordinary_sheet_reference_unchanged() {
            // Plain sheet-qualified cell references must not be affected.
            let ast = parse_formula("=Sheet1!A1").expect("classic parse");
            match ast.node_type {
                ASTNodeType::Reference { .. } => {}
                other => panic!("expected reference node, got {other:?}"),
            }
            let ast = parse_span("=Sheet1!A1").expect("span parse");
            match ast.node_type {
                ASTNodeType::Reference { .. } => {}
                other => panic!("expected reference node, got {other:?}"),
            }
        }

        #[test]
        fn regression_bare_error_literal_unchanged() {
            assert_error_kind("=#REF!", ExcelErrorKind::Ref);
            assert_error_kind("=#DIV/0!", ExcelErrorKind::Div);
            assert_error_kind("=#VALUE!", ExcelErrorKind::Value);
            assert_error_kind("=#N/A", ExcelErrorKind::Na);
            assert_error_kind("=#ref!", ExcelErrorKind::Ref);
        }

        #[test]
        fn cross_parser_differential() {
            // The classic and span parsers must produce identical ASTs for
            // sheet-qualified error literals across all supported forms.
            for formula in [
                "=#REF!",
                "=Sheet1!#REF!",
                "='My Sheet'!#REF!",
                "=Sheet1!#DIV/0!",
                "=[1]Sheet1!#REF!",
                "=sheet1!#ref!",
            ] {
                let classic = {
                    let tok = Tokenizer::new(formula).expect("tokenize");
                    let mut parser = Parser::new(tok.items, false);
                    parser.parse().expect("classic parse")
                };
                let span = parse_span(formula).expect("span parse");
                let classic_kind = match &classic.node_type {
                    ASTNodeType::Literal(LiteralValue::Error(e)) => e.kind,
                    other => panic!("classic non-error for {formula:?}: {other:?}"),
                };
                let span_kind = match &span.node_type {
                    ASTNodeType::Literal(LiteralValue::Error(e)) => e.kind,
                    other => panic!("span non-error for {formula:?}: {other:?}"),
                };
                assert_eq!(classic_kind, span_kind, "kind mismatch for {formula:?}");
            }
        }
    }

    #[test]
    fn parser_try_from_formula_is_fallible() {
        let err = match Parser::try_from_formula("=\"unterminated") {
            Ok(_) => panic!("expected tokenizer error"),
            Err(err) => err,
        };
        assert!(err.message.contains("Reached end"));
    }

    // Helper function to check if a formula contains a range reference with expected properties
    fn check_range_in_formula(formula: &str, range_check: impl Fn(&ReferenceType) -> bool) -> bool {
        let ast = parse_formula(formula).unwrap();
        let deps = ast.get_dependencies();

        deps.iter().any(|ref_type| match ref_type {
            ReferenceType::Range { .. } => range_check(ref_type),
            _ => false,
        })
    }

    #[test]
    fn test_contains_volatile_with_classifier() {
        let tokenizer = Tokenizer::new("=RAND()+A1").unwrap();
        let mut parser = Parser::new(tokenizer.items, false).with_volatility_classifier(|name| {
            name.eq_ignore_ascii_case("RAND")
                || name.eq_ignore_ascii_case("NOW")
                || name.eq_ignore_ascii_case("TODAY")
        });
        let ast = parser.parse().unwrap();
        assert!(ast.contains_volatile());

        let tokenizer = Tokenizer::new("=SUM(1,2,3)").unwrap();
        let mut parser = Parser::new(tokenizer.items, false)
            .with_volatility_classifier(|name| name.eq_ignore_ascii_case("RAND"));
        let ast = parser.parse().unwrap();
        assert!(!ast.contains_volatile());
    }

    #[test]
    fn test_refs_iterator_and_visitor_basic() {
        let ast = parse_formula("=A1 + SUM(B2:C3, NamedRange, Table1[Col])").unwrap();

        // Iterator should find references in stable order (left-to-right depth-first)
        let refs: Vec<RefView> = ast.refs().collect();
        assert!(!refs.is_empty());

        // Expect first is A1 cell
        match refs.first().unwrap() {
            RefView::Cell {
                sheet, row, col, ..
            } => {
                assert!(sheet.is_none());
                assert_eq!((*row, *col), (1, 1));
            }
            _ => panic!("expected first ref to be a Cell"),
        }

        // Visitor should hit same count
        let mut count = 0;
        ast.visit_refs(|_| count += 1);
        assert_eq!(count, refs.len());
    }

    #[test]
    fn test_collect_references_policy_no_expand() {
        let ast = parse_formula("=SUM(B2:C3)").unwrap();
        let policy = CollectPolicy {
            expand_small_ranges: false,
            range_expansion_limit: 0,
            include_names: true,
        };
        let refs = ast.collect_references(&policy);
        assert_eq!(refs.len(), 1);
        match &refs[0] {
            ReferenceType::Range {
                start_row,
                start_col,
                end_row,
                end_col,
                ..
            } => {
                assert_eq!(
                    (*start_row, *start_col, *end_row, *end_col),
                    (Some(2), Some(2), Some(3), Some(3))
                );
            }
            _ => panic!("expected a Range"),
        }
    }

    #[test]
    fn test_collect_references_policy_expand_small_range() {
        let ast = parse_formula("=SUM(B2:C3)").unwrap();
        let policy = CollectPolicy {
            expand_small_ranges: true,
            range_expansion_limit: 16,
            include_names: true,
        };
        let refs = ast.collect_references(&policy);
        // B2:C3 is 4 cells
        assert_eq!(refs.len(), 4);
        // Ensure cells include B2 and C3
        let mut have_b2 = false;
        let mut have_c3 = false;
        for r in refs {
            match r {
                ReferenceType::Cell { row, col, .. } if row == 2 && col == 2 => have_b2 = true,
                ReferenceType::Cell { row, col, .. } if row == 3 && col == 3 => have_c3 = true,
                _ => {}
            }
        }
        assert!(have_b2 && have_c3);
    }

    #[test]
    fn test_collect_references_policy_exclude_names() {
        let ast = parse_formula("=NamedRef + A1").unwrap();
        let policy = CollectPolicy {
            expand_small_ranges: false,
            range_expansion_limit: 0,
            include_names: false,
        };
        let refs = ast.collect_references(&policy);
        // Should only include A1
        assert_eq!(refs.len(), 1);
        match &refs[0] {
            ReferenceType::Cell { row, col, .. } => assert_eq!((*row, *col), (1, 1)),
            _ => panic!("expected a Cell ref"),
        }
    }

    #[test]
    fn test_parse_openformula_cell_reference() {
        let ast = parse_formula_with_dialect("=SUM([.A1])", FormulaDialect::OpenFormula).unwrap();

        let (name, args) = match &ast.node_type {
            ASTNodeType::Function { name, args } => (name, args),
            _ => panic!("expected Function node"),
        };

        assert_eq!(name, "SUM");
        assert_eq!(args.len(), 1);

        match &args[0].node_type {
            ASTNodeType::Reference { reference, .. } => {
                assert_eq!(reference, &ReferenceType::cell(None, 1, 1));
            }
            other => panic!("expected Reference argument, got {other:?}"),
        }
    }

    #[test]
    fn test_parse_openformula_sheet_range() {
        let ast =
            parse_formula_with_dialect("=SUM([Sheet One.A1:.B2])", FormulaDialect::OpenFormula)
                .unwrap();

        let args = match &ast.node_type {
            ASTNodeType::Function { name, args } => {
                assert_eq!(name, "SUM");
                args
            }
            _ => panic!("expected Function node"),
        };

        assert_eq!(args.len(), 1);

        match &args[0].node_type {
            ASTNodeType::Reference { reference, .. } => {
                assert_eq!(
                    reference,
                    &ReferenceType::range(
                        Some("Sheet One".to_string()),
                        Some(1),
                        Some(1),
                        Some(2),
                        Some(2),
                    )
                );
            }
            other => panic!("expected range reference, got {other:?}"),
        }
    }

    #[test]
    fn test_parse_simple_formula() {
        let ast = parse_formula("=A1+B2").unwrap();

        if let ASTNodeType::BinaryOp { op, left, right } = ast.node_type {
            assert_eq!(op, "+");

            if let ASTNodeType::Reference { reference, .. } = left.node_type {
                assert_eq!(reference, ReferenceType::cell(None, 1, 1));
            } else {
                panic!("Expected Reference node for left operand");
            }

            if let ASTNodeType::Reference { reference, .. } = right.node_type {
                assert_eq!(reference, ReferenceType::cell(None, 2, 2));
            } else {
                panic!("Expected Reference node for right operand");
            }
        } else {
            panic!("Expected BinaryOp node");
        }
    }

    #[test]
    fn test_parse_function_call() {
        let ast = parse_formula("=SUM(A1:B2)").unwrap();

        println!("AST: {ast:?}");

        if let ASTNodeType::Function { name, args } = ast.node_type {
            assert_eq!(name, "SUM");
            assert_eq!(args.len(), 1);

            if let ASTNodeType::Reference {
                original,
                reference,
            } = &args[0].node_type
            {
                assert_eq!(original, "A1:B2");
                assert_eq!(
                    reference,
                    &ReferenceType::range(None, Some(1), Some(1), Some(2), Some(2))
                );
            } else {
                panic!("Expected Reference node for function argument");
            }
        } else {
            panic!("Expected Function node");
        }
    }

    #[test]
    fn test_operator_precedence() {
        let ast = parse_formula("=A1+B2*C3").unwrap();

        if let ASTNodeType::BinaryOp {
            op: op1,
            left: left1,
            right: right1,
        } = ast.node_type
        {
            assert_eq!(op1, "+");

            if let ASTNodeType::Reference { reference, .. } = left1.node_type {
                assert_eq!(reference, ReferenceType::cell(None, 1, 1));
            } else {
                panic!("Expected Reference node for left operand of +");
            }

            if let ASTNodeType::BinaryOp {
                op: op2,
                left: left2,
                right: right2,
            } = right1.node_type
            {
                assert_eq!(op2, "*");

                if let ASTNodeType::Reference { reference, .. } = left2.node_type {
                    assert_eq!(reference, ReferenceType::cell(None, 2, 2));
                } else {
                    panic!("Expected Reference node for left operand of *");
                }

                if let ASTNodeType::Reference { reference, .. } = right2.node_type {
                    assert_eq!(reference, ReferenceType::cell(None, 3, 3));
                } else {
                    panic!("Expected Reference node for right operand of *");
                }
            } else {
                panic!("Expected BinaryOp node for right operand of +");
            }
        } else {
            panic!("Expected BinaryOp node");
        }
    }

    #[test]
    fn test_parentheses() {
        let ast = parse_formula("=(A1+B2)*C3").unwrap();

        if let ASTNodeType::BinaryOp { op, left, right } = ast.node_type {
            assert_eq!(op, "*");

            if let ASTNodeType::BinaryOp { op: inner_op, .. } = left.node_type {
                assert_eq!(inner_op, "+");
            } else {
                panic!("Expected BinaryOp node for left operand");
            }

            if let ASTNodeType::Reference { reference, .. } = right.node_type {
                assert_eq!(reference, ReferenceType::cell(None, 3, 3));
            } else {
                panic!("Expected Reference node for right operand");
            }
        } else {
            panic!("Expected BinaryOp node");
        }
    }

    #[test]
    fn test_function_multiple_args() {
        let ast = parse_formula("=IF(A1>0,B1,C1)").unwrap();

        println!("AST: {ast:?}");

        if let ASTNodeType::Function { name, args } = ast.node_type {
            assert_eq!(name, "IF");
            assert_eq!(args.len(), 3);

            // Check first argument (condition)
            if let ASTNodeType::BinaryOp { op, .. } = &args[0].node_type {
                assert_eq!(op, ">");
            } else {
                panic!("Expected BinaryOp node for first argument");
            }

            // Check second and third arguments (true/false results)
            if let ASTNodeType::Reference { reference, .. } = &args[1].node_type {
                assert_eq!(reference, &ReferenceType::cell(None, 1, 2));
            } else {
                panic!("Expected Reference node for second argument");
            }

            if let ASTNodeType::Reference { reference, .. } = &args[2].node_type {
                assert_eq!(reference, &ReferenceType::cell(None, 1, 3));
            } else {
                panic!("Expected Reference node for third argument");
            }
        } else {
            panic!("Expected Function node");
        }
    }

    #[test]
    fn test_functions_with_optional_arguments() {
        // Test with all arguments provided
        let ast = parse_formula("=VLOOKUP(A1,B1:C10,2,FALSE)").unwrap();
        if let ASTNodeType::Function { name, args } = ast.node_type {
            assert_eq!(name, "VLOOKUP");
            assert_eq!(args.len(), 4);
        } else {
            panic!("Expected Function node");
        }

        // Test with missing optional argument
        let ast = parse_formula("=VLOOKUP(A1,B1:C10,2)").unwrap();
        if let ASTNodeType::Function { name, args } = ast.node_type {
            assert_eq!(name, "VLOOKUP");
            assert_eq!(args.len(), 3);
        } else {
            panic!("Expected Function node");
        }

        // Test with multiple optional arguments - some specified, some not
        let ast = parse_formula("=IFERROR(A1/B1,)").unwrap();
        if let ASTNodeType::Function { name, args } = &ast.node_type {
            assert_eq!(name, "IFERROR");
            assert_eq!(args.len(), 2);
            // Second argument should be an empty string
            if let ASTNodeType::Literal(LiteralValue::Text(text)) = &args[1].node_type {
                assert_eq!(text, "");
            } else {
                panic!("Expected empty text literal for omitted argument");
            }
        } else {
            panic!("Expected Function node");
        }

        // Test skipping middle arguments
        let ast = parse_formula("=IF(A1>0,,C1)").unwrap();
        if let ASTNodeType::Function { name, args } = ast.node_type {
            assert_eq!(name, "IF");
            assert_eq!(args.len(), 3);
            // Middle argument should be empty
            if let ASTNodeType::Literal(LiteralValue::Text(text)) = &args[1].node_type {
                assert_eq!(text, "");
            } else {
                panic!("Expected empty text literal for omitted middle argument");
            }
        } else {
            panic!("Expected Function node");
        }

        // Test with multiple trailing empty arguments
        let ast = parse_formula("=IF(A1>0,,)").unwrap();
        if let ASTNodeType::Function { name, args } = ast.node_type {
            assert_eq!(name, "IF");
            assert_eq!(args.len(), 3);
            // Both optional arguments should be empty
            if let ASTNodeType::Literal(LiteralValue::Text(text)) = &args[1].node_type {
                assert_eq!(text, "");
            } else {
                panic!("Expected empty text literal for second argument");
            }
            if let ASTNodeType::Literal(LiteralValue::Text(text)) = &args[2].node_type {
                assert_eq!(text, "");
            } else {
                panic!("Expected empty text literal for third argument");
            }
        } else {
            panic!("Expected Function node");
        }

        // Test with complex empty arguments combination
        let ast = parse_formula("=CHOOSE(1,A1,,C1,,E1)").unwrap();
        if let ASTNodeType::Function { name, args } = ast.node_type {
            assert_eq!(name, "CHOOSE");
            assert_eq!(args.len(), 6);
            // Check the empty arguments (3rd and 5th)
            if let ASTNodeType::Literal(LiteralValue::Text(text)) = &args[2].node_type {
                assert_eq!(text, "");
            } else {
                panic!("Expected empty text literal for third argument");
            }
            if let ASTNodeType::Literal(LiteralValue::Text(text)) = &args[4].node_type {
                assert_eq!(text, "");
            } else {
                panic!("Expected empty text literal for fifth argument");
            }
        } else {
            panic!("Expected Function node");
        }
    }

    #[test]
    fn test_nested_functions() {
        let ast = parse_formula("=IF(SUM(A1:A10)>100,MAX(B1:B10),0)").unwrap();

        println!("AST: {ast:?}");

        if let ASTNodeType::Function { name, args } = ast.node_type {
            assert_eq!(name, "IF");
            assert_eq!(args.len(), 3);

            // Check first argument (SUM(...) > 100)
            if let ASTNodeType::BinaryOp { op, left, .. } = &args[0].node_type {
                assert_eq!(op, ">");

                if let ASTNodeType::Function {
                    name: inner_name, ..
                } = &left.node_type
                {
                    assert_eq!(inner_name, "SUM");
                } else {
                    panic!("Expected Function node for left side of comparison");
                }
            } else {
                panic!("Expected BinaryOp node for first argument");
            }

            // Check second argument (MAX(...))
            if let ASTNodeType::Function {
                name: inner_name, ..
            } = &args[1].node_type
            {
                assert_eq!(inner_name, "MAX");
            } else {
                panic!("Expected Function node for second argument");
            }

            // Check third argument (0)
            if let ASTNodeType::Literal(LiteralValue::Number(num)) = &args[2].node_type {
                assert_eq!(*num, 0.0);
            } else {
                panic!("Expected Number literal for third argument");
            }
        } else {
            panic!("Expected Function node");
        }
    }

    #[test]
    fn test_unary_operators() {
        let ast = parse_formula("=-A1").unwrap();

        if let ASTNodeType::UnaryOp { op, expr } = ast.node_type {
            assert_eq!(op, "-");

            if let ASTNodeType::Reference { reference, .. } = expr.node_type {
                assert_eq!(reference, ReferenceType::cell(None, 1, 1));
            } else {
                panic!("Expected Reference node for operand");
            }
        } else {
            panic!("Expected UnaryOp node");
        }
    }

    #[test]
    fn test_double_unary_operator() {
        let ast = parse_formula("=--A1").unwrap();

        if let ASTNodeType::UnaryOp { op, expr: _ } = ast.node_type {
            assert_eq!(op, "-");
        }
    }

    #[test]
    fn test_implicit_intersection_operator_parses() {
        use crate::parser::{TableReference, TableSpecifier};

        // Range
        let ast = parse_formula("=@A1:A3").unwrap();
        match ast.node_type {
            ASTNodeType::UnaryOp { op, expr } => {
                assert_eq!(op, "@");
                match expr.node_type {
                    ASTNodeType::Reference { reference, .. } => {
                        assert_eq!(
                            reference,
                            ReferenceType::range(None, Some(1), Some(1), Some(3), Some(1))
                        );
                    }
                    other => panic!("Expected Reference operand for @, got {other:?}"),
                }
            }
            other => panic!("Expected UnaryOp for implicit intersection, got {other:?}"),
        }

        // Table reference (table evaluation may be unsupported, but parsing should succeed)
        let ast = parse_formula("=@Table1[Col]").unwrap();
        match ast.node_type {
            ASTNodeType::UnaryOp { op, expr } => {
                assert_eq!(op, "@");
                match expr.node_type {
                    ASTNodeType::Reference { reference, .. } => {
                        assert_eq!(
                            reference,
                            ReferenceType::Table(TableReference {
                                name: "Table1".to_string(),
                                specifier: Some(TableSpecifier::Column("Col".to_string())),
                            })
                        );
                    }
                    other => panic!("Expected Reference operand for @, got {other:?}"),
                }
            }
            other => panic!("Expected UnaryOp for implicit intersection, got {other:?}"),
        }

        // Function call
        let ast = parse_formula("=@SEQUENCE(3,1)").unwrap();
        match ast.node_type {
            ASTNodeType::UnaryOp { op, expr } => {
                assert_eq!(op, "@");
                match expr.node_type {
                    ASTNodeType::Function { name, args } => {
                        assert_eq!(name, "SEQUENCE");
                        assert_eq!(args.len(), 2);
                    }
                    other => panic!("Expected Function operand for @, got {other:?}"),
                }
            }
            other => panic!("Expected UnaryOp for implicit intersection, got {other:?}"),
        }
    }

    #[test]
    fn test_infinite_range_formulas() {
        // Column-wise infinite range (A:A)
        let formula = "=SUM(A:A)";
        let ast = parse_formula(formula).unwrap();

        if let ASTNodeType::Function { name, args } = ast.node_type {
            assert_eq!(name, "SUM");
            assert_eq!(args.len(), 1);

            if let ASTNodeType::Reference { reference, .. } = &args[0].node_type {
                if let ReferenceType::Range {
                    start_col,
                    end_col,
                    start_row,
                    end_row,
                    ..
                } = reference
                {
                    assert_eq!(*start_col, Some(1));
                    assert_eq!(*end_col, Some(1));
                    assert_eq!(*start_row, None);
                    assert_eq!(*end_row, None);
                } else {
                    panic!("Expected Range reference");
                }
            } else {
                panic!("Expected Reference node");
            }
        } else {
            panic!("Expected Function node");
        }

        // Row-wise infinite range (1:1)
        let formula = "=SUM(1:1)";
        let ast = parse_formula(formula).unwrap();

        if let ASTNodeType::Function { name, args } = ast.node_type {
            assert_eq!(name, "SUM");
            assert_eq!(args.len(), 1);

            if let ASTNodeType::Reference { reference, .. } = &args[0].node_type {
                if let ReferenceType::Range {
                    start_col,
                    end_col,
                    start_row,
                    end_row,
                    ..
                } = reference
                {
                    assert_eq!(*start_col, None);
                    assert_eq!(*end_col, None);
                    assert_eq!(*start_row, Some(1));
                    assert_eq!(*end_row, Some(1));
                } else {
                    panic!("Expected Range reference");
                }
            } else {
                panic!("Expected Reference node");
            }
        } else {
            panic!("Expected Function node");
        }

        // Partially bounded range (A1:A)
        let formula = "=SUM(A1:A)";
        assert!(check_range_in_formula(formula, |r| {
            if let ReferenceType::Range {
                start_col,
                end_col,
                start_row,
                end_row,
                ..
            } = r
            {
                return *start_col == Some(1)
                    && *end_col == Some(1)
                    && *start_row == Some(1)
                    && end_row.is_none();
            }
            false
        }));

        // Partially bounded range (A:A10)
        let formula = "=SUM(A:A10)";
        assert!(check_range_in_formula(formula, |r| {
            if let ReferenceType::Range {
                start_col,
                end_col,
                start_row,
                end_row,
                ..
            } = r
            {
                return *start_col == Some(1)
                    && *end_col == Some(1)
                    && start_row.is_none()
                    && *end_row == Some(10);
            }
            false
        }));

        // Sheet reference with infinite range
        let formula = "=SUM(Sheet1!A:A)";
        assert!(check_range_in_formula(formula, |r| {
            if let ReferenceType::Range {
                sheet,
                start_col,
                end_col,
                start_row,
                end_row,
                ..
            } = r
            {
                return sheet.as_ref().is_some_and(|s| s == "Sheet1")
                    && *start_col == Some(1)
                    && *end_col == Some(1)
                    && start_row.is_none()
                    && end_row.is_none();
            }
            false
        }));
    }

    #[test]
    fn test_array_literal() {
        let ast = parse_formula("={1,2;3,4}").unwrap();

        if let ASTNodeType::Array(rows) = ast.node_type {
            assert_eq!(rows.len(), 2);
            assert_eq!(rows[0].len(), 2);
            assert_eq!(rows[1].len(), 2);

            // Check values in the array
            if let ASTNodeType::Literal(LiteralValue::Number(num)) = &rows[0][0].node_type {
                assert_eq!(*num, 1.0);
            } else {
                panic!("Expected Number literal for [0][0]");
            }

            if let ASTNodeType::Literal(LiteralValue::Number(num)) = &rows[1][1].node_type {
                assert_eq!(*num, 4.0);
            } else {
                panic!("Expected Number literal for [1][1]");
            }
        } else {
            panic!("Expected Array node");
        }
    }

    #[test]
    fn test_complex_formula() {
        let ast = parse_formula("=IF(AND(A1>0,B1<10),SUM(C1:C10)/COUNT(C1:C10),\"N/A\")").unwrap();

        println!("AST: {ast:?}");

        if let ASTNodeType::Function { name, args } = ast.node_type {
            assert_eq!(name, "IF");
            assert_eq!(args.len(), 3);

            // Check first argument (AND(...))
            if let ASTNodeType::Function {
                name: inner_name, ..
            } = &args[0].node_type
            {
                assert_eq!(inner_name, "AND");
            } else {
                panic!("Expected Function node for first argument");
            }

            // Check second argument (SUM(...)/COUNT(...))
            if let ASTNodeType::BinaryOp { op, .. } = &args[1].node_type {
                assert_eq!(op, "/");
            } else {
                panic!("Expected BinaryOp node for second argument");
            }

            // Check third argument ("N/A")
            if let ASTNodeType::Literal(LiteralValue::Text(text)) = &args[2].node_type {
                assert_eq!(text, "N/A");
            } else {
                panic!("Expected Text literal for third argument");
            }
        } else {
            panic!("Expected Function node");
        }
    }

    #[test]
    fn test_error_handling() {
        let result = parse_formula("=SUM(A1:B2");
        assert!(result.is_err());

        let result = parse_formula("=A1+");
        assert!(result.is_err());
    }

    #[test]
    fn test_whitespace_handling() {
        let ast = parse_formula("= A1 + B2 ").unwrap();

        if let ASTNodeType::BinaryOp { op, left, right } = ast.node_type {
            assert_eq!(op, "+");

            if let ASTNodeType::Reference { reference, .. } = left.node_type {
                assert_eq!(reference, ReferenceType::cell(None, 1, 1));
            } else {
                panic!("Expected Reference node for left operand");
            }

            if let ASTNodeType::Reference { reference, .. } = right.node_type {
                assert_eq!(reference, ReferenceType::cell(None, 2, 2));
            } else {
                panic!("Expected Reference node for right operand");
            }
        } else {
            panic!("Expected BinaryOp node");
        }
    }

    #[test]
    fn test_string_literals() {
        let ast = parse_formula("=\"Hello\"").unwrap();

        if let ASTNodeType::Literal(LiteralValue::Text(text)) = ast.node_type {
            assert_eq!(text, "Hello");
        } else {
            panic!("Expected Text literal");
        }

        // Test string with escaped quotes
        let ast = parse_formula("=\"Hello\"\"World\"").unwrap();

        if let ASTNodeType::Literal(LiteralValue::Text(text)) = ast.node_type {
            assert_eq!(text, "Hello\"World");
        } else {
            panic!("Expected Text literal");
        }
    }

    #[test]
    fn test_boolean_literals() {
        let ast = parse_formula("=TRUE").unwrap();

        if let ASTNodeType::Literal(LiteralValue::Boolean(value)) = ast.node_type {
            assert!(value);
        } else {
            panic!("Expected Boolean literal");
        }

        let ast = parse_formula("=FALSE").unwrap();

        if let ASTNodeType::Literal(LiteralValue::Boolean(value)) = ast.node_type {
            assert!(!value);
        } else {
            panic!("Expected Boolean literal");
        }

        // Lowercase/mixed-case forms must also parse as boolean literals (Excel
        // is case-insensitive for TRUE/FALSE).
        for (formula, expected) in [
            ("=true", true),
            ("=false", false),
            ("=True", true),
            ("=TrUe", true),
            ("=fAlSe", false),
        ] {
            let ast = parse_formula(formula).unwrap();
            match ast.node_type {
                ASTNodeType::Literal(LiteralValue::Boolean(v)) => {
                    assert_eq!(v, expected, "classic parser: {formula}");
                }
                other => {
                    panic!("classic parser: expected Boolean literal for {formula}, got {other:?}")
                }
            }

            let ast = crate::parser::parse(formula).unwrap();
            match ast.node_type {
                ASTNodeType::Literal(LiteralValue::Boolean(v)) => {
                    assert_eq!(v, expected, "span parser: {formula}");
                }
                other => {
                    panic!("span parser: expected Boolean literal for {formula}, got {other:?}")
                }
            }
        }
    }

    #[test]
    fn test_lowercase_boolean_in_function_call() {
        type ParseFn = fn(&str) -> Result<ASTNode, ParserError>;
        let parsers: [ParseFn; 2] = [parse_formula, |s| crate::parser::parse(s)];
        for parse in parsers {
            let ast = parse("=IF(true,1,2)").unwrap();
            let ASTNodeType::Function { name, args } = ast.node_type else {
                panic!("expected Function node");
            };
            assert_eq!(name, "IF");
            assert_eq!(args.len(), 3);
            match &args[0].node_type {
                ASTNodeType::Literal(LiteralValue::Boolean(true)) => {}
                other => panic!("expected Boolean(true) as first arg, got {other:?}"),
            }
        }
    }

    #[test]
    fn test_lowercase_boolean_in_binary_op() {
        type ParseFn = fn(&str) -> Result<ASTNode, ParserError>;
        let parsers: [ParseFn; 2] = [parse_formula, |s| crate::parser::parse(s)];
        for parse in parsers {
            let ast = parse("=a1+true").unwrap();
            let ASTNodeType::BinaryOp { op, left, right } = ast.node_type else {
                panic!("expected BinaryOp node");
            };
            assert_eq!(op, "+");
            match &left.node_type {
                ASTNodeType::Reference { .. } => {}
                other => panic!("expected Reference on lhs, got {other:?}"),
            }
            match &right.node_type {
                ASTNodeType::Literal(LiteralValue::Boolean(true)) => {}
                other => panic!("expected Boolean(true) on rhs, got {other:?}"),
            }
        }
    }

    #[test]
    fn test_named_ranges_containing_bool_substrings_are_not_booleans() {
        type ParseFn = fn(&str) -> Result<ASTNode, ParserError>;
        let parsers: [ParseFn; 2] = [parse_formula, |s| crate::parser::parse(s)];
        for parse in parsers {
            for name in ["TRUENAME", "trueish", "NOT_TRUE", "false_positive"] {
                let formula = format!("={name}");
                let ast = parse(&formula).unwrap();
                match &ast.node_type {
                    ASTNodeType::Reference {
                        reference: ReferenceType::NamedRange(actual),
                        ..
                    } => {
                        assert_eq!(actual, name, "formula {formula}");
                    }
                    other => panic!("expected NamedRange({name}), got {other:?}"),
                }
            }
        }
    }

    #[test]
    fn test_error_literals() {
        let ast = parse_formula("=#DIV/0!").unwrap();

        if let ASTNodeType::Literal(LiteralValue::Error(error)) = ast.node_type {
            assert_eq!(error, ExcelError::new_div());
        } else {
            panic!("Expected Error literal");
        }
    }

    #[test]
    fn test_empty_function_arguments() {
        // Parsing a function call with an empty argument list.
        let ast = parse_formula("=SUM()").unwrap();
        if let ASTNodeType::Function { name, args } = ast.node_type {
            assert_eq!(name, "SUM");
            assert_eq!(args.len(), 0);
        } else {
            panic!("Expected a Function node");
        }
    }

    mod modern_error_literals {
        use super::*;
        use formualizer_common::ExcelErrorKind;

        fn expect_error_kind(ast: &ASTNode, expected: ExcelErrorKind) {
            match &ast.node_type {
                ASTNodeType::Literal(LiteralValue::Error(e)) => {
                    assert_eq!(e.kind, expected);
                }
                other => panic!("expected error literal, got {other:?}"),
            }
        }

        fn parse_both(formula: &str) -> ASTNode {
            let token_ast =
                parse_formula(formula).unwrap_or_else(|e| panic!("token parse {formula}: {e:?}"));
            let span_ast = crate::parser::parse(formula)
                .unwrap_or_else(|e| panic!("span parse {formula}: {e:?}"));
            assert_eq!(
                token_ast.node_type, span_ast.node_type,
                "token and span parsers diverged for {formula}"
            );
            token_ast
        }

        #[test]
        fn spill_literal_parses() {
            let ast = parse_both("=#SPILL!");
            expect_error_kind(&ast, ExcelErrorKind::Spill);
        }

        #[test]
        fn spill_literal_lowercase_parses() {
            let ast = parse_both("=#spill!");
            expect_error_kind(&ast, ExcelErrorKind::Spill);
        }

        #[test]
        fn calc_literal_parses() {
            let ast = parse_both("=#CALC!");
            expect_error_kind(&ast, ExcelErrorKind::Calc);
        }

        #[test]
        fn calc_literal_lowercase_parses() {
            let ast = parse_both("=#calc!");
            expect_error_kind(&ast, ExcelErrorKind::Calc);
        }

        #[test]
        fn spill_in_iferror_function_argument() {
            let ast = parse_both("=IFERROR(A1, #SPILL!)");
            match ast.node_type {
                ASTNodeType::Function { name, args } => {
                    assert_eq!(name, "IFERROR");
                    assert_eq!(args.len(), 2);
                    expect_error_kind(&args[1], ExcelErrorKind::Spill);
                }
                other => panic!("expected IFERROR call, got {other:?}"),
            }
        }

        #[test]
        fn calc_in_arithmetic_expression() {
            // Nonsensical semantically, but must parse syntactically.
            let ast = parse_both("=#CALC! + 1");
            match ast.node_type {
                ASTNodeType::BinaryOp { op, left, right } => {
                    assert_eq!(op, "+");
                    expect_error_kind(&left, ExcelErrorKind::Calc);
                    match right.node_type {
                        ASTNodeType::Literal(LiteralValue::Int(n)) => assert_eq!(n, 1),
                        ASTNodeType::Literal(LiteralValue::Number(n)) => assert_eq!(n, 1.0),
                        ref other => panic!("expected numeric 1, got {other:?}"),
                    }
                }
                other => panic!("expected binary op, got {other:?}"),
            }
        }

        #[test]
        fn bogus_modern_error_is_rejected_by_parser() {
            assert!(parse_formula("=#BOGUS!").is_err());
            assert!(crate::parser::parse("=#BOGUS!").is_err());
        }

        #[test]
        fn typo_spil_rejected_by_parser() {
            assert!(parse_formula("=#SPIL!").is_err());
            assert!(crate::parser::parse("=#SPIL!").is_err());
        }

        #[test]
        fn spill_display_roundtrips_to_excel_literal() {
            // Display of the kind matches the canonical Excel literal.
            assert_eq!(format!("{}", ExcelErrorKind::Spill), "#SPILL!");
            assert_eq!(format!("{}", ExcelErrorKind::Calc), "#CALC!");
        }
    }

    mod spill_operator {
        use super::parse_formula;
        use crate::parser::{ASTNodeType, ReferenceType};
        use crate::pretty::pretty_parse_render;

        fn assert_unary_ref(ast: crate::parser::ASTNode, op: &str, expected: ReferenceType) {
            match ast.node_type {
                ASTNodeType::UnaryOp { op: o, expr } => {
                    assert_eq!(o, op);
                    match expr.node_type {
                        ASTNodeType::Reference { reference, .. } => {
                            assert_eq!(reference, expected);
                        }
                        other => panic!("expected Reference under UnaryOp, got {other:?}"),
                    }
                }
                other => panic!("expected UnaryOp({op}, ...), got {other:?}"),
            }
        }

        #[test]
        fn test_spill_basic() {
            // Classic Parser path
            let ast = parse_formula("=A1#").expect("parse =A1#");
            assert_unary_ref(ast, "#", ReferenceType::cell(None, 1, 1));

            // Span parse path
            let ast = crate::parser::parse("=A1#").expect("span parse =A1#");
            assert_unary_ref(ast, "#", ReferenceType::cell(None, 1, 1));
        }

        #[test]
        fn test_spill_in_arithmetic() {
            for ast in [
                parse_formula("=B2#+1").expect("classic"),
                crate::parser::parse("=B2#+1").expect("span"),
            ] {
                match ast.node_type {
                    ASTNodeType::BinaryOp { op, left, right } => {
                        assert_eq!(op, "+");
                        match left.node_type {
                            ASTNodeType::UnaryOp { op: o, expr } => {
                                assert_eq!(o, "#");
                                assert!(matches!(expr.node_type, ASTNodeType::Reference { .. }));
                            }
                            other => panic!("expected UnaryOp on left, got {other:?}"),
                        }
                        match right.node_type {
                            ASTNodeType::Literal(_) => {}
                            other => panic!("expected literal on right, got {other:?}"),
                        }
                    }
                    other => panic!("expected BinaryOp, got {other:?}"),
                }
            }
        }

        #[test]
        fn test_spill_in_function() {
            for ast in [
                parse_formula("=SUM(A1#)").expect("classic"),
                crate::parser::parse("=SUM(A1#)").expect("span"),
            ] {
                match ast.node_type {
                    ASTNodeType::Function { name, args } => {
                        assert_eq!(name, "SUM");
                        assert_eq!(args.len(), 1);
                        match &args[0].node_type {
                            ASTNodeType::UnaryOp { op, expr } => {
                                assert_eq!(op, "#");
                                assert!(matches!(expr.node_type, ASTNodeType::Reference { .. }));
                            }
                            other => panic!("expected UnaryOp arg, got {other:?}"),
                        }
                    }
                    other => panic!("expected Function, got {other:?}"),
                }
            }
        }

        #[test]
        fn test_spill_with_implicit_intersection() {
            // =@A1# → @ wraps the spill ref.
            for ast in [
                parse_formula("=@A1#").expect("classic"),
                crate::parser::parse("=@A1#").expect("span"),
            ] {
                match ast.node_type {
                    ASTNodeType::UnaryOp { op, expr } => {
                        assert_eq!(op, "@");
                        match expr.node_type {
                            ASTNodeType::UnaryOp {
                                op: inner_op,
                                expr: inner,
                            } => {
                                assert_eq!(inner_op, "#");
                                assert!(matches!(inner.node_type, ASTNodeType::Reference { .. }));
                            }
                            other => panic!("expected UnaryOp(#) under @, got {other:?}"),
                        }
                    }
                    other => panic!("expected UnaryOp(@, ...), got {other:?}"),
                }
            }
        }

        #[test]
        fn test_spill_sheet_qualified() {
            for ast in [
                parse_formula("=Sheet1!A1#").expect("classic"),
                crate::parser::parse("=Sheet1!A1#").expect("span"),
            ] {
                assert_unary_ref(
                    ast,
                    "#",
                    ReferenceType::cell(Some("Sheet1".to_string()), 1, 1),
                );
            }
        }

        #[test]
        fn test_anchorarray_xlfn_still_function() {
            // Legacy serialization should still be a function call.
            for ast in [
                parse_formula("=_xlfn.ANCHORARRAY(A1)").expect("classic"),
                crate::parser::parse("=_xlfn.ANCHORARRAY(A1)").expect("span"),
            ] {
                match ast.node_type {
                    ASTNodeType::Function { name, args } => {
                        assert!(name.eq_ignore_ascii_case("_xlfn.ANCHORARRAY"));
                        assert_eq!(args.len(), 1);
                    }
                    other => panic!("expected Function, got {other:?}"),
                }
            }
        }

        #[test]
        fn test_error_literal_still_parses() {
            // Negative regression — error literals must remain literals.
            let ast = parse_formula("=#REF!").expect("=#REF!");
            assert!(matches!(ast.node_type, ASTNodeType::Literal(_)));
            let ast = crate::parser::parse("=#REF!").expect("span =#REF!");
            assert!(matches!(ast.node_type, ASTNodeType::Literal(_)));
        }

        #[test]
        fn test_sheet_prefixed_error_literal_still_parses() {
            // The key invariant for #71: `Sheet1!#REF!` must NOT be split
            // into `Sheet1!` + spill `#`. The classic Parser path produces a
            // Reference node (sheet-qualified error) and the span path
            // produces a Literal(Error) — both pre-existing behaviors that we
            // simply must not regress.
            let classic = parse_formula("=Sheet1!#REF!").expect("classic");
            assert!(matches!(
                classic.node_type,
                ASTNodeType::Reference { .. } | ASTNodeType::Literal(_)
            ));
            let span = crate::parser::parse("=Sheet1!#REF!").expect("span");
            assert!(matches!(
                span.node_type,
                ASTNodeType::Reference { .. } | ASTNodeType::Literal(_)
            ));
        }

        #[test]
        fn test_double_spill_parses() {
            // =A1## — accept and produce nested UnaryOp(#, UnaryOp(#, A1)).
            for ast in [
                parse_formula("=A1##").expect("classic"),
                crate::parser::parse("=A1##").expect("span"),
            ] {
                match ast.node_type {
                    ASTNodeType::UnaryOp { op, expr } => {
                        assert_eq!(op, "#");
                        match expr.node_type {
                            ASTNodeType::UnaryOp { op: inner_op, .. } => {
                                assert_eq!(inner_op, "#");
                            }
                            other => panic!("expected nested UnaryOp(#), got {other:?}"),
                        }
                    }
                    other => panic!("expected outer UnaryOp(#), got {other:?}"),
                }
            }
        }

        #[test]
        fn test_bare_hash_is_error() {
            assert!(parse_formula("=#").is_err());
            assert!(crate::parser::parse("=#").is_err());
        }

        #[test]
        fn test_spill_display_roundtrip() {
            // parse → pretty → parse must yield the same AST shape.
            let pretty = pretty_parse_render("=A1#").expect("pretty");
            assert_eq!(pretty, "=A1#");
            let again = pretty_parse_render(&pretty).expect("pretty round");
            assert_eq!(pretty, again);

            let pretty = pretty_parse_render("=SUM(B2#)+1").expect("pretty");
            assert_eq!(pretty, "=SUM(B2#) + 1");
            let again = pretty_parse_render(&pretty).expect("pretty round");
            assert_eq!(pretty, again);
        }
    }

    mod reference_operators {
        use super::parse_formula;
        use crate::parser::{ASTNode, ASTNodeType, ReferenceType};
        use crate::pretty::pretty_parse_render;

        fn parse_both(formula: &str) -> [ASTNode; 2] {
            let classic = parse_formula(formula)
                .unwrap_or_else(|e| panic!("classic parser failed for {formula:?}: {e:?}"));
            let span = crate::parser::parse(formula)
                .unwrap_or_else(|e| panic!("span parser failed for {formula:?}: {e:?}"));
            [classic, span]
        }

        fn assert_both_err(formula: &str) {
            assert!(
                parse_formula(formula).is_err(),
                "classic parser unexpectedly accepted {formula:?}"
            );
            assert!(
                crate::parser::parse(formula).is_err(),
                "span parser unexpectedly accepted {formula:?}"
            );
        }

        fn assert_range_ref(node: &ASTNode, expected_str: &str) {
            match &node.node_type {
                ASTNodeType::Reference {
                    reference,
                    original,
                } => {
                    assert!(
                        matches!(reference, ReferenceType::Range { .. }),
                        "expected Range ref for {expected_str:?}, got {reference:?}"
                    );
                    assert_eq!(original, expected_str);
                }
                other => panic!("expected Reference({expected_str:?}), got {other:?}"),
            }
        }

        fn assert_cell_ref(node: &ASTNode, expected_str: &str) {
            match &node.node_type {
                ASTNodeType::Reference {
                    reference,
                    original,
                } => {
                    assert!(
                        matches!(reference, ReferenceType::Cell { .. }),
                        "expected Cell ref for {expected_str:?}, got {reference:?}"
                    );
                    assert_eq!(original, expected_str);
                }
                other => panic!("expected Reference({expected_str:?}), got {other:?}"),
            }
        }

        #[test]
        fn space_intersection_basic() {
            for ast in parse_both("=A1:A3 B1:B3") {
                match ast.node_type {
                    ASTNodeType::BinaryOp { op, left, right } => {
                        assert_eq!(op, " ");
                        assert_range_ref(&left, "A1:A3");
                        assert_range_ref(&right, "B1:B3");
                    }
                    other => panic!("expected BinaryOp(\" \", ...), got {other:?}"),
                }
            }
        }

        #[test]
        fn space_intersection_inside_function() {
            for ast in parse_both("=SUM(A1:A3 A2:C2)") {
                match ast.node_type {
                    ASTNodeType::Function { name, args } => {
                        assert_eq!(name, "SUM");
                        assert_eq!(args.len(), 1);
                        match &args[0].node_type {
                            ASTNodeType::BinaryOp { op, left, right } => {
                                assert_eq!(op, " ");
                                assert_range_ref(left, "A1:A3");
                                assert_range_ref(right, "A2:C2");
                            }
                            other => panic!("expected BinaryOp arg, got {other:?}"),
                        }
                    }
                    other => panic!("expected Function, got {other:?}"),
                }
            }
        }

        #[test]
        fn colon_composed_with_function() {
            for ast in parse_both("=OFFSET(A1,1,1):B10") {
                match ast.node_type {
                    ASTNodeType::BinaryOp { op, left, right } => {
                        assert_eq!(op, ":");
                        match &left.node_type {
                            ASTNodeType::Function { name, .. } => {
                                assert_eq!(name, "OFFSET");
                            }
                            other => panic!("expected OFFSET function on left, got {other:?}"),
                        }
                        assert_cell_ref(&right, "B10");
                    }
                    other => panic!("expected BinaryOp(:, ...), got {other:?}"),
                }
            }
        }

        #[test]
        fn colon_composed_with_index() {
            for ast in parse_both("=INDEX(A:A,1):B10") {
                match ast.node_type {
                    ASTNodeType::BinaryOp { op, left, right } => {
                        assert_eq!(op, ":");
                        match &left.node_type {
                            ASTNodeType::Function { name, .. } => {
                                assert_eq!(name, "INDEX");
                            }
                            other => panic!("expected INDEX function on left, got {other:?}"),
                        }
                        assert_cell_ref(&right, "B10");
                    }
                    other => panic!("expected BinaryOp(:, ...), got {other:?}"),
                }
            }
        }

        #[test]
        fn colon_composed_with_paren() {
            for ast in parse_both("=(A1:A3):A5") {
                match ast.node_type {
                    ASTNodeType::BinaryOp { op, left, right } => {
                        assert_eq!(op, ":");
                        assert_range_ref(&left, "A1:A3");
                        assert_cell_ref(&right, "A5");
                    }
                    other => panic!("expected BinaryOp(:, ...), got {other:?}"),
                }
            }
        }

        #[test]
        fn cross_sheet_range() {
            // 'Sheet1'!A1:'Sheet2'!B1 must compose as BinaryOp(:, A1, B1) with
            // distinct sheets on each side.
            for ast in parse_both("='Sheet1'!A1:'Sheet2'!B1") {
                match ast.node_type {
                    ASTNodeType::BinaryOp { op, left, right } => {
                        assert_eq!(op, ":");
                        match &left.node_type {
                            ASTNodeType::Reference { reference, .. } => match reference {
                                ReferenceType::Cell { sheet, .. } => {
                                    assert_eq!(sheet.as_deref(), Some("Sheet1"));
                                }
                                other => panic!("expected Sheet1 cell, got {other:?}"),
                            },
                            other => panic!("expected Reference on left, got {other:?}"),
                        }
                        match &right.node_type {
                            ASTNodeType::Reference { reference, .. } => match reference {
                                ReferenceType::Cell { sheet, .. } => {
                                    assert_eq!(sheet.as_deref(), Some("Sheet2"));
                                }
                                other => panic!("expected Sheet2 cell, got {other:?}"),
                            },
                            other => panic!("expected Reference on right, got {other:?}"),
                        }
                    }
                    other => panic!("expected BinaryOp(:, ...), got {other:?}"),
                }
            }
        }

        #[test]
        fn chained_colon() {
            // =A1:A3:A5 — the first simple range remains on the fast path, then
            // the second colon is parsed as a composed reference operator.
            for ast in parse_both("=A1:A3:A5") {
                match ast.node_type {
                    ASTNodeType::BinaryOp { op, left, right } => {
                        assert_eq!(op, ":");
                        assert_range_ref(&left, "A1:A3");
                        assert_cell_ref(&right, "A5");
                    }
                    other => panic!("expected BinaryOp(:, ...), got {other:?}"),
                }
            }
        }

        #[test]
        fn intersection_precedence_below_colon() {
            // =A1:B2 C1:D2 → BinaryOp(" ", Range(A1:B2), Range(C1:D2)).
            // Both sides must be ranges (the simple-range fast path is preserved).
            for ast in parse_both("=A1:B2 C1:D2") {
                match ast.node_type {
                    ASTNodeType::BinaryOp { op, left, right } => {
                        assert_eq!(op, " ");
                        assert_range_ref(&left, "A1:B2");
                        assert_range_ref(&right, "C1:D2");
                    }
                    other => panic!("expected BinaryOp(\" \", ...), got {other:?}"),
                }
            }
        }

        #[test]
        fn implicit_intersection_binds_tighter_than_colon() {
            // =(@A1):A3 must produce BinaryOp(:, UnaryOp(@, A1), A3) — i.e. '@'
            // attaches to A1 first because it is a prefix unary. The parentheses
            // force a composed colon instead of the simple-range fast path.
            for ast in parse_both("=(@A1):A3") {
                match ast.node_type {
                    ASTNodeType::BinaryOp { op, left, right: _ } => {
                        assert_eq!(op, ":");
                        match &left.node_type {
                            ASTNodeType::UnaryOp { op, .. } => assert_eq!(op, "@"),
                            other => panic!("expected UnaryOp(@, ...) on left, got {other:?}"),
                        }
                    }
                    other => panic!("expected BinaryOp(:, ...), got {other:?}"),
                }
            }
        }

        #[test]
        fn trailing_space_after_ref_is_not_intersection() {
            // =A1 — trailing whitespace must not turn A1 into a binary op.
            for ast in parse_both("=A1 ") {
                assert!(matches!(ast.node_type, ASTNodeType::Reference { .. }));
            }
        }

        #[test]
        fn colon_with_no_rhs_is_error() {
            assert_both_err("=A1: ");
            assert_both_err("=A1:");
        }

        #[test]
        fn leading_colon_is_error() {
            assert_both_err("= :A1");
        }

        #[test]
        fn space_between_function_name_and_paren_is_error() {
            assert_both_err("=SUM A1");
        }

        #[test]
        fn simple_range_remains_single_operand() {
            // Regression guard: =A1:B2 still tokenizes as one Operand:Range.
            use crate::tokenizer::{TokenStream, TokenType, Tokenizer};
            let classic = Tokenizer::new("=A1:B2").unwrap();
            assert_eq!(classic.items.len(), 1);
            assert_eq!(classic.items[0].token_type, TokenType::Operand);
            assert_eq!(classic.items[0].value, "A1:B2");
            let span = TokenStream::new("=A1:B2").unwrap();
            assert_eq!(span.spans.len(), 1);
            assert_eq!(span.spans[0].token_type, TokenType::Operand);
        }

        #[test]
        fn pretty_print_intersection_and_colon() {
            // Intersection space prints with single-space gap; colon prints tight.
            let pretty = pretty_parse_render("=A1:A3 B1:B3").unwrap();
            assert_eq!(pretty, "=A1:A3 B1:B3");
            let again = pretty_parse_render(&pretty).unwrap();
            assert_eq!(pretty, again);

            let pretty = pretty_parse_render("=OFFSET(A1,1,1):B10").unwrap();
            assert_eq!(pretty, "=OFFSET(A1, 1, 1):B10");
            let again = pretty_parse_render(&pretty).unwrap();
            assert_eq!(pretty, again);
        }
    }
}

#[cfg(test)]
mod fingerprint_tests {
    use formualizer_common::LiteralValue;

    use crate::tokenizer::*;

    use crate::parser::{ASTNode, ASTNodeType};

    #[test]
    fn test_fingerprint_whitespace_insensitive() {
        // Test that formulas with different whitespace have the same fingerprint
        let f1 = "=SUM(a1, 2)";
        let f2 = "=  SUM( A1 ,2 )"; // diff whitespace/casing

        let fp1 = crate::parser::parse(f1).unwrap().fingerprint();
        let fp2 = crate::parser::parse(f2).unwrap().fingerprint();

        assert_eq!(
            fp1, fp2,
            "Formulas with different whitespace should have the same fingerprint"
        );

        // Different values should have different fingerprints
        let fp3 = crate::parser::parse("=SUM(A1,3)").unwrap().fingerprint();
        assert_ne!(
            fp1, fp3,
            "Formulas with different values should have different fingerprints"
        );
    }

    #[test]
    fn test_fingerprint_case_insensitivity() {
        // Test that formulas with different casing have the same fingerprint
        let f1 = "=sum(a1)";
        let f2 = "=SUM(A1)";

        let fp1 = crate::parser::parse(f1).unwrap().fingerprint();
        let fp2 = crate::parser::parse(f2).unwrap().fingerprint();

        assert_eq!(
            fp1, fp2,
            "Formulas with different casing should have the same fingerprint"
        );
    }

    #[test]
    fn test_fingerprint_different_structure() {
        // Test that formulas with different structure have different fingerprints
        let f1 = "=SUM(A1,B1)";
        let f2 = "=SUM(A1+B1)";

        let fp1 = crate::parser::parse(f1).unwrap().fingerprint();
        let fp2 = crate::parser::parse(f2).unwrap().fingerprint();

        assert_ne!(
            fp1, fp2,
            "Formulas with different structure should have different fingerprints"
        );
    }

    #[test]
    fn test_fingerprint_ignores_source_token() {
        // Create two identical ASTNodes but with different source_token values
        let value = LiteralValue::Number(42.0);
        let node_type = ASTNodeType::Literal(value);

        let token1 = Token::new("42".to_string(), TokenType::Operand, TokenSubType::Number);
        let token2 = Token::new("42.0".to_string(), TokenType::Operand, TokenSubType::Number);

        let node1 = ASTNode::new(node_type.clone(), Some(token1));
        let node2 = ASTNode::new(node_type, Some(token2));

        assert_eq!(
            node1.fingerprint(),
            node2.fingerprint(),
            "Fingerprints should be equal for nodes with same structure but different source_token"
        );
    }

    #[test]
    fn test_fingerprint_deterministic() {
        // Test that the fingerprint is deterministic across calls
        let formula = "=SUM(A1:B10)/COUNT(A1:B10)";
        let ast = crate::parser::parse(formula).unwrap();

        let fp1 = ast.fingerprint();
        let fp2 = ast.fingerprint();

        assert_eq!(
            fp1, fp2,
            "Fingerprint should be deterministic for the same AST"
        );
    }

    #[test]
    fn test_fingerprint_complex_formula() {
        // Test with a more complex formula
        let f1 = "=IF(AND(A1>0,B1<10),SUM(C1:C10)/COUNT(C1:C10),\"N/A\")";
        let f2 = "=IF(AND(A1>0,B1<10),SUM(C1:C10)/COUNT(C1:C10),\"N/A\")";

        let fp1 = crate::parser::parse(f1).unwrap().fingerprint();
        let fp2 = crate::parser::parse(f2).unwrap().fingerprint();

        assert_eq!(
            fp1, fp2,
            "Identical complex formulas should have the same fingerprint"
        );

        // Slightly different formula
        let f3 = "=IF(AND(A1>0,B1<=10),SUM(C1:C10)/COUNT(C1:C10),\"N/A\")";
        let fp3 = crate::parser::parse(f3).unwrap().fingerprint();

        assert_ne!(
            fp1, fp3,
            "Different complex formulas should have different fingerprints"
        );
    }

    #[test]
    fn test_validation_requirements() {
        // Test the specific validation example from the requirements
        let f1 = "=SUM(a1, 2)";
        let f2 = "=  SUM( A1 ,2 )"; // diff whitespace/casing
        let fp1 = crate::parser::parse(f1).unwrap().fingerprint();
        let fp2 = crate::parser::parse(f2).unwrap().fingerprint();
        assert_eq!(
            fp1, fp2,
            "Formulas with different whitespace and casing should have the same fingerprint"
        );

        let fp3 = crate::parser::parse("=SUM(A1,3)").unwrap().fingerprint();
        assert_ne!(
            fp1, fp3,
            "Formulas with different values should have different fingerprints"
        );
    }
}

#[cfg(test)]
mod normalise_tests {
    use crate::parser::normalise_reference;

    #[test]
    fn test_normalise_cell_references() {
        // Test normalizing cell references
        assert_eq!(normalise_reference("a1").unwrap(), "A1");
        assert_eq!(normalise_reference("$a$1").unwrap(), "$A$1");
        assert_eq!(normalise_reference("$A$1").unwrap(), "$A$1");
        assert_eq!(normalise_reference("Sheet1!$b$2").unwrap(), "Sheet1!$B$2");
        assert_eq!(normalise_reference("'Sheet1'!$b$2").unwrap(), "Sheet1!$B$2");
        assert_eq!(
            normalise_reference("'my sheet'!$b$2").unwrap(),
            "'my sheet'!$B$2"
        );
    }

    #[test]
    fn test_normalise_range_references() {
        // Test normalizing range references
        assert_eq!(normalise_reference("a1:b2").unwrap(), "A1:B2");
        assert_eq!(normalise_reference("$a$1:$b$2").unwrap(), "$A$1:$B$2");
        assert_eq!(
            normalise_reference("Sheet1!$a$1:$b$2").unwrap(),
            "Sheet1!$A$1:$B$2"
        );
        assert_eq!(
            normalise_reference("'my sheet'!$a$1:$b$2").unwrap(),
            "'my sheet'!$A$1:$B$2"
        );
        assert_eq!(normalise_reference("$a:$a").unwrap(), "$A:$A");
        assert_eq!(normalise_reference("$1:$1").unwrap(), "$1:$1");
    }

    #[test]
    fn test_normalise_table_references() {
        // Test normalizing table references
        assert_eq!(
            normalise_reference("Table1[Column1]").unwrap(),
            "Table1[Column1]"
        );
        assert_eq!(
            normalise_reference("Table1[ Column1 ]").unwrap(),
            "Table1[Column1]"
        );
        assert_eq!(
            normalise_reference("Table1[Column1:Column2]").unwrap(),
            "Table1[Column1:Column2]"
        );
        assert_eq!(
            normalise_reference("Table1[ Column1 : Column2 ]").unwrap(),
            "Table1[Column1:Column2]"
        );
        // Special items should remain unchanged
        assert_eq!(
            normalise_reference("Table1[#Headers]").unwrap(),
            "Table1[#Headers]"
        );
    }

    #[test]
    fn test_normalise_named_ranges() {
        // Named ranges should remain unchanged
        assert_eq!(normalise_reference("SalesData").unwrap(), "SalesData");
    }

    #[test]
    fn test_validation_examples() {
        // These are the examples given in the validation section
        assert_eq!(normalise_reference("a1").unwrap(), "A1");
        assert_eq!(
            normalise_reference("'my sheet'!$b$2").unwrap(),
            "'my sheet'!$B$2"
        );
        assert_eq!(normalise_reference("A:A").unwrap(), "A:A");
        assert_eq!(
            normalise_reference("Table1[ column ]").unwrap(),
            "Table1[column]"
        );
    }
}

#[cfg(test)]
mod reference_tests {
    use crate::parser::ReferenceType;
    use crate::parser::*;
    use crate::tokenizer::{TokenType, Tokenizer};

    #[test]
    fn test_cell_reference_parsing() {
        // Simple cell reference
        let reference = "A1";
        let ref_type = ReferenceType::from_string(reference).unwrap();
        assert_eq!(ref_type, ReferenceType::cell(None, 1, 1));

        // Cell reference with sheet
        let reference = "Sheet1!B2";
        let ref_type = ReferenceType::from_string(reference).unwrap();
        assert_eq!(
            ref_type,
            ReferenceType::cell(Some("Sheet1".to_string()), 2, 2)
        );

        // Cell reference with quoted sheet name
        let reference = "'Sheet 1'!C3";
        let ref_type = ReferenceType::from_string(reference).unwrap();
        assert_eq!(
            ref_type,
            ReferenceType::cell(Some("Sheet 1".to_string()), 3, 3)
        );

        // Cell reference with absolute reference
        let reference = "$D$4";
        let ref_type = ReferenceType::from_string(reference).unwrap();
        assert_eq!(
            ref_type,
            ReferenceType::cell_with_abs(None, 4, 4, true, true)
        );
    }

    #[test]
    fn test_range_reference_parsing() {
        // Simple range
        let reference = "A1:B2";
        let ref_type = ReferenceType::from_string(reference).unwrap();
        assert_eq!(
            ref_type,
            ReferenceType::range(None, Some(1), Some(1), Some(2), Some(2))
        );

        // Range with sheet
        let reference = "Sheet1!C3:D4";
        let ref_type = ReferenceType::from_string(reference).unwrap();
        assert_eq!(
            ref_type,
            ReferenceType::range(
                Some("Sheet1".to_string()),
                Some(3),
                Some(3),
                Some(4),
                Some(4),
            )
        );

        // Range with quoted sheet name
        let reference = "'Sheet 1'!E5:F6";
        let ref_type = ReferenceType::from_string(reference).unwrap();
        assert_eq!(
            ref_type,
            ReferenceType::range(
                Some("Sheet 1".to_string()),
                Some(5),
                Some(5),
                Some(6),
                Some(6),
            )
        );

        // Range with absolute references
        let reference = "$G$7:$H$8";
        let ref_type = ReferenceType::from_string(reference).unwrap();
        assert_eq!(
            ref_type,
            ReferenceType::range_with_abs(
                None,
                Some(7),
                Some(7),
                Some(8),
                Some(8),
                true,
                true,
                true,
                true
            )
        );
    }

    #[test]
    fn test_infinite_range_parsing() {
        // Infinite column range (A:A)
        let reference = "A:A";
        let ref_type = ReferenceType::from_string(reference).unwrap();
        assert_eq!(
            ref_type,
            ReferenceType::range(None, None, Some(1), None, Some(1))
        );

        // Infinite row range (1:1)
        let reference = "1:1";
        let ref_type = ReferenceType::from_string(reference).unwrap();
        assert_eq!(
            ref_type,
            ReferenceType::range(None, Some(1), None, Some(1), None)
        );

        // Row range with sheet
        let reference = "Sheet1!3:4";
        let ref_type = ReferenceType::from_string(reference).unwrap();
        assert_eq!(
            ref_type,
            ReferenceType::range(Some("Sheet1".to_string()), Some(3), None, Some(4), None)
        );

        // Column range with sheet
        let reference = "Sheet1!C:D";
        let ref_type = ReferenceType::from_string(reference).unwrap();
        assert_eq!(
            ref_type,
            ReferenceType::range(Some("Sheet1".to_string()), None, Some(3), None, Some(4))
        );

        // Infinite column range with sheet (Sheet1!A:A)
        let reference = "Sheet1!A:A";
        let ref_type = ReferenceType::from_string(reference).unwrap();
        assert_eq!(
            ref_type,
            ReferenceType::range(Some("Sheet1".to_string()), None, Some(1), None, Some(1))
        );

        // Range with column-only to column-only (A:B)
        let reference = "A:B";
        let ref_type = ReferenceType::from_string(reference).unwrap();
        assert_eq!(
            ref_type,
            ReferenceType::range(None, None, Some(1), None, Some(2))
        );

        // Range with row-only to row-only (1:5)
        let reference = "1:5";
        let ref_type = ReferenceType::from_string(reference).unwrap();
        assert_eq!(
            ref_type,
            ReferenceType::range(None, Some(1), None, Some(5), None)
        );

        // Range with bounded start, unbounded end (A1:A)
        let reference = "A1:A";
        let ref_type = ReferenceType::from_string(reference).unwrap();
        assert_eq!(
            ref_type,
            ReferenceType::range(None, Some(1), Some(1), None, Some(1))
        );

        // Range with unbounded start, bounded end (A:A10)
        let reference = "A:A10";
        let ref_type = ReferenceType::from_string(reference).unwrap();
        assert_eq!(
            ref_type,
            ReferenceType::range(None, None, Some(1), Some(10), Some(1))
        );
    }

    #[test]
    fn test_range_to_string() {
        // Test to_string representation for normal ranges
        let range = ReferenceType::range(None, Some(1), Some(1), Some(2), Some(2));
        assert_eq!(range.to_excel_string(), "A1:B2");

        // Test to_string for infinite column range
        let range = ReferenceType::range(None, None, Some(1), None, Some(1));
        assert_eq!(range.to_excel_string(), "A:A");

        // Test to_string for infinite row range
        let range = ReferenceType::range(None, Some(1), None, Some(1), None);
        assert_eq!(range.to_excel_string(), "1:1");

        // Test to_string for partially infinite range (A1:A)
        let range = ReferenceType::range(None, Some(1), Some(1), None, Some(1));
        assert_eq!(range.to_excel_string(), "A1:A");

        // Test to_string for partially infinite range with sheet
        let range =
            ReferenceType::range(Some("Sheet1".to_string()), None, Some(1), Some(10), Some(1));
        assert_eq!(range.to_excel_string(), "Sheet1!A:A10");
    }

    #[test]
    fn test_table_reference_parsing() {
        // Table reference
        let reference = "Table1[Column1]";
        let ref_type = ReferenceType::from_string(reference).unwrap();

        // Check that we get a table reference with the correct name and column
        if let ReferenceType::Table(table_ref) = ref_type {
            assert_eq!(table_ref.name, "Table1");

            if let Some(TableSpecifier::Column(column)) = table_ref.specifier {
                assert_eq!(column, "Column1");
            } else {
                panic!("Expected Column specifier");
            }
        } else {
            panic!("Expected Table reference");
        }
    }

    #[test]
    fn test_external_workbook_reference_parsing() {
        let ref_type = ReferenceType::from_string("[33]Sheet1!$B:$B").unwrap();
        assert_eq!(
            ref_type,
            ReferenceType::External(ExternalReference {
                raw: "[33]Sheet1!$B:$B".to_string(),
                book: ExternalBookRef::Token("[33]".to_string()),
                sheet: "Sheet1".to_string(),
                kind: ExternalRefKind::range_with_abs(
                    None,
                    Some(2),
                    None,
                    Some(2),
                    false,
                    true,
                    false,
                    true,
                ),
            })
        );

        let ref_type = ReferenceType::from_string("'[My Book.xlsx]Sheet1'!A1").unwrap();
        assert_eq!(
            ref_type,
            ReferenceType::External(ExternalReference {
                raw: "'[My Book.xlsx]Sheet1'!A1".to_string(),
                book: ExternalBookRef::Token("[My Book.xlsx]".to_string()),
                sheet: "Sheet1".to_string(),
                kind: ExternalRefKind::cell(1, 1),
            })
        );
    }

    #[test]
    fn test_external_workbook_reference_paths_and_urls() {
        let ref_type = ReferenceType::from_string("'[C:\\Users\\me\\Book.xlsx]Sheet1'!A1").unwrap();
        assert_eq!(
            ref_type,
            ReferenceType::External(ExternalReference {
                raw: "'[C:\\Users\\me\\Book.xlsx]Sheet1'!A1".to_string(),
                book: ExternalBookRef::Token("[C:\\Users\\me\\Book.xlsx]".to_string()),
                sheet: "Sheet1".to_string(),
                kind: ExternalRefKind::cell(1, 1),
            })
        );

        let ref_type = ReferenceType::from_string("'C:\\Users\\me\\[Book.xlsx]Sheet1'!A1").unwrap();
        assert_eq!(
            ref_type,
            ReferenceType::External(ExternalReference {
                raw: "'C:\\Users\\me\\[Book.xlsx]Sheet1'!A1".to_string(),
                book: ExternalBookRef::Token("C:\\Users\\me\\[Book.xlsx]".to_string()),
                sheet: "Sheet1".to_string(),
                kind: ExternalRefKind::cell(1, 1),
            })
        );

        let ref_type =
            ReferenceType::from_string("[\\\\server\\share\\Book.xlsx]Sheet1!A1").unwrap();
        assert_eq!(
            ref_type,
            ReferenceType::External(ExternalReference {
                raw: "[\\\\server\\share\\Book.xlsx]Sheet1!A1".to_string(),
                book: ExternalBookRef::Token("[\\\\server\\share\\Book.xlsx]".to_string()),
                sheet: "Sheet1".to_string(),
                kind: ExternalRefKind::cell(1, 1),
            })
        );

        let ref_type =
            ReferenceType::from_string("'[https://example.com/Book.xlsx]Sheet1'!1:3").unwrap();
        assert_eq!(
            ref_type,
            ReferenceType::External(ExternalReference {
                raw: "'[https://example.com/Book.xlsx]Sheet1'!1:3".to_string(),
                book: ExternalBookRef::Token("[https://example.com/Book.xlsx]".to_string()),
                sheet: "Sheet1".to_string(),
                kind: ExternalRefKind::range(Some(1), None, Some(3), None),
            })
        );

        // Sheet names containing ']' but no '[' should not be treated as external.
        let ref_type = ReferenceType::from_string("'foo]bar'!A1").unwrap();
        assert_eq!(
            ref_type,
            ReferenceType::cell(Some("foo]bar".to_string()), 1, 1)
        );
    }

    #[test]
    fn test_external_workbook_sheet_names_with_spaces() {
        let ref_type = ReferenceType::from_string("'[Book.xlsx]My Sheet'!$A$1").unwrap();
        assert_eq!(
            ref_type,
            ReferenceType::External(ExternalReference {
                raw: "'[Book.xlsx]My Sheet'!$A$1".to_string(),
                book: ExternalBookRef::Token("[Book.xlsx]".to_string()),
                sheet: "My Sheet".to_string(),
                kind: ExternalRefKind::cell_with_abs(1, 1, true, true),
            })
        );
    }

    #[test]
    fn test_external_workbook_unix_style_paths() {
        let ref_type = ReferenceType::from_string("'/tmp/[Book.xlsx]Sheet1'!A1").unwrap();
        assert_eq!(
            ref_type,
            ReferenceType::External(ExternalReference {
                raw: "'/tmp/[Book.xlsx]Sheet1'!A1".to_string(),
                book: ExternalBookRef::Token("/tmp/[Book.xlsx]".to_string()),
                sheet: "Sheet1".to_string(),
                kind: ExternalRefKind::cell(1, 1),
            })
        );
    }

    #[test]
    fn test_external_workbook_sheet_name_can_contain_close_bracket() {
        let ref_type =
            ReferenceType::from_string("'C:\\Users\\me\\[Book.xlsx]S]heet1'!A1").unwrap();
        assert_eq!(
            ref_type,
            ReferenceType::External(ExternalReference {
                raw: "'C:\\Users\\me\\[Book.xlsx]S]heet1'!A1".to_string(),
                book: ExternalBookRef::Token("C:\\Users\\me\\[Book.xlsx]".to_string()),
                sheet: "S]heet1".to_string(),
                kind: ExternalRefKind::cell(1, 1),
            })
        );
    }

    #[test]
    fn test_external_workbook_token_and_sheet_name_allow_escaped_quotes() {
        let ref_type = ReferenceType::from_string("'[O''Reilly.xlsx]Sheet1'!A1").unwrap();
        assert_eq!(
            ref_type,
            ReferenceType::External(ExternalReference {
                raw: "'[O''Reilly.xlsx]Sheet1'!A1".to_string(),
                book: ExternalBookRef::Token("[O'Reilly.xlsx]".to_string()),
                sheet: "Sheet1".to_string(),
                kind: ExternalRefKind::cell(1, 1),
            })
        );

        let ref_type = ReferenceType::from_string("'[Book.xlsx]Bob''s Sheet'!A1").unwrap();
        assert_eq!(
            ref_type,
            ReferenceType::External(ExternalReference {
                raw: "'[Book.xlsx]Bob''s Sheet'!A1".to_string(),
                book: ExternalBookRef::Token("[Book.xlsx]".to_string()),
                sheet: "Bob's Sheet".to_string(),
                kind: ExternalRefKind::cell(1, 1),
            })
        );
    }

    #[test]
    fn test_sheet_scoped_table_reference_is_not_external() {
        let ref_type = ReferenceType::from_string("Sheet1!Table1[Column1]").unwrap();
        assert_eq!(
            ref_type,
            ReferenceType::Table(TableReference {
                name: "Table1".to_string(),
                specifier: Some(TableSpecifier::Column("Column1".to_string())),
            })
        );
    }

    #[test]
    fn test_named_range_parsing() {
        // Named range
        let reference = "SalesData";
        let ref_type = ReferenceType::from_string(reference).unwrap();
        assert_eq!(ref_type, ReferenceType::NamedRange(reference.to_string()));
    }

    #[test]
    fn test_column_to_number() {
        assert_eq!(ReferenceType::column_to_number("A").unwrap(), 1);
        assert_eq!(ReferenceType::column_to_number("Z").unwrap(), 26);
        assert_eq!(ReferenceType::column_to_number("AA").unwrap(), 27);
        assert_eq!(ReferenceType::column_to_number("AB").unwrap(), 28);
        assert_eq!(ReferenceType::column_to_number("BA").unwrap(), 53);
        assert_eq!(ReferenceType::column_to_number("ZZ").unwrap(), 702);
        assert_eq!(ReferenceType::column_to_number("AAA").unwrap(), 703);
    }

    #[test]
    fn test_number_to_column() {
        assert_eq!(ReferenceType::number_to_column(1), "A");
        assert_eq!(ReferenceType::number_to_column(26), "Z");
        assert_eq!(ReferenceType::number_to_column(27), "AA");
        assert_eq!(ReferenceType::number_to_column(28), "AB");
        assert_eq!(ReferenceType::number_to_column(53), "BA");
        assert_eq!(ReferenceType::number_to_column(702), "ZZ");
        assert_eq!(ReferenceType::number_to_column(703), "AAA");
    }

    #[test]
    fn test_get_dependencies() {
        // Parse a formula and check its dependencies
        let formula = "=A1+B1*SUM(C1:D2)";
        let tokenizer = Tokenizer::new(formula).unwrap();
        let mut parser = Parser::new(tokenizer.items, false);
        let ast = parser.parse().unwrap();

        let dependencies = ast.get_dependencies();

        // We expect three dependencies: A1, B1, and C1:D2
        assert_eq!(dependencies.len(), 3);

        let deps: Vec<ReferenceType> = dependencies.into_iter().cloned().collect();

        assert!(deps.contains(&ReferenceType::cell(None, 1, 1))); // A1
        assert!(deps.contains(&ReferenceType::cell(None, 1, 2))); // B1
        assert!(deps.contains(&ReferenceType::range(
            None,
            Some(1),
            Some(3),
            Some(2),
            Some(4)
        ))); // C1:D2
    }

    #[test]
    fn test_get_dependency_strings() {
        // Parse a formula and check its dependency strings
        let formula = "=A1+B1*SUM(C1:D2)";
        let tokenizer = Tokenizer::new(formula).unwrap();
        let mut parser = Parser::new(tokenizer.items, false);
        let ast = parser.parse().unwrap();

        let dependencies = ast.get_dependency_strings();

        // We expect three dependencies: A1, B1, and C1:D2
        assert_eq!(dependencies.len(), 3);
        assert!(dependencies.contains(&"A1".to_string()));
        assert!(dependencies.contains(&"B1".to_string()));
        assert!(dependencies.contains(&"C1:D2".to_string()));
    }

    #[test]
    fn test_complex_formula_dependencies() {
        let formula = "=IF(SUM(Sheet1!A1:A10)>100,MAX(Table1[Amount]),MIN('Data Sheet'!B1:B5))";
        let tokenizer = Tokenizer::new(formula).unwrap();
        let mut parser = Parser::new(tokenizer.items, false);
        let ast = parser.parse().unwrap();

        let dependencies = ast.get_dependency_strings();
        println!("Dependencies: {dependencies:?}");

        assert_eq!(dependencies.len(), 3);
        assert!(dependencies.contains(&"Sheet1!A1:A10".to_string()));
        assert!(dependencies.contains(&"Table1[Amount]".to_string()));
        assert!(dependencies.contains(&"'Data Sheet'!B1:B5".to_string()));
    }

    #[test]
    fn test_xlfn_function_parsing() {
        let formula = "=_xlfn.XLOOKUP(J7, 'GI XWALK'!$Q:$Q,'GI XWALK'!$R:$R,,0)";
        let tokenizer = Tokenizer::new(formula).unwrap();
        println!("tokenizer: {:?}", tokenizer.items);
        let mut parser = Parser::new(tokenizer.items, false);
        let ast = parser.parse().unwrap();
        println!("ast: {ast:?}");
    }

    #[test]
    fn test_dual_bracket_structured_reference_parsing() {
        use crate::parser::{SpecialItem, TableSpecifier};
        let formula = "=EffortDB[[#All],[NPI]:[JMG Group]]";
        let tokenizer = Tokenizer::new(formula).unwrap();
        let mut parser = Parser::new(tokenizer.items, false);
        let ast = parser.parse().unwrap();

        let ASTNodeType::Reference {
            original,
            reference,
        } = &ast.node_type
        else {
            panic!("Expected Reference node");
        };
        assert_eq!(original, &"EffortDB[[#All],[NPI]:[JMG Group]]".to_string());

        let ReferenceType::Table(table_ref) = reference else {
            panic!("Expected Table reference");
        };
        assert_eq!(table_ref.name, "EffortDB");
        let Some(TableSpecifier::Combination(parts)) = &table_ref.specifier else {
            panic!("Expected Combination, got {:?}", table_ref.specifier);
        };
        let parts: Vec<TableSpecifier> = parts.iter().map(|p| (**p).clone()).collect();
        assert_eq!(
            parts,
            vec![
                TableSpecifier::SpecialItem(SpecialItem::All),
                TableSpecifier::ColumnRange("NPI".to_string(), "JMG Group".to_string()),
            ]
        );
    }

    #[test]
    fn test_table_reference_with_simple_column() {
        // Test a simple table reference with just a column
        let reference = "Table1[Column1]";
        let ref_type = ReferenceType::from_string(reference).unwrap();

        if let ReferenceType::Table(table_ref) = ref_type {
            assert_eq!(table_ref.name, "Table1");

            if let Some(specifier) = table_ref.specifier {
                match specifier {
                    TableSpecifier::Column(column) => {
                        assert_eq!(column, "Column1");
                    }
                    _ => panic!("Expected Column specifier"),
                }
            } else {
                panic!("Expected specifier to be Some");
            }
        } else {
            panic!("Expected Table reference");
        }
    }

    #[test]
    fn test_table_reference_with_non_ascii_column_names() {
        for (reference, expected_table, expected_column) in [
            ("Sales[Акт]", "Sales", "Акт"),
            ("Café[Crème brûlée]", "Café", "Crème brûlée"),
            ("分析[数量]", "分析", "数量"),
        ] {
            let ref_type = ReferenceType::from_string(reference).unwrap();

            match ref_type {
                ReferenceType::Table(table_ref) => {
                    assert_eq!(table_ref.name, expected_table);
                    match table_ref.specifier {
                        Some(TableSpecifier::Column(column)) => {
                            assert_eq!(column, expected_column)
                        }
                        other => panic!("Expected Column specifier, got {other:?}"),
                    }
                }
                other => panic!("Expected Table reference, got {other:?}"),
            }
        }
    }

    #[test]
    fn test_table_reference_with_column_range() {
        // Test a table reference with a column range
        let reference = "Table1[Column1:Column2]";
        let ref_type = ReferenceType::from_string(reference).unwrap();

        if let ReferenceType::Table(table_ref) = ref_type {
            assert_eq!(table_ref.name, "Table1");

            if let Some(specifier) = table_ref.specifier {
                match specifier {
                    TableSpecifier::ColumnRange(start, end) => {
                        assert_eq!(start, "Column1");
                        assert_eq!(end, "Column2");
                    }
                    _ => panic!("Expected ColumnRange specifier"),
                }
            } else {
                panic!("Expected specifier to be Some");
            }
        } else {
            panic!("Expected Table reference");
        }
    }

    #[test]
    fn test_table_reference_with_special_item() {
        // Test a table reference with a special item
        let reference = "Table1[#Headers]";
        let ref_type = ReferenceType::from_string(reference).unwrap();

        if let ReferenceType::Table(table_ref) = ref_type {
            assert_eq!(table_ref.name, "Table1");

            if let Some(specifier) = table_ref.specifier {
                match specifier {
                    TableSpecifier::SpecialItem(item) => {
                        assert_eq!(item, SpecialItem::Headers);
                    }
                    _ => panic!("Expected SpecialItem specifier"),
                }
            } else {
                panic!("Expected specifier to be Some");
            }
        } else {
            panic!("Expected Table reference");
        }
    }

    #[test]
    fn test_single_bracket_structured_reference_parsing() {
        let formula = "=EffortDB[#All]";
        let tokenizer = Tokenizer::new(formula).unwrap();
        println!("tokenizer: {:?}", tokenizer.items);
        let mut parser = Parser::new(tokenizer.items, false);
        let ast = parser.parse().unwrap();
        println!("ast: {ast:?}");
    }

    #[test]
    fn test_table_reference_without_specifier() {
        // Test a table reference without any specifier (entire table)
        let reference = "Table1";
        let ref_type = ReferenceType::from_string(reference).unwrap();

        // After our column name length limit (max 3 chars), "Table1" can't be parsed as a cell
        // reference anymore (Table is 5 chars). It should be treated as a named range.
        if let ReferenceType::NamedRange(name) = ref_type {
            assert_eq!(name, "Table1");
        } else {
            panic!("Expected NamedRange, got: {ref_type:?}");
        }
    }

    #[test]
    fn test_table_item_with_column_reference() {
        use crate::parser::SpecialItem;
        // Test a table reference with an item specifier and column
        let reference = "Table1[[#Data],[Column1]]";
        let ref_type = ReferenceType::from_string(reference).unwrap();

        let ReferenceType::Table(table_ref) = ref_type else {
            panic!("Expected Table reference");
        };
        assert_eq!(table_ref.name, "Table1");
        let Some(TableSpecifier::Combination(parts)) = table_ref.specifier else {
            panic!("Expected Combination specifier");
        };
        let parts: Vec<TableSpecifier> = parts.into_iter().map(|p| *p).collect();
        assert_eq!(
            parts,
            vec![
                TableSpecifier::SpecialItem(SpecialItem::Data),
                TableSpecifier::Column("Column1".to_string()),
            ]
        );
    }

    #[test]
    fn test_table_this_row_with_column_reference() {
        use crate::parser::SpecialItem;
        // Test a table reference with this row specifier and column
        let reference = "Table1[[@],[Column1]]";
        let ref_type = ReferenceType::from_string(reference).unwrap();

        let ReferenceType::Table(table_ref) = ref_type else {
            panic!("Expected Table reference");
        };
        assert_eq!(table_ref.name, "Table1");
        let Some(TableSpecifier::Combination(parts)) = table_ref.specifier else {
            panic!("Expected Combination specifier");
        };
        let parts: Vec<TableSpecifier> = parts.into_iter().map(|p| *p).collect();
        assert_eq!(
            parts,
            vec![
                TableSpecifier::SpecialItem(SpecialItem::ThisRow),
                TableSpecifier::Column("Column1".to_string()),
            ]
        );
    }

    #[test]
    fn test_table_multiple_item_specifiers() {
        // Test a table reference with multiple item specifiers
        let reference = "Table1[[#Headers],[#Data]]";
        let ref_type = ReferenceType::from_string(reference).unwrap();

        if let ReferenceType::Table(table_ref) = ref_type {
            assert_eq!(table_ref.name, "Table1");

            // Currently our implementation doesn't fully parse complex specifiers,
            // but we should at least verify it's parsed as a table reference
            assert!(table_ref.specifier.is_some());

            // Note: In the future, we should enhance this to properly parse
            // complex structured references and verify the exact specifier
        } else {
            panic!("Expected Table reference");
        }
    }

    // Note: The following tests are for future functionality and currently only validate
    // that the existing parsing mechanism doesn't break on these formats.

    #[test]
    fn test_table_reference_with_spill() {
        // Spill operator (#) postfix on a table reference (issue #71).
        let formula = "=Table1[#Data]#";
        let tokenizer = Tokenizer::new(formula).expect("tokenize spill on table ref");
        // Last non-whitespace token is the spill postfix `#`.
        let last = tokenizer
            .items
            .iter()
            .rev()
            .find(|t| t.token_type != TokenType::Whitespace)
            .expect("non-empty");
        assert_eq!(last.token_type, TokenType::OpPostfix);
        assert_eq!(last.value, "#");
    }

    #[test]
    fn test_table_intersection() {
        // Test table intersection reference
        // Currently our implementation doesn't properly handle table intersections,
        // so this test just verifies current behavior
        let formula = "=Table1[@] Table2[#All]";
        let tokenizer = Tokenizer::new(formula).unwrap();

        // Just verify the tokenizer doesn't crash
        assert!(!tokenizer.items.is_empty());

        // Note: In the future, this should be enhanced to properly parse
        // table intersections and verify they're handled correctly
    }

    #[test]
    fn structured_combination_roundtrip_prints_nested_brackets() {
        use crate::parser::{ReferenceType, SpecialItem, TableReference, TableSpecifier};
        let s = "Table1[[#Headers],[#Data]]";
        let r = ReferenceType::from_string(s).expect("parse ok");
        // Expect canonical nested-bracket printing
        assert_eq!(r.to_string(), s);
        // Also sanity-check structure
        match r {
            ReferenceType::Table(TableReference {
                name,
                specifier: Some(TableSpecifier::Combination(parts)),
            }) => {
                assert_eq!(name, "Table1");
                assert!(
                    parts
                        .iter()
                        .any(|p| matches!(**p, TableSpecifier::SpecialItem(SpecialItem::Headers)))
                );
                assert!(
                    parts
                        .iter()
                        .any(|p| matches!(**p, TableSpecifier::SpecialItem(SpecialItem::Data)))
                );
            }
            _ => panic!("expected table combination"),
        }
    }

    #[test]
    fn structured_combination_preserves_duplicate_specials_in_order() {
        use crate::parser::{ReferenceType, SpecialItem, TableReference, TableSpecifier};
        // The OOXML grammar (`combination := item ("," item)*`) permits repeats.
        // After the issue #73 rewrite, the parser preserves them in source order
        // instead of silently de-duplicating.
        let s = "Table1[[#Data],[#Data],[#Totals],[#Totals]]";
        let r = ReferenceType::from_string(s).expect("parse ok");
        assert_eq!(r.to_string(), s);
        let ReferenceType::Table(TableReference {
            specifier: Some(TableSpecifier::Combination(parts)),
            ..
        }) = r
        else {
            panic!("expected table combination");
        };
        let parts: Vec<TableSpecifier> = parts.into_iter().map(|p| *p).collect();
        assert_eq!(
            parts,
            vec![
                TableSpecifier::SpecialItem(SpecialItem::Data),
                TableSpecifier::SpecialItem(SpecialItem::Data),
                TableSpecifier::SpecialItem(SpecialItem::Totals),
                TableSpecifier::SpecialItem(SpecialItem::Totals),
            ]
        );
    }
}

#[cfg(test)]
mod structured_references {
    //! Coverage for issue #73: real parser for structured (table) references.
    //!
    //! Each test runs across both the classic [`Parser`] and the span-based
    //! [`crate::parse`] entrypoint to catch any divergence between paths.
    use crate::parser::{
        ASTNodeType, Parser, ReferenceType, SpecialItem, TableReference, TableRowSpecifier,
        TableSpecifier,
    };
    use crate::tokenizer::Tokenizer;

    fn parse_via_classic(formula: &str) -> Result<ReferenceType, String> {
        let tokenizer = Tokenizer::new(formula).map_err(|e| e.to_string())?;
        let mut parser = Parser::new(tokenizer.items, false);
        let ast = parser.parse().map_err(|e| e.to_string())?;
        match ast.node_type {
            ASTNodeType::Reference { reference, .. } => Ok(reference),
            other => Err(format!("expected reference node, got {other:?}")),
        }
    }

    fn parse_via_span(formula: &str) -> Result<ReferenceType, String> {
        let ast = crate::parse(formula).map_err(|e| e.to_string())?;
        match ast.node_type {
            ASTNodeType::Reference { reference, .. } => Ok(reference),
            other => Err(format!("expected reference node, got {other:?}")),
        }
    }

    /// Parse via both paths and require they agree.
    fn parse_both(formula: &str) -> Result<ReferenceType, String> {
        let classic = parse_via_classic(formula)?;
        let span = parse_via_span(formula)?;
        assert_eq!(
            classic, span,
            "classic vs span parser disagree for {formula}"
        );
        Ok(classic)
    }

    fn expect_table(formula: &str) -> TableReference {
        let r = parse_both(formula).expect("parse ok");
        match r {
            ReferenceType::Table(t) => t,
            other => panic!("expected Table, got {other:?}"),
        }
    }

    fn expect_parse_err(formula: &str) {
        let classic = parse_via_classic(formula);
        let span = parse_via_span(formula);
        assert!(
            classic.is_err(),
            "classic parser unexpectedly accepted {formula}: {classic:?}"
        );
        assert!(
            span.is_err(),
            "span parser unexpectedly accepted {formula}: {span:?}"
        );
    }

    fn expect_combination(spec: Option<TableSpecifier>) -> Vec<TableSpecifier> {
        match spec {
            Some(TableSpecifier::Combination(parts)) => parts.into_iter().map(|b| *b).collect(),
            other => panic!("expected Combination, got {other:?}"),
        }
    }

    // ----------- positive: simple regression -----------

    #[test]
    fn simple_column() {
        let t = expect_table("=Table1[Column1]");
        assert_eq!(t.name, "Table1");
        assert_eq!(
            t.specifier,
            Some(TableSpecifier::Column("Column1".to_string()))
        );
    }

    #[test]
    fn simple_column_range() {
        let t = expect_table("=Table1[Column1:Column2]");
        assert_eq!(
            t.specifier,
            Some(TableSpecifier::ColumnRange(
                "Column1".to_string(),
                "Column2".to_string()
            ))
        );
    }

    #[test]
    fn simple_specials() {
        for (s, expected) in [
            ("=Table1[#All]", SpecialItem::All),
            ("=Table1[#Headers]", SpecialItem::Headers),
            ("=Table1[#Data]", SpecialItem::Data),
            ("=Table1[#Totals]", SpecialItem::Totals),
        ] {
            let t = expect_table(s);
            assert_eq!(t.specifier, Some(TableSpecifier::SpecialItem(expected)));
        }
    }

    #[test]
    fn this_row_at_only() {
        let t = expect_table("=Table1[@]");
        assert_eq!(
            t.specifier,
            Some(TableSpecifier::Row(TableRowSpecifier::Current))
        );
    }

    // ----------- positive: combinations preserving column parts -----------

    #[test]
    fn all_with_column_range_preserves_both_parts() {
        let t = expect_table("=Table1[[#All],[A]:[B]]");
        let parts = expect_combination(t.specifier);
        assert_eq!(
            parts,
            vec![
                TableSpecifier::SpecialItem(SpecialItem::All),
                TableSpecifier::ColumnRange("A".to_string(), "B".to_string()),
            ]
        );
    }

    #[test]
    fn headers_with_column() {
        let t = expect_table("=Table1[[#Headers],[Column1]]");
        let parts = expect_combination(t.specifier);
        assert_eq!(
            parts,
            vec![
                TableSpecifier::SpecialItem(SpecialItem::Headers),
                TableSpecifier::Column("Column1".to_string()),
            ]
        );
    }

    #[test]
    fn data_with_column_range() {
        let t = expect_table("=Table1[[#Data],[Column1]:[Column2]]");
        let parts = expect_combination(t.specifier);
        assert_eq!(
            parts,
            vec![
                TableSpecifier::SpecialItem(SpecialItem::Data),
                TableSpecifier::ColumnRange("Column1".to_string(), "Column2".to_string()),
            ]
        );
    }

    #[test]
    fn totals_with_column() {
        let t = expect_table("=Table1[[#Totals],[Column1]]");
        let parts = expect_combination(t.specifier);
        assert_eq!(
            parts,
            vec![
                TableSpecifier::SpecialItem(SpecialItem::Totals),
                TableSpecifier::Column("Column1".to_string()),
            ]
        );
    }

    #[test]
    fn effort_db_full_range_preserves_columns() {
        let t = expect_table("=EffortDB[[#All],[NPI]:[JMG Group]]");
        assert_eq!(t.name, "EffortDB");
        let parts = expect_combination(t.specifier);
        assert_eq!(
            parts,
            vec![
                TableSpecifier::SpecialItem(SpecialItem::All),
                TableSpecifier::ColumnRange("NPI".to_string(), "JMG Group".to_string()),
            ]
        );
    }

    #[test]
    fn column_range_with_spaces_in_names() {
        let t = expect_table("=Table1[[Col A]:[Col B]]");
        assert_eq!(
            t.specifier,
            Some(TableSpecifier::ColumnRange(
                "Col A".to_string(),
                "Col B".to_string()
            ))
        );
    }

    // ----------- positive: this-row variants -----------

    #[test]
    fn this_row_with_column_combination() {
        let t = expect_table("=Table1[[@],[Column1]]");
        let parts = expect_combination(t.specifier);
        assert_eq!(
            parts,
            vec![
                TableSpecifier::SpecialItem(SpecialItem::ThisRow),
                TableSpecifier::Column("Column1".to_string()),
            ]
        );
    }

    #[test]
    fn this_row_at_column_shorthand() {
        let t = expect_table("=Table1[@Column1]");
        let parts = expect_combination(t.specifier);
        assert_eq!(
            parts,
            vec![
                TableSpecifier::SpecialItem(SpecialItem::ThisRow),
                TableSpecifier::Column("Column1".to_string()),
            ]
        );
    }

    #[test]
    fn this_row_legacy_form() {
        let t = expect_table("=Table1[[#This Row],[Col]]");
        let parts = expect_combination(t.specifier);
        assert_eq!(
            parts,
            vec![
                TableSpecifier::SpecialItem(SpecialItem::ThisRow),
                TableSpecifier::Column("Col".to_string()),
            ]
        );
    }

    // ----------- positive: case-insensitivity -----------

    #[test]
    fn specials_are_case_insensitive() {
        let t = expect_table("=Table1[#headers]");
        assert_eq!(
            t.specifier,
            Some(TableSpecifier::SpecialItem(SpecialItem::Headers))
        );
        let t = expect_table("=Table1[#ALL]");
        assert_eq!(
            t.specifier,
            Some(TableSpecifier::SpecialItem(SpecialItem::All))
        );
        let t = expect_table("=Table1[[#this row],[col]]");
        let parts = expect_combination(t.specifier);
        assert_eq!(
            parts,
            vec![
                TableSpecifier::SpecialItem(SpecialItem::ThisRow),
                TableSpecifier::Column("col".to_string()),
            ]
        );
    }

    // ----------- positive: ' escape inside column names -----------
    //
    // OOXML / MS-XLSX uses a per-character escape: `'X` represents a literal
    // `X` (where X is one of `[`, `]`, `'`). Excel itself serializes a
    // column named `Col ]` as `[Col ']]` (single apostrophe before the
    // escaped `]`). We follow that canonical encoding here.

    #[test]
    fn column_name_with_escaped_close_bracket() {
        let t = expect_table("=Table1[Col ']]");
        assert_eq!(
            t.specifier,
            Some(TableSpecifier::Column("Col ]".to_string()))
        );
    }

    #[test]
    fn column_name_with_escaped_open_bracket() {
        let t = expect_table("=Table1[Col '[end]");
        assert_eq!(
            t.specifier,
            Some(TableSpecifier::Column("Col [end".to_string()))
        );
    }

    #[test]
    fn column_name_with_escaped_apostrophe() {
        // `''` -> literal `'`
        let t = expect_table("=Table1[O''Brien]");
        assert_eq!(
            t.specifier,
            Some(TableSpecifier::Column("O'Brien".to_string()))
        );
    }

    #[test]
    fn combination_with_escaped_close_bracket() {
        let t = expect_table("=Table1[[#Headers],[Col ']]]");
        let parts = expect_combination(t.specifier);
        assert_eq!(
            parts,
            vec![
                TableSpecifier::SpecialItem(SpecialItem::Headers),
                TableSpecifier::Column("Col ]".to_string()),
            ]
        );
    }

    // ----------- positive: non-ASCII column names -----------

    #[test]
    fn unicode_column_names() {
        for (formula, table, col) in [
            ("=Sales[Акт]", "Sales", "Акт"),
            ("=Café[Crème brûlée]", "Café", "Crème brûlée"),
            ("=分析[数量]", "分析", "数量"),
        ] {
            let t = expect_table(formula);
            assert_eq!(t.name, table);
            assert_eq!(t.specifier, Some(TableSpecifier::Column(col.to_string())));
        }
    }

    // ----------- positive: roundtrip via Display -----------

    #[test]
    fn display_roundtrips() {
        for input in [
            "Table1[Column1]",
            "Table1[Column1:Column2]",
            "Table1[#Headers]",
            "Table1[#Data]",
            "Table1[#Totals]",
            "Table1[#All]",
            "Table1[@]",
            "Table1[[#All],[A]:[B]]",
            "Table1[[#Headers],[Column1]]",
            "Table1[[#Data],[Column1]:[Column2]]",
            "Table1[[#Totals],[Column1]]",
            "Table1[[@],[Column1]]",
        ] {
            let r = ReferenceType::from_string(input).expect("parse ok");
            let printed = r.to_string();
            let r2 = ReferenceType::from_string(&printed).expect("reparse ok");
            assert_eq!(r, r2, "roundtrip changed AST for {input}: {printed}");
        }
    }

    // ----------- positive: sheet-scoped -----------

    #[test]
    fn sheet_scoped_table_ref_still_drops_sheet() {
        let r = ReferenceType::from_string("Sheet1!Table1[Column1]").unwrap();
        assert_eq!(
            r,
            ReferenceType::Table(TableReference {
                name: "Table1".to_string(),
                specifier: Some(TableSpecifier::Column("Column1".to_string())),
            })
        );
    }

    // ----------- negative -----------

    #[test]
    fn rejects_trailing_garbage_after_column() {
        expect_parse_err("=Table1[Col]junk");
    }

    #[test]
    fn rejects_trailing_garbage_after_empty_specifier() {
        // Tokenizer may already split; verify the full formula still errors.
        let classic = parse_via_classic("=Table1[]abc");
        let span = parse_via_span("=Table1[]abc");
        assert!(classic.is_err(), "classic accepted: {classic:?}");
        assert!(span.is_err(), "span accepted: {span:?}");
    }

    #[test]
    fn rejects_unknown_special_item() {
        expect_parse_err("=Table1[#unknown]");
    }

    #[test]
    fn rejects_garbage_inside_combination() {
        expect_parse_err("=Table1[[#Data],junk]");
    }

    #[test]
    fn rejects_unterminated_bracket() {
        // Tokenizer error.
        assert!(Tokenizer::new("=Table1[Col").is_err());
        assert!(crate::parse("=Table1[Col").is_err());
    }

    #[test]
    fn rejects_malformed_escape() {
        // [Col '] — the ' is supposed to escape the next char; here it escapes ']'
        // which means the bracket never terminates.
        assert!(Tokenizer::new("=Table1[[Col ']]").is_err());
        assert!(crate::parse("=Table1[[Col ']]").is_err());
    }
}

#[cfg(test)]
mod sheet_ref_tests {
    use crate::parser::ReferenceType;
    use formualizer_common::{AxisBound, SheetLocator, SheetRef};

    #[test]
    fn parse_sheet_ref_preserves_abs_flags() {
        let r = ReferenceType::parse_sheet_ref("$A$1").unwrap();
        match r {
            SheetRef::Cell(cell) => {
                assert!(matches!(cell.sheet, SheetLocator::Current));
                assert_eq!(cell.coord.row(), 0);
                assert_eq!(cell.coord.col(), 0);
                assert!(cell.coord.row_abs());
                assert!(cell.coord.col_abs());
            }
            _ => panic!("expected cell"),
        }

        let r = ReferenceType::parse_sheet_ref("Sheet1!A$1").unwrap();
        match r {
            SheetRef::Cell(cell) => {
                assert_eq!(cell.sheet.name(), Some("Sheet1"));
                assert!(cell.coord.row_abs());
                assert!(!cell.coord.col_abs());
            }
            _ => panic!("expected cell"),
        }
    }

    #[test]
    fn parse_sheet_ref_supports_open_ended_ranges() {
        let r = ReferenceType::parse_sheet_ref("$A:$B").unwrap();
        match r {
            SheetRef::Range(range) => {
                assert!(range.start_row.is_none());
                assert!(range.end_row.is_none());
                assert_eq!(range.start_col.unwrap().index, 0);
                assert!(range.start_col.unwrap().abs);
                assert_eq!(range.end_col.unwrap().index, 1);
                assert!(range.end_col.unwrap().abs);
            }
            _ => panic!("expected range"),
        }

        let r = ReferenceType::parse_sheet_ref("1:$3").unwrap();
        match r {
            SheetRef::Range(range) => {
                assert!(range.start_col.is_none());
                assert!(range.end_col.is_none());
                let sr = range.start_row.unwrap();
                let er = range.end_row.unwrap();
                assert_eq!(sr.index, 0);
                assert!(!sr.abs);
                assert_eq!(er.index, 2);
                assert!(er.abs);
            }
            _ => panic!("expected range"),
        }

        let r = ReferenceType::parse_sheet_ref("A1:A").unwrap();
        match r {
            SheetRef::Range(range) => {
                assert_eq!(range.start_row.unwrap().index, 0);
                assert_eq!(range.start_col.unwrap().index, 0);
                assert!(range.end_row.is_none());
                assert_eq!(range.end_col.unwrap().index, 0);
            }
            _ => panic!("expected range"),
        }
    }

    #[test]
    fn parse_sheet_ref_allows_external_workbook_prefix() {
        let r = ReferenceType::parse_sheet_ref("[33]Sheet1!$B:$B").unwrap();
        match r {
            SheetRef::Range(range) => {
                assert_eq!(range.sheet.name(), Some("[33]Sheet1"));
                assert!(range.start_row.is_none());
                assert!(range.end_row.is_none());
                let sc = range.start_col.unwrap();
                let ec = range.end_col.unwrap();
                assert_eq!(sc.index, 1);
                assert!(sc.abs);
                assert_eq!(ec.index, 1);
                assert!(ec.abs);
            }
            _ => panic!("expected range"),
        }
    }

    #[test]
    fn to_sheet_ref_lossy_defaults_to_relative() {
        let rt = ReferenceType::cell(None, 1, 1);
        let sr = rt.to_sheet_ref_lossy().unwrap();
        match sr {
            SheetRef::Cell(cell) => {
                assert!(!cell.coord.row_abs());
                assert!(!cell.coord.col_abs());
                assert!(matches!(cell.sheet, SheetLocator::Current));
            }
            _ => panic!("expected cell"),
        }

        let rt = ReferenceType::range(Some("Sheet1".to_string()), None, Some(1), None, Some(1));
        let sr = rt.to_sheet_ref_lossy().unwrap();
        match sr {
            SheetRef::Range(range) => {
                assert_eq!(range.sheet.name(), Some("Sheet1"));
                assert!(range.start_row.is_none());
                assert_eq!(range.start_col, Some(AxisBound::new(0, false)));
                assert_eq!(range.end_col, Some(AxisBound::new(0, false)));
            }
            _ => panic!("expected range"),
        }
    }
}

#[cfg(test)]
mod semantics_regressions {
    use crate::parser::{ASTNodeType, Parser, ReferenceType};
    use crate::tokenizer::Tokenizer;

    #[test]
    fn exponent_is_right_associative() {
        let t = Tokenizer::new("=2^3^2").unwrap();
        let mut p = Parser::new(t.items, false);
        let ast = p.parse().unwrap();

        match ast.node_type {
            ASTNodeType::BinaryOp { op, left: _, right } => {
                assert_eq!(op, "^");
                // Expected: 2^(3^2)
                match right.node_type {
                    ASTNodeType::BinaryOp { op: op2, .. } => assert_eq!(op2, "^"),
                    other => panic!("expected right child to be exponent, got {other:?}"),
                }
            }
            other => panic!("expected BinaryOp, got {other:?}"),
        }
    }

    #[test]
    fn unary_minus_binds_tighter_than_exponent() {
        let t = Tokenizer::new("=-2^2").unwrap();
        let mut p = Parser::new(t.items, false);
        let ast = p.parse().unwrap();

        // Excel: =-2^2 means (-2)^2 = 4
        match ast.node_type {
            ASTNodeType::BinaryOp { op, left, .. } => {
                assert_eq!(op, "^");
                match left.node_type {
                    ASTNodeType::UnaryOp { op: op2, .. } => assert_eq!(op2, "-"),
                    other => panic!("expected unary under exponent, got {other:?}"),
                }
            }
            other => panic!("expected BinaryOp, got {other:?}"),
        }
    }

    mod scientific_notation {
        use crate::parser::{ASTNode, ASTNodeType, Parser, ParserError, ReferenceType, parse};
        use crate::tokenizer::Tokenizer;
        use formualizer_common::LiteralValue;

        fn parse_formula(formula: &str) -> Result<ASTNode, ParserError> {
            let tokenizer = Tokenizer::new(formula).map_err(|e| ParserError {
                message: e.to_string(),
                position: Some(e.pos),
            })?;
            let mut parser = Parser::new(tokenizer.items, false);
            parser.parse()
        }

        fn assert_parsers_agree(formula: &str) {
            let token_ast = parse_formula(formula);
            let span_ast = parse(formula);
            match (&token_ast, &span_ast) {
                (Ok(a), Ok(b)) => assert_eq!(
                    a.node_type, b.node_type,
                    "token vs span parser disagree on {formula:?}"
                ),
                (Err(_), Err(_)) => {}
                other => panic!("token vs span parser disagree on {formula:?}: {other:?}"),
            }
        }

        #[test]
        fn test_sci_number_basic() {
            let ast = parse_formula("=1.5E+3").unwrap();
            match ast.node_type {
                ASTNodeType::Literal(LiteralValue::Number(n)) => assert_eq!(n, 1500.0),
                other => panic!("expected Literal Number, got {other:?}"),
            }
            assert_parsers_agree("=1.5E+3");
        }

        #[test]
        fn test_sci_minus_cell_ref() {
            // `=1E-A1` should parse as `1E - A1`, not as a single named range.
            let ast = parse_formula("=1E-A1").unwrap();
            match ast.node_type {
                ASTNodeType::BinaryOp { op, left, right } => {
                    assert_eq!(op, "-");
                    match left.node_type {
                        ASTNodeType::Reference { reference, .. } => match reference {
                            ReferenceType::NamedRange(name) => assert_eq!(name, "1E"),
                            other => panic!("expected NamedRange(\"1E\"), got {other:?}"),
                        },
                        other => panic!("expected reference on lhs, got {other:?}"),
                    }
                    match right.node_type {
                        ASTNodeType::Reference { reference, .. } => {
                            assert_eq!(reference, ReferenceType::cell(None, 1, 1))
                        }
                        other => panic!("expected A1 reference on rhs, got {other:?}"),
                    }
                }
                other => panic!("expected BinaryOp, got {other:?}"),
            }
            assert_parsers_agree("=1E-A1");
        }

        #[test]
        fn test_sci_plus_cell_ref() {
            let ast = parse_formula("=1E+A1").unwrap();
            match ast.node_type {
                ASTNodeType::BinaryOp { op, left, right } => {
                    assert_eq!(op, "+");
                    match left.node_type {
                        ASTNodeType::Reference { reference, .. } => match reference {
                            ReferenceType::NamedRange(name) => assert_eq!(name, "1E"),
                            other => panic!("expected NamedRange(\"1E\"), got {other:?}"),
                        },
                        other => panic!("expected reference on lhs, got {other:?}"),
                    }
                    match right.node_type {
                        ASTNodeType::Reference { reference, .. } => {
                            assert_eq!(reference, ReferenceType::cell(None, 1, 1))
                        }
                        other => panic!("expected A1 reference on rhs, got {other:?}"),
                    }
                }
                other => panic!("expected BinaryOp, got {other:?}"),
            }
            assert_parsers_agree("=1E+A1");
        }

        #[test]
        fn test_sci_dangling_lower_e_plus_errors() {
            // `=1e+` no longer becomes a silent NamedRange. The `+` is left
            // dangling, which the parser must reject.
            assert!(parse_formula("=1e+").is_err());
            assert!(parse("=1e+").is_err());
        }

        #[test]
        fn test_sci_dangling_decimal_minus_errors() {
            assert!(parse_formula("=1.5e-").is_err());
            assert!(parse("=1.5e-").is_err());
        }

        #[test]
        fn test_sci_dangling_upper_e_plus_errors() {
            assert!(parse_formula("=1E+").is_err());
            assert!(parse("=1E+").is_err());
        }

        #[test]
        fn test_sci_existing_numeric_literals_still_parse() {
            for (formula, expected) in [
                ("=1.5e-3", 0.0015),
                ("=5e10", 5e10),
                ("=1e2", 100.0),
                ("=1.", 1.0),
                ("=.5", 0.5),
            ] {
                let ast = parse_formula(formula)
                    .unwrap_or_else(|e| panic!("failed to parse {formula:?}: {}", e.message));
                match ast.node_type {
                    ASTNodeType::Literal(LiteralValue::Number(n)) => {
                        assert!(
                            (n - expected).abs() < 1e-9,
                            "{formula} -> {n}, expected {expected}"
                        );
                    }
                    other => panic!("expected Number for {formula}, got {other:?}"),
                }
                assert_parsers_agree(formula);
            }
        }
    }

    mod lambda_iife {
        use crate::parser::parse as span_parse;
        use crate::parser::{ASTNode, ASTNodeType, Parser};
        use crate::pretty::canonical_formula;
        use crate::tokenizer::Tokenizer;
        use formualizer_common::LiteralValue;

        fn parse_classic(formula: &str) -> ASTNode {
            let tokenizer = Tokenizer::new(formula).expect("tokenize");
            let mut parser = Parser::new(tokenizer.items, false);
            parser.parse().expect("classic parser")
        }

        fn parse_both(formula: &str) -> ASTNode {
            let classic = parse_classic(formula);
            let span = span_parse(formula).expect("span parser");
            assert_eq!(
                classic.fingerprint(),
                span.fingerprint(),
                "classic vs span parser produced different ASTs for {formula:?}"
            );
            classic
        }

        #[test]
        fn test_lambda_immediate_invocation_unary() {
            let ast = parse_both("=LAMBDA(x,x+1)(5)");
            let (callee, args) = match ast.node_type {
                ASTNodeType::Call { callee, args } => (callee, args),
                other => panic!("expected Call, got {other:?}"),
            };
            assert_eq!(args.len(), 1);
            match &args[0].node_type {
                ASTNodeType::Literal(LiteralValue::Number(n)) => assert_eq!(*n, 5.0),
                other => panic!("expected literal 5, got {other:?}"),
            }
            match callee.node_type {
                ASTNodeType::Function {
                    name,
                    args: fn_args,
                } => {
                    assert_eq!(name.to_uppercase(), "LAMBDA");
                    assert_eq!(fn_args.len(), 2);
                    // First arg is the parameter name 'x' (parsed as a NamedRange ref).
                    match &fn_args[1].node_type {
                        ASTNodeType::BinaryOp { op, .. } => assert_eq!(op, "+"),
                        other => panic!("expected binary op body, got {other:?}"),
                    }
                }
                other => panic!("expected Function callee, got {other:?}"),
            }
        }

        #[test]
        fn test_lambda_immediate_invocation_binary() {
            let ast = parse_both("=LAMBDA(a,b,a+b)(1,2)");
            let (callee, args) = match ast.node_type {
                ASTNodeType::Call { callee, args } => (callee, args),
                other => panic!("expected Call, got {other:?}"),
            };
            assert_eq!(args.len(), 2);
            match callee.node_type {
                ASTNodeType::Function {
                    name,
                    args: fn_args,
                } => {
                    assert_eq!(name.to_uppercase(), "LAMBDA");
                    assert_eq!(fn_args.len(), 3);
                }
                other => panic!("expected Function callee, got {other:?}"),
            }
        }

        #[test]
        fn test_parenthesized_lambda_invocation() {
            let ast = parse_both("=(LAMBDA(x,x))(5)");
            match ast.node_type {
                ASTNodeType::Call { callee, args } => {
                    assert_eq!(args.len(), 1);
                    match callee.node_type {
                        ASTNodeType::Function { name, .. } => {
                            assert_eq!(name.to_uppercase(), "LAMBDA")
                        }
                        other => panic!("expected Function callee, got {other:?}"),
                    }
                }
                other => panic!("expected Call, got {other:?}"),
            }
        }

        #[test]
        fn test_double_call_via_grouping() {
            // (f())() => Call(Function(f, []), [])
            // Note: tokenizer sees `f(` as Func/Open, so the first call binds
            // to Function. The trailing `()` is the postfix Call.
            let ast = parse_both("=f()()");
            match ast.node_type {
                ASTNodeType::Call { callee, args } => {
                    assert!(args.is_empty(), "outer call should have no args");
                    match callee.node_type {
                        ASTNodeType::Function {
                            name,
                            args: inner_args,
                        } => {
                            assert_eq!(name, "f");
                            assert!(inner_args.is_empty());
                        }
                        other => panic!("expected Function f callee, got {other:?}"),
                    }
                }
                other => panic!("expected Call, got {other:?}"),
            }
        }

        #[test]
        fn test_double_postfix_call() {
            // (LAMBDA(x,x))(5)(6) => two postfix Call nodes stacked.
            let ast = parse_both("=(LAMBDA(x,x))(5)(6)");
            match ast.node_type {
                ASTNodeType::Call { callee, args } => {
                    assert_eq!(args.len(), 1);
                    match &args[0].node_type {
                        ASTNodeType::Literal(LiteralValue::Number(n)) => assert_eq!(*n, 6.0),
                        other => panic!("expected literal 6, got {other:?}"),
                    }
                    match callee.node_type {
                        ASTNodeType::Call {
                            callee: inner_callee,
                            args: inner_args,
                        } => {
                            assert_eq!(inner_args.len(), 1);
                            match inner_callee.node_type {
                                ASTNodeType::Function { name, .. } => {
                                    assert_eq!(name.to_uppercase(), "LAMBDA")
                                }
                                other => panic!("expected Function callee, got {other:?}"),
                            }
                        }
                        other => panic!("expected nested Call, got {other:?}"),
                    }
                }
                other => panic!("expected Call, got {other:?}"),
            }
        }

        #[test]
        fn test_lambda_nested_in_let_uses_plain_function_call() {
            // LET body's `f(3)` is a regular Function(f, [3]), not a Call node.
            let ast = parse_both("=LET(f,LAMBDA(x,x*2),f(3))");
            let args = match ast.node_type {
                ASTNodeType::Function { name, args } => {
                    assert_eq!(name.to_uppercase(), "LET");
                    args
                }
                other => panic!("expected LET function, got {other:?}"),
            };
            assert_eq!(args.len(), 3);
            match &args[2].node_type {
                ASTNodeType::Function { name, args: inner } => {
                    assert_eq!(name, "f");
                    assert_eq!(inner.len(), 1);
                }
                other => panic!("expected Function f(3), got {other:?}"),
            }
        }

        #[test]
        fn test_call_on_number_literal() {
            // Permissive parse: `(1+2)(3)` parses as Call(BinaryOp, [3]).
            let ast = parse_both("=(1+2)(3)");
            match ast.node_type {
                ASTNodeType::Call { callee, args } => {
                    assert_eq!(args.len(), 1);
                    match callee.node_type {
                        ASTNodeType::BinaryOp { op, .. } => assert_eq!(op, "+"),
                        other => panic!("expected BinaryOp callee, got {other:?}"),
                    }
                }
                other => panic!("expected Call, got {other:?}"),
            }
        }

        #[test]
        fn test_call_on_grouped_reference() {
            // `(A1)(3)` — parens force the LHS to be parsed as a primary, so the
            // trailing `(3)` becomes a postfix Call. (`A1(3)` itself tokenizes
            // as a function token `A1(` and so parses as Function("A1", [3]).)
            let ast = parse_both("=(A1)(3)");
            match ast.node_type {
                ASTNodeType::Call { callee, args } => {
                    assert_eq!(args.len(), 1);
                    match callee.node_type {
                        ASTNodeType::Reference { .. } => {}
                        other => panic!("expected Reference callee, got {other:?}"),
                    }
                }
                other => panic!("expected Call, got {other:?}"),
            }
        }

        #[test]
        fn test_lambda_empty_body_call_parses() {
            // `LAMBDA()(1)` parses; evaluator may complain. Parser should accept.
            let ast = parse_both("=LAMBDA()(1)");
            match ast.node_type {
                ASTNodeType::Call { args, .. } => assert_eq!(args.len(), 1),
                other => panic!("expected Call, got {other:?}"),
            }
        }

        #[test]
        fn test_bare_lambda_still_parses_as_function() {
            let ast = parse_both("=LAMBDA(x, x+1)");
            match ast.node_type {
                ASTNodeType::Function { name, args } => {
                    assert_eq!(name.to_uppercase(), "LAMBDA");
                    assert_eq!(args.len(), 2);
                }
                other => panic!("expected Function, got {other:?}"),
            }
        }

        #[test]
        fn test_lambda_as_argument_unchanged() {
            let ast = parse_both("=SUM(LAMBDA(x,x),1,2,3)");
            match ast.node_type {
                ASTNodeType::Function { name, args } => {
                    assert_eq!(name.to_uppercase(), "SUM");
                    assert_eq!(args.len(), 4);
                    matches!(args[0].node_type, ASTNodeType::Function { .. });
                }
                other => panic!("expected Function, got {other:?}"),
            }
        }

        #[test]
        fn test_pretty_print_call_round_trips() {
            let ast = parse_both("=LAMBDA(x,x+1)(5)");
            let printed = canonical_formula(&ast);
            // Pretty printer should keep the call shape.
            assert!(
                printed.contains("LAMBDA(") && printed.ends_with("(5)"),
                "unexpected pretty output: {printed}"
            );
            // Re-parsing the pretty form yields an equivalent fingerprint.
            let reparsed = span_parse(&printed).expect("reparse pretty output");
            assert_eq!(reparsed.fingerprint(), ast.fingerprint());
        }
    }

    #[test]
    fn quoted_sheet_name_allows_escaped_single_quote() {
        let r = ReferenceType::from_string("'Bob''s Sheet'!A1").unwrap();
        assert_eq!(
            r,
            ReferenceType::cell(Some("Bob's Sheet".to_string()), 1, 1)
        );
    }

    mod sheet_3d_references {
        use crate::parser::{
            ASTNode, ASTNodeType, Parser, ParserError, ReferenceType, parse as parse_span,
        };
        use crate::tokenizer::Tokenizer;

        fn parse_classic(formula: &str) -> Result<ASTNode, ParserError> {
            let tokenizer = Tokenizer::new(formula).map_err(|e| ParserError {
                message: e.to_string(),
                position: Some(e.pos),
            })?;
            let mut parser = Parser::new(tokenizer.items, false);
            parser.parse()
        }

        fn parse_both(formula: &str) -> ASTNode {
            let classic = parse_classic(formula).expect("classic parser");
            let span = parse_span(formula).expect("span parser");
            // Both paths should agree on the parsed reference shape.
            assert_eq!(classic.node_type, span.node_type);
            classic
        }

        fn extract_reference(ast: &ASTNode) -> &ReferenceType {
            match &ast.node_type {
                ASTNodeType::Reference { reference, .. } => reference,
                other => panic!("expected reference, got {other:?}"),
            }
        }

        #[test]
        fn test_3d_cell_bare() {
            let ast = parse_both("=Sheet1:Sheet3!A1");
            assert_eq!(
                extract_reference(&ast),
                &ReferenceType::Cell3D {
                    sheet_first: "Sheet1".to_string(),
                    sheet_last: "Sheet3".to_string(),
                    row: 1,
                    col: 1,
                    row_abs: false,
                    col_abs: false,
                }
            );
        }

        #[test]
        fn test_3d_cell_quoted() {
            let ast = parse_both("='Sheet 1':'Sheet 3'!A1");
            assert_eq!(
                extract_reference(&ast),
                &ReferenceType::Cell3D {
                    sheet_first: "Sheet 1".to_string(),
                    sheet_last: "Sheet 3".to_string(),
                    row: 1,
                    col: 1,
                    row_abs: false,
                    col_abs: false,
                }
            );
        }

        #[test]
        fn test_3d_range() {
            let ast = parse_both("=Sheet1:Sheet3!A1:B2");
            assert_eq!(
                extract_reference(&ast),
                &ReferenceType::Range3D {
                    sheet_first: "Sheet1".to_string(),
                    sheet_last: "Sheet3".to_string(),
                    start_row: Some(1),
                    start_col: Some(1),
                    end_row: Some(2),
                    end_col: Some(2),
                    start_row_abs: false,
                    start_col_abs: false,
                    end_row_abs: false,
                    end_col_abs: false,
                }
            );
        }

        #[test]
        fn test_3d_range_absolute() {
            let ast = parse_both("=Sheet1:Sheet3!$A$1:$B$2");
            assert_eq!(
                extract_reference(&ast),
                &ReferenceType::Range3D {
                    sheet_first: "Sheet1".to_string(),
                    sheet_last: "Sheet3".to_string(),
                    start_row: Some(1),
                    start_col: Some(1),
                    end_row: Some(2),
                    end_col: Some(2),
                    start_row_abs: true,
                    start_col_abs: true,
                    end_row_abs: true,
                    end_col_abs: true,
                }
            );
        }

        #[test]
        fn test_3d_inside_sum() {
            let ast = parse_both("=SUM(Sheet1:Sheet3!A1)");
            let args = match &ast.node_type {
                ASTNodeType::Function { name, args } => {
                    assert_eq!(name, "SUM");
                    args
                }
                other => panic!("expected function, got {other:?}"),
            };
            assert_eq!(args.len(), 1);
            assert_eq!(
                extract_reference(&args[0]),
                &ReferenceType::Cell3D {
                    sheet_first: "Sheet1".to_string(),
                    sheet_last: "Sheet3".to_string(),
                    row: 1,
                    col: 1,
                    row_abs: false,
                    col_abs: false,
                }
            );
        }

        #[test]
        fn test_3d_quoted_escape() {
            let ast = parse_both("='Bob''s Sheet':'End Sheet'!A1");
            assert_eq!(
                extract_reference(&ast),
                &ReferenceType::Cell3D {
                    sheet_first: "Bob's Sheet".to_string(),
                    sheet_last: "End Sheet".to_string(),
                    row: 1,
                    col: 1,
                    row_abs: false,
                    col_abs: false,
                }
            );
        }

        #[test]
        fn test_sheet_named_with_embedded_colon() {
            // Excel forbids ':' in sheet names, so a quoted sheet whose name
            // contains ':' must still parse as a single-sheet reference.
            let r = ReferenceType::from_string("'Weird:Name'!A1").unwrap();
            assert_eq!(
                r,
                ReferenceType::Cell {
                    sheet: Some("Weird:Name".to_string()),
                    row: 1,
                    col: 1,
                    row_abs: false,
                    col_abs: false,
                }
            );
        }

        #[test]
        fn test_incomplete_3d_reference() {
            // Sheet1: with empty second sheet name should be a parse error.
            assert!(parse_classic("=Sheet1:!A1").is_err());
            assert!(parse_span("=Sheet1:!A1").is_err());
        }

        #[test]
        fn test_3d_without_cell_part() {
            // Sheet range without any cell reference is invalid.
            assert!(parse_classic("=Sheet1:Sheet3!").is_err());
            assert!(parse_span("=Sheet1:Sheet3!").is_err());
        }

        #[test]
        fn test_3d_display_roundtrip() {
            let cases = [
                "=Sheet1:Sheet3!A1",
                "=Sheet1:Sheet3!A1:B2",
                "=Sheet1:Sheet3!$A$1:$B$2",
                "='Sheet 1':'Sheet 3'!A1",
                "='Bob''s Sheet':'End Sheet'!A1",
            ];
            for input in cases {
                let ast = parse_both(input);
                let r = extract_reference(&ast);
                let rendered = format!("={r}");
                assert_eq!(rendered, input, "display roundtrip mismatch for {input}");
                let reparsed_ast = parse_both(&rendered);
                assert_eq!(
                    extract_reference(&reparsed_ast),
                    r,
                    "reparse mismatch for {input}"
                );
            }
        }
    }
}

#[cfg(test)]
mod string_colon_interaction {
    //! Regression coverage for issue #79: `parse_string` previously discarded
    //! the pending `A1:` prefix when followed by a double-quoted string.

    use crate::parser::{ASTNodeType, Parser, ReferenceType};
    use crate::tokenizer::Tokenizer;

    fn extract_reference(ast: &crate::parser::ASTNode) -> ReferenceType {
        match &ast.node_type {
            ASTNodeType::Reference { reference, .. } => reference.clone(),
            other => panic!("expected Reference AST, got {other:?}"),
        }
    }

    #[test]
    fn test_cross_sheet_range_still_parses() {
        // Single-quoted sheet continuation must still produce a single Range
        // reference. Use a single-sheet form that exercises the `:`-glue path
        // currently supported end-to-end by both parsers.
        let formula = "='Sheet 1:Sheet 3'!A1:C10";

        let tokenizer = Tokenizer::new(formula).unwrap();
        let mut parser = Parser::new(tokenizer.items, false);
        let ast = parser
            .parse()
            .expect("classic parser should accept formula");
        let reference = extract_reference(&ast);
        assert!(
            matches!(reference, ReferenceType::Range { .. }),
            "expected Range reference, got {reference:?}"
        );

        let span_ast = crate::parser::parse(formula).expect("span parser should accept formula");
        let span_reference = extract_reference(&span_ast);
        assert_eq!(reference, span_reference);
    }

    #[test]
    fn test_colon_string_raises() {
        let formula = "=A1:\"text\"";

        let tokenizer = Tokenizer::new(formula).unwrap();
        let mut parser = Parser::new(tokenizer.items, false);
        let err = parser.parse().expect_err(
            "classic parser must reject `=A1:\"text\"` rather than silently discard the prefix",
        );
        assert!(
            !err.message.is_empty(),
            "parser error message should be non-empty"
        );

        let span_err =
            crate::parser::parse(formula).expect_err("span parser must reject `=A1:\"text\"`");
        assert!(!span_err.message.is_empty());
    }

    #[test]
    fn test_colon_string_in_function() {
        let formula = "=SUM(A1:\"text\")";

        let tokenizer = Tokenizer::new(formula).unwrap();
        let mut parser = Parser::new(tokenizer.items, false);
        assert!(
            parser.parse().is_err(),
            "classic parser must reject `=SUM(A1:\"text\")`"
        );

        assert!(
            crate::parser::parse(formula).is_err(),
            "span parser must reject `=SUM(A1:\"text\")`"
        );
    }
}

#[cfg(test)]
mod r1c1_disambiguation {
    //! Regression tests for issue #76: R1C1-shaped operands must never be
    //! misclassified as table references in the A1 (Excel) dialect.
    //!
    //! This issue does NOT add R1C1 dialect support. Acceptable outcomes for
    //! R1C1-shaped input are: existing `NamedRange` behaviour, or a clean
    //! `ParserError`. The forbidden outcome is `ReferenceType::Table(...)`.
    use crate::parser::{ASTNode, ASTNodeType, Parser, ReferenceType, TableReference, parse};
    use crate::tokenizer::Tokenizer;

    fn parse_classic(formula: &str) -> ASTNode {
        let tokenizer = Tokenizer::new(formula).expect("tokenize");
        let mut parser = Parser::new(tokenizer.items, false);
        parser.parse().expect("classic parse")
    }

    fn parse_span(formula: &str) -> ASTNode {
        parse(formula).expect("span parse")
    }

    fn assert_not_table(formula: &str, ast: &ASTNode) {
        if let ASTNodeType::Reference {
            reference: ReferenceType::Table(TableReference { name, specifier }),
            ..
        } = &ast.node_type
        {
            panic!(
                "R1C1-shaped input {formula:?} produced a Table reference: \
                 name={name:?}, specifier={specifier:?}"
            );
        }
    }

    /// `=R[1]C[2]` must NOT classify as a Table. With the structured-references
    /// strict trailing-garbage rejection in place, the table path errors out;
    /// the R1C1 pre-check then reroutes it as a NamedRange.
    #[test]
    fn test_r1c1_bracketed_offsets_not_table() {
        let ref_type = ReferenceType::from_string("R[1]C[2]");
        if let Ok(ReferenceType::Table(t)) = ref_type {
            panic!("expected non-Table outcome for R[1]C[2], got Table({t:?})")
        }

        let classic = parse_classic("=R[1]C[2]");
        assert_not_table("=R[1]C[2]", &classic);
        let spanned = parse_span("=R[1]C[2]");
        assert_not_table("=R[1]C[2]", &spanned);
    }

    /// `=R1C1` must NOT classify as a Table. Existing behaviour is `NamedRange`.
    #[test]
    fn test_r1c1_absolute() {
        let ref_type = ReferenceType::from_string("R1C1").expect("R1C1 should parse");
        assert!(
            !matches!(ref_type, ReferenceType::Table(_)),
            "R1C1 must not be a Table reference, got {ref_type:?}"
        );
        assert_not_table("=R1C1", &parse_classic("=R1C1"));
        assert_not_table("=R1C1", &parse_span("=R1C1"));
    }

    /// `=R1C[2]` must NOT classify as a Table. Pre-fix it produced
    /// `Table { name: "R1C", specifier: Column("2") }`.
    #[test]
    fn test_r1c1_mixed() {
        let ref_type = ReferenceType::from_string("R1C[2]");
        if let Ok(ReferenceType::Table(t)) = ref_type {
            panic!("expected non-Table for R1C[2], got {t:?}")
        }
        assert_not_table("=R1C[2]", &parse_classic("=R1C[2]"));
        assert_not_table("=R1C[2]", &parse_span("=R1C[2]"));
    }

    /// `=R[-1]C` must NOT classify as a Table.
    #[test]
    fn test_r1c1_negative_offset() {
        let ref_type = ReferenceType::from_string("R[-1]C");
        if let Ok(ReferenceType::Table(t)) = ref_type {
            panic!("expected non-Table for R[-1]C, got {t:?}")
        }
        assert_not_table("=R[-1]C", &parse_classic("=R[-1]C"));
        assert_not_table("=R[-1]C", &parse_span("=R[-1]C"));
    }

    /// `=RC[1]` must NOT classify as a Table. Pre-fix it produced
    /// `Table { name: "RC", specifier: Column("1") }`.
    #[test]
    fn test_r1c1_rc_with_bracket_only_col() {
        let ref_type = ReferenceType::from_string("RC[1]");
        if let Ok(ReferenceType::Table(t)) = ref_type {
            panic!("expected non-Table for RC[1], got {t:?}")
        }
        assert_not_table("=RC[1]", &parse_classic("=RC[1]"));
        assert_not_table("=RC[1]", &parse_span("=RC[1]"));
    }

    /// `=R5C[1]` must NOT classify as a Table.
    #[test]
    fn test_r1c1_row_digit_col_bracket() {
        let ref_type = ReferenceType::from_string("R5C[1]");
        if let Ok(ReferenceType::Table(t)) = ref_type {
            panic!("expected non-Table for R5C[1], got {t:?}")
        }
        assert_not_table("=R5C[1]", &parse_classic("=R5C[1]"));
        assert_not_table("=R5C[1]", &parse_span("=R5C[1]"));
    }

    /// `=R1` must remain a normal A1 cell reference (column R, row 1).
    /// Critical: do not over-broaden the heuristic.
    #[test]
    fn test_a1_r1_still_cell() {
        let r = ReferenceType::from_string("R1").expect("R1 should parse");
        match r {
            ReferenceType::Cell {
                row, col, sheet, ..
            } => {
                assert_eq!(row, 1);
                assert_eq!(col, 18); // 'R'
                assert!(sheet.is_none());
            }
            other => panic!("=R1 must remain an A1 cell, got {other:?}"),
        }
    }

    /// `=C5` must remain a normal A1 cell reference (column C, row 5).
    #[test]
    fn test_a1_c5_still_cell() {
        let r = ReferenceType::from_string("C5").expect("C5 should parse");
        assert!(
            matches!(r, ReferenceType::Cell { row: 5, col: 3, .. }),
            "=C5 must remain an A1 cell, got {r:?}"
        );
    }

    /// Regression: real Table references must keep working.
    #[test]
    fn test_table_reference_unchanged() {
        let r = ReferenceType::from_string("Table1[Col]").expect("Table1[Col] should parse");
        match r {
            ReferenceType::Table(t) => {
                assert_eq!(t.name, "Table1");
            }
            other => panic!("expected Table reference, got {other:?}"),
        }
    }

    /// Regression: external workbook refs are unaffected.
    #[test]
    fn test_external_workbook_ref_unchanged() {
        let r = ReferenceType::from_string("[1]Sheet1!A1").expect("external ref should parse");
        assert!(
            matches!(r, ReferenceType::External(_)),
            "=[1]Sheet1!A1 must remain External, got {r:?}"
        );
    }

    /// Cross-parser differential: classic and span-based parsers must agree on
    /// the high-level outcome (table vs not-table) for R1C1-shaped input.
    #[test]
    fn test_cross_parser_agreement_r1c1() {
        for formula in [
            "=R[1]C[2]",
            "=R1C1",
            "=RC",
            "=R[-1]C",
            "=R1C[2]",
            "=RC[1]",
            "=R5C[1]",
        ] {
            let classic = parse_classic(formula);
            let spanned = parse_span(formula);
            assert_not_table(formula, &classic);
            assert_not_table(formula, &spanned);
        }
    }
}