visi-core 0.2.2

Embeddable spreadsheet engine: Excel formula compilation and evaluation, dependency-tracked recalculation, and .xlsx import/export
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
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
4835
4836
4837
4838
4839
4840
4841
4842
4843
4844
4845
4846
4847
4848
4849
4850
4851
4852
4853
4854
4855
4856
4857
4858
4859
4860
4861
4862
4863
4864
4865
4866
4867
4868
4869
4870
4871
4872
4873
4874
4875
4876
4877
4878
4879
4880
4881
4882
4883
4884
4885
4886
4887
4888
4889
4890
4891
4892
4893
4894
4895
4896
4897
4898
4899
4900
4901
4902
4903
4904
4905
4906
4907
4908
4909
4910
4911
4912
4913
4914
4915
4916
4917
4918
4919
4920
4921
4922
4923
4924
4925
4926
4927
4928
4929
4930
4931
4932
4933
4934
4935
4936
4937
4938
4939
4940
4941
4942
4943
4944
4945
4946
4947
4948
4949
4950
4951
4952
4953
4954
4955
4956
4957
4958
4959
4960
4961
4962
4963
4964
4965
4966
4967
4968
4969
4970
4971
4972
4973
4974
4975
4976
4977
4978
4979
4980
4981
4982
4983
4984
4985
4986
4987
4988
4989
4990
4991
4992
4993
4994
4995
4996
4997
4998
4999
5000
5001
5002
5003
5004
5005
5006
5007
5008
5009
5010
5011
5012
5013
5014
5015
5016
5017
5018
5019
5020
5021
5022
5023
5024
5025
5026
5027
5028
5029
5030
5031
5032
5033
5034
5035
5036
5037
5038
5039
5040
5041
5042
5043
5044
5045
5046
5047
5048
5049
5050
5051
5052
5053
5054
5055
5056
5057
5058
5059
5060
5061
5062
5063
5064
5065
5066
5067
5068
5069
5070
5071
5072
5073
5074
5075
5076
5077
5078
5079
5080
5081
5082
5083
5084
5085
5086
5087
5088
5089
5090
5091
5092
5093
5094
5095
5096
5097
5098
5099
5100
5101
5102
5103
5104
5105
5106
5107
5108
5109
5110
5111
5112
5113
5114
5115
5116
5117
5118
5119
5120
5121
5122
5123
5124
5125
5126
5127
5128
5129
5130
5131
5132
5133
5134
5135
5136
5137
5138
5139
5140
5141
5142
5143
5144
5145
5146
5147
5148
5149
5150
5151
5152
5153
5154
5155
5156
5157
5158
5159
5160
5161
5162
5163
5164
5165
5166
5167
5168
5169
5170
5171
5172
5173
5174
5175
5176
5177
5178
5179
5180
5181
5182
5183
5184
5185
5186
5187
5188
5189
5190
5191
5192
5193
//! A tree-walking interpreter for VBA execution.
//!
//! Scope includes expressions, control flow, `Sub`/`Function`/`Property` calls,
//! `On Error`, class modules, `Dim As New` auto-instantiation, `Class_Initialize` /
//! `Class_Terminate` lifecycle tracking, custom events (`Event`/`RaiseEvent`/`WithEvents`),
//! document modules, and — when a [`Host`] is attached — the workbook host object
//! model and synchronous host events (`Worksheet_Change`, `Worksheet_Calculate`,
//! `Workbook_SheetChange`, `Workbook_SheetCalculate`, `Workbook_Open`, `Auto_Open`,
//! `Workbook_BeforeClose`, `Workbook_BeforeSave`).

use std::collections::HashMap;
use std::rc::Rc;

use super::ast::*;
use super::builtins;
use super::host::{Host, ObjRef};
use super::value::{self, ArithMode, Operand, VResult, Variant, VbaError};
use super::{VbaModule, VbaModuleKind, VbaProject};

/// How many statements a single `run` may execute before giving up.
const DEFAULT_MAX_OPS: u64 = 5_000_000;
/// How deep procedure calls may nest.
const DEFAULT_MAX_DEPTH: usize = 64;

/// Error 438 — the "object doesn't support this property or method" that
/// everything outside the implemented scope reports.
fn out_of_scope(what: &str) -> VbaError {
    VbaError::new(
        438,
        format!("Object doesn't support this property or method: {what} is not available"),
    )
}

/// The same refusal, for something that needs a workbook when none is attached.
fn needs_workbook(what: &str) -> VbaError {
    VbaError::new(
        438,
        format!(
            "Object doesn't support this property or method: {what} needs a workbook, and this run has none"
        ),
    )
}

/// Non-local control flow out of a statement.
#[derive(Debug, Clone, PartialEq)]
enum Flow {
    /// Fall through to the next statement.
    Normal,
    /// `Exit Sub` / `Exit Function` / `Exit Property`.
    ExitProc,
    /// `Exit For`.
    ExitFor,
    /// `Exit Do` (and `Exit While`).
    ExitDo,
    /// `GoTo`, or a jump into an error handler. Unwinds to the procedure
    /// body, where labels live.
    Goto(String),
}

/// What `On Error` is currently set to.
#[derive(Debug, Clone, PartialEq)]
enum Handler {
    /// No handler: an error propagates out of the procedure.
    None,
    /// `On Error Resume Next`.
    ResumeNext,
    /// `On Error GoTo <label>`.
    Goto(String),
}

/// Procedures sharing a name in a module (e.g. Sub/Function vs Property Get/Let/Set).
#[derive(Debug, Clone, Default)]
pub struct MemberProcs {
    pub sub_or_func: Option<Rc<Procedure>>,
    pub prop_get: Option<Rc<Procedure>>,
    pub prop_let: Option<Rc<Procedure>>,
    pub prop_set: Option<Rc<Procedure>>,
}

impl MemberProcs {
    pub fn insert(&mut self, proc: Rc<Procedure>) {
        match proc.kind {
            ProcKind::Sub | ProcKind::Function => self.sub_or_func = Some(proc),
            ProcKind::PropertyGet => self.prop_get = Some(proc),
            ProcKind::PropertyLet => self.prop_let = Some(proc),
            ProcKind::PropertySet => self.prop_set = Some(proc),
        }
    }

    pub fn first(&self) -> Option<Rc<Procedure>> {
        self.sub_or_func
            .as_ref()
            .or(self.prop_get.as_ref())
            .or(self.prop_let.as_ref())
            .or(self.prop_set.as_ref())
            .cloned()
    }
}

/// A parsed module environment in the VBA project.
#[derive(Debug, Clone)]
pub struct ModuleEnv {
    pub name: String,
    pub kind: VbaModuleKind,
    pub bound_sheet_id: Option<u64>,
    pub procs: HashMap<String, MemberProcs>,
    pub events: HashMap<String, Rc<Stmt>>,
    pub globals: HashMap<String, Variant>,
    pub auto_new_vars: HashMap<String, String>,
    pub with_events_vars: HashMap<String, String>,
    pub default_member: Option<String>,
    pub ast: Module,
}

impl ModuleEnv {
    pub fn new(
        name: String,
        kind: VbaModuleKind,
        bound_sheet_id: Option<u64>,
        ast: Module,
    ) -> Self {
        let mut procs: HashMap<String, MemberProcs> = HashMap::new();
        let mut events: HashMap<String, Rc<Stmt>> = HashMap::new();
        let mut globals: HashMap<String, Variant> = HashMap::new();
        let mut auto_new_vars: HashMap<String, String> = HashMap::new();
        let mut with_events_vars: HashMap<String, String> = HashMap::new();
        let mut default_member: Option<String> = None;

        for item in &ast.items {
            match item {
                ModuleItem::Attribute {
                    name: attr_name,
                    values,
                    ..
                } => {
                    if attr_name.to_ascii_lowercase().ends_with(".vb_usermemid")
                        && let Some(val_expr) = values.first()
                        && is_zero_expr(val_expr)
                        && let Some((member, _)) = attr_name.split_once('.')
                    {
                        default_member = Some(member.to_ascii_lowercase());
                    }
                }
                ModuleItem::Declaration(stmt) => match stmt {
                    Stmt::Dim {
                        vars, with_events, ..
                    } => {
                        for v in vars {
                            let key = v.name.to_ascii_lowercase();
                            if *with_events {
                                let ty_name =
                                    v.ty.as_ref()
                                        .and_then(|t| t.path.last())
                                        .cloned()
                                        .unwrap_or_default();
                                with_events_vars.insert(key.clone(), ty_name);
                                globals.insert(key, Variant::Object(ObjRef::Nothing));
                            } else if v.ty.as_ref().is_some_and(|t| t.is_new) {
                                let cls_name =
                                    v.ty.as_ref()
                                        .unwrap()
                                        .path
                                        .last()
                                        .cloned()
                                        .unwrap_or_default();
                                auto_new_vars.insert(key.clone(), cls_name);
                                globals.insert(key, Variant::Object(ObjRef::Nothing));
                            } else {
                                globals.insert(key, default_for(v.ty.as_ref()));
                            }
                        }
                    }
                    Stmt::Const { vars, .. } => {
                        for v in vars {
                            let key = v.name.to_ascii_lowercase();
                            globals.insert(key, default_for(v.ty.as_ref()));
                        }
                    }
                    Stmt::EventDef {
                        name: event_name, ..
                    } => {
                        events.insert(event_name.to_ascii_lowercase(), Rc::new(stmt.clone()));
                    }
                    _ => {}
                },
                ModuleItem::Procedure(p) => {
                    let key = p.name.to_ascii_lowercase();
                    for s in &p.body {
                        if let Stmt::Attribute {
                            name: attr_name,
                            values,
                            ..
                        } = s
                            && (attr_name.to_ascii_lowercase().ends_with(".vb_usermemid")
                                || attr_name.eq_ignore_ascii_case("vb_usermemid"))
                            && let Some(val_expr) = values.first()
                            && is_zero_expr(val_expr)
                        {
                            default_member = Some(key.clone());
                        }
                    }
                    procs.entry(key).or_default().insert(Rc::new(p.clone()));
                }
                ModuleItem::Conditional {
                    branches,
                    else_items,
                    ..
                } => {
                    for (_, b_items) in branches {
                        for b_item in b_items {
                            if let ModuleItem::Procedure(p) = b_item {
                                procs
                                    .entry(p.name.to_ascii_lowercase())
                                    .or_default()
                                    .insert(Rc::new(p.clone()));
                            }
                        }
                    }
                    if let Some(e_items) = else_items {
                        for e_item in e_items {
                            if let ModuleItem::Procedure(p) = e_item {
                                procs
                                    .entry(p.name.to_ascii_lowercase())
                                    .or_default()
                                    .insert(Rc::new(p.clone()));
                            }
                        }
                    }
                }
                _ => {}
            }
        }

        Self {
            name,
            kind,
            bound_sheet_id,
            procs,
            events,
            globals,
            auto_new_vars,
            with_events_vars,
            default_member,
            ast,
        }
    }
}

fn is_zero_expr(e: &Expr) -> bool {
    match e {
        Expr::Literal(Literal::Number { value, .. }) => *value == 0.0,
        Expr::Literal(Literal::Str(s)) => s == "0",
        _ => false,
    }
}

#[derive(Debug, Clone)]
pub struct EventSubscription {
    pub event_name: String,
    pub listener_module: String,
    pub listener_var_name: String,
    pub listener_instance: Option<u64>,
}

#[derive(Debug, Clone)]
pub struct UserClassInstance {
    pub id: u64,
    pub class_name: String,
    pub fields: HashMap<String, Variant>,
    pub auto_new_fields: HashMap<String, String>,
    pub with_events_fields: HashMap<String, String>,
    pub event_sinks: Vec<EventSubscription>,
    pub ref_count: usize,
    pub terminating: bool,
}

/// One procedure activation.
struct Frame {
    locals: HashMap<String, Variant>,
    auto_new_locals: HashMap<String, String>,
    with_events_locals: HashMap<String, String>,
    handler: Handler,
    in_handler: bool,
    failed_at: Option<usize>,
    with_stack: Vec<Variant>,
    me: Option<ObjRef>,
    module_name: String,
}

impl Frame {
    fn new() -> Self {
        Self {
            locals: HashMap::new(),
            auto_new_locals: HashMap::new(),
            with_events_locals: HashMap::new(),
            handler: Handler::None,
            in_handler: false,
            failed_at: None,
            with_stack: Vec::new(),
            me: None,
            module_name: String::new(),
        }
    }
}

/// The state `Err` exposes.
#[derive(Debug, Clone, Default)]
struct ErrState {
    number: i32,
    description: String,
}

/// Runs VBA procedures across single-module or multi-module projects.
pub struct Interpreter<'w> {
    modules: HashMap<String, ModuleEnv>,
    instances: HashMap<u64, UserClassInstance>,
    next_instance_id: u64,
    active_module: String,
    err: ErrState,
    ops: u64,
    max_ops: u64,
    depth: usize,
    max_depth: usize,
    host: Option<Host<'w>>,
    event_depth: usize,
}

impl<'w> Interpreter<'w> {
    /// Builds an interpreter over a single parsed module.
    pub fn new(module: Module) -> Self {
        let mut name = "Module1".to_string();
        for item in &module.items {
            if let ModuleItem::Attribute {
                name: attr_name,
                values,
                ..
            } = item
                && attr_name.eq_ignore_ascii_case("vb_name")
                && let Some(Expr::Literal(Literal::Str(n))) = values.first()
            {
                name = n.clone();
            }
        }
        let env = ModuleEnv::new(name.clone(), VbaModuleKind::Standard, None, module);
        let mut modules = HashMap::new();
        modules.insert(name.to_ascii_lowercase(), env);
        Self {
            modules,
            instances: HashMap::new(),
            next_instance_id: 1,
            active_module: name.to_ascii_lowercase(),
            err: ErrState::default(),
            ops: 0,
            max_ops: DEFAULT_MAX_OPS,
            depth: 0,
            max_depth: DEFAULT_MAX_DEPTH,
            host: None,
            event_depth: 0,
        }
    }

    /// Builds an interpreter from a list of project modules.
    pub fn from_modules(modules_list: Vec<VbaModule>, target_module: Option<&str>) -> Self {
        let mut modules = HashMap::new();
        let mut default_active = String::new();

        for m in modules_list {
            let parsed = super::parser::parse_module(&m.source)
                .unwrap_or_else(|_| Module { items: Vec::new() });
            let env = ModuleEnv::new(m.name.clone(), m.kind, m.bound_sheet_id, parsed);
            let lower = m.name.to_ascii_lowercase();
            if default_active.is_empty() || m.kind == VbaModuleKind::Standard {
                default_active = lower.clone();
            }
            modules.insert(lower, env);
        }

        let active_module = target_module
            .map(|t| t.to_ascii_lowercase())
            .unwrap_or(default_active);

        Self {
            modules,
            instances: HashMap::new(),
            next_instance_id: 1,
            active_module,
            err: ErrState::default(),
            ops: 0,
            max_ops: DEFAULT_MAX_OPS,
            depth: 0,
            max_depth: DEFAULT_MAX_DEPTH,
            host: None,
            event_depth: 0,
        }
    }

    /// Builds an interpreter from a `VbaProject`.
    pub fn from_project(project: &VbaProject, target_module: Option<&str>) -> VResult<Self> {
        let mut modules = HashMap::new();
        let mut default_active = String::new();

        for m in &project.modules {
            let parsed = super::parser::parse_module(&m.source).map_err(|e| {
                VbaError::new(
                    13,
                    format!("Syntax error in module {}: {}", m.name, e.message),
                )
            })?;
            let env = ModuleEnv::new(m.name.clone(), m.kind, m.bound_sheet_id, parsed);
            let lower = m.name.to_ascii_lowercase();
            if default_active.is_empty() || m.kind == VbaModuleKind::Standard {
                default_active = lower.clone();
            }
            modules.insert(lower, env);
        }

        let active_module = if let Some(t) = target_module {
            let lower_t = t.to_ascii_lowercase();
            if !modules.contains_key(&lower_t) {
                return Err(VbaError::new(35, format!("Module not found: {t}")));
            }
            lower_t
        } else {
            default_active
        };

        Ok(Self {
            modules,
            instances: HashMap::new(),
            next_instance_id: 1,
            active_module,
            err: ErrState::default(),
            ops: 0,
            max_ops: DEFAULT_MAX_OPS,
            depth: 0,
            max_depth: DEFAULT_MAX_DEPTH,
            host: None,
            event_depth: 0,
        })
    }

    /// Adds a parsed module to this interpreter.
    pub fn add_module(
        &mut self,
        name: &str,
        kind: VbaModuleKind,
        bound_sheet_id: Option<u64>,
        ast: Module,
    ) {
        let env = ModuleEnv::new(name.to_string(), kind, bound_sheet_id, ast);
        self.modules.insert(name.to_ascii_lowercase(), env);
    }

    /// Binds a workbook, enabling the host object model.
    pub fn with_host(mut self, host: Host<'w>) -> Self {
        self.host = Some(host);
        self
    }

    /// Whether the run changed the workbook.
    pub fn mutated(&self) -> bool {
        self.host.as_ref().is_some_and(|h| h.mutated())
    }

    /// Settles any outstanding recalculation.
    pub fn finish(&mut self) {
        if let Some(h) = self.host.as_mut() {
            h.finish();
        }
        // Clean up remaining global class instances
        let mut all_globals = Vec::new();
        for m in self.modules.values_mut() {
            for v in m.globals.values() {
                all_globals.push(v.clone());
            }
        }
        for g in all_globals {
            self.dec_ref(&g);
        }
    }

    fn host(&mut self, what: &str) -> VResult<&mut Host<'w>> {
        self.host.as_mut().ok_or_else(|| needs_workbook(what))
    }

    /// Caps how many statements a run may execute.
    pub fn with_max_ops(mut self, max_ops: u64) -> Self {
        self.max_ops = max_ops;
        self
    }

    /// Whether events are currently enabled.
    pub fn enable_events(&self) -> bool {
        self.host.as_ref().is_none_or(|h| h.enable_events)
    }

    /// Returns the resolved type name for a variant (e.g. "Class1" for UserClass).
    pub fn type_name_of(&self, v: &Variant) -> String {
        match v {
            Variant::Object(ObjRef::UserClass(id)) => {
                if let Some(inst) = self.instances.get(id) {
                    inst.class_name.clone()
                } else {
                    "Object".to_string()
                }
            }
            Variant::Object(ObjRef::Nothing) => "Nothing".to_string(),
            _ => v.type_name().to_string(),
        }
    }

    pub fn class_name_of(&self, id: u64) -> String {
        self.instances
            .get(&id)
            .map(|i| i.class_name.clone())
            .unwrap_or_else(|| "Object".to_string())
    }

    /// Runs the named procedure and returns its value.
    pub fn run(&mut self, name: &str, args: Vec<Variant>) -> VResult<Variant> {
        self.ops = 0;
        self.init_all_modules()?;
        let res = self.call_procedure(name, args)?;
        self.drain_and_fire_events()?;
        Ok(res)
    }

    /// Runs startup macro events (`Workbook_Open` in `ThisWorkbook` then `Auto_Open` in standard modules).
    pub fn run_open_events(&mut self) -> VResult<()> {
        self.ops = 0;
        self.init_all_modules()?;

        // 1. Workbook_Open in ThisWorkbook (document module)
        if let Some(m_env) = self.modules.get("thisworkbook")
            && let Some(mp) = m_env.procs.get("workbook_open")
            && let Some(sub) = mp.first()
        {
            let mut frame = Frame::new();
            frame.module_name = "thisworkbook".to_string();
            frame.me = Some(ObjRef::Workbook);
            let old_active = self.active_module.clone();
            self.active_module = "thisworkbook".to_string();
            let res = self.call_body_with_frame(&sub, Vec::new(), &mut frame);
            self.active_module = old_active;
            res?;
        }

        // 2. Auto_Open in standard modules
        let std_mods: Vec<String> = self
            .modules
            .values()
            .filter(|m| m.kind == VbaModuleKind::Standard)
            .map(|m| m.name.clone())
            .collect();

        for mod_name in std_mods {
            if let Some(m_env) = self.modules.get(&mod_name.to_ascii_lowercase())
                && let Some(mp) = m_env.procs.get("auto_open")
                && let Some(sub) = mp.first()
            {
                let mut frame = Frame::new();
                frame.module_name = mod_name.clone();
                let old_active = self.active_module.clone();
                self.active_module = mod_name.to_ascii_lowercase();
                let res = self.call_body_with_frame(&sub, Vec::new(), &mut frame);
                self.active_module = old_active;
                res?;
            }
        }

        self.drain_and_fire_events()?;
        Ok(())
    }

    /// Fires `Workbook_BeforeClose` event. Returns true if canceled.
    pub fn fire_workbook_before_close(&mut self) -> VResult<bool> {
        if !self.enable_events() {
            return Ok(false);
        }
        if let Some(m_env) = self.modules.get("thisworkbook")
            && let Some(mp) = m_env.procs.get("workbook_beforeclose")
            && let Some(sub) = mp.first()
        {
            let mut frame = Frame::new();
            frame.module_name = "thisworkbook".to_string();
            frame.me = Some(ObjRef::Workbook);
            let param_name = sub
                .params
                .first()
                .map(|p| p.name.to_ascii_lowercase())
                .unwrap_or_else(|| "cancel".to_string());
            frame
                .locals
                .insert(param_name.clone(), Variant::Boolean(false));
            let old_active = self.active_module.clone();
            self.active_module = "thisworkbook".to_string();
            self.exec_procedure_body(&sub.body, &mut frame)?;
            self.active_module = old_active;
            let canceled = frame
                .locals
                .get(&param_name)
                .is_some_and(|v| v.to_bool().unwrap_or(false));
            return Ok(canceled);
        }
        Ok(false)
    }

    /// Fires `Workbook_BeforeSave` event. Returns true if canceled.
    pub fn fire_workbook_before_save(&mut self, save_as_ui: bool) -> VResult<bool> {
        if !self.enable_events() {
            return Ok(false);
        }
        if let Some(m_env) = self.modules.get("thisworkbook")
            && let Some(mp) = m_env.procs.get("workbook_beforesave")
            && let Some(sub) = mp.first()
        {
            let mut frame = Frame::new();
            frame.module_name = "thisworkbook".to_string();
            frame.me = Some(ObjRef::Workbook);
            if let Some(p1) = sub.params.first() {
                frame
                    .locals
                    .insert(p1.name.to_ascii_lowercase(), Variant::Boolean(save_as_ui));
            }
            let cancel_name = sub
                .params
                .get(1)
                .map(|p| p.name.to_ascii_lowercase())
                .unwrap_or_else(|| "cancel".to_string());
            frame
                .locals
                .insert(cancel_name.clone(), Variant::Boolean(false));
            let old_active = self.active_module.clone();
            self.active_module = "thisworkbook".to_string();
            self.exec_procedure_body(&sub.body, &mut frame)?;
            self.active_module = old_active;
            let canceled = frame
                .locals
                .get(&cancel_name)
                .is_some_and(|v| v.to_bool().unwrap_or(false));
            return Ok(canceled);
        }
        Ok(false)
    }

    fn init_all_modules(&mut self) -> VResult<()> {
        let mod_names: Vec<String> = self.modules.keys().cloned().collect();
        for mod_name in mod_names {
            let items = if let Some(m) = self.modules.get(&mod_name) {
                m.ast.items.clone()
            } else {
                continue;
            };
            for item in &items {
                if let ModuleItem::Declaration(stmt) = item {
                    let mut frame = Frame::new();
                    frame.module_name = mod_name.clone();
                    let old_active = self.active_module.clone();
                    self.active_module = mod_name.clone();
                    let r = self.exec_stmt(stmt, &mut frame, true);
                    self.active_module = old_active;
                    if let Some(m) = self.modules.get_mut(&mod_name) {
                        for (k, v) in frame.locals {
                            m.globals.insert(k, v);
                        }
                    }
                    r?;
                }
            }
        }
        Ok(())
    }

    fn find_class_module(&self, class_name: &str) -> Option<&ModuleEnv> {
        let lower = class_name.to_ascii_lowercase();
        self.modules
            .get(&lower)
            .filter(|m| m.kind == VbaModuleKind::Class)
    }

    fn find_document_module_name_by_sheet_id(&self, sheet_id: u64) -> Option<String> {
        self.modules
            .values()
            .find(|m| m.kind == VbaModuleKind::Document && m.bound_sheet_id == Some(sheet_id))
            .map(|m| m.name.to_ascii_lowercase())
    }

    pub fn instantiate_class(&mut self, class_name: &str) -> VResult<Variant> {
        let module = self.find_class_module(class_name).cloned().ok_or_else(|| {
            VbaError::new(
                424,
                format!("Object required: Class '{class_name}' not defined"),
            )
        })?;

        let id = self.next_instance_id;
        self.next_instance_id += 1;

        let mut fields = HashMap::new();
        let mut auto_new_fields = HashMap::new();
        let mut with_events_fields = HashMap::new();

        for (name, val) in &module.globals {
            fields.insert(name.clone(), val.clone());
        }
        for (name, cls) in &module.auto_new_vars {
            auto_new_fields.insert(name.clone(), cls.clone());
        }
        for (name, cls) in &module.with_events_vars {
            with_events_fields.insert(name.clone(), cls.clone());
        }

        let instance = UserClassInstance {
            id,
            class_name: module.name.clone(),
            fields,
            auto_new_fields,
            with_events_fields,
            event_sinks: Vec::new(),
            ref_count: 1,
            terminating: false,
        };
        self.instances.insert(id, instance);

        // Call Class_Initialize if present
        let init_proc = module
            .procs
            .get("class_initialize")
            .and_then(|mp| mp.first());
        if let Some(proc) = init_proc {
            let mut frame = Frame::new();
            frame.module_name = module.name.to_ascii_lowercase();
            frame.me = Some(ObjRef::UserClass(id));
            let old_active = self.active_module.clone();
            self.active_module = module.name.to_ascii_lowercase();
            let res = self.call_body_with_frame(&proc, Vec::new(), &mut frame);
            self.active_module = old_active;
            res?;
        }

        Ok(Variant::Object(ObjRef::UserClass(id)))
    }

    fn inc_ref(&mut self, val: &Variant) {
        if let Variant::Object(ObjRef::UserClass(id)) = val
            && let Some(inst) = self.instances.get_mut(id)
        {
            inst.ref_count += 1;
        }
    }

    fn dec_ref(&mut self, val: &Variant) {
        if let Variant::Object(ObjRef::UserClass(id)) = val {
            let mut terminate_proc = None;
            let mut class_mod_name = String::new();
            let mut fields_to_dec = Vec::new();

            if let Some(inst) = self.instances.get_mut(id) {
                if inst.ref_count > 0 {
                    inst.ref_count -= 1;
                }
                if inst.ref_count == 0 && !inst.terminating {
                    inst.terminating = true;
                    class_mod_name = inst.class_name.to_ascii_lowercase();
                    if let Some(m_env) = self.modules.get(&class_mod_name)
                        && let Some(mp) = m_env.procs.get("class_terminate")
                    {
                        terminate_proc = mp.first();
                    }
                    fields_to_dec = inst.fields.values().cloned().collect();
                }
            }

            if let Some(proc) = terminate_proc {
                let mut frame = Frame::new();
                frame.module_name = class_mod_name.clone();
                frame.me = Some(ObjRef::UserClass(*id));
                let old_active = self.active_module.clone();
                self.active_module = class_mod_name;
                let _ = self.call_body_with_frame(&proc, Vec::new(), &mut frame);
                self.active_module = old_active;
            }

            if let Some(inst) = self.instances.get(id)
                && inst.terminating
                && inst.ref_count == 0
            {
                for f in fields_to_dec {
                    self.dec_ref(&f);
                }
                self.instances.remove(id);
            }
        }
    }

    fn add_event_subscriptions(
        &mut self,
        target_inst_id: u64,
        listener_module: &str,
        listener_var_name: &str,
        listener_inst: Option<ObjRef>,
    ) {
        let listener_inst_id = match listener_inst {
            Some(ObjRef::UserClass(lid)) => Some(lid),
            _ => None,
        };
        let class_name = if let Some(inst) = self.instances.get(&target_inst_id) {
            inst.class_name.to_ascii_lowercase()
        } else {
            return;
        };

        let events: Vec<String> = if let Some(m_env) = self.modules.get(&class_name) {
            m_env.events.keys().cloned().collect()
        } else {
            Vec::new()
        };

        if let Some(inst) = self.instances.get_mut(&target_inst_id) {
            for evt in events {
                inst.event_sinks.push(EventSubscription {
                    event_name: evt,
                    listener_module: listener_module.to_string(),
                    listener_var_name: listener_var_name.to_string(),
                    listener_instance: listener_inst_id,
                });
            }
        }
    }

    fn remove_event_subscriptions(
        &mut self,
        target_inst_id: u64,
        listener_module: &str,
        listener_var_name: &str,
    ) {
        if let Some(inst) = self.instances.get_mut(&target_inst_id) {
            inst.event_sinks.retain(|s| {
                !(s.listener_module.eq_ignore_ascii_case(listener_module)
                    && s.listener_var_name.eq_ignore_ascii_case(listener_var_name))
            });
        }
    }

    fn drain_and_fire_events(&mut self) -> VResult<()> {
        if !self.enable_events() {
            if let Some(h) = self.host.as_mut() {
                h.pending_cell_changes.clear();
                h.pending_calculate_sheets.clear();
            }
            return Ok(());
        }

        self.event_depth += 1;
        if self.event_depth > self.max_depth {
            self.event_depth -= 1;
            return Err(VbaError::new(28, "Out of stack space"));
        }

        while let Some(change) = self
            .host
            .as_mut()
            .and_then(|h| h.pending_cell_changes.pop())
        {
            let sheet_id = change.sheet_id;
            let token = self.host("event range")?.new_range(
                change.sheet_id,
                change.row,
                change.col,
                change.height,
                change.width,
            );

            // 1. Worksheet_Change on the specific sheet document module
            if let Some(sheet_mod_name) = self.find_document_module_name_by_sheet_id(sheet_id)
                && let Some(m_env) = self.modules.get(&sheet_mod_name)
                && let Some(mp) = m_env.procs.get("worksheet_change")
                && let Some(sub) = mp.first()
            {
                let mut frame = Frame::new();
                frame.module_name = sheet_mod_name.clone();
                frame.me = Some(ObjRef::Worksheet(sheet_id));
                let old_active = self.active_module.clone();
                self.active_module = sheet_mod_name;
                let res = self.call_body_with_frame(&sub, vec![Variant::Object(token)], &mut frame);
                self.active_module = old_active;
                res?;
            }

            // 2. Workbook_SheetChange on ThisWorkbook
            if let Some(m_env) = self.modules.get("thisworkbook")
                && let Some(mp) = m_env.procs.get("workbook_sheetchange")
                && let Some(sub) = mp.first()
            {
                let mut frame = Frame::new();
                frame.module_name = "thisworkbook".to_string();
                frame.me = Some(ObjRef::Workbook);
                let old_active = self.active_module.clone();
                self.active_module = "thisworkbook".to_string();
                let res = self.call_body_with_frame(
                    &sub,
                    vec![
                        Variant::Object(ObjRef::Worksheet(sheet_id)),
                        Variant::Object(token),
                    ],
                    &mut frame,
                );
                self.active_module = old_active;
                res?;
            }
        }

        while let Some(sheet_id) = self
            .host
            .as_mut()
            .and_then(|h| h.pending_calculate_sheets.pop())
        {
            // 1. Worksheet_Calculate on sheet
            if let Some(sheet_mod_name) = self.find_document_module_name_by_sheet_id(sheet_id)
                && let Some(m_env) = self.modules.get(&sheet_mod_name)
                && let Some(mp) = m_env.procs.get("worksheet_calculate")
                && let Some(sub) = mp.first()
            {
                let mut frame = Frame::new();
                frame.module_name = sheet_mod_name.clone();
                frame.me = Some(ObjRef::Worksheet(sheet_id));
                let old_active = self.active_module.clone();
                self.active_module = sheet_mod_name;
                let res = self.call_body_with_frame(&sub, Vec::new(), &mut frame);
                self.active_module = old_active;
                res?;
            }

            // 2. Workbook_SheetCalculate on ThisWorkbook
            if let Some(m_env) = self.modules.get("thisworkbook")
                && let Some(mp) = m_env.procs.get("workbook_sheetcalculate")
                && let Some(sub) = mp.first()
            {
                let mut frame = Frame::new();
                frame.module_name = "thisworkbook".to_string();
                frame.me = Some(ObjRef::Workbook);
                let old_active = self.active_module.clone();
                self.active_module = "thisworkbook".to_string();
                let res = self.call_body_with_frame(
                    &sub,
                    vec![Variant::Object(ObjRef::Worksheet(sheet_id))],
                    &mut frame,
                );
                self.active_module = old_active;
                res?;
            }
        }

        self.event_depth -= 1;
        Ok(())
    }

    fn find_procedure_in_scope(
        &self,
        name: &str,
        frame: &Frame,
    ) -> Option<(String, Rc<Procedure>)> {
        let lower = name.to_ascii_lowercase();

        // 1. Current frame's me (if class or document instance)
        if let Some(me_obj) = frame.me {
            match me_obj {
                ObjRef::UserClass(id) => {
                    if let Some(inst) = self.instances.get(&id) {
                        let cls = inst.class_name.to_ascii_lowercase();
                        if let Some(m_env) = self.modules.get(&cls)
                            && let Some(mp) = m_env.procs.get(&lower)
                            && let Some(p) = mp.first()
                        {
                            return Some((cls, p));
                        }
                    }
                }
                ObjRef::Worksheet(sheet_id) => {
                    if let Some(doc_name) = self.find_document_module_name_by_sheet_id(sheet_id)
                        && let Some(m_env) = self.modules.get(&doc_name)
                        && let Some(mp) = m_env.procs.get(&lower)
                        && let Some(p) = mp.first()
                    {
                        return Some((doc_name, p));
                    }
                }
                ObjRef::Workbook => {
                    if let Some(m_env) = self.modules.get("thisworkbook")
                        && let Some(mp) = m_env.procs.get(&lower)
                        && let Some(p) = mp.first()
                    {
                        return Some(("thisworkbook".to_string(), p));
                    }
                }
                _ => {}
            }
        }

        // 2. Active module
        if let Some(m_env) = self.modules.get(&self.active_module)
            && let Some(mp) = m_env.procs.get(&lower)
            && let Some(p) = mp.first()
        {
            return Some((self.active_module.clone(), p));
        }

        // 3. Other standard modules
        for (m_name, m_env) in &self.modules {
            if m_env.kind == VbaModuleKind::Standard
                && *m_name != self.active_module
                && let Some(mp) = m_env.procs.get(&lower)
                && let Some(p) = mp.first()
            {
                return Some((m_name.clone(), p));
            }
        }

        None
    }

    fn call_procedure(&mut self, name: &str, args: Vec<Variant>) -> VResult<Variant> {
        let lower = name.to_ascii_lowercase();
        let mut target_mod = None;
        let mut target_proc = None;

        if let Some(m_env) = self.modules.get(&self.active_module)
            && let Some(mp) = m_env.procs.get(&lower)
            && let Some(p) = mp.first()
        {
            target_mod = Some(self.active_module.clone());
            target_proc = Some(p);
        }

        if target_proc.is_none() {
            for (m_name, m_env) in &self.modules {
                if m_env.kind == VbaModuleKind::Standard
                    && let Some(mp) = m_env.procs.get(&lower)
                    && let Some(p) = mp.first()
                {
                    target_mod = Some(m_name.clone());
                    target_proc = Some(p);
                    break;
                }
            }
        }

        if target_proc.is_none() {
            for (m_name, m_env) in &self.modules {
                if let Some(mp) = m_env.procs.get(&lower)
                    && let Some(p) = mp.first()
                {
                    target_mod = Some(m_name.clone());
                    target_proc = Some(p);
                    break;
                }
            }
        }

        let (mod_name, proc) = match (target_mod, target_proc) {
            (Some(m), Some(p)) => (m, p),
            _ => {
                return Err(VbaError::new(
                    35,
                    format!("Sub or Function not defined: {name}"),
                ));
            }
        };

        let mut frame = Frame::new();
        frame.module_name = mod_name.clone();
        if let Some(m_env) = self.modules.get(&mod_name)
            && m_env.kind == VbaModuleKind::Document
        {
            if let Some(sheet_id) = m_env.bound_sheet_id {
                frame.me = Some(ObjRef::Worksheet(sheet_id));
            } else {
                frame.me = Some(ObjRef::Workbook);
            }
        }

        let old_active = self.active_module.clone();
        self.active_module = mod_name;
        let result = self.call_body_with_frame(&proc, args, &mut frame);
        self.active_module = old_active;
        result
    }

    fn call_body_with_frame(
        &mut self,
        proc: &Procedure,
        args: Vec<Variant>,
        frame: &mut Frame,
    ) -> VResult<Variant> {
        self.depth += 1;
        if self.depth > self.max_depth {
            self.depth -= 1;
            return Err(VbaError::new(28, "Out of stack space"));
        }

        for (i, param) in proc.params.iter().enumerate() {
            let value = args.get(i).cloned().unwrap_or(Variant::Empty);
            let key = param.name.to_ascii_lowercase();
            self.inc_ref(&value);
            if param.ty.as_ref().is_some_and(|t| t.is_new) {
                let cls = param
                    .ty
                    .as_ref()
                    .unwrap()
                    .path
                    .last()
                    .cloned()
                    .unwrap_or_default();
                frame.auto_new_locals.insert(key.clone(), cls);
            }
            frame.locals.insert(key, value);
        }

        let ret_key = proc.name.to_ascii_lowercase();
        if proc.kind != ProcKind::Sub {
            frame
                .locals
                .entry(ret_key.clone())
                .or_insert(Variant::Empty);
        }

        let body_res = self.exec_procedure_body(&proc.body, frame);

        let ret = if proc.kind == ProcKind::Sub {
            Variant::Empty
        } else {
            frame
                .locals
                .get(&ret_key)
                .cloned()
                .unwrap_or(Variant::Empty)
        };

        // Dec ref local variables
        let locals = std::mem::take(&mut frame.locals);
        for (_, val) in locals {
            self.dec_ref(&val);
        }

        self.depth -= 1;
        body_res?;
        Ok(ret)
    }

    /// Runs a procedure body, resolving `GoTo` against its top-level labels.
    fn exec_procedure_body(&mut self, body: &[Stmt], frame: &mut Frame) -> VResult<()> {
        let mut pc = 0usize;
        while pc < body.len() {
            let flow = match self.exec_stmt(&body[pc], frame, false) {
                Ok(f) => f,
                Err(e) => {
                    frame.failed_at = Some(pc);
                    match self.take_handler(frame) {
                        Handler::ResumeNext => {
                            self.set_err(&e);
                            pc += 1;
                            continue;
                        }
                        Handler::Goto(label) => {
                            self.set_err(&e);
                            frame.in_handler = true;
                            Flow::Goto(label)
                        }
                        Handler::None => return Err(e),
                    }
                }
            };
            match flow {
                Flow::Normal => pc += 1,
                Flow::ExitProc => return Ok(()),
                Flow::ExitFor | Flow::ExitDo => pc += 1,
                Flow::Goto(label) => {
                    if label == "\0resume-next" {
                        pc = frame.failed_at.map(|i| i + 1).unwrap_or(pc + 1);
                        frame.in_handler = false;
                        continue;
                    }
                    match Self::find_label(body, &label) {
                        Some(i) => pc = i,
                        None => {
                            return Err(VbaError::new(
                                erl_label_error(),
                                format!("Label not defined: {label}"),
                            ));
                        }
                    }
                }
            }
        }
        Ok(())
    }

    fn find_label(body: &[Stmt], label: &str) -> Option<usize> {
        body.iter()
            .position(|s| matches!(s, Stmt::Label { name, .. } if name.eq_ignore_ascii_case(label)))
    }

    fn take_handler(&self, frame: &Frame) -> Handler {
        if frame.in_handler {
            Handler::None
        } else {
            frame.handler.clone()
        }
    }

    fn set_err(&mut self, e: &VbaError) {
        self.err = ErrState {
            number: e.number,
            description: e.description.clone(),
        };
    }

    fn exec_block(&mut self, body: &[Stmt], frame: &mut Frame) -> VResult<Flow> {
        for stmt in body {
            match self.exec_stmt(stmt, frame, false) {
                Ok(Flow::Normal) => {}
                Ok(other) => return Ok(other),
                Err(e) => match self.take_handler(frame) {
                    Handler::ResumeNext => {
                        self.set_err(&e);
                        continue;
                    }
                    Handler::Goto(label) => {
                        self.set_err(&e);
                        frame.in_handler = true;
                        return Ok(Flow::Goto(label));
                    }
                    Handler::None => return Err(e),
                },
            }
        }
        Ok(Flow::Normal)
    }

    fn tick(&mut self) -> VResult<()> {
        self.ops += 1;
        if self.ops > self.max_ops {
            return Err(VbaError::new(
                16,
                "Expression too complex: statement limit exceeded (possible infinite loop)",
            ));
        }
        Ok(())
    }

    fn exec_stmt(&mut self, stmt: &Stmt, frame: &mut Frame, module_level: bool) -> VResult<Flow> {
        self.tick()?;
        match stmt {
            Stmt::Label { .. } => Ok(Flow::Normal),

            Stmt::Dim {
                vars, with_events, ..
            } => {
                for v in vars {
                    let key = v.name.to_ascii_lowercase();
                    if *with_events {
                        let ty_name =
                            v.ty.as_ref()
                                .and_then(|t| t.path.last())
                                .cloned()
                                .unwrap_or_default();
                        frame.with_events_locals.insert(key.clone(), ty_name);
                        frame.locals.insert(key, Variant::Object(ObjRef::Nothing));
                    } else if v.ty.as_ref().is_some_and(|t| t.is_new) {
                        let cls =
                            v.ty.as_ref()
                                .unwrap()
                                .path
                                .last()
                                .cloned()
                                .unwrap_or_default();
                        frame.auto_new_locals.insert(key.clone(), cls);
                        frame.locals.insert(key, Variant::Object(ObjRef::Nothing));
                    } else {
                        let initial = default_for(v.ty.as_ref());
                        frame.locals.insert(key, initial);
                    }
                }
                Ok(Flow::Normal)
            }

            Stmt::Const { vars, .. } => {
                for v in vars {
                    let value = match &v.value {
                        Some(e) => self.eval(e, frame)?,
                        None => Variant::Empty,
                    };
                    self.inc_ref(&value);
                    frame.locals.insert(v.name.to_ascii_lowercase(), value);
                }
                Ok(Flow::Normal)
            }

            Stmt::Assign {
                target, value, set, ..
            } => {
                let v = self.eval(value, frame)?;
                let v = if *set { v } else { self.scalar(v)? };
                self.assign_with(target, v, frame, module_level, *set)?;
                Ok(Flow::Normal)
            }

            Stmt::Call { expr, .. } => {
                self.eval(expr, frame)?;
                Ok(Flow::Normal)
            }

            Stmt::If {
                branches,
                else_body,
                ..
            } => {
                for (cond, body) in branches {
                    let c = self.eval(cond, frame)?;
                    if self.scalar(c)?.to_bool_condition()? {
                        return self.exec_block(body, frame);
                    }
                }
                if let Some(body) = else_body {
                    return self.exec_block(body, frame);
                }
                Ok(Flow::Normal)
            }

            Stmt::SelectCase {
                subject,
                cases,
                case_else,
                ..
            } => {
                let s = self.eval(subject, frame)?;
                let s = self.scalar(s)?;
                let text_compare = matches!(s, Variant::Str(_)) && is_constant(subject);
                let bool_compare =
                    matches!(s, Variant::Boolean(_)) && is_statically_boolean(subject);
                for clause in cases {
                    for m in &clause.matches {
                        if self.case_matches(&s, m, frame, text_compare, bool_compare)? {
                            return self.exec_block(&clause.body, frame);
                        }
                    }
                }
                if let Some(body) = case_else {
                    return self.exec_block(body, frame);
                }
                Ok(Flow::Normal)
            }

            Stmt::For {
                var,
                from,
                to,
                step,
                body,
                ..
            } => self.exec_for(var, from, to, step.as_ref(), body, frame),

            Stmt::ForEach {
                var,
                iterable,
                body,
                ..
            } => self.exec_for_each(var, iterable, body, frame),

            Stmt::DoLoop {
                pre, post, body, ..
            } => self.exec_do(pre.as_ref(), post.as_ref(), body, frame),

            Stmt::With { subject, body, .. } => {
                let subject = self.eval(subject, frame)?;
                frame.with_stack.push(subject);
                let flow = self.exec_block(body, frame);
                frame.with_stack.pop();
                flow
            }

            Stmt::Exit { kind, .. } => Ok(match kind {
                ExitKind::Sub | ExitKind::Function | ExitKind::Property => Flow::ExitProc,
                ExitKind::For => Flow::ExitFor,
                ExitKind::Do | ExitKind::While => Flow::ExitDo,
            }),

            Stmt::GoTo { label, .. } => Ok(Flow::Goto(label.clone())),

            Stmt::OnError { kind, .. } => {
                frame.handler = match kind {
                    OnErrorKind::GoTo(label) => Handler::Goto(label.clone()),
                    OnErrorKind::ResumeNext => Handler::ResumeNext,
                    OnErrorKind::Disable => Handler::None,
                };
                frame.in_handler = false;
                Ok(Flow::Normal)
            }

            Stmt::Resume { kind, .. } => {
                frame.in_handler = false;
                Ok(match kind {
                    ResumeKind::Label(label) => Flow::Goto(label.clone()),
                    ResumeKind::Next => Flow::Goto("\0resume-next".to_string()),
                    ResumeKind::Retry => Flow::Goto("\0resume-next".to_string()),
                })
            }

            Stmt::Stop { .. } | Stmt::End { .. } => Ok(Flow::ExitProc),

            Stmt::EventDef { .. } => Ok(Flow::Normal),

            Stmt::RaiseEvent { name, args, .. } => {
                let mut arg_vals = self.eval_args(args, frame)?;
                let Some(ObjRef::UserClass(inst_id)) = frame.me else {
                    return Err(VbaError::new(
                        438,
                        "RaiseEvent must be called within a class instance",
                    ));
                };

                let sinks = self
                    .instances
                    .get(&inst_id)
                    .map(|inst| inst.event_sinks.clone())
                    .unwrap_or_default();
                let lower_event = name.to_ascii_lowercase();

                for sink in sinks {
                    if sink.event_name == lower_event {
                        let handler_name = format!("{}_{}", sink.listener_var_name, name);
                        if let Some(m_env) = self.modules.get(&sink.listener_module)
                            && let Some(mp) = m_env.procs.get(&handler_name.to_ascii_lowercase())
                            && let Some(proc) = mp.first()
                        {
                            let mut handler_frame = Frame::new();
                            handler_frame.module_name = sink.listener_module.clone();
                            handler_frame.me = sink.listener_instance.map(ObjRef::UserClass);
                            let old_active = self.active_module.clone();
                            self.active_module = sink.listener_module.clone();

                            for (i, p) in proc.params.iter().enumerate() {
                                let v = arg_vals.get(i).cloned().unwrap_or(Variant::Empty);
                                handler_frame.locals.insert(p.name.to_ascii_lowercase(), v);
                            }

                            self.exec_procedure_body(&proc.body, &mut handler_frame)?;

                            for (i, p) in proc.params.iter().enumerate() {
                                if p.by != Some(PassBy::Value)
                                    && let Some(new_val) =
                                        handler_frame.locals.get(&p.name.to_ascii_lowercase())
                                    && i < arg_vals.len()
                                {
                                    arg_vals[i] = new_val.clone();
                                }
                            }

                            self.active_module = old_active;
                        }
                    }
                }

                // Copy ByRef parameter changes back to caller's variables if args were identifiers
                for (i, a) in args.iter().enumerate() {
                    if let Some(Expr::Ident { name: arg_var, .. }) = &a.value
                        && i < arg_vals.len()
                    {
                        let pos = a.value.as_ref().unwrap().pos();
                        self.assign_with(
                            &Expr::Ident {
                                name: arg_var.clone(),
                                pos,
                            },
                            arg_vals[i].clone(),
                            frame,
                            false,
                            false,
                        )?;
                    }
                }

                Ok(Flow::Normal)
            }

            Stmt::Attribute { .. } => Ok(Flow::Normal),

            Stmt::ReDim { .. } => Err(out_of_scope("ReDim")),
            Stmt::Erase { .. } => Err(out_of_scope("Erase")),
            Stmt::GoSub { .. } | Stmt::Return { .. } => Err(out_of_scope("GoSub")),
            Stmt::OnGoto { .. } => Err(out_of_scope("On ... GoTo")),
            Stmt::TypeDef { .. } => Err(out_of_scope("Type")),
            Stmt::EnumDef { .. } => Err(out_of_scope("Enum")),
            Stmt::Declare { .. } => Err(out_of_scope("Declare")),
            Stmt::Implements { .. } => Err(out_of_scope("Implements")),
            Stmt::Opaque { keyword, .. } => Err(out_of_scope(keyword)),
        }
    }

    fn case_matches(
        &mut self,
        subject: &Variant,
        m: &CaseMatch,
        frame: &mut Frame,
        text_compare: bool,
        bool_compare: bool,
    ) -> VResult<bool> {
        let cmp =
            |lhs: &Variant, rhs: &Variant, kind: Operand| -> VResult<Option<std::cmp::Ordering>> {
                if text_compare {
                    return Ok(Some(lhs.to_vba_string()?.cmp(&rhs.to_vba_string()?)));
                }
                value::compare_ctx(lhs, rhs, Operand::Runtime, kind)
            };
        let cast = |v: Variant| -> VResult<Variant> {
            if bool_compare {
                return Ok(Variant::Boolean(v.to_bool()?));
            }
            Ok(v)
        };
        Ok(match m {
            CaseMatch::Value(e) => {
                let v = cast(self.eval(e, frame)?)?;
                cmp(subject, &v, operand_kind(e))? == Some(std::cmp::Ordering::Equal)
            }
            CaseMatch::Range(lo_e, hi_e) => {
                let lo = cast(self.eval(lo_e, frame)?)?;
                let hi = cast(self.eval(hi_e, frame)?)?;
                let a = cmp(subject, &lo, operand_kind(lo_e))?;
                let b = cmp(subject, &hi, operand_kind(hi_e))?;
                matches!(a, Some(o) if o != std::cmp::Ordering::Less)
                    && matches!(b, Some(o) if o != std::cmp::Ordering::Greater)
            }
            CaseMatch::Is(op, e) => {
                let v = cast(self.eval(e, frame)?)?;
                let ord = cmp(subject, &v, operand_kind(e))?;
                match ord {
                    None => false,
                    Some(o) => compare_with(*op, o),
                }
            }
        })
    }

    fn exec_for(
        &mut self,
        var: &Expr,
        from: &Expr,
        to: &Expr,
        step: Option<&Expr>,
        body: &[Stmt],
        frame: &mut Frame,
    ) -> VResult<Flow> {
        let start = self.eval(from, frame)?.to_f64()?;
        let limit = self.eval(to, frame)?.to_f64()?;
        let step_v = match step {
            Some(e) => self.eval(e, frame)?.to_f64()?,
            None => 1.0,
        };
        if step_v == 0.0 {
            return Err(VbaError::new(
                5,
                "Invalid procedure call or argument: For step is 0",
            ));
        }

        let mut current = start;
        loop {
            self.tick()?;
            self.assign(var, number_like(current, start, step_v), frame, false)?;
            let done = if step_v > 0.0 {
                current > limit
            } else {
                current < limit
            };
            if done {
                break;
            }
            match self.exec_block(body, frame)? {
                Flow::Normal => {}
                Flow::ExitFor => break,
                other => return Ok(other),
            }
            current += step_v;
        }
        Ok(Flow::Normal)
    }

    fn exec_do(
        &mut self,
        pre: Option<&(DoTest, Expr)>,
        post: Option<&(DoTest, Expr)>,
        body: &[Stmt],
        frame: &mut Frame,
    ) -> VResult<Flow> {
        loop {
            self.tick()?;
            if let Some((test, cond)) = pre {
                let c = self.eval(cond, frame)?;
                let c = self.scalar(c)?.to_bool_condition()?;
                let stop = match test {
                    DoTest::While => !c,
                    DoTest::Until => c,
                };
                if stop {
                    break;
                }
            }
            match self.exec_block(body, frame)? {
                Flow::Normal => {}
                Flow::ExitDo => break,
                other => return Ok(other),
            }
            if let Some((test, cond)) = post {
                let c = self.eval(cond, frame)?;
                let c = self.scalar(c)?.to_bool_condition()?;
                let stop = match test {
                    DoTest::While => !c,
                    DoTest::Until => c,
                };
                if stop {
                    break;
                }
            }
        }
        Ok(Flow::Normal)
    }

    fn assign(
        &mut self,
        target: &Expr,
        value: Variant,
        frame: &mut Frame,
        set: bool,
    ) -> VResult<()> {
        self.assign_with(target, value, frame, false, set)
    }

    fn assign_with(
        &mut self,
        target: &Expr,
        v: Variant,
        frame: &mut Frame,
        module_level: bool,
        set: bool,
    ) -> VResult<()> {
        match target {
            Expr::Member {
                target: obj, name, ..
            } => {
                let owner = self.member_owner(obj.as_deref(), frame)?;
                let Variant::Object(owner_obj) = owner else {
                    return Err(VbaError::new(
                        424,
                        format!("Object required: .{name} on a {}", owner.type_name()),
                    ));
                };
                return self.set_member_on_object(&owner_obj, name, &[], &v, set);
            }
            Expr::Call {
                target: t, args, ..
            } => {
                if let Expr::Member {
                    target: inner_obj,
                    name: prop_name,
                    ..
                } = t.as_ref()
                {
                    let owner = self.member_owner(inner_obj.as_deref(), frame)?;
                    if let Variant::Object(owner_obj) = &owner
                        && matches!(owner_obj, ObjRef::UserClass(_))
                    {
                        let arg_vals = self.eval_args(args, frame)?;
                        return self.set_member_on_object(owner_obj, prop_name, &arg_vals, &v, set);
                    }
                }
                if let Expr::Ident {
                    name: ident_name, ..
                } = t.as_ref()
                    && let Some(Variant::Object(obj)) = self.lookup(ident_name, frame)
                    && let ObjRef::UserClass(id) = obj
                {
                    let arg_vals = self.eval_args(args, frame)?;
                    let cls_name = self
                        .instances
                        .get(&id)
                        .map(|inst| inst.class_name.clone())
                        .unwrap_or_default();
                    if let Some(def_member) = self
                        .modules
                        .get(&cls_name.to_ascii_lowercase())
                        .and_then(|m| m.default_member.clone())
                    {
                        return self.set_member_on_object(&obj, &def_member, &arg_vals, &v, set);
                    }
                }
                if !set {
                    let obj = self.eval(target, frame);
                    if let Ok(Variant::Object(obj)) = obj {
                        self.host("assignment to an object")?
                            .assign_default(&obj, &v)?;
                        self.drain_and_fire_events()?;
                        return Ok(());
                    }
                }
                return Err(out_of_scope("array or property assignment"));
            }
            Expr::Bang {
                target: obj_expr,
                name,
                ..
            } => {
                let owner = self.eval(obj_expr, frame)?;
                let Variant::Object(owner_obj) = owner else {
                    return Err(VbaError::new(
                        424,
                        format!("Object required: !{name} on a {}", owner.type_name()),
                    ));
                };
                return self.set_member_on_object(&owner_obj, name, &[], &v, set);
            }
            _ => {}
        }

        match target {
            Expr::Ident { name, .. } => {
                let key = name.to_ascii_lowercase();
                self.inc_ref(&v);

                // Handle WithEvents dynamic registration
                let is_with_events = frame.with_events_locals.contains_key(&key)
                    || self
                        .modules
                        .get(&self.active_module)
                        .is_some_and(|m| m.with_events_vars.contains_key(&key));

                if is_with_events {
                    let active_mod = self.active_module.clone();
                    if let Some(old_val) = self.lookup(&key, frame)
                        && let Variant::Object(ObjRef::UserClass(old_id)) = old_val
                    {
                        self.remove_event_subscriptions(old_id, &active_mod, &key);
                    }
                    if let Variant::Object(ObjRef::UserClass(new_id)) = &v {
                        self.add_event_subscriptions(*new_id, &active_mod, &key, frame.me);
                    }
                }

                if module_level {
                    if let Some(m) = self.modules.get_mut(&self.active_module)
                        && let Some(old) = m.globals.insert(key, v)
                    {
                        self.dec_ref(&old);
                    }
                } else if frame.locals.contains_key(&key)
                    || frame.auto_new_locals.contains_key(&key)
                    || (!self.module_has_global(&self.active_module, &key)
                        && !self.instance_has_field(frame.me, &key))
                {
                    if let Some(old) = frame.locals.insert(key, v) {
                        self.dec_ref(&old);
                    }
                } else if self.instance_has_field(frame.me, &key) {
                    if let Some(ObjRef::UserClass(id)) = frame.me
                        && let Some(inst) = self.instances.get_mut(&id)
                        && let Some(old) = inst.fields.insert(key, v)
                    {
                        self.dec_ref(&old);
                    }
                } else if self.module_has_global(&self.active_module, &key) {
                    if let Some(m) = self.modules.get_mut(&self.active_module)
                        && let Some(old) = m.globals.insert(key, v)
                    {
                        self.dec_ref(&old);
                    }
                } else {
                    frame.locals.insert(key, v);
                }
                Ok(())
            }
            other => Err(VbaError::new(
                erl_assign_error(),
                format!("Cannot assign to this expression ({other:?})"),
            )),
        }
    }

    fn module_has_global(&self, mod_name: &str, key: &str) -> bool {
        self.modules
            .get(mod_name)
            .is_some_and(|m| m.globals.contains_key(key))
    }

    fn instance_has_field(&self, me: Option<ObjRef>, key: &str) -> bool {
        if let Some(ObjRef::UserClass(id)) = me {
            self.instances
                .get(&id)
                .is_some_and(|i| i.fields.contains_key(key))
        } else {
            false
        }
    }

    fn set_member_on_object(
        &mut self,
        obj: &ObjRef,
        name: &str,
        args: &[Variant],
        value: &Variant,
        set: bool,
    ) -> VResult<()> {
        match obj {
            ObjRef::Nothing => Err(VbaError::new(
                91,
                format!("Object variable or With block variable not set: .{name}"),
            )),
            ObjRef::UserClass(id) => {
                let cls_name = self
                    .instances
                    .get(id)
                    .map(|inst| inst.class_name.clone())
                    .ok_or_else(|| VbaError::new(91, "Object variable not set"))?;
                let lower_cls = cls_name.to_ascii_lowercase();
                let lower_name = name.to_ascii_lowercase();

                let mut prop_proc = None;
                if let Some(m_env) = self.modules.get(&lower_cls)
                    && let Some(mp) = m_env.procs.get(&lower_name)
                {
                    if set {
                        prop_proc = mp.prop_set.clone().or_else(|| mp.prop_let.clone());
                    } else {
                        prop_proc = mp.prop_let.clone().or_else(|| mp.prop_set.clone());
                    }
                }

                if let Some(proc) = prop_proc {
                    let mut full_args = args.to_vec();
                    full_args.push(value.clone());
                    let mut frame = Frame::new();
                    frame.module_name = cls_name.clone();
                    frame.me = Some(ObjRef::UserClass(*id));
                    let old_active = self.active_module.clone();
                    self.active_module = cls_name;
                    let res = self.call_body_with_frame(&proc, full_args, &mut frame);
                    self.active_module = old_active;
                    res?;
                    return Ok(());
                }

                if args.is_empty() {
                    self.inc_ref(value);
                    let old = if let Some(inst) = self.instances.get_mut(id) {
                        inst.fields.insert(lower_name, value.clone())
                    } else {
                        None
                    };
                    if let Some(old) = old {
                        self.dec_ref(&old);
                    }
                    return Ok(());
                }

                Err(VbaError::new(
                    438,
                    format!("Object doesn't support this property or method: .{name}"),
                ))
            }
            ObjRef::Worksheet(sheet_id) => {
                if let Some(mod_name) = self.find_document_module_name_by_sheet_id(*sheet_id) {
                    let mut prop_proc = None;
                    if let Some(m_env) = self.modules.get(&mod_name)
                        && let Some(mp) = m_env.procs.get(&name.to_ascii_lowercase())
                    {
                        if set {
                            prop_proc = mp.prop_set.clone().or_else(|| mp.prop_let.clone());
                        } else {
                            prop_proc = mp.prop_let.clone().or_else(|| mp.prop_set.clone());
                        }
                    }
                    if let Some(proc) = prop_proc {
                        let mut full_args = args.to_vec();
                        full_args.push(value.clone());
                        let mut frame = Frame::new();
                        frame.module_name = mod_name.clone();
                        frame.me = Some(ObjRef::Worksheet(*sheet_id));
                        let old_active = self.active_module.clone();
                        self.active_module = mod_name;
                        let res = self.call_body_with_frame(&proc, full_args, &mut frame);
                        self.active_module = old_active;
                        res?;
                        return Ok(());
                    }
                }
                self.host(&format!(".{name}"))?
                    .set_member(obj, name, args, value)?;
                self.drain_and_fire_events()?;
                Ok(())
            }
            ObjRef::Workbook => {
                if let Some(m_env) = self.modules.get("thisworkbook") {
                    let mut prop_proc = None;
                    if let Some(mp) = m_env.procs.get(&name.to_ascii_lowercase()) {
                        if set {
                            prop_proc = mp.prop_set.clone().or_else(|| mp.prop_let.clone());
                        } else {
                            prop_proc = mp.prop_let.clone().or_else(|| mp.prop_set.clone());
                        }
                    }
                    if let Some(proc) = prop_proc {
                        let mut full_args = args.to_vec();
                        full_args.push(value.clone());
                        let mut frame = Frame::new();
                        frame.module_name = "thisworkbook".to_string();
                        frame.me = Some(ObjRef::Workbook);
                        let old_active = self.active_module.clone();
                        self.active_module = "thisworkbook".to_string();
                        let res = self.call_body_with_frame(&proc, full_args, &mut frame);
                        self.active_module = old_active;
                        res?;
                        return Ok(());
                    }
                }
                self.host(&format!(".{name}"))?
                    .set_member(obj, name, args, value)?;
                self.drain_and_fire_events()?;
                Ok(())
            }
            other => {
                self.host(&format!(".{name}"))?
                    .set_member(other, name, args, value)?;
                self.drain_and_fire_events()?;
                Ok(())
            }
        }
    }

    fn lookup(&mut self, name: &str, frame: &mut Frame) -> Option<Variant> {
        let key = name.to_ascii_lowercase();

        // 1. Check local variable in frame with auto-new check
        if frame.auto_new_locals.contains_key(&key) {
            let val = frame.locals.get(&key).cloned();
            if val
                .as_ref()
                .is_none_or(|v| matches!(v, Variant::Empty | Variant::Object(ObjRef::Nothing)))
            {
                let cls = frame.auto_new_locals.get(&key).unwrap().clone();
                if let Ok(new_inst) = self.instantiate_class(&cls) {
                    self.inc_ref(&new_inst);
                    frame.locals.insert(key.clone(), new_inst.clone());
                    return Some(new_inst);
                }
            }
        }
        if let Some(v) = frame.locals.get(&key) {
            return Some(v.clone());
        }

        // 2. Check instance fields if inside a class instance
        if let Some(ObjRef::UserClass(id)) = frame.me {
            let auto_cls = self.instances.get(&id).and_then(|inst| {
                if inst.auto_new_fields.contains_key(&key) {
                    let val = inst.fields.get(&key);
                    if val.is_none_or(|v| {
                        matches!(v, Variant::Empty | Variant::Object(ObjRef::Nothing))
                    }) {
                        return inst.auto_new_fields.get(&key).cloned();
                    }
                }
                None
            });
            if let Some(cls) = auto_cls
                && let Ok(new_inst) = self.instantiate_class(&cls)
            {
                self.inc_ref(&new_inst);
                if let Some(inst) = self.instances.get_mut(&id) {
                    inst.fields.insert(key.clone(), new_inst.clone());
                }
                return Some(new_inst);
            }
            if let Some(inst) = self.instances.get(&id)
                && let Some(v) = inst.fields.get(&key)
            {
                return Some(v.clone());
            }
        }

        // 3. Check current module's globals
        let auto_cls = self.modules.get(&self.active_module).and_then(|m| {
            if m.auto_new_vars.contains_key(&key) {
                let val = m.globals.get(&key);
                if val
                    .is_none_or(|v| matches!(v, Variant::Empty | Variant::Object(ObjRef::Nothing)))
                {
                    return m.auto_new_vars.get(&key).cloned();
                }
            }
            None
        });
        if let Some(cls) = auto_cls
            && let Ok(new_inst) = self.instantiate_class(&cls)
        {
            self.inc_ref(&new_inst);
            if let Some(m) = self.modules.get_mut(&self.active_module) {
                m.globals.insert(key.clone(), new_inst.clone());
            }
            return Some(new_inst);
        }
        if let Some(m) = self.modules.get(&self.active_module)
            && let Some(v) = m.globals.get(&key)
        {
            return Some(v.clone());
        }

        // 4. Check document modules / singleton names
        if key == "thisworkbook" {
            return Some(Variant::Object(ObjRef::Workbook));
        }
        for m in self.modules.values() {
            if m.kind == VbaModuleKind::Document && m.name.eq_ignore_ascii_case(name) {
                if let Some(sheet_id) = m.bound_sheet_id {
                    return Some(Variant::Object(ObjRef::Worksheet(sheet_id)));
                } else {
                    return Some(Variant::Object(ObjRef::Workbook));
                }
            }
        }

        // 5. Check public globals in other standard modules
        for m in self.modules.values() {
            if m.kind == VbaModuleKind::Standard
                && m.name != self.active_module
                && let Some(v) = m.globals.get(&key)
            {
                return Some(v.clone());
            }
        }

        None
    }

    fn eval(&mut self, e: &Expr, frame: &mut Frame) -> VResult<Variant> {
        self.tick()?;
        match e {
            Expr::Literal(l) => Ok(literal_to_variant(l)),

            Expr::Paren { expr, .. } => self.eval(expr, frame),

            Expr::Ident { name, .. } => {
                if let Some(v) = self.lookup(name, frame) {
                    return Ok(v);
                }
                if let Some(v) = self.builtin_constant(name) {
                    return Ok(v);
                }
                if let Some(h) = self.host.as_mut()
                    && let Some(obj) = h.global(name)
                {
                    return Ok(Variant::Object(obj));
                }
                if self.host.is_none() && super::host::is_host_name(name) {
                    return Err(needs_workbook(name));
                }
                if let Some((proc_mod, proc)) = self.find_procedure_in_scope(name, frame) {
                    let mut call_frame = Frame::new();
                    call_frame.module_name = proc_mod.clone();
                    if proc_mod == frame.module_name {
                        call_frame.me = frame.me;
                    }
                    let old_active = self.active_module.clone();
                    self.active_module = proc_mod;
                    let res = self.call_body_with_frame(&proc, Vec::new(), &mut call_frame);
                    self.active_module = old_active;
                    return res;
                }
                if let Some(v) = builtins::call(name, &[])? {
                    return Ok(v);
                }
                Ok(Variant::Empty)
            }

            Expr::Unary { op, expr, .. } => {
                let v = self.eval(expr, frame)?;
                let v = self.scalar(v)?;
                let mode = if is_constant(expr) {
                    ArithMode::Constant
                } else {
                    ArithMode::Promote
                };
                match op {
                    UnOp::Neg => value::neg(&v, mode),
                    UnOp::Pos => value::pos(&v, mode),
                    UnOp::Not => value::not(&v),
                }
            }

            Expr::Binary { op, lhs, rhs, .. } => {
                let a = self.eval(lhs, frame)?;
                if *op == BinOp::Is {
                    let b = self.eval(rhs, frame)?;
                    return is_comparison(&a, &b);
                }
                let a = self.scalar(a)?;
                if matches!(
                    op,
                    BinOp::And | BinOp::Or | BinOp::Xor | BinOp::Eqv | BinOp::Imp
                ) && matches!(a, Variant::Str(_))
                {
                    // Logical operators convert the left operand before the
                    // right expression is evaluated. Fuzz found
                    // `("a" + "Z") Eqv ("1" \ 0)`: Excel raises the left
                    // type mismatch (13), not the right division by zero (11).
                    a.to_bool()?;
                }
                let b = self.eval(rhs, frame)?;
                let b = self.scalar(b)?;
                let mode = if is_statically_typed(lhs) && is_statically_typed(rhs) {
                    ArithMode::Constant
                } else {
                    ArithMode::Promote
                };
                let kinds = (operand_kind(lhs), operand_kind(rhs));
                eval_binary(*op, &a, &b, mode, kinds)
            }

            Expr::Call { target, args, .. } => self.eval_call(target, args, frame),

            Expr::Member { target, name, .. } => {
                if let Some(t) = target
                    && let Expr::Ident { name: obj, .. } = t.as_ref()
                    && obj.eq_ignore_ascii_case("err")
                {
                    return Ok(match name.to_ascii_lowercase().as_str() {
                        "number" => Variant::Long(self.err.number),
                        "description" => Variant::Str(self.err.description.clone()),
                        other => return Err(out_of_scope(&format!("Err.{other}"))),
                    });
                }
                // Check module-qualified procedure/global access
                if let Some(t) = target
                    && let Expr::Ident {
                        name: mod_ident, ..
                    } = t.as_ref()
                {
                    let lower_mod = mod_ident.to_ascii_lowercase();
                    if let Some(m_env) = self.modules.get(&lower_mod)
                        && m_env.kind == VbaModuleKind::Standard
                    {
                        if let Some(v) = m_env.globals.get(&name.to_ascii_lowercase()) {
                            return Ok(v.clone());
                        }
                        if let Some(mp) = m_env.procs.get(&name.to_ascii_lowercase())
                            && let Some(proc) = mp.first()
                        {
                            let mut call_frame = Frame::new();
                            call_frame.module_name = lower_mod.clone();
                            let old_active = self.active_module.clone();
                            self.active_module = lower_mod;
                            let res = self.call_body_with_frame(&proc, Vec::new(), &mut call_frame);
                            self.active_module = old_active;
                            return res;
                        }
                    }
                }
                self.member(target.as_deref(), name, &[], frame)
            }

            Expr::Bang { target, name, .. } => {
                let owner = self.eval(target, frame)?;
                let Variant::Object(obj) = owner else {
                    return Err(VbaError::new(
                        424,
                        format!("Object required: !{name} on a {}", owner.type_name()),
                    ));
                };
                self.get_member_on_object(&obj, name, &[])
            }

            Expr::Me { .. } => {
                let me = frame
                    .me
                    .ok_or_else(|| VbaError::new(543, "Invalid use of Me keyword"))?;
                Ok(Variant::Object(me))
            }

            Expr::New { ty, .. } => {
                let class_name = ty.path.last().map(|s| s.as_str()).unwrap_or("");
                self.instantiate_class(class_name)
            }

            Expr::TypeOf { expr, ty, .. } => {
                let val = self.eval(expr, frame)?;
                let type_name = ty.path.last().map(|s| s.as_str()).unwrap_or("");
                Ok(Variant::Boolean(self.type_of_matches(&val, type_name)))
            }

            Expr::AddressOf { .. } => Ok(Variant::Long(0)),
        }
    }

    fn member_owner(&mut self, target: Option<&Expr>, frame: &mut Frame) -> VResult<Variant> {
        match target {
            Some(e) => self.eval(e, frame),
            None => frame
                .with_stack
                .last()
                .cloned()
                .ok_or_else(|| {
                    VbaError::new(
                        91,
                        "Object variable or With block variable not set: a leading '.' outside a With block",
                    )
                }),
        }
    }

    fn member(
        &mut self,
        target: Option<&Expr>,
        name: &str,
        args: &[Variant],
        frame: &mut Frame,
    ) -> VResult<Variant> {
        let owner = self.member_owner(target, frame)?;
        let Variant::Object(obj) = owner else {
            return Err(VbaError::new(
                424,
                format!("Object required: .{name} on a {}", owner.type_name()),
            ));
        };
        self.get_member_on_object(&obj, name, args)
    }

    fn get_member_on_object(
        &mut self,
        obj: &ObjRef,
        name: &str,
        args: &[Variant],
    ) -> VResult<Variant> {
        match obj {
            ObjRef::Nothing => Err(VbaError::new(
                91,
                format!("Object variable or With block variable not set: .{name}"),
            )),
            ObjRef::UserClass(id) => {
                let cls_name = self
                    .instances
                    .get(id)
                    .map(|inst| inst.class_name.clone())
                    .ok_or_else(|| VbaError::new(91, "Object variable not set"))?;
                let lower_cls = cls_name.to_ascii_lowercase();
                let lower_name = name.to_ascii_lowercase();

                if let Some(m_env) = self.modules.get(&lower_cls)
                    && let Some(mp) = m_env.procs.get(&lower_name)
                    && let Some(proc) = mp.prop_get.clone().or_else(|| mp.sub_or_func.clone())
                {
                    let mut frame = Frame::new();
                    frame.module_name = cls_name.clone();
                    frame.me = Some(ObjRef::UserClass(*id));
                    let old_active = self.active_module.clone();
                    self.active_module = cls_name;
                    let res = self.call_body_with_frame(&proc, args.to_vec(), &mut frame);
                    self.active_module = old_active;
                    return res;
                }

                let auto_cls = self.instances.get(id).and_then(|inst| {
                    if inst.auto_new_fields.contains_key(&lower_name) {
                        let val = inst.fields.get(&lower_name);
                        if val.is_none_or(|v| {
                            matches!(v, Variant::Empty | Variant::Object(ObjRef::Nothing))
                        }) {
                            return inst.auto_new_fields.get(&lower_name).cloned();
                        }
                    }
                    None
                });
                if let Some(cls) = auto_cls
                    && let Ok(new_inst) = self.instantiate_class(&cls)
                {
                    self.inc_ref(&new_inst);
                    if let Some(inst) = self.instances.get_mut(id) {
                        inst.fields.insert(lower_name.clone(), new_inst.clone());
                    }
                    return Ok(new_inst);
                }
                if let Some(inst) = self.instances.get(id)
                    && let Some(v) = inst.fields.get(&lower_name).cloned()
                {
                    if args.is_empty() {
                        return Ok(v);
                    }
                    if let Variant::Object(nested_obj) = &v {
                        return self.get_member_on_object(nested_obj, "item", args);
                    }
                }

                Err(VbaError::new(
                    438,
                    format!("Object doesn't support this property or method: .{name}"),
                ))
            }
            ObjRef::Worksheet(sheet_id) => {
                if let Some(mod_name) = self.find_document_module_name_by_sheet_id(*sheet_id)
                    && let Some(m_env) = self.modules.get(&mod_name)
                    && let Some(mp) = m_env.procs.get(&name.to_ascii_lowercase())
                    && let Some(proc) = mp.prop_get.clone().or_else(|| mp.sub_or_func.clone())
                {
                    let mut frame = Frame::new();
                    frame.module_name = mod_name.clone();
                    frame.me = Some(ObjRef::Worksheet(*sheet_id));
                    let old_active = self.active_module.clone();
                    self.active_module = mod_name;
                    let res = self.call_body_with_frame(&proc, args.to_vec(), &mut frame);
                    self.active_module = old_active;
                    return res;
                }
                self.host(&format!(".{name}"))?.get_member(obj, name, args)
            }
            ObjRef::Workbook => {
                if let Some(m_env) = self.modules.get("thisworkbook")
                    && let Some(mp) = m_env.procs.get(&name.to_ascii_lowercase())
                    && let Some(proc) = mp.prop_get.clone().or_else(|| mp.sub_or_func.clone())
                {
                    let mut frame = Frame::new();
                    frame.module_name = "thisworkbook".to_string();
                    frame.me = Some(ObjRef::Workbook);
                    let old_active = self.active_module.clone();
                    self.active_module = "thisworkbook".to_string();
                    let res = self.call_body_with_frame(&proc, args.to_vec(), &mut frame);
                    self.active_module = old_active;
                    return res;
                }
                self.host(&format!(".{name}"))?.get_member(obj, name, args)
            }
            other => self
                .host(&format!(".{name}"))?
                .get_member(other, name, args),
        }
    }

    fn scalar(&mut self, v: Variant) -> VResult<Variant> {
        match v {
            Variant::Object(ObjRef::UserClass(id)) => {
                let cls_name = self
                    .instances
                    .get(&id)
                    .map(|inst| inst.class_name.clone())
                    .unwrap_or_default();
                let def_member = self
                    .modules
                    .get(&cls_name.to_ascii_lowercase())
                    .and_then(|m| m.default_member.clone());
                if let Some(def_member) = def_member {
                    let res =
                        self.get_member_on_object(&ObjRef::UserClass(id), &def_member, &[])?;
                    return self.scalar(res);
                }
                Err(VbaError::new(
                    438,
                    "Object doesn't support this property or method: default property not found",
                ))
            }
            Variant::Object(obj) => self.host("using an object as a value")?.default_value(&obj),
            other => Ok(other),
        }
    }

    fn type_of_matches(&self, v: &Variant, type_name: &str) -> bool {
        let Variant::Object(obj) = v else {
            return false;
        };
        match obj {
            ObjRef::Nothing => false,
            ObjRef::UserClass(id) => {
                if let Some(inst) = self.instances.get(id) {
                    inst.class_name.eq_ignore_ascii_case(type_name)
                        || type_name.eq_ignore_ascii_case("object")
                } else {
                    false
                }
            }
            ObjRef::Worksheet(_) => {
                type_name.eq_ignore_ascii_case("worksheet")
                    || type_name.eq_ignore_ascii_case("object")
            }
            ObjRef::Workbook => {
                type_name.eq_ignore_ascii_case("workbook")
                    || type_name.eq_ignore_ascii_case("object")
            }
            ObjRef::Range(_) => {
                type_name.eq_ignore_ascii_case("range") || type_name.eq_ignore_ascii_case("object")
            }
            ObjRef::Application => {
                type_name.eq_ignore_ascii_case("application")
                    || type_name.eq_ignore_ascii_case("object")
            }
            ObjRef::ListObject(_) => {
                type_name.eq_ignore_ascii_case("listobject")
                    || type_name.eq_ignore_ascii_case("object")
            }
            ObjRef::ListColumn(..) => {
                type_name.eq_ignore_ascii_case("listcolumn")
                    || type_name.eq_ignore_ascii_case("object")
            }
            ObjRef::ListRow(..) => {
                type_name.eq_ignore_ascii_case("listrow")
                    || type_name.eq_ignore_ascii_case("object")
            }
            ObjRef::PivotTable(_) => {
                type_name.eq_ignore_ascii_case("pivottable")
                    || type_name.eq_ignore_ascii_case("object")
            }
            ObjRef::PivotField(..) => {
                type_name.eq_ignore_ascii_case("pivotfield")
                    || type_name.eq_ignore_ascii_case("object")
            }
            ObjRef::Interior(_) => {
                type_name.eq_ignore_ascii_case("interior")
                    || type_name.eq_ignore_ascii_case("object")
            }
            ObjRef::Font(_) => {
                type_name.eq_ignore_ascii_case("font") || type_name.eq_ignore_ascii_case("object")
            }
            _ => type_name.eq_ignore_ascii_case("object"),
        }
    }

    fn exec_for_each(
        &mut self,
        var: &Expr,
        iterable: &Expr,
        body: &[Stmt],
        frame: &mut Frame,
    ) -> VResult<Flow> {
        let subject = self.eval(iterable, frame)?;
        let items = match subject {
            Variant::Object(obj) => self.host("For Each")?.iterate(&obj)?,
            Variant::Array(a) => a.values.clone(),
            other => {
                return Err(VbaError::new(
                    438,
                    format!(
                        "Object doesn't support this property or method: For Each over a {}",
                        other.type_name()
                    ),
                ));
            }
        };
        for item in items {
            self.tick()?;
            self.assign_with(var, item, frame, false, true)?;
            match self.exec_block(body, frame)? {
                Flow::Normal => {}
                Flow::ExitFor => break,
                other => return Ok(other),
            }
        }
        Ok(Flow::Normal)
    }

    fn eval_call(&mut self, target: &Expr, args: &[Arg], frame: &mut Frame) -> VResult<Variant> {
        if let Expr::Member {
            target: Some(obj),
            name,
            ..
        } = target
            && let Expr::Ident { name: o, .. } = obj.as_ref()
            && o.eq_ignore_ascii_case("err")
            && name.eq_ignore_ascii_case("raise")
        {
            let values = self.eval_args(args, frame)?;
            let number = values
                .first()
                .map(|v| v.to_f64())
                .transpose()?
                .unwrap_or(0.0) as i32;
            let description = match values.get(2) {
                Some(v) => v.to_vba_string()?,
                None => describe_error(number),
            };
            return Err(VbaError::new(number, description));
        }

        if let Expr::Member {
            target: obj, name, ..
        } = target
        {
            if let Some(t) = obj
                && let Expr::Ident {
                    name: mod_ident, ..
                } = t.as_ref()
            {
                let lower_mod = mod_ident.to_ascii_lowercase();
                if let Some(m_env) = self.modules.get(&lower_mod)
                    && m_env.kind == VbaModuleKind::Standard
                    && let Some(mp) = m_env.procs.get(&name.to_ascii_lowercase())
                    && let Some(proc) = mp.first()
                {
                    let values = self.eval_args(args, frame)?;
                    let mut call_frame = Frame::new();
                    call_frame.module_name = lower_mod.clone();
                    let old_active = self.active_module.clone();
                    self.active_module = lower_mod;
                    let res = self.call_body_with_frame(&proc, values, &mut call_frame);
                    self.active_module = old_active;
                    return res;
                }
            }
            let values = self.eval_args(args, frame)?;
            return self.member(obj.as_deref(), name, &values, frame);
        }

        let Expr::Ident { name, .. } = target else {
            return Err(out_of_scope("this call target"));
        };

        if let Some((proc_mod, proc)) = self.find_procedure_in_scope(name, frame) {
            let values = self.eval_args(args, frame)?;
            let mut call_frame = Frame::new();
            call_frame.module_name = proc_mod.clone();
            if proc_mod == frame.module_name {
                call_frame.me = frame.me;
            }
            let old_active = self.active_module.clone();
            self.active_module = proc_mod;
            let res = self.call_body_with_frame(&proc, values, &mut call_frame);
            self.active_module = old_active;
            return res;
        }

        if let Some(val) = self.lookup(name, frame) {
            if let Variant::Object(ObjRef::UserClass(id)) = val {
                let values = self.eval_args(args, frame)?;
                let cls_name = self
                    .instances
                    .get(&id)
                    .map(|inst| inst.class_name.clone())
                    .unwrap_or_default();
                if let Some(def_member) = self
                    .modules
                    .get(&cls_name.to_ascii_lowercase())
                    .and_then(|m| m.default_member.clone())
                {
                    return self.get_member_on_object(&ObjRef::UserClass(id), &def_member, &values);
                }
                return Err(VbaError::new(
                    438,
                    "Object doesn't support this property or method: default member not found",
                ));
            }
            if let Variant::Array(a) = val {
                let values = self.eval_args(args, frame)?;
                let row = values
                    .first()
                    .map(|v| v.to_f64())
                    .transpose()?
                    .unwrap_or(0.0);
                let col = match values.get(1) {
                    Some(v) => v.to_f64()?,
                    None => 0.0,
                };
                return a.get(row as usize, col as usize);
            }
        }

        let values = self.eval_args(args, frame)?;

        if name.eq_ignore_ascii_case("typename")
            && let Some(arg) = values.first()
        {
            return Ok(Variant::Str(self.type_name_of(arg)));
        }

        let values = if OBJECT_AWARE_BUILTINS.contains(&name.to_ascii_lowercase().as_str()) {
            values
        } else {
            values
                .into_iter()
                .map(|v| self.scalar(v))
                .collect::<VResult<Vec<_>>>()?
        };
        if let Some(v) = builtins::call(name, &values)? {
            return Ok(v);
        }
        if let Some(h) = self.host.as_mut()
            && let Some(r) = h.global_call(name, &values)
        {
            return r;
        }
        if self.host.is_none() && super::host::is_host_name(name) {
            return Err(needs_workbook(name));
        }
        Err(VbaError::new(
            35,
            format!("Sub or Function not defined: {name}"),
        ))
    }

    fn eval_args(&mut self, args: &[Arg], frame: &mut Frame) -> VResult<Vec<Variant>> {
        let mut out = Vec::with_capacity(args.len());
        for a in args {
            match &a.value {
                Some(e) => out.push(self.eval(e, frame)?),
                None => out.push(Variant::Empty),
            }
        }
        Ok(out)
    }

    fn builtin_constant(&self, name: &str) -> Option<Variant> {
        Some(match name.to_ascii_lowercase().as_str() {
            "vbnullstring" => Variant::Str(String::new()),
            "vbcrlf" => Variant::Str("\r\n".to_string()),
            "vbcr" => Variant::Str("\r".to_string()),
            "vblf" => Variant::Str("\n".to_string()),
            "vbtab" => Variant::Str("\t".to_string()),
            "vbnewline" => Variant::Str("\n".to_string()),
            "vbobjecterror" => Variant::Long(-2147221504),
            _ => return None,
        })
    }
}

/// VBA reports an undefined label and a bad assignment target as compile
/// errors, which have no `Err.Number`. 13 is the closest runtime analogue and
/// keeps the differential comparison meaningful rather than inventing a
/// number Excel would never produce.
fn erl_label_error() -> i32 {
    13
}
fn erl_assign_error() -> i32 {
    13
}

fn describe_error(number: i32) -> String {
    match number {
        5 => "Invalid procedure call or argument",
        6 => "Overflow",
        9 => "Subscript out of range",
        11 => "Division by zero",
        13 => "Type mismatch",
        94 => "Invalid use of Null",
        _ => "Application-defined or object-defined error",
    }
    .to_string()
}

fn compare_with(op: BinOp, ord: std::cmp::Ordering) -> bool {
    use std::cmp::Ordering::*;
    match op {
        BinOp::Eq => ord == Equal,
        BinOp::Ne => ord != Equal,
        BinOp::Lt => ord == Less,
        BinOp::Gt => ord == Greater,
        BinOp::Le => ord != Greater,
        BinOp::Ge => ord != Less,
        _ => false,
    }
}

/// Whether an expression is a compile-time constant.
///
/// This is *constness*, not static typing, and the two come apart in both
/// directions -- see [`is_statically_typed`], which is what decides whether
/// arithmetic overflows or promotes (§28). `CInt(32767)` is statically typed
/// and not constant; `(Empty + 1)` is constant and not statically typed.
fn is_constant(e: &Expr) -> bool {
    match e {
        // `Null` is not foldable, so nothing containing it is constant.
        // `(False & Null) = (0.1 / -2.5)` is simply False, where the same
        // comparison with a foldable string is error 13.
        Expr::Literal(Literal::Null) => false,
        Expr::Literal(_) => true,
        Expr::Paren { expr, .. } => is_constant(expr),
        Expr::Unary { expr, .. } => is_constant(expr),
        Expr::Binary { lhs, rhs, .. } => is_constant(lhs) && is_constant(rhs),
        _ => false,
    }
}

/// Intrinsics whose return type is declared numeric rather than `Variant`.
///
/// This matters for comparison, not for arithmetic. `value::compare_ctx`'s
/// "constant" case is really "the compiler knows this side's numeric type
/// statically", and a call to one of these qualifies just as a literal does:
/// `(1.5 & "abc") <> CLng(a)` is error 13, while `(1.5 & "abc") <> a` with
/// `a = -1` compares fine, because `a` is a `Variant` and the runtime
/// number-sorts-before-string rule applies instead. Measured.
///
/// `Len`, `Val` and `Sgn` belong here alongside the `C*` conversions, and the
/// discriminating case has to hold the *string* side constant to show it:
/// against `(-32768 & -2.5)` all four raise error 13 while `Int(a)`, `Abs(a)`
/// and a bare `a` do not. An earlier round put `Len` in on the strength of
/// its `As Long` signature, tested it against a *runtime* string -- where
/// nothing is strict, see `compare_ctx` -- concluded it did not belong, and
/// took it out again. `Int` and `Abs` stay out for a reason that is visible
/// in their signatures: they return the type they were handed, so a Variant
/// argument makes them Variant, where `Len` is always `Long`.
const STATICALLY_NUMERIC: &[&str] = &[
    "cint", "clng", "cdbl", "csng", "ccur", "cbool", "cbyte", "len", "val", "sgn",
];

/// Intrinsics whose return type is declared `Boolean`.
///
/// The same "the compiler knows this statically" idea as
/// [`STATICALLY_NUMERIC`] (which lists `cbool` too, for the numeric
/// comparison rule), used by `Select Case` to decide whether to convert its
/// case values with `CBool`. Measured for `CBool`, `IsNumeric`, `IsNull`,
/// `IsEmpty`, `IsDate` and `IsObject`; `IsArray` and `IsError` measure the
/// same way in Excel but are not implemented here yet, and are listed so they
/// arrive with the right behaviour rather than silently as Variants.
const STATICALLY_BOOLEAN: &[&str] = &[
    "cbool",
    "isnumeric",
    "isnull",
    "isempty",
    "isdate",
    "isobject",
    "isarray",
    "iserror",
];

/// Intrinsics whose return type is declared `String`.
///
/// The pair `True Eqv CStr(True)` (error 13) against `LCase("TRUE") Eqv True`
/// (True) is what pins the distinction down -- see [`value::logical_pair`].
///
/// `TypeName` was added on the strength of a measurement, not its signature:
/// `TypeName(32767) >= False` is error 13 in Excel while
/// `LCase("Integer") >= (Not True)` is True, and the difference is exactly
/// that `TypeName` returns `String` where `LCase` returns `Variant`. Found by
/// `fuzz/fuzz_vba.py`. `LCase`, `UCase`, `Left` and the rest stay out for the
/// reason above -- it is their `$`-suffixed forms that are typed `String`.
///
/// `StrReverse`, `Replace` and `Join` are the members of that same family with
/// **no** `$` form, so the plain name is the typed-`String` one. Measured, and
/// the contrast with their Variant-returning neighbours is what places them:
///
///   StrReverse("abc")        > True    error 13
///   Replace("abc", "a", "z") > True    error 13
///   Join(Array("a", "b"))    > True    error 13
///   Trim("abc")              > True    True
///   LTrim("abc")             > True    True
///
/// `StrReverse` is the one `fuzz/fuzz_vba.py` found, as a whole procedure
/// diverging on which error it raised: Excel stopped at the comparison with
/// 13 while visi ran on to a later division by zero and raised 11.
///
/// `Join` is listed though it is not implemented yet (the call raises 35
/// first), for the reason `IsArray` is listed in [`STATICALLY_BOOLEAN`] -- so
/// it arrives with the right type rather than silently as a Variant.
const STATICALLY_STRING: &[&str] = &["cstr", "typename", "strreverse", "replace", "join"];

/// Whether an expression's *static* type is `Boolean`, as the VBA compiler
/// would know it.
///
/// This is the distinction `Select Case` turns on, and it is invisible in the
/// value: `Select Case CBool(a)` matches `Case 1`, while `Select Case a` with
/// `a = True` does not, though both subjects are `True` at run time. A
/// constant expression qualifies because the compiler folds it (`Select Case
/// (1 = 1)` behaves as `Select Case True`); a Variant never does, whatever it
/// happens to hold.
fn is_statically_boolean(e: &Expr) -> bool {
    match e {
        Expr::Paren { expr, .. } => is_statically_boolean(expr),
        // `Not` of a Boolean is a Boolean, so it carries the static type
        // through: `Select Case (Not IsEmpty("Z"))` takes `Case 0, 1` -- the
        // case values convert with `CBool` -- where the same subject read as
        // a plain -1 takes `Case Else`. `Not` of a *number* is a number and
        // does not, which the `Variant::Boolean` check at the use site
        // enforces anyway: `Select Case (Not 5)` is -6 and matches neither.
        // Measured; found by `fuzz/fuzz_vba.py`.
        Expr::Unary {
            op: UnOp::Not,
            expr,
            ..
        } => is_statically_boolean(expr),
        Expr::Call { target, .. } => matches!(target.as_ref(), Expr::Ident { name, .. }
            if STATICALLY_BOOLEAN.contains(&name.to_ascii_lowercase().as_str())),
        Expr::Binary { op, lhs, rhs, .. }
            if matches!(op, BinOp::IntDiv | BinOp::Mod)
                && is_literal_bool(lhs)
                && is_literal_string(rhs) =>
        {
            false
        }
        Expr::Binary {
            op: BinOp::Eq | BinOp::Ne | BinOp::Lt | BinOp::Gt | BinOp::Le | BinOp::Ge,
            ..
        } => is_statically_typed(e),
        _ => is_constant(e),
    }
}

fn is_literal_bool(e: &Expr) -> bool {
    match e {
        Expr::Paren { expr, .. } => is_literal_bool(expr),
        Expr::Literal(Literal::Bool(_)) => true,
        _ => false,
    }
}

fn is_literal_string(e: &Expr) -> bool {
    match e {
        Expr::Paren { expr, .. } => is_literal_string(expr),
        Expr::Literal(Literal::Str(_)) => true,
        _ => false,
    }
}

/// Whether the compiler knows this expression's type without its value.
///
/// A call to one of the declared-return-type intrinsics qualifies, and so
/// does **arithmetic over them** -- `Len(CStr(a)) / 2` is a `Double` as
/// surely as `Len(CStr(a))` is a `Long`, because every operand's type is
/// known. One `Variant` operand loses it for the whole expression, which is
/// why `Len(CStr(a)) + a` is not static.
///
/// The propagation is measured, not assumed:
///
/// ```text
/// a = -3 : Len(CStr(a))       = "-7False"   error 13   (bare call)
/// a = -3 : (Len(CStr(a)) / 2) = "-7False"   error 13   (propagated)
/// a = -3 : (Len(CStr(a)) + 1) = "-7False"   error 13   (propagated)
/// a = -3 : (Len(CStr(a)) + a) = "-7False"   False      (a Variant operand)
/// a = -3 : (a / (-32768))     = "-7False"   False      (no static operand)
/// a = -3 : (CLng(a) * 2)      = "-6.0"      True       (numeric, not text)
/// ```
///
/// That last row is the positive half: against a statically typed number the
/// string must parse *and then compares numerically*, where a `Variant`
/// partner would compare it as text and say False.
///
/// **Comparison and `&` propagate too**, which §18 left open for want of a
/// measurement and §24 supplied. A comparison is statically `Boolean` only
/// when both its operands are statically typed, because a `Variant` operand
/// could make it `Null` -- and that is the whole of the rule §16 had written
/// as a 4x4 table with an unexplained cell:
///
/// ```text
/// "0" >= (3# >= CDbl(0))       True    every operand statically typed
/// "0" >= (Len(CStr(0)) >= 1)   True    likewise
/// "0" >= ("1" >= -7)           True    a string *literal* is statically typed
/// "0" >= (3# >= Empty)         False   `Empty` is a Variant, so this is not
/// b = 1 : "0" >= (3# >= b)     False   nor is a variable
/// "0" >= IsEmpty(Empty)        True    but a declared-Boolean call is
/// ```
///
/// The last two rows are what say this is about the static *type* rather than
/// about `Empty` appearing anywhere: `IsEmpty(Empty)` is declared `Boolean`
/// and converts, while `(3# >= Empty)` does not.
fn is_statically_typed(e: &Expr) -> bool {
    match e {
        // `Empty` and `Null` are `Variant`, not statically typed values. This
        // is the distinction the whole §24 rule turns on: `(3# >= Empty)` is
        // a compile-time *constant* and still not a compile-time `Boolean`.
        Expr::Literal(Literal::Empty | Literal::Null) => false,
        Expr::Literal(_) => true,
        Expr::Paren { expr, .. } | Expr::Unary { expr, .. } => is_statically_typed(expr),
        Expr::Binary { op, lhs, rhs, .. } => {
            matches!(
                op,
                BinOp::Add
                    | BinOp::Sub
                    | BinOp::Mul
                    | BinOp::Div
                    | BinOp::IntDiv
                    | BinOp::Mod
                    | BinOp::Pow
                    // `&` yields a `String` whatever it is handed, and a
                    // comparison a `Boolean` -- provided every operand is
                    // itself statically typed. `("1" & "3")` is strict
                    // where `(Empty & "13")` is not.
                    | BinOp::Concat
                    | BinOp::Eq
                    | BinOp::Ne
                    | BinOp::Lt
                    | BinOp::Gt
                    | BinOp::Le
                    | BinOp::Ge
            ) && is_statically_typed(lhs)
                && is_statically_typed(rhs)
                || matches!(
                    op,
                    BinOp::And | BinOp::Or | BinOp::Xor | BinOp::Eqv | BinOp::Imp
                )
        }
        // Boolean- and String-returning intrinsics count for the same reason
        // the numeric ones do: the compiler knows the type without the value.
        Expr::Call { target, .. } => matches!(target.as_ref(), Expr::Ident { name, .. }
        if {
            let name = name.to_ascii_lowercase();
            STATICALLY_NUMERIC.contains(&name.as_str())
                || STATICALLY_BOOLEAN.contains(&name.as_str())
                || STATICALLY_STRING.contains(&name.as_str())
        }),
        _ => false,
    }
}

/// How `value::compare_ctx` should treat an operand.
fn operand_kind(e: &Expr) -> Operand {
    let statically_typed = is_statically_typed(e);
    match e {
        Expr::Literal(_) => Operand::Literal,
        // A parenthesised or signed literal is still just a literal, however
        // many layers deep: `(Not True)` behaves as `False` does, where the
        // *folded* `(3# >= Empty)` does not, and the two differ only in that
        // one bottoms out at a literal through unary operators and the other
        // through a comparison. Measured -- `TypeName(32767) >= (Not True)`
        // is error 13 while `TypeName(0) >= (3# >= Empty)` compares as text.
        // This used to check one level, which put `(Not True)` and `(-7)` in
        // the wrong bucket.
        Expr::Paren { expr, .. } | Expr::Unary { expr, .. }
            if operand_kind(expr) == Operand::Literal =>
        {
            Operand::Literal
        }
        // Constant *and* statically typed. A constant expression over `Empty`
        // is neither one thing nor the other -- the compiler can fold it but
        // its type is `Variant`, so it behaves exactly as a variable does.
        // `(3# >= Empty)` and `(Empty & "13")` are the measured cases (§24).
        _ if is_constant(e) && statically_typed => Operand::ConstExpr,
        _ if statically_typed => Operand::Static,
        _ => Operand::Runtime,
    }
}

/// The one constant-folding quirk this interpreter reproduces.
///
/// `True Mod "12"` is the **Boolean** `False`, and `True \ "12"` is `True`,
/// where the same expressions with either operand in a variable give the
/// ordinary `Long` results. The model that fits every measurement is that
/// when the *left* operand is a constant `Boolean` and the right is a
/// constant `String`, `\` and `Mod` convert **both** sides with `CBool` and
/// return a `Boolean`.
///
/// Confirmed against eighteen cases, including the ones that pin down how
/// narrow it is: `"12" Mod True` is `Long 0` (so it is left-specific),
/// `True Mod 12` is `Integer -1` (so the partner must be a String),
/// `a = True : a Mod "12"` is `Long -1` (so both must be constants), and
/// `True And "12"` is `Long 12` (so it is only `\` and `Mod`).
/// `True Mod "0"` is error 11, which the CBool conversion explains: `"0"`
/// becomes `False`, i.e. zero.
fn constant_bool_int_op(op: BinOp, a: &Variant, b: &Variant, mode: ArithMode) -> Option<()> {
    (mode == ArithMode::Constant
        && matches!(op, BinOp::IntDiv | BinOp::Mod)
        && matches!(a, Variant::Boolean(_))
        && matches!(b, Variant::Str(_)))
    .then_some(())
}

fn eval_binary(
    op: BinOp,
    a: &Variant,
    b: &Variant,
    mode: ArithMode,
    kinds: (Operand, Operand),
) -> VResult<Variant> {
    use BinOp::*;
    if constant_bool_int_op(op, a, b, mode).is_some() {
        let l: i64 = if a.to_bool()? { -1 } else { 0 };
        let r: i64 = if b.to_bool()? { -1 } else { 0 };
        if r == 0 {
            return Err(VbaError::div_by_zero());
        }
        let v = if op == IntDiv { l / r } else { l % r };
        return Ok(Variant::Boolean(v != 0));
    }
    match op {
        Add => value::add(a, b, mode),
        Sub => value::sub(a, b, mode),
        Mul => value::mul(a, b, mode),
        Div => value::div(a, b),
        IntDiv => value::int_div(a, b),
        Mod => value::modulo(a, b),
        Pow => value::pow(a, b, mode),
        Concat => value::concat(a, b),
        Eq | Ne | Lt | Gt | Le | Ge => match value::compare_ctx(a, b, kinds.0, kinds.1)? {
            None => Ok(Variant::Null),
            Some(ord) => Ok(Variant::Boolean(compare_with(op, ord))),
        },
        // And/Or/Imp are three-valued; Xor and Eqv are not (a Null operand
        // always makes their result unknown).
        And => null_on_the_right(a, b, kinds, value::and(a, b, kinds)),
        Or => null_on_the_right(a, b, kinds, value::or(a, b, kinds)),
        Xor => null_on_the_right(a, b, kinds, value::logical(a, b, kinds, |x, y| x ^ y)),
        Eqv => null_on_the_right(a, b, kinds, value::logical(a, b, kinds, |x, y| !(x ^ y))),
        Imp => null_on_the_right(a, b, kinds, value::imp(a, b, kinds)),
        Like => Err(out_of_scope("Like")),
        // Handled before the operands are dereferenced -- see `eval`.
        Is => is_comparison(a, b),
    }
}

/// Builtins that must see an object rather than its default member.
///
/// Short on purpose. `TypeName` and `VarType` exist to report *what a value
/// is*, and `IsObject` to report whether it is one at all, so dereferencing
/// their argument would make them structurally unable to answer. Everything
/// else -- `Len`, `IsNumeric`, `CStr` -- is asking about the value, which for
/// a `Range` means the cell.
const OBJECT_AWARE_BUILTINS: &[&str] = &["typename", "vartype", "isobject"];

/// `Is`: reference identity.
///
/// Both operands must be objects. `Nothing` is one, which is what makes
/// `r Is Nothing` the ordinary way to test an unset reference; anything else
/// is error 424, VBA's "Object required".
fn is_comparison(a: &Variant, b: &Variant) -> VResult<Variant> {
    match (a.as_object(), b.as_object()) {
        (Some(x), Some(y)) => Ok(Variant::Boolean(x.same_object(y))),
        _ => Err(VbaError::new(424, "Object required: Is compares objects")),
    }
}

/// A statically typed `String` on the **left** of a logical operator, with
/// `Null` on the right, is error 94.
///
/// | Expression | Excel |
/// | --- | --- |
/// | `"  3  " Imp Null`, `"3" And Null`, `"1.5" Or Null`, `"0" Or Null` | error 94 |
/// | `("  " & "3") Or Null`, `CStr(3) Or Null` | error 94 |
/// | `a = Null : "  3  " Or a` | error 94 -- the *Null* may be a variable |
/// | `a = "  3  " : a Imp Null` | not an error -- the **String** may not |
/// | `Null Or "  3  "`, `Null And "  3  "`, `Null Xor "  3  "` | not an error -- it is left-specific |
/// | `"abc" Imp Null`, `"True" Or Null` | error 13 -- the string's own conversion is checked first |
/// | `3 Imp Null`, `255 Imp Null` | not an error -- the operand must be a String |
///
/// Which is why this wraps the operator rather than short-circuiting it: the
/// conversion failures have to surface as themselves, and only a *successful*
/// operation becomes the 94. Measured with `fuzz/vba_expr_probe.py`.
fn null_on_the_right(
    lhs: &Variant,
    rhs: &Variant,
    kinds: (Operand, Operand),
    computed: VResult<Variant>,
) -> VResult<Variant> {
    let statically_string = matches!(lhs, Variant::Str(_)) && kinds.0 != Operand::Runtime;
    if statically_string && rhs.is_null() {
        computed?;
        return Err(VbaError::invalid_null());
    }
    computed
}

fn literal_to_variant(l: &Literal) -> Variant {
    use super::lexer::TypeSuffix;
    match l {
        Literal::Number {
            value,
            base,
            suffix,
            is_float,
        } => match suffix {
            Some(TypeSuffix::Integer) => Variant::Integer(*value as i16),
            Some(TypeSuffix::Long) => Variant::Long(*value as i32),
            Some(TypeSuffix::Single) => Variant::Single(*value as f32),
            Some(TypeSuffix::Double) => Variant::Double(*value),
            Some(TypeSuffix::Currency) => Variant::Currency((value * 10_000.0).round() as i64),
            Some(TypeSuffix::String) => Variant::Str(value::format_number(*value)),
            None => {
                // A fraction or exponent forces Double, which the lexer
                // records: `1E3` is a Double even though `1000` is a Long.
                let _ = base;
                Variant::from_literal(*value, *is_float || value.fract() != 0.0)
            }
        },
        Literal::Str(s) => Variant::Str(s.clone()),
        Literal::Bool(b) => Variant::Boolean(*b),
        Literal::Empty => Variant::Empty,
        Literal::Null => Variant::Null,
        // `#6/22/2026#` is the Date 46195, and `CStr` of it is `6/22/26`.
        // The engine's own date parser reads the literal, so a date written
        // in a macro and a date typed into a cell go through one
        // implementation. A literal it cannot read is Empty rather than a
        // wrong number -- the same refusal Phase 1 made for every date.
        Literal::Date(text) => match crate::core::date::parse_date(text) {
            Some((d, _)) => Variant::Date(crate::core::date::date_to_excel_serial(d)),
            None => Variant::Empty,
        },
        Literal::Nothing => Variant::Object(ObjRef::Nothing),
    }
}

/// A `For` counter keeps the type its bounds imply, so `For i = 1 To 3`
/// counts in `Integer`s and `For x = 1.5 To 3` in `Double`s.
fn number_like(current: f64, start: f64, step: f64) -> Variant {
    let integral = current.fract() == 0.0 && start.fract() == 0.0 && step.fract() == 0.0;
    Variant::from_literal(current, !integral)
}

fn default_for(ty: Option<&TypeRef>) -> Variant {
    let Some(ty) = ty else {
        return Variant::Empty;
    };
    if ty.is_new {
        return Variant::Object(ObjRef::Nothing);
    }
    let Some(last) = ty.path.last() else {
        return Variant::Empty;
    };
    match last.to_ascii_lowercase().as_str() {
        "integer" => Variant::Integer(0),
        "long" => Variant::Long(0),
        "single" => Variant::Single(0.0),
        "double" => Variant::Double(0.0),
        "currency" => Variant::Currency(0),
        "boolean" => Variant::Boolean(false),
        "string" => Variant::Str(String::new()),
        "date" => Variant::Date(0.0),
        "variant" => Variant::Empty,
        _ => Variant::Object(ObjRef::Nothing),
    }
}

#[cfg(test)]
mod tests {
    use super::super::parser::parse_module;
    use super::*;

    /// Runs a body inside a Function and reports `TypeName|CStr` -- the same
    /// pair `fuzz/vba_variant_probe.bas` prints from Excel, so a test's
    /// expected string can be pasted straight from a probe run.
    fn run(body: &str) -> String {
        let src = format!("Function F()\n{body}\nEnd Function\n");
        let module = parse_module(&src).unwrap_or_else(|e| panic!("{e}\n{src}"));
        match Interpreter::new(module).run("F", Vec::new()) {
            Ok(v) => format!(
                "{}|{}",
                v.type_name(),
                v.to_vba_string().unwrap_or_default()
            ),
            Err(e) => format!("ERR|{}", e.number),
        }
    }

    fn expr(e: &str) -> String {
        run(&format!("    F = {e}"))
    }

    // ---- expressions ----------------------------------------------------

    #[test]
    fn arithmetic_and_types_match_the_excel_probe() {
        // Each expectation is what `fuzz/vba_variant_probe.bas` returned from
        // Excel 16.112 for the same expression.
        assert_eq!(expr("1 + 1"), "Integer|2");
        assert_eq!(expr("32767 + 1"), "ERR|6");
        assert_eq!(expr("1 / 2"), "Double|0.5");
        assert_eq!(expr("4 / 2"), "Double|2");
        assert_eq!(expr("7 \\ 2"), "Integer|3");
        assert_eq!(expr("-7 \\ 2"), "Integer|-3");
        assert_eq!(expr("7.6 \\ 2"), "Long|4");
        assert_eq!(expr("7 Mod 2"), "Integer|1");
        assert_eq!(expr("-7 Mod 2"), "Integer|-1");
        assert_eq!(expr("7.6 Mod 2"), "Long|0");
        assert_eq!(expr("2 ^ 2"), "Double|4");
        assert_eq!(expr("1.5 + 1"), "Double|2.5");
        assert_eq!(expr("1 / 0"), "ERR|11");
    }

    #[test]
    fn precedence_is_the_one_measured_in_phase_0() {
        // The parser's table, exercised through evaluation.
        assert_eq!(expr("2 ^ 3 ^ 2"), "Double|64");
        assert_eq!(expr("-2 ^ 2"), "Double|-4");
        assert_eq!(expr("2 + 3 & 4"), "String|54");
        assert_eq!(expr("1 = 1 And 1 = 0"), "Boolean|False");
        assert_eq!(expr("Not 1 = 0"), "Boolean|True");
        assert_eq!(expr("2 * 10 \\ 3"), "Integer|6");
        assert_eq!(expr("1 + 7 Mod 3"), "Integer|2");
    }

    #[test]
    fn string_coercion_matches_the_probe() {
        assert_eq!(expr("\"1\" + 1"), "Double|2");
        assert_eq!(expr("\"1\" + \"2\""), "String|12");
        assert_eq!(expr("\"abc\" + 1"), "ERR|13");
        assert_eq!(expr("1 & 2"), "String|12");
        assert_eq!(expr("\"  3  \" + 1"), "Double|4");
    }

    #[test]
    fn booleans_and_bitwise_operators_match_the_probe() {
        assert_eq!(expr("True + 1"), "Integer|0");
        assert_eq!(expr("True + True"), "Integer|-2");
        assert_eq!(expr("True And False"), "Boolean|False");
        assert_eq!(expr("5 And 3"), "Integer|1");
        assert_eq!(expr("Not 5"), "Integer|-6");
        assert_eq!(expr("CInt(True)"), "Integer|-1");
    }

    #[test]
    fn empty_and_null_behave_as_measured() {
        assert_eq!(expr("Empty + 1"), "Integer|1");
        assert_eq!(expr("Empty & \"a\""), "String|a");
        assert_eq!(expr("Null & \"a\""), "String|a");
        assert_eq!(expr("IsNull(Null + 1)"), "Boolean|True");
        assert_eq!(expr("Empty = 0"), "Boolean|True");
        assert_eq!(expr("Empty = \"\""), "Boolean|True");
    }

    #[test]
    fn conversions_use_bankers_rounding() {
        assert_eq!(expr("CLng(0.5)"), "Long|0");
        assert_eq!(expr("CLng(1.5)"), "Long|2");
        assert_eq!(expr("CLng(2.5)"), "Long|2");
        assert_eq!(expr("CLng(-1.5)"), "Long|-2");
        assert_eq!(expr("CInt(32768)"), "ERR|6");
        assert_eq!(expr("Int(-1.5)"), "Double|-2");
        assert_eq!(expr("Fix(-1.5)"), "Double|-1");
        assert_eq!(expr("CDbl(\"1e3\")"), "Double|1000");
    }

    // ---- control flow ---------------------------------------------------

    #[test]
    fn for_loops_run_and_can_be_exited() {
        assert_eq!(
            run("    Dim t\n    For i = 1 To 5\n        t = t + i * i\n    Next i\n    F = t"),
            "Integer|55"
        );
        assert_eq!(
            run(
                "    Dim t\n    For i = 1 To 10\n        If i > 3 Then Exit For\n        t = t + 1\n    Next i\n    F = t"
            ),
            "Integer|3"
        );
        // A negative step counts down.
        assert_eq!(
            run("    Dim t\n    For i = 5 To 1 Step -1\n        t = t + i\n    Next i\n    F = t"),
            "Integer|15"
        );
        // A loop whose bounds exclude the start never runs.
        assert_eq!(
            run(
                "    Dim t\n    t = 0\n    For i = 5 To 1\n        t = t + 1\n    Next i\n    F = t"
            ),
            "Integer|0"
        );
    }

    #[test]
    fn every_do_form_terminates_correctly() {
        assert_eq!(
            run("    Dim i\n    i = 0\n    Do While i < 5\n        i = i + 1\n    Loop\n    F = i"),
            "Integer|5"
        );
        assert_eq!(
            run(
                "    Dim i\n    i = 0\n    Do Until i >= 5\n        i = i + 1\n    Loop\n    F = i"
            ),
            "Integer|5"
        );
        // A post-tested loop always runs its body at least once.
        assert_eq!(
            run("    Dim i\n    i = 9\n    Do\n        i = i + 1\n    Loop While i < 5\n    F = i"),
            "Integer|10"
        );
        assert_eq!(
            run("    Dim i\n    i = 0\n    While i < 3\n        i = i + 1\n    Wend\n    F = i"),
            "Integer|3"
        );
    }

    #[test]
    fn select_case_covers_values_ranges_and_is() {
        let body = |x: &str| {
            format!(
                "    Dim r\n    Select Case {x}\n    Case 1, 2\n        r = \"a\"\n    \
                 Case 3 To 5\n        r = \"b\"\n    Case Is >= 6\n        r = \"c\"\n    \
                 Case Else\n        r = \"d\"\n    End Select\n    F = r"
            )
        };
        assert_eq!(run(&body("2")), "String|a");
        assert_eq!(run(&body("4")), "String|b");
        assert_eq!(run(&body("9")), "String|c");
        assert_eq!(run(&body("0")), "String|d");
    }

    #[test]
    fn if_elseif_else_picks_one_branch() {
        let body = |x: &str| {
            format!(
                "    Dim r\n    If {x} > 5 Then\n        r = 1\n    ElseIf {x} > 2 Then\n        \
                 r = 2\n    Else\n        r = 3\n    End If\n    F = r"
            )
        };
        assert_eq!(run(&body("9")), "Integer|1");
        assert_eq!(run(&body("4")), "Integer|2");
        assert_eq!(run(&body("1")), "Integer|3");
    }

    #[test]
    fn goto_jumps_to_a_procedure_level_label() {
        assert_eq!(
            run("    Dim t\n    t = 1\n    GoTo Skip\n    t = 99\nSkip:\n    F = t"),
            "Integer|1"
        );
    }

    // ---- procedures -----------------------------------------------------

    #[test]
    fn functions_call_each_other_and_return_by_name() {
        let src = "Function Outer()\n    Outer = Inner(3) + Inner(4)\nEnd Function\n\
                   Function Inner(n)\n    Inner = n * n\nEnd Function\n";
        let m = parse_module(src).unwrap();
        let v = Interpreter::new(m).run("Outer", Vec::new()).unwrap();
        assert_eq!(v, Variant::Integer(25));
    }

    #[test]
    fn recursion_works_and_is_bounded() {
        let src = "Function Fact(n)\n    If n <= 1 Then\n        Fact = 1\n    Else\n        \
                   Fact = n * Fact(n - 1)\n    End If\nEnd Function\n";
        let m = parse_module(src).unwrap();
        let v = Interpreter::new(m)
            .run("Fact", vec![Variant::Integer(5)])
            .unwrap();
        assert_eq!(v, Variant::Integer(120));

        // Unbounded recursion stops rather than blowing the Rust stack.
        let src = "Function Boom()\n    Boom = Boom()\nEnd Function\n";
        let m = parse_module(src).unwrap();
        let e = Interpreter::new(m).run("Boom", Vec::new()).unwrap_err();
        assert_eq!(e.number, 28);
    }

    #[test]
    fn a_sub_returns_empty_and_exits_early() {
        let src = "Sub S()\n    Exit Sub\nEnd Sub\n";
        let m = parse_module(src).unwrap();
        assert_eq!(
            Interpreter::new(m).run("S", Vec::new()).unwrap(),
            Variant::Empty
        );
    }

    #[test]
    fn an_infinite_loop_hits_the_op_budget_instead_of_hanging() {
        let src = "Function F()\n    Do While True\n    Loop\nEnd Function\n";
        let m = parse_module(src).unwrap();
        let e = Interpreter::new(m)
            .with_max_ops(10_000)
            .run("F", Vec::new())
            .unwrap_err();
        assert_eq!(e.number, 16);
    }

    // ---- error handling -------------------------------------------------

    #[test]
    fn on_error_goto_runs_the_handler_and_exposes_err() {
        assert_eq!(
            run(
                "    On Error GoTo Failed\n    F = 1 / 0\n    Exit Function\nFailed:\n    \
                 F = \"ERR|\" & Err.Number"
            ),
            "String|ERR|11"
        );
        assert_eq!(
            run(
                "    On Error GoTo Failed\n    F = CLng(\"nope\")\n    Exit Function\nFailed:\n    \
                 F = Err.Description"
            ),
            "String|Type mismatch"
        );
    }

    #[test]
    fn on_error_resume_next_continues_at_the_failing_statement() {
        assert_eq!(
            run("    Dim t\n    On Error Resume Next\n    t = 1 / 0\n    t = 7\n    F = t"),
            "Integer|7"
        );
    }

    /// The reason `exec_block` handles errors rather than only the procedure
    /// loop: resuming has to continue inside the loop body, not after it.
    #[test]
    fn resume_next_resumes_inside_a_nested_block() {
        assert_eq!(
            run(
                "    Dim t\n    t = 0\n    On Error Resume Next\n    For i = 1 To 3\n        \
                 t = t + 1 / 0\n        t = t + 1\n    Next i\n    F = t"
            ),
            "Integer|3"
        );
    }

    #[test]
    fn on_error_goto_0_disarms_the_handler() {
        let src = "Function F()\n    On Error Resume Next\n    On Error GoTo 0\n    \
                   F = 1 / 0\nEnd Function\n";
        let m = parse_module(src).unwrap();
        assert_eq!(
            Interpreter::new(m).run("F", Vec::new()).unwrap_err().number,
            11
        );
    }

    #[test]
    fn an_error_inside_a_handler_is_not_caught_by_the_same_handler() {
        // Without this, a handler that itself fails loops forever.
        let src = "Function F()\n    On Error GoTo Failed\n    F = 1 / 0\n    Exit Function\n\
                   Failed:\n    F = 1 / 0\nEnd Function\n";
        let m = parse_module(src).unwrap();
        assert_eq!(
            Interpreter::new(m).run("F", Vec::new()).unwrap_err().number,
            11
        );
    }

    #[test]
    fn err_raise_produces_a_catchable_error() {
        assert_eq!(
            run(
                "    On Error GoTo Failed\n    Err.Raise 5\n    Exit Function\nFailed:\n    \
                 F = Err.Number"
            ),
            "Long|5"
        );
    }

    // ---- builtins -------------------------------------------------------

    #[test]
    fn string_builtins_are_one_based_like_vba() {
        assert_eq!(expr("Len(\"abcd\")"), "Long|4");
        assert_eq!(expr("Left(\"abcd\", 2)"), "String|ab");
        assert_eq!(expr("Right(\"abcd\", 2)"), "String|cd");
        assert_eq!(expr("Mid(\"abcd\", 2, 2)"), "String|bc");
        assert_eq!(expr("Mid(\"abcd\", 3)"), "String|cd");
        assert_eq!(expr("InStr(\"abcd\", \"cd\")"), "Long|3");
        assert_eq!(expr("InStr(\"abcd\", \"z\")"), "Long|0");
        assert_eq!(expr("InStr(3, \"abcabc\", \"a\")"), "Long|4");
        assert_eq!(expr("UCase(\"aB\")"), "String|AB");
        assert_eq!(expr("Trim(\"  a  \")"), "String|a");
        assert_eq!(expr("Replace(\"aXbXc\", \"X\", \"-\")"), "String|a-b-c");
        assert_eq!(expr("Chr(65)"), "String|A");
        assert_eq!(expr("Asc(\"A\")"), "Integer|65");
        // Mid is 1-based, so 0 is an error rather than a clamp.
        assert_eq!(expr("Mid(\"abcd\", 0)"), "ERR|5");
    }

    #[test]
    fn inspection_builtins_report_the_subtype() {
        assert_eq!(expr("TypeName(1)"), "String|Integer");
        assert_eq!(expr("TypeName(1.5)"), "String|Double");
        assert_eq!(expr("TypeName(\"a\")"), "String|String");
        assert_eq!(expr("TypeName(True)"), "String|Boolean");
        assert_eq!(expr("TypeName(100000)"), "String|Long");
        assert_eq!(expr("IsNumeric(\"12\")"), "Boolean|True");
        assert_eq!(expr("IsNumeric(\"ab\")"), "Boolean|False");
        assert_eq!(expr("IsEmpty(Empty)"), "Boolean|True");
    }

    #[test]
    fn math_builtins_keep_the_arguments_width() {
        assert_eq!(expr("Abs(-3)"), "Integer|3");
        assert_eq!(expr("Abs(-3.5)"), "Double|3.5");
        assert_eq!(expr("Sgn(-9)"), "Integer|-1");
        assert_eq!(expr("Sqr(9)"), "Double|3");
        assert_eq!(expr("Sqr(-1)"), "ERR|5");
    }

    #[test]
    fn a_typed_dim_starts_at_its_types_zero_not_empty() {
        // Observable: `Dim s As String` makes s "" rather than Empty.
        assert_eq!(
            run("    Dim s As String\n    F = TypeName(s)"),
            "String|String"
        );
        assert_eq!(run("    Dim n As Long\n    F = TypeName(n)"), "String|Long");
        assert_eq!(run("    Dim v\n    F = TypeName(v)"), "String|Empty");
    }

    // ---- three-valued logic, comparison, loop counters -------------------
    //
    // All measured against Excel 16.112 after fuzz/fuzz_vba.py flagged them.

    #[test]
    fn and_or_and_imp_are_three_valued() {
        // A falsy operand determines And; a truthy one determines Or. The
        // deciding operand is returned unchanged, keeping its type.
        assert_eq!(expr("False And Null"), "Boolean|False");
        assert_eq!(expr("True Or Null"), "Boolean|True");
        assert_eq!(expr("IsNull(True And Null)"), "Boolean|True");
        assert_eq!(expr("IsNull(False Or Null)"), "Boolean|True");
        // Numeric operands keep their own subtype through the same rule.
        assert_eq!(
            run("    Dim a\n    a = 0\n    F = (a And Null)"),
            "Integer|0"
        );
        assert_eq!(
            run("    Dim a\n    a = 5\n    F = (a Or Null)"),
            "Integer|5"
        );
        assert_eq!(
            run("    Dim a\n    a = 5\n    F = IsNull(a And Null)"),
            "Boolean|True"
        );
        assert_eq!(
            run("    Dim a\n    a = 0\n    F = IsNull(a Or Null)"),
            "Boolean|True"
        );
        // Imp is determined by a true consequent or a false antecedent.
        assert_eq!(expr("Null Imp True"), "Boolean|True");
        assert_eq!(expr("False Imp Null"), "Boolean|True");
        // Xor and Eqv are not three-valued: Null always wins.
        assert_eq!(expr("IsNull(Null Xor True)"), "Boolean|True");
        assert_eq!(expr("IsNull(Null Eqv True)"), "Boolean|True");
        // Not propagates Null. A bare `Not Null` only errors if the caller
        // then stringifies the returned Null (for example via CStr).
        assert_eq!(expr("IsNull(Not Null)"), "Boolean|True");
    }

    #[test]
    fn string_versus_number_comparison_depends_on_constant_ness() {
        // The four rules in `value::compare_ctx`, each with the Excel result
        // that established it.

        // Both constant: numeric, and error 13 if the string will not parse.
        assert_eq!(expr("\"10\" = 10"), "Boolean|True");
        assert_eq!(expr("\"2\" > 10"), "Boolean|False");
        assert_eq!(expr("\"\" = 0"), "ERR|13");
        assert_eq!(expr("\"abc\" > 1"), "ERR|13");

        // Numeric constant, string variable: numeric, falling back rather
        // than erroring when the string will not parse.
        assert_eq!(
            run("    Dim a\n    a = \"2\"\n    F = (a > 10)"),
            "Boolean|False"
        );
        assert_eq!(
            run("    Dim a\n    a = \"1.5\"\n    F = (a = 1.5)"),
            "Boolean|True"
        );
        assert_eq!(
            run("    Dim a\n    a = \"\"\n    F = (a = 0)"),
            "Boolean|False"
        );
        assert_eq!(
            run("    Dim a\n    a = \"abc\"\n    F = (a = 1)"),
            "Boolean|False"
        );

        // String constant, numeric variable: string comparison.
        assert_eq!(
            run("    Dim b\n    b = 10\n    F = (\"2\" > b)"),
            "Boolean|True"
        );
        assert_eq!(
            run("    Dim b\n    b = 1\n    F = (\"abc\" > b)"),
            "Boolean|True"
        );

        // A call whose return type is declared numeric counts as statically
        // typed, exactly as a literal does -- see `STATICALLY_NUMERIC`.
        assert_eq!(
            run("    Dim a\n    a = True\n    F = ((1.5 & \"abc\") <> CLng(a))"),
            "ERR|13"
        );
        // The same comparison against a plain Variant uses the runtime rule
        // and does not error.
        assert_eq!(
            run("    Dim a\n    a = -1\n    F = ((1.5 & \"abc\") <> a)"),
            "Boolean|True"
        );
        assert_eq!(
            run("    Dim a\n    a = 2147483647\n    F = (\"Z\" <> a)"),
            "Boolean|True"
        );

        // Against a numeric constant the string is coerced by its numeric
        // *prefix*, as Val takes it -- which is what separates these two,
        // identical by every structural property: "1.5False" has the prefix
        // 1.5, "True255" has none.
        assert_eq!(expr("(Not 2!) <= (\"1.5\" & False)"), "Boolean|True");
        assert_eq!(expr("(-True) <> (True & &HFF)"), "ERR|13");
        assert_eq!(expr("\"False\" = -0.04"), "ERR|13");
        assert_eq!(expr("\"1.5abc\" > 1"), "Boolean|True");
        // Null is not foldable, so nothing containing it is constant, and
        // this falls back to the runtime ordering instead of erroring.
        assert_eq!(expr("(False & Null) = (0.1 / -2.5)"), "Boolean|False");

        // A statically-typed numeric partner is strict whatever the string
        // side looks like -- but only the C* conversions qualify. `Len` does
        // not, despite its documented `As Long` signature.
        assert_eq!(
            run("    Dim a\n    a = True\n    F = ((1.5 & \"abc\") <> CLng(a))"),
            "ERR|13"
        );
        assert_eq!(
            run("    Dim a\n    a = 1\n    F = ((\"abc\" & a) <> Len(CStr(\"Z\")))"),
            "Boolean|True"
        );

        // A Boolean partner converts the string with CBool, so the words
        // compare as booleans. A numeric partner does not: `"True" = -1` is
        // error 13.
        assert_eq!(
            run("    Dim a\n    a = \"True\"\n    F = (a = True)"),
            "Boolean|True"
        );
        assert_eq!(expr("\"True\" = -1"), "ERR|13");

        // Both variables: a number sorts before a string, whatever it is.
        // This is the row that defeats every simpler theory -- "1.5" and 1.5
        // are equal both numerically and textually, and Excel says False.
        assert_eq!(
            run("    Dim a, b\n    a = \"1.5\"\n    b = 1.5\n    F = (a = b)"),
            "Boolean|False"
        );
        assert_eq!(
            run("    Dim a, b\n    a = \"2\"\n    b = 10\n    F = (a > b)"),
            "Boolean|True"
        );
    }

    /// A `Select Case` whose subject is a *constant* string compares as
    /// text, even against numeric cases -- and the same string held in a
    /// variable does not. Both halves measured; the split is the same
    /// constant-vs-runtime one the arithmetic and comparison rules have.
    #[test]
    fn a_constant_string_select_subject_compares_as_text() {
        let sel = |subject: &str| {
            format!(
                "    Dim r\n    Select Case {subject}\n    Case 2 To 5\n        r = \"range\"\n    \
                 Case Else\n        r = \"else\"\n    End Select\n    F = r"
            )
        };
        // Constant subjects: "32768abc" sorts between "2" and "5" as text.
        assert_eq!(run(&sel("\"32768abc\"")), "String|range");
        assert_eq!(run(&sel("(32768 & \"abc\")")), "String|range");
        assert_eq!(run(&sel("\"3\"")), "String|range");
        assert_eq!(run(&sel("\"abc\"")), "String|else");
        assert_eq!(run(&sel("\"7\"")), "String|else");
        assert_eq!(run(&sel("\"1x\"")), "String|else");
        assert_eq!(run(&sel("\"\"")), "String|else");
        // Numeric constant subjects are unaffected.
        assert_eq!(run(&sel("3")), "String|range");
        assert_eq!(run(&sel("7")), "String|else");

        // The same strings in a *variable* use the numeric rule instead, so
        // "32768abc" no longer matches while "3" still does.
        let sel_var = |value: &str| {
            format!(
                "    Dim a, r\n    a = {value}\n    Select Case a\n    Case 2 To 5\n        \
                 r = \"range\"\n    Case Else\n        r = \"else\"\n    End Select\n    F = r"
            )
        };
        assert_eq!(run(&sel_var("\"32768abc\"")), "String|else");
        assert_eq!(run(&sel_var("\"3\"")), "String|range");
        assert_eq!(run(&sel_var("\"7\"")), "String|else");
        assert_eq!(run(&sel_var("\"abc\"")), "String|else");
    }

    #[test]
    fn a_constant_string_subject_also_governs_value_and_is_cases() {
        let sel = |cases: &str| {
            format!(
                "    Dim r\n    Select Case \"abc\"\n{cases}    Case Else\n        r = \"else\"\n    End Select\n    F = r"
            )
        };
        assert_eq!(
            run(&sel("    Case 3\n        r = \"value\"\n")),
            "String|else"
        );
        // "abc" >= "2" as text, so this one matches.
        assert_eq!(
            run(&sel("    Case Is >= 2\n        r = \"is\"\n")),
            "String|is"
        );
    }

    #[test]
    fn select_case_null_subject_matches_no_case_form() {
        // Measured with fuzz/vba_expr_probe.py after fuzz/fuzz_vba.py found
        // `Select Case Null` incorrectly taking a `Case 2 To 5` arm.
        let sel = |cases: &str| {
            format!(
                "    Dim r\n    Select Case Null\n{cases}    Case Else\n        r = \"else\"\n    End Select\n    F = r"
            )
        };
        assert_eq!(
            run(&sel("    Case 2 To 5\n        r = \"range\"\n")),
            "String|else"
        );
        assert_eq!(
            run(&sel("    Case 0, 1\n        r = \"value\"\n")),
            "String|else"
        );
        assert_eq!(
            run(&sel("    Case Is > 2\n        r = \"is\"\n")),
            "String|else"
        );
    }

    // ---- error ordering (docs/vba-error-ordering.md) --------------------

    #[test]
    fn zero_divided_by_zero_is_overflow_not_division_by_zero() {
        // Measured: only floating-point `/` makes the distinction.
        assert_eq!(expr("1 / 0"), "ERR|11");
        assert_eq!(expr("-1 / 0"), "ERR|11");
        assert_eq!(expr("1.5 / 0"), "ERR|11");
        assert_eq!(expr("0 / 0"), "ERR|6");
        assert_eq!(expr("False / 0"), "ERR|6");
        // `\` and `Mod` stay at 11 even for 0 op 0.
        assert_eq!(expr("0 \\ 0"), "ERR|11");
        assert_eq!(expr("0 Mod 0"), "ERR|11");
    }

    #[test]
    fn logical_operators_convert_the_left_operand_before_evaluating_the_right() {
        // Found by fuzz/fuzz_vba.py: the left type mismatch wins over the
        // right division by zero.
        assert_eq!(expr("(\"a\" + \"Z\") Eqv (\"1\" \\ 0)"), "ERR|13");
    }

    #[test]
    fn division_coerces_both_operands_before_testing_the_divisor() {
        // A type mismatch beats a division by zero. Testing the divisor
        // first masked the real error.
        assert_eq!(expr("\"xxxx\" / 0"), "ERR|13");
        assert_eq!(expr("\"\" / 0"), "ERR|13");
        assert_eq!(expr("0 / \"xxxx\""), "ERR|13");
        assert_eq!(expr("\"abc\" / Null"), "ERR|13");
    }

    #[test]
    fn a_static_string_over_a_null_is_invalid_use_of_null() {
        // Left-specific, and only for a statically typed string. See
        // `null_on_the_right` for the measured table.
        for e in [
            "\"  3  \" Imp Null",
            "\"3\" And Null",
            "\"1.5\" Or Null",
            "\"0\" Or Null",
            "\"  3  \" Xor Null",
            "\"  3  \" Eqv Null",
            "(\"  \" & \"3\") Or Null",
            "CStr(3) Or Null",
        ] {
            assert_eq!(expr(e), "ERR|94", "{e}");
        }
        assert_eq!(
            run("    Dim a\n    a = Null\n    F = IsNull(\"  3  \" Or a)"),
            "ERR|94"
        );
        // A runtime string does not trigger it, and neither does a Null on
        // the left.
        assert_eq!(
            run("    Dim a\n    a = \"  3  \"\n    F = IsNull(a Imp Null)"),
            "Boolean|False"
        );
        assert_eq!(expr("IsNull(Null Or \"  3  \")"), "Boolean|False");
        assert_eq!(expr("IsNull(Null Xor \"  3  \")"), "Boolean|True");
        // The string's own conversion is checked first: these stay 13.
        assert_eq!(expr("\"abc\" Imp Null"), "ERR|13");
        assert_eq!(expr("\"True\" Or Null"), "ERR|13");
        // A numeric operand is unaffected.
        assert_eq!(expr("IsNull(255 Imp Null)"), "Boolean|False");
    }

    #[test]
    fn a_statically_typed_numeric_partner_is_strict_only_against_a_constant_string() {
        // `Len`, `Val` and `Sgn` are declared numeric like the `C*`
        // conversions, so a constant string compared against one has to parse
        // whole; `Int` and `Abs` return their argument's type and do not.
        let with = |e: &str| run(&format!("    Dim va\n    va = 1\n    F = {e}"));
        for f in ["CLng(va)", "Len(CStr(va))", "Val(CStr(va))", "Sgn(va)"] {
            assert_eq!(with(&format!("({f} > (-32768 & -2.5))")), "ERR|13", "{f}");
        }
        for f in ["Int(va)", "Abs(va)", "va"] {
            assert_eq!(
                with(&format!("({f} > (-32768 & -2.5))")),
                "Boolean|True",
                "{f}"
            );
        }
        // A *runtime* string is not held to that: it compares numerically
        // when it parses, and falls back to the ordering when it does not,
        // rather than erroring.
        assert_eq!(
            run("    Dim va, vb\n    va = 5\n    vb = \"1\"\n    F = (CLng(va) < vb)"),
            "Boolean|False"
        );
        assert_eq!(with("(CLng(va) < (\"abc\" & va))"), "Boolean|True");
    }

    #[test]
    fn negating_the_long_minimum_between_constants_wraps_to_itself() {
        // `-(-2147483648)` is arithmetically 2147483648, and Excel gives back
        // the Long -2147483648 -- plain two's complement, and wrong. Narrow:
        // the Integer minimum errors instead, and at run time the whole thing
        // widens to a Double. All three measured, and matched deliberately,
        // since a macro doing this should behave the same way here.
        assert_eq!(expr("TypeName(-(Not 2147483647))"), "String|Long");
        assert_eq!(expr("CStr(-(Not 2147483647))"), "String|-2147483648");
        assert_eq!(expr("CStr(-(Not 32767))"), "ERR|6");
        assert_eq!(
            run("    Dim a\n    a = 2147483647\n    F = CStr(-(Not a))"),
            "String|2147483648"
        );
    }

    #[test]
    fn select_case_sees_not_of_a_boolean_as_statically_boolean() {
        // §7's rule -- `Select Case` converts its case values to the
        // subject's *static* type -- carries through `Not`, because `Not` of
        // a Boolean is a Boolean. Measured; `fuzz/fuzz_vba.py` found it as a
        // case that took `Case Else` here and `Case 0, 1` in Excel, which
        // then raised on an expression the other arm never evaluates.
        let sel = |subject: &str| {
            run(&format!(
                "    Dim c\n    Select Case {subject}\n    Case 0, 1\n        c = \"one\"\n                     Case 2 To 5\n        c = \"range\"\n    Case Else\n        c = \"else\"\n                     End Select\n    F = c"
            ))
        };
        assert_eq!(sel("(Not IsEmpty(\"Z\"))"), "String|one");
        assert_eq!(sel("(Not IsEmpty(\"\"))"), "String|one");
        assert_eq!(sel("(Not (IsEmpty(\"Z\")))"), "String|one");
        assert_eq!(sel("(Not CBool(0))"), "String|one");
        assert_eq!(sel("IsEmpty(\"Z\")"), "String|one");
        // `Not` of a *number* is a number, so this stays on the numeric path
        // and matches nothing.
        assert_eq!(sel("(Not 5)"), "String|else");
    }

    #[test]
    fn logical_expression_width_is_static_for_arithmetic_overflow() {
        // Found by fuzz/fuzz_vba.py: this overflows as `2 - (Not 2147483647)`
        // does, even though the logical expression's operand may be Variant.
        assert_eq!(
            run("    Dim vc\n    vc = 10\n    F = ((\"  3  \" And vc) - (Not 2147483647))"),
            "ERR|6"
        );
    }

    #[test]
    fn overflow_between_constants_is_really_between_statically_typed_operands() {
        // §28. The fixed-width arithmetic that makes `32767 + 1` error 6 is
        // chosen by static *typing*, not by constness, and the two come apart
        // in both directions. Measured; `fuzz/fuzz_vba.py` found it on seed
        // 314159 through `CInt(vb) ^ (vb Mod va)`.
        //
        // Typed but not constant: these overflow.
        assert_eq!(expr("CStr(CInt(32767) + 1)"), "ERR|6");
        assert_eq!(expr("CStr(CInt(32767) * 2)"), "ERR|6");
        assert_eq!(expr("CStr(CInt(32767) + CInt(1))"), "ERR|6");
        assert_eq!(expr("CStr(Sgn(1) + 32767)"), "ERR|6");
        assert_eq!(expr("CStr(CLng(2147483647) + 1)"), "ERR|6");
        assert_eq!(expr("CStr(CInt(32767) ^ 4652)"), "ERR|6");
        assert_eq!(expr("CStr(CDbl(32767) ^ 4652)"), "ERR|6");
        assert_eq!(expr("CStr(Len(\"abcde\") ^ 4652)"), "ERR|6");
        // Constant but not typed: `Empty` is a `Variant`, so this promotes
        // exactly as a variable does. visi had this backwards.
        assert_eq!(expr("CStr((Empty + 32767) + 1)"), "String|32768");
        // Unchanged: literals overflow, a variable promotes.
        assert_eq!(expr("CStr(32767 + 1)"), "ERR|6");
        assert_eq!(
            run("    Dim a\n    a = 32767\n    F = CStr(a + 1)"),
            "String|32768"
        );
        assert_eq!(
            run("    Dim a\n    a = 1\n    F = CStr(CInt(32767) + a)"),
            "String|32768"
        );
        // Typed, but the width is `Long`, so there is nothing to overflow.
        assert_eq!(expr("CStr(Len(\"abcde\") + 32763)"), "String|32768");
        assert_eq!(expr("CStr(CInt(Empty) + 32768)"), "String|32768");
        // `^` overflows at runtime too; this was found by fuzz/fuzz_vba.py
        // after earlier tests had incorrectly expected an infinity here.
        assert_eq!(
            run("    Dim vb\n    vb = 4652\n    F = CStr(32767 ^ vb)"),
            "ERR|6"
        );
    }

    #[test]
    fn a_statically_string_value_compares_as_text_against_a_runtime_number() {
        // §27. The other half of §23's split: a declared `String` against a
        // *runtime* number compares as text with the number via `CStr`,
        // exactly as a literal does, where a `Variant`-returning intrinsic
        // orders. Measured; `fuzz/fuzz_vba.py` found it on seed 987654.
        //
        // `a` is a variable throughout, so the number is never static and the
        // strictness of §13/§23 never applies -- these differ only in how
        // well the compiler knows the *string*.
        let with = |setup: &str, e: &str| run(&format!("    Dim a, b\n{setup}\n    F = CStr({e})"));
        assert_eq!(with("    a = 5", "(a < \"10\")"), "String|False");
        assert_eq!(with("    a = 5", "(a < CStr(10))"), "String|False");
        assert_eq!(with("    a = 5", "(a < (CStr(1) & \"0\"))"), "String|False");
        assert_eq!(
            with("    a = 5\n    b = 10", "(a < CStr(b))"),
            "String|False"
        );
        // A `Variant`-returning intrinsic is not statically `String`, so the
        // runtime rule applies instead: the number sorts first.
        assert_eq!(with("    a = 5", "(a < Trim(\"10\"))"), "String|True");
        // Text, and never an error, even when the string will not convert --
        // this is the row the ordering got wrong in both directions.
        assert_eq!(with("    a = -2", "(a < CStr(\"\"))"), "String|False");
        assert_eq!(with("    a = -2", "(a < StrReverse(\"\"))"), "String|False");
        assert_eq!(with("    a = -2", "(a < CStr(\"abc\"))"), "String|True");
        assert_eq!(with("    a = -2", "(a < \"\")"), "String|False");
        // The case as the fuzzer found it: the fold is statically `String`
        // through `&`, so it compares as text and the whole thing is False.
        assert_eq!(
            with(
                "    a = 1\n    b = 1",
                "(((True * 1E3) & Len(CStr(\"Z\"))) > ((-a) - (b ^ 255)))"
            ),
            "String|False"
        );
    }

    #[test]
    fn is_numeric_of_empty_is_true_and_of_null_is_false() {
        // §26. `Empty` answers as the 0 it coerces to; `Null` answers for
        // nothing; `""` is not numeric despite comparing equal to `Empty`.
        // Measured. `fuzz/fuzz_vba.py` found it on seed 862021 as
        // `(Not vc) Xor IsNumeric(Empty)`, which is 1 when the operand is
        // False and -2 when it is True.
        assert_eq!(expr("CStr(IsNumeric(Empty))"), "String|True");
        assert_eq!(expr("CStr(IsNumeric(Null))"), "String|False");
        assert_eq!(expr("CStr(IsNumeric(\"\"))"), "String|False");
        assert_eq!(
            run("    Dim vc\n    vc = -2.5\n    F = CStr((Not vc) Xor IsNumeric(Empty))"),
            "String|-2"
        );
    }

    #[test]
    fn instr_of_an_empty_haystack_is_zero() {
        // `InStr("", "")` is 0 while `InStr("a", "")` is 1: an empty needle
        // matches at the start position only when there is a string to match
        // in. Measured; this used to report 1 for the empty/empty pair.
        assert_eq!(expr("CStr(InStr(\"\", \"\"))"), "String|0");
        assert_eq!(expr("CStr(InStr(Empty, \"\"))"), "String|0");
        assert_eq!(expr("CStr(InStr(\"a\", \"\"))"), "String|1");
        assert_eq!(expr("CStr(InStr(\"\", \"a\"))"), "String|0");
    }

    #[test]
    fn static_typing_propagates_through_arithmetic() {
        // `Len(CStr(a)) / 2` is a Double as surely as `Len(CStr(a))` is a
        // Long -- every operand's type is known -- so the strictness of the
        // test above applies to the whole expression. One Variant operand
        // loses it.
        //
        // Found by `fuzz/fuzz_vba.py` on an unseen seed, which is worth
        // noting: the rule itself is §13, already implemented and tested, and
        // what was missing was only that it stopped at the top-level call.
        let with = |e: &str| run(&format!("    Dim a\n    a = -3\n    F = {e}"));
        assert_eq!(with("(Len(CStr(a)) = \"-7False\")"), "ERR|13");
        assert_eq!(with("((Len(CStr(a)) / 2) = \"-7False\")"), "ERR|13");
        assert_eq!(with("((Len(CStr(a)) + 1) = \"-7False\")"), "ERR|13");
        assert_eq!(with("((CLng(a) / 2) = \"abc\")"), "ERR|13");
        assert_eq!(
            with("((Len(CStr(a)) / (-32768)) = ((-7) & (0 > \"1.5\")))"),
            "ERR|13"
        );
        // A Variant operand anywhere in the arithmetic makes the whole
        // expression a Variant, and then the string compares as text.
        assert_eq!(with("((Len(CStr(a)) + a) = \"-7False\")"), "Boolean|False");
        assert_eq!(with("((a / (-32768)) = \"-7False\")"), "Boolean|False");
        assert_eq!(with("((a + 1) = \"-7False\")"), "Boolean|False");
        // The positive half: against a statically typed number a string that
        // *does* parse compares **numerically**, where a Variant partner
        // would compare it as text and say False.
        assert_eq!(with("((CLng(a) * 2) = \"-6.0\")"), "Boolean|True");
    }

    #[test]
    fn static_typing_propagates_through_comparison_and_concatenation() {
        // §24. The half of §18 it explicitly left open: `&` yields a `String`
        // and a comparison a `Boolean`, provided every operand is itself
        // statically typed. `Empty` is a `Variant`, so a fold over it is
        // neither -- which is what §16's "one cell that resists explanation"
        // actually was.
        //
        // The Boolean side. All measured with `fuzz/vba_expr_probe.py`
        // against the same literal string, so only the partner varies:
        // convert says True (CBool("0") is 0, and 0 >= -1), text says False
        // ("0" sorts below "True").
        assert_eq!(expr("(\"0\" >= (3# >= CDbl(0)))"), "Boolean|True");
        assert_eq!(expr("(\"0\" >= (Len(CStr(0)) >= 1))"), "Boolean|True");
        assert_eq!(expr("(\"0\" >= (\"1\" >= -7))"), "Boolean|True");
        assert_eq!(expr("(\"0\" >= (2 >= 1))"), "Boolean|True");
        assert_eq!(expr("(\"0\" >= (1 = 1))"), "Boolean|True");
        // ...and the same shapes with a `Variant` operand, which could yield
        // `Null` and so is not statically `Boolean`. A declared-Boolean call
        // over `Empty` still is, which is what says this is about the static
        // type and not about `Empty` appearing anywhere.
        assert_eq!(expr("(\"0\" >= (3# >= Empty))"), "Boolean|False");
        assert_eq!(expr("(\"0\" >= (Empty = Empty))"), "Boolean|False");
        assert_eq!(expr("(\"0\" < (3# >= Empty))"), "Boolean|True");
        assert_eq!(expr("(\"0\" >= IsEmpty(Empty))"), "Boolean|True");
        assert_eq!(expr("(\"0\" >= CBool(Empty))"), "Boolean|True");
        assert_eq!(
            run("    Dim b\n    b = 1\n    F = (\"0\" >= (3# >= b))"),
            "Boolean|False"
        );
        // The String side, against a Boolean that is *not* static, where a
        // statically typed String compares as text and a Variant takes the
        // numeric rules. `("1" + "3")` is the case the fuzzer reduced to:
        // a fold of two string literals is a `String` as surely as a literal
        // is, where a fold over `Empty` is not.
        let folded = |s: &str| expr(&format!("({s} <= (\"\" <> Empty))"));
        assert_eq!(folded("\"13\""), "Boolean|True");
        assert_eq!(folded("(\"1\" + \"3\")"), "Boolean|True");
        assert_eq!(folded("(\"1\" & \"3\")"), "Boolean|True");
        assert_eq!(folded("CStr(13)"), "Boolean|True");
        assert_eq!(folded("(CStr(13) & CStr(0))"), "Boolean|True");
        assert_eq!(folded("(Empty & \"13\")"), "Boolean|False");
        assert_eq!(
            run("    Dim a\n    a = \"13\"\n    F = (a <= (\"\" <> Empty))"),
            "Boolean|False"
        );
        // Against a Boolean that *is* static, every string kind converts --
        // including the fold, which used to take the numeric path here and
        // is what `fuzz/fuzz_vba.py` found on seed 271828.
        assert_eq!(expr("((\"1\" + \"3\") <= False)"), "Boolean|True");
        assert_eq!(expr("((Empty & \"13\") <= False)"), "Boolean|True");
        assert_eq!(expr("((\"1\" + \"3\") = True)"), "Boolean|True");
        assert_eq!(expr("((\"1\" + \"3\") > False)"), "Boolean|False");
        // A fold that will not convert is error 13, exactly as the literal
        // it is: the strictness follows the static `String` type.
        assert_eq!(expr("((\"1\" + \"  3  \") <= False)"), "ERR|13");
        assert_eq!(expr("((\"abc\" + \"d\") > True)"), "ERR|13");
        // ...while the same unconvertible string through a Variant orders
        // above the number (§23) instead of raising.
        assert_eq!(expr("((Empty & \"1  3  \") <= False)"), "Boolean|False");
        // Text, not an error, when the Boolean is not static -- even though
        // the string will not convert.
        assert_eq!(
            expr("((\"1\" & \"  3  \") <= (\"\" <> Empty))"),
            "Boolean|True"
        );
    }

    #[test]
    fn a_string_converts_with_cbool_against_a_static_boolean() {
        // Measured with `fuzz/vba_expr_probe.py`. This used to read "compares
        // as text", which fit `("011" < False)` -- True under both readings --
        // and was wrong about every case that discriminates them:
        // `a = "-1"` makes `a = True` **True**, which no text comparison
        // produces. `fuzz/fuzz_vba.py` found it on a generated case whose
        // visible symptom was a *cell* holding the wrong value.
        //
        // The rule: convert the string with `CBool`, compare as Booleans, and
        // fall back to the ordinary runtime ordering only when the conversion
        // fails. Ordering is numeric, so True (-1) sorts below False (0).
        let with = |setup: &str, e: &str| run(&format!("    Dim va, vb\n{setup}\n    F = {e}"));
        assert_eq!(with("    va = \"011\"", "(va = True)"), "Boolean|True");
        assert_eq!(with("    va = \"0\"", "(va = False)"), "Boolean|True");
        assert_eq!(with("    va = \"2\"", "(va = True)"), "Boolean|True");
        assert_eq!(with("    va = \"-1\"", "(va = True)"), "Boolean|True");
        assert_eq!(with("    va = \"1.5\"", "(va = True)"), "Boolean|True");
        assert_eq!(with("    va = \"-1\"", "(va <> True)"), "Boolean|False");
        assert_eq!(with("    va = \"011\"", "(va < False)"), "Boolean|True");
        assert_eq!(with("    va = \"011\"", "(va > False)"), "Boolean|False");
        assert_eq!(with("    va = \"011\"", "(va > True)"), "Boolean|False");
        // The two that pin down *that* there is a fallback: `CBool` raises for
        // both, yet neither comparison does -- they are simply unequal. What
        // the fallback *is* takes the ordering cases in
        // `an_unconvertible_runtime_string_sorts_above_a_static_boolean`;
        // equality cannot tell text from ordering.
        assert_eq!(with("    va = \"abc\"", "(va = True)"), "Boolean|False");
        assert_eq!(with("    va = \"\"", "(va = False)"), "Boolean|False");
        // A *statically* String operand takes the same conversion but does
        // **not** get that fallback -- it is error 13 instead. The
        // discriminating rows, all measured: the same string reaches the
        // fallback through a Variant or through a Variant-returning
        // intrinsic, and error 13 only through one declared `As String`.
        assert_eq!(expr("CStr(32767) >= (Not True)"), "Boolean|False");
        assert_eq!(expr("TypeName(32767) >= False"), "ERR|13");
        assert_eq!(expr("(TypeName(32767) >= (Not True))"), "ERR|13");
        assert_eq!(expr("LCase(\"Integer\") >= (Not True)"), "Boolean|True");
        assert_eq!(
            run("    Dim va\n    va = TypeName(32767)\n    F = (va >= (Not True))"),
            "Boolean|True"
        );
        assert_eq!(with("    va = \"011\"", "(va < CBool(0))"), "Boolean|True");
        assert_eq!(
            with("    va = \"011\"", "(va < IsNull(32768))"),
            "Boolean|True"
        );
        // A string *literal* converts too, and a conversion failure is
        // error 13 rather than the text fallback.
        assert_eq!(expr("(\"abc\" < True)"), "ERR|13");
        assert_eq!(expr("(\"Z\" < True)"), "ERR|13");
        assert_eq!(expr("(False >= \"abc\")"), "ERR|13");
        assert_eq!(expr("(\"\" = False)"), "ERR|13");
        // These two are what the numeric reading got wrong, and they are the
        // same rule: `CBool("011")` and `CBool("12")` are both True (-1),
        // which sorts *below* False (0). `("011" < False)` in particular sat
        // in this file as an unexplained divergence for the whole of Phase 1;
        // `fuzz/fuzz_vba.py` re-surfaced it as `(False > "12")` and the
        // `CBool` model accounts for both.
        assert_eq!(expr("(\"011\" < False)"), "Boolean|True");
        assert_eq!(expr("(False > \"12\")"), "Boolean|True");
        assert_eq!(expr("(\"0\" = False)"), "Boolean|True");
        // Neither side is statically typed here -- `Empty` is a `Variant`, so
        // the fold over it is not a `String` and the comparison is not a
        // `Boolean` -- so both fall to the numeric rules: `"1"` becomes 1, and
        // `1 <= 0` is False, where the conversion would say True. See §24.
        assert_eq!(
            expr("((Empty & \"1\") <= (\"\" <> Empty))"),
            "Boolean|False"
        );
        // Against a Boolean that is *not* statically `Boolean` -- here a
        // comparison with an `Empty` operand -- a statically typed `String`
        // compares as text, with the Boolean rendered "True"/"False".
        assert_eq!(expr("TypeName(0) >= (3# >= Empty)"), "Boolean|False");
        assert_eq!(expr("(3# >= Empty) >= TypeName(0)"), "Boolean|True");
        assert_eq!(expr("CStr(0) >= (3# >= Empty)"), "Boolean|False");
        assert_eq!(expr("(Not True) <= CStr(32767)"), "Boolean|False");
        assert_eq!(expr("False >= TypeName(0)"), "ERR|13");
        // ...where a comparison whose operands *are* all statically typed is
        // a statically known Boolean, and converts. This pair looks like an
        // exception about static strings and is not one: the two differ in
        // the **Boolean**, not the string -- see §24 and the test below.
        assert_eq!(expr("(\"000\" < (\"1\" >= -7))"), "Boolean|False");
        assert_eq!(
            run("    Dim va\n    va = \"000\"\n    F = (va < (\"1\" >= -7))"),
            "Boolean|False"
        );
        assert_eq!(expr("(Right(100000, 3) < (\"1\" >= -7))"), "Boolean|False");
        // A *static* Boolean partner converts against every string kind,
        // including a static one.
        assert_eq!(expr("(CStr(0) >= CBool(1))"), "Boolean|True");
        assert_eq!(expr("(\"000\" < CBool(1))"), "Boolean|False");
        assert_eq!(expr("(TypeName(0) >= CBool(1))"), "ERR|13");
        // A Boolean *variable* is not static at all, so none of this applies
        // and the runtime rule takes over: a number sorts before a string.
        assert_eq!(
            with("    va = \"011\"\n    vb = False", "(va < vb)"),
            "Boolean|False"
        );
        // The words take the same path -- `CBool` accepts them too --
        // case-insensitively, and order as the Booleans they become.
        assert_eq!(with("    va = \"True\"", "(va < False)"), "Boolean|True");
        assert_eq!(with("    va = \"true\"", "(va = True)"), "Boolean|True");
        assert_eq!(with("    va = \"TRUE\"", "(va = True)"), "Boolean|True");
        assert_eq!(with("    va = \"true\"", "(va = False)"), "Boolean|False");
        // A Boolean variable is not static: the number sorts before the
        // string, so "011" is Greater and `<` is False.
        assert_eq!(
            with("    va = \"011\"\n    vb = False", "(va < vb)"),
            "Boolean|False"
        );
        // A numeric partner is unaffected, and still refuses the words.
        assert_eq!(with("    va = \"011\"", "(va < 0)"), "Boolean|False");
        assert_eq!(expr("(\"True\" = -1)"), "ERR|13");
    }

    #[test]
    fn an_unconvertible_runtime_string_sorts_above_a_static_boolean() {
        // When `CBool` will not take the string, a *runtime* one falls back to
        // the ordinary runtime rule -- the number sorts first, so the string
        // is Greater whatever the two spell. This was written as a text
        // comparison, which every case available at the time agreed with:
        // `"abc"`, `"Integer"` and `""` all sort on the same side of
        // `"True"`/`"False"` as the ordering rule puts them, so the two
        // readings only come apart on a string that does not -- `"ABC"`,
        // whose `A` sorts below both words.
        //
        // Measured with `fuzz/vba_expr_probe.py`; every expectation here is
        // what Excel returned. Found while reducing the `StrReverse` case in
        // `statically_string_intrinsics_are_strict_against_a_boolean`.
        let with = |setup: &str, e: &str| run(&format!("    Dim va\n{setup}\n    F = {e}"));
        assert_eq!(with("    va = \"ABC\"", "(va > True)"), "Boolean|True");
        assert_eq!(with("    va = \"ABC\"", "(va < True)"), "Boolean|False");
        assert_eq!(with("    va = \"ABC\"", "(va >= False)"), "Boolean|True");
        // The same through a `Variant`-returning intrinsic, which is how the
        // fuzzer's generated code reaches it.
        assert_eq!(expr("Chr(65) > True"), "Boolean|True");
        assert_eq!(expr("Chr(65) > False"), "Boolean|True");
        assert_eq!(expr("Hex(255) > True"), "Boolean|True");
        assert_eq!(expr("Space(2) > True"), "Boolean|True");
        // The cases the text reading was derived from still hold -- they are
        // simply blind to the difference.
        assert_eq!(with("    va = \"abc\"", "(va = True)"), "Boolean|False");
        assert_eq!(expr("LCase(\"Integer\") >= (Not True)"), "Boolean|True");
    }

    #[test]
    fn statically_string_intrinsics_are_strict_against_a_boolean() {
        // `StrReverse`, `Replace` and `Join` are declared `As String` and have
        // no `$` form, so the plain name is the typed one -- an unconvertible
        // result against a statically known Boolean is error 13, where the
        // Variant-returning neighbours fall back to ordering instead.
        //
        // `fuzz/fuzz_vba.py` found this as a whole-procedure divergence: Excel
        // stopped at `StrReverse(False) > (Not False)` with 13 while visi took
        // the comparison as True, ran into the other branch, and raised 11 on
        // a division by zero Excel never reached. Measured with
        // `fuzz/vba_expr_probe.py`; see `STATICALLY_STRING`.
        assert_eq!(expr("StrReverse(False) > (Not False)"), "ERR|13");
        assert_eq!(expr("StrReverse(\"abc\") > True"), "ERR|13");
        assert_eq!(expr("StrReverse(\"abc\") > 5"), "ERR|13");
        assert_eq!(expr("True > StrReverse(\"abc\")"), "ERR|13");
        assert_eq!(expr("Replace(\"abc\", \"a\", \"z\") > True"), "ERR|13");
        // A *numeric* partner is strict the same way, and was already wrong
        // for `CStr`/`TypeName` before `StrReverse` joined them: the strictness
        // keyed off the string being *constant* rather than merely typed.
        assert_eq!(expr("CStr(\"abc\") > 5"), "ERR|13");
        assert_eq!(expr("TypeName(1) > 5"), "ERR|13");
        assert_eq!(expr("CStr(\"abc\") >= 0"), "ERR|13");
        assert_eq!(expr("CStr(\"abc\") > CLng(1)"), "ERR|13");
        assert_eq!(expr("TypeName(1) > CLng(5)"), "ERR|13");
        // Variant-returning neighbours are unaffected, against either partner.
        assert_eq!(expr("Trim(\"abc\") > True"), "Boolean|True");
        assert_eq!(expr("LTrim(\"abc\") > True"), "Boolean|True");
        assert_eq!(expr("Trim(\"abc\") > 5"), "Boolean|True");
        assert_eq!(expr("Chr(65) > 5"), "Boolean|True");
        // A typed string that *does* convert is not an error.
        assert_eq!(expr("CStr(\"11\") > 5"), "Boolean|True");
        // Two strings still compare as text, whatever their kinds.
        assert_eq!(expr("TypeName(1) > \"5\""), "Boolean|True");
        // The same string through a Variant is not statically typed, so it
        // compares rather than erroring -- the row that makes this about the
        // declared return type and not the value.
        assert_eq!(
            run("    Dim va\n    va = StrReverse(\"abc\")\n    F = (va > True)"),
            "Boolean|True"
        );
        assert_eq!(
            run("    Dim va\n    va = 5\n    F = (StrReverse(\"abc\") > va)"),
            "Boolean|True"
        );
        // A convertible result still converts: `CBool("11")` is True (-1),
        // which sorts below False (0).
        assert_eq!(expr("StrReverse(\"11\") > False"), "Boolean|False");
    }

    #[test]
    fn division_overflows_rather_than_returning_an_infinity() {
        // `/` was the last operator handing back an INF where Excel raises
        // error 6, at run time as well as between constants. Measured with
        // `fuzz/vba_expr_probe.py`; `^` remains the one operator that does
        // produce infinities, and feeding one of those to `/` raises too.
        assert_eq!(expr("1E308 / 1E-308"), "ERR|6");
        assert_eq!(
            run("    Dim a, b\n    a = 1E308\n    b = 1E-308\n    F = a / b"),
            "ERR|6"
        );
        assert_eq!(
            run("    Dim a, b\n    a = 3.75\n    b = a ^ 32767\n    F = b / 2"),
            "ERR|6"
        );
        // Ordinary division is untouched, and so are the two zero cases.
        assert_eq!(expr("1 / 2"), "Double|0.5");
        assert_eq!(expr("1 / 0"), "ERR|11");
        assert_eq!(expr("0 / 0"), "ERR|6");
    }

    #[test]
    fn pow_overflow_raises_at_runtime_too() {
        // Measured after fuzz/fuzz_vba.py found `b = 3# : e = 32767 : b ^ e`.
        assert_eq!(expr("3.75 ^ 32767"), "ERR|6");
        assert_eq!(expr("255 ^ 255"), "ERR|6");
        assert_eq!(run("    Dim a\n    a = 3.75\n    F = (a ^ 32767)"), "ERR|6");
        assert_eq!(run("    Dim a\n    a = 255\n    F = (a ^ 255)"), "ERR|6");
        // A finite result is unaffected.
        assert_eq!(expr("2 ^ 10"), "Double|1024");
    }

    #[test]
    fn overflowing_pow_raises_before_arithmetic_can_observe_infinity() {
        // `^` raises overflow when the result exceeds Double range, even at
        // runtime. A previous model let it produce INF and only made later
        // arithmetic reject it.
        assert_eq!(run("    Dim a\n    a = 255\n    F = (a ^ 255)"), "ERR|6");
        assert_eq!(run("    Dim a\n    a = 255\n    F = -(a ^ 255)"), "ERR|6");
        assert_eq!(
            run("    Dim a\n    a = 255\n    F = ((a ^ 255) & \"x\")"),
            "ERR|6"
        );
        assert_eq!(
            run("    Dim a, b\n    a = 255\n    b = (a ^ 255)\n    F = (b + 1)"),
            "ERR|6"
        );
        assert_eq!(run("    Dim a\n    a = 1E300\n    F = (a * a)"), "ERR|6");
        // Finite overflow of an addition is still fine.
        assert_eq!(
            run("    Dim a, b\n    a = 1E300\n    b = 1E300\n    F = (a + b)"),
            "Double|2E+300"
        );
    }

    #[test]
    fn imp_follows_its_definition_rather_than_a_hand_rolled_table() {
        // `255 Imp Null` is `Not 255 Or Null` = `-256 Or Null` = -256,
        // because -256 is truthy. A hand-rolled three-valued table said Null.
        assert_eq!(
            run("    Dim a\n    a = 255\n    F = (a Imp Null)"),
            "Integer|-256"
        );
        // The measured endpoints still hold.
        assert_eq!(expr("Null Imp True"), "Boolean|True");
        assert_eq!(expr("False Imp Null"), "Boolean|True");
        assert_eq!(expr("5 Imp 3"), "Integer|-5");
    }

    #[test]
    fn single_combined_with_long_widens_past_both() {
        // A Single cannot hold every Long, so VBA goes to Double -- but a
        // Single with an Integer stays Single. Both measured.
        assert_eq!(run("    Dim a\n    a = 2!\n    F = (a + 1)"), "Single|3");
        assert_eq!(
            run("    Dim a, b\n    a = 2!\n    b = 1&\n    F = (a * b)"),
            "Double|2"
        );
        assert_eq!(
            run("    Dim a\n    a = 2!\n    F = (a - 0.5)"),
            "Double|1.5"
        );
    }

    /// Which operators coerce a `Null`'s partner before propagating, and
    /// which short-circuit. Measured in both directions with `IsNull`.
    #[test]
    fn only_plus_short_circuits_past_a_bad_partner() {
        // `+` alone returns Null without looking at the other side --
        // plausibly because it cannot tell addition from concatenation
        // without inspecting both, so it gives up first.
        assert_eq!(expr("IsNull(Null + \"Z\")"), "Boolean|True");
        assert_eq!(expr("IsNull(\"Z\" + Null)"), "Boolean|True");
        assert_eq!(expr("IsNull(Null + \"12\")"), "Boolean|True");

        // Every other operator coerces the partner, and a bad string wins.
        for e in [
            "\"Z\" - Null",
            "Null - \"Z\"",
            "\"Z\" * Null",
            "\"Z\" / Null",
            "\"Z\" ^ Null",
            "\"Z\" Mod Null",
            "Null Mod \"Z\"",
            "\"Z\" \\ Null",
            "\"Z\" And Null",
            "Null Or \"Z\"",
        ] {
            assert_eq!(expr(e), "ERR|13", "for {e}");
        }

        // `&` keeps the non-Null side rather than propagating at all.
        assert_eq!(expr("\"Z\" & Null"), "String|Z");

        // A well-formed partner still propagates.
        assert_eq!(expr("IsNull(1 - Null)"), "Boolean|True");
        assert_eq!(expr("IsNull(Null Mod 3)"), "Boolean|True");
    }

    #[test]
    fn unary_sign_promotes_on_overflow_at_runtime() {
        // Same constant-vs-runtime split the binary operators have.
        assert_eq!(
            run("    Dim a\n    a = 2147483647\n    F = (-(Not a))"),
            "Double|2147483648"
        );
        assert_eq!(
            run("    Dim a\n    a = 2147483647\n    F = TypeName(-(Not a))"),
            "String|Double"
        );
        // Integer widens to Long the same way.
        assert_eq!(
            run("    Dim a\n    a = 32767\n    F = (-(Not a))"),
            "Long|32768"
        );
    }

    #[test]
    fn a_statically_boolean_select_subject_converts_its_cases_with_cbool() {
        // Every row measured against Excel 16.112 with
        // `fuzz/vba_expr_probe.py`. A *statically* Boolean subject converts
        // each case value with CBool and compares the Booleans; a Variant
        // holding a Boolean does not, and compares numerically with True as
        // -1. The two halves of this test are the same subject value either
        // side of that line.
        let sel = |subject: &str, cases: &str| {
            format!(
                "    Dim r\n    Select Case {subject}\n{cases}    Case Else\n        r = \"else\"\n    End Select\n    F = r"
            )
        };
        let hit = |subject: &str, case: &str| {
            run(&sel(
                subject,
                &format!("    Case {case}\n        r = \"a\"\n"),
            ))
        };

        // Statically Boolean: a folded constant, or a Boolean-returning
        // intrinsic over a variable.
        for subject in [
            "(1 = 1)",
            "True",
            "CBool(1)",
            "IsNumeric(0)",
            // Found by fuzz/fuzz_vba.py: a non-constant comparison is still
            // statically Boolean when both operands are statically typed.
            "(Val(&O17) >= (True > 3#))",
        ] {
            assert_eq!(hit(subject, "1"), "String|a", "{subject} vs Case 1");
            assert_eq!(hit(subject, "0"), "String|else", "{subject} vs Case 0");
            assert_eq!(hit(subject, "0, 1"), "String|a", "{subject} vs Case 0, 1");
            // Both ends become True, so the range is True To True.
            assert_eq!(hit(subject, "2 To 5"), "String|a", "{subject} vs 2 To 5");
            // ... while `0 To 1` becomes False To True, i.e. 0 To -1, which
            // is empty. This row is why the conversion cannot be "compare as
            // Booleans" -- it has to happen before the comparison.
            assert_eq!(hit(subject, "0 To 1"), "String|else", "{subject} vs 0 To 1");
            assert_eq!(hit(subject, "Is = 1"), "String|a", "{subject} vs Is = 1");
            assert_eq!(hit(subject, "Is > 0"), "String|else", "{subject} vs Is > 0");
            assert_eq!(hit(subject, "Is < 0"), "String|a", "{subject} vs Is < 0");
        }
        assert_eq!(hit("(1 = 2)", "0, 1"), "String|a");
        assert_eq!(hit("(1 = 2)", "2 To 5"), "String|else");
        // CBool(Null) is error 94, and the case value goes through CBool.
        assert_eq!(
            run(&sel("CBool(1)", "    Case Null\n        r = \"a\"\n")),
            "ERR|94"
        );

        // The same values in a Variant compare numerically instead.
        let via_var = |value: &str, case: &str| {
            run(&format!(
                "    Dim a, r\n    a = {value}\n    Select Case a\n    Case {case}\n        \
                 r = \"a\"\n    Case Else\n        r = \"else\"\n    End Select\n    F = r"
            ))
        };
        assert_eq!(via_var("True", "0, 1"), "String|else");
        assert_eq!(via_var("True", "-1"), "String|a");
        assert_eq!(via_var("True", "2 To 5"), "String|else");
        assert_eq!(via_var("True", "Is < 0"), "String|a");
        assert_eq!(via_var("False", "0, 1"), "String|a");
    }

    #[test]
    fn select_case_constant_bool_int_op_subject_is_not_statically_boolean() {
        // Reproduces fuzz_results/failures/vba_exec_case_197. `True \\ "12"`
        // folds to the Boolean True as an expression, but Excel does not use
        // the statically-Boolean `Select Case` rule for that folded result, so
        // `Case 0, 1` is not taken.
        assert_eq!(
            run(
                "    Dim r\n    Select Case (True \\ \"12\")\n    Case 0, 1\n        r = \"value\"\n    Case Else\n        r = \"else\"\n    End Select\n    F = r"
            ),
            "String|else"
        );
    }

    /// The constant-folding quirk in `constant_bool_int_op`, with the
    /// negative controls that pin down how narrow it is.
    #[test]
    fn a_constant_boolean_over_a_constant_string_folds_to_a_boolean() {
        assert_eq!(expr("True Mod \"12\""), "Boolean|False");
        assert_eq!(expr("True \\ \"12\""), "Boolean|True");
        assert_eq!(expr("False \\ \"12\""), "Boolean|False");
        // "0" becomes False, i.e. zero, so these divide by zero.
        assert_eq!(expr("True Mod \"0\""), "ERR|11");
        assert_eq!(expr("True \\ \"0\""), "ERR|11");

        // Left-specific.
        assert_eq!(expr("\"12\" Mod True"), "Long|0");
        assert_eq!(expr("\"12\" \\ True"), "Long|-12");
        // The partner has to be a String.
        assert_eq!(expr("True Mod 12"), "Integer|-1");
        assert_eq!(expr("True \\ 12"), "Integer|0");
        // Both have to be constants.
        assert_eq!(
            run("    Dim a\n    a = True\n    F = (a Mod \"12\")"),
            "Long|-1"
        );
        assert_eq!(
            run("    Dim b\n    b = \"12\"\n    F = (True Mod b)"),
            "Long|-1"
        );
        // Only `\\` and `Mod`.
        assert_eq!(expr("True And \"12\""), "Long|12");
        assert_eq!(expr("True Or \"12\""), "Long|-1");
        assert_eq!(expr("True Eqv \"12\""), "Long|12");
    }

    #[test]
    fn integer_operators_process_the_left_operand_first() {
        // Which error surfaces depends on the order: the left operand
        // overflowing a Long beats a bad string on the right, and vice versa.
        assert_eq!(
            run("    Dim a\n    a = \"32768100000\"\n    F = (a Mod \"Double\")"),
            "ERR|6"
        );
        assert_eq!(
            run("    Dim a\n    a = \"Double\"\n    F = (a Mod \"32768100000\")"),
            "ERR|13"
        );
        assert_eq!(
            run("    Dim a\n    a = \"32768100000\"\n    F = (a Mod 3)"),
            "ERR|6"
        );
    }

    /// The whole `Null` table, from a sweep of every intrinsic against real
    /// Excel. There is no principle behind the split, so the test enumerates
    /// it -- `Hex` propagates but `Chr` rejects, `String` propagates but
    /// `Space` rejects, `CVar` propagates where every other `C*` rejects.
    #[test]
    fn every_intrinsic_handles_null_the_way_excel_does() {
        for f in [
            "CVar", "Abs", "Int", "Fix", "Round", "Len", "UCase", "LCase", "Trim", "LTrim",
            "RTrim", "Hex", "Oct",
        ] {
            assert_eq!(
                expr(&format!("IsNull({f}(Null))")),
                "Boolean|True",
                "{f} should propagate"
            );
        }
        for e in [
            "Left(Null, 1)",
            "Right(Null, 1)",
            "Mid(Null, 1, 1)",
            "InStr(Null, \"a\")",
            "String(2, Null)",
            "StrComp(Null, \"a\")",
        ] {
            assert_eq!(
                expr(&format!("IsNull({e})")),
                "Boolean|True",
                "{e} should propagate"
            );
        }
        for f in [
            "CStr",
            "CInt",
            "CLng",
            "CDbl",
            "CSng",
            "CBool",
            "CCur",
            "Val",
            "Sgn",
            "Sqr",
            "Exp",
            "Log",
            "Sin",
            "Cos",
            "Tan",
            "Atn",
            "Space",
            "StrReverse",
            "Chr",
            "Asc",
        ] {
            assert_eq!(expr(&format!("{f}(Null)")), "ERR|94", "{f} should reject");
        }
        assert_eq!(expr("Replace(Null, \"a\", \"b\")"), "ERR|94");
        // Inspection functions look at it rather than propagating or rejecting.
        assert_eq!(expr("TypeName(Null)"), "String|Null");
        assert_eq!(expr("IsNull(Null)"), "Boolean|True");
        assert_eq!(expr("IsNumeric(Null)"), "Boolean|False");
        assert_eq!(expr("IsEmpty(Null)"), "Boolean|False");
    }

    #[test]
    fn conversions_reject_null_rather_than_propagating_it() {
        // `CStr(Null)` raises error 94. Propagating a Null instead was a real
        // mismatch: callers put it under `On Error Resume Next` expecting the
        // assignment to be skipped, and a returned Null poisoned everything
        // downstream of it.
        assert_eq!(expr("CStr(Null)"), "ERR|94");
        assert_eq!(expr("CDbl(Null)"), "ERR|94");
        assert_eq!(expr("CLng(Null)"), "ERR|94");
        // String functions do propagate.
        assert_eq!(expr("IsNull(UCase(Null))"), "Boolean|True");
        assert_eq!(expr("IsNull(Left(Null, 1))"), "Boolean|True");
        // Inspection functions look at it rather than propagating.
        assert_eq!(expr("TypeName(Null)"), "String|Null");
        assert_eq!(expr("IsNull(Null)"), "Boolean|True");
    }

    #[test]
    fn fuzz_statement_conditions_read_null_as_false_unlike_cbool() {
        // Harvested from fuzz/fuzz_vba.py's win32com (Windows) run, seed 1,
        // case 2: `If (-Null) Then ... Else ... End If` ran the Else branch
        // in real Excel rather than raising 94 the way `CBool(Null)` does --
        // visi previously shared one `to_bool` between statement conditions
        // and CBool/the logical operators, so `If Null Then` raised 94 too.
        //
        // Measured directly (win32com, real Windows Excel) that this is a
        // real, separate rule rather than a slip in the Gen2 case: `If Null
        // Then` takes the Else branch, `Do While Null` never loops, and `Do
        // Until Null` loops until an explicit exit (the condition reads as
        // False, never True) -- while `CBool(Null)` still raises 94 in that
        // same session. Two different coercions behind what looks like one
        // "read as boolean" idea.
        assert_eq!(
            run("    If Null Then\n        F = \"T\"\n    Else\n        F = \"F\"\n    End If"),
            "String|F"
        );
        assert_eq!(
            run(
                "    Dim n As Integer\n    n = 0\n    Do While Null\n        n = n + 1\n    Loop\n    F = n"
            ),
            "Integer|0"
        );
        assert_eq!(
            run(
                "    Dim n As Integer\n    n = 0\n    Do Until Null\n        n = n + 1\n        If n > 3 Then Exit Do\n    Loop\n    F = n"
            ),
            "Integer|4"
        );
        // The explicit conversion is untouched -- still 94.
        assert_eq!(expr("CBool(Null)"), "ERR|94");
    }

    #[test]
    fn fuzz_not_null_propagates_until_observed() {
        // Harvested from fuzz/fuzz_vba.py win32com case 20: assigning
        // `Not Null` does not raise, and concatenation later skips the Null.
        assert_eq!(expr("IsNull(Not Null)"), "Boolean|True");
        assert_eq!(
            run("    Dim a, b\n    a = Not Null\n    b = \"x\" & a\n    F = b"),
            "String|x"
        );
    }

    #[test]
    fn the_words_true_and_false_coerce_on_the_integer_path_only() {
        // Measured. The integer/logical path accepts them as -1 and 0; the
        // floating-point path has never heard of them.
        assert_eq!(expr("\"True\" Xor 1"), "Integer|-2");
        assert_eq!(expr("\"False\" Xor 1"), "Integer|1");
        assert_eq!(expr("\"True\" \\ 1"), "Integer|-1");
        assert_eq!(expr("\"True\" Mod 2"), "Integer|-1");
        assert_eq!(expr("CBool(\"True\")"), "Boolean|True");
        // Case-insensitive, and space-tolerant.
        assert_eq!(expr("\"true\" Xor 1"), "Integer|-2");
        assert_eq!(expr("\"TRUE\" Xor 1"), "Integer|-2");
        // `Not` keeps it a Boolean, because both sides of the operation are
        // one; `Xor` with a number goes bitwise and yields an Integer.
        assert_eq!(expr("Not \"True\""), "Boolean|False");

        // Against a Boolean partner the fold is suppressed only when *both*
        // sides are statically typed -- a literal, or a call with a declared
        // return type. `CStr` is declared `As String`; `LCase` returns a
        // Variant, and that pair is what separates the two halves.
        assert_eq!(expr("True Eqv \"True\""), "ERR|13");
        assert_eq!(expr("\"True\" Eqv True"), "ERR|13");
        assert_eq!(expr("True Eqv CStr(True)"), "ERR|13");
        assert_eq!(
            run("    Dim a\n    a = 3.75\n    F = (IsNumeric(a) Eqv CStr(True))"),
            "ERR|13"
        );
        // ... and happens as soon as either side is a Variant.
        assert_eq!(expr("LCase(\"TRUE\") Eqv True"), "Boolean|True");
        assert_eq!(expr("LCase(False) Eqv IsNull(True)"), "Boolean|True");
        assert_eq!(
            run("    Dim a\n    a = True\n    F = (a Eqv \"True\")"),
            "Boolean|True"
        );
        assert_eq!(
            run("    Dim a\n    a = \"false\"\n    F = (a Eqv False)"),
            "Boolean|True"
        );
        assert_eq!(
            run("    Dim a\n    a = \"true\"\n    F = (a Eqv False)"),
            "Boolean|False"
        );
        assert_eq!(
            run("    Dim a, b\n    a = \"true\"\n    b = False\n    F = (a Eqv b)"),
            "Boolean|False"
        );

        // The floating-point path still rejects them.
        for e in [
            "\"True\" + 1",
            "\"False\" + 1",
            "\"True\" * 2",
            "CDbl(\"True\")",
        ] {
            assert_eq!(expr(e), "ERR|13", "for {e}");
        }
        assert_eq!(expr("IsNumeric(\"True\")"), "Boolean|False");

        // The exact shape the fuzzer hit: Trim of a comparison yields the
        // word, which then has to work as a logical operand.
        assert_eq!(expr("Trim((1 >= 2)) Xor 5"), "Integer|5");
    }

    #[test]
    fn a_string_outside_double_range_fails_to_convert() {
        // Error 6 from the *conversion*, not a quiet infinity -- and not the
        // 13 an unparseable string gives.
        assert_eq!(
            run("    Dim a\n    a = \"1E+2923\"\n    F = (a ^ 255)"),
            "ERR|6"
        );
        assert_eq!(
            run("    Dim a\n    a = \"1E400\"\n    F = (a + 1)"),
            "ERR|6"
        );
        // The power itself overflows too, even with runtime operands.
        assert_eq!(
            run("    Dim a\n    a = \"255\"\n    F = (a ^ 255)"),
            "ERR|6"
        );
        assert_eq!(run("    Dim a\n    a = 255\n    F = (a ^ 255)"), "ERR|6");
    }

    #[test]
    fn an_empty_string_never_coerces_to_a_number() {
        // Measured across every operator: `"" - 3`, `"" + 3`, `"" * 3`,
        // `"" \ 3`, `"" And 1`, `Not ""` and `CDbl("")` are all error 13.
        for e in [
            "\"\" - 3",
            "\"\" + 3",
            "\"\" * 3",
            "\"\" \\ 3",
            "Not \"\"",
            "CDbl(\"\")",
        ] {
            assert_eq!(expr(e), "ERR|13", "for {e}");
        }
    }

    #[test]
    fn val_always_returns_a_double() {
        // Measured directly. A previous version typed the result like a
        // literal, inferred from a fuzz case where `Val` may never have run.
        assert_eq!(expr("Val(255)"), "Double|255");
        assert_eq!(expr("Val(\"1.5\")"), "Double|1.5");
        assert_eq!(expr("Val(\"100000\")"), "Double|100000");
        assert_eq!(run("    Dim a\n    a = 1%\n    F = Val(a)"), "Double|1");
    }

    #[test]
    fn a_zero_base_with_a_negative_exponent_is_an_error() {
        assert_eq!(
            run("    Dim a, b\n    a = 0\n    b = -1\n    F = (a ^ b)"),
            "ERR|5"
        );
        assert_eq!(
            run("    Dim a, b\n    a = 0\n    b = -246\n    F = (a ^ b)"),
            "ERR|5"
        );
        // Zero and positive exponents are fine, as is a negative exponent
        // over a non-zero base.
        assert_eq!(
            run("    Dim a, b\n    a = 0\n    b = 0\n    F = (a ^ b)"),
            "Double|1"
        );
        assert_eq!(
            run("    Dim a, b\n    a = 0\n    b = 2\n    F = (a ^ b)"),
            "Double|0"
        );
        assert_eq!(
            run("    Dim a, b\n    a = 2\n    b = -2\n    F = (a ^ b)"),
            "Double|0.25"
        );
    }

    #[test]
    fn logical_operators_range_check_their_operands_too() {
        // Same rule as `\\` and `Mod`: the operands must fit a Long.
        assert_eq!(expr("True Or \"2147483648\""), "ERR|6");
        assert_eq!(expr("1 And \"2147483648\""), "ERR|6");
        // Operands that round into a Long are fine.
        assert_eq!(expr("True Or \"3.752147483647\""), "Long|-1");
        assert_eq!(expr("1 And \"12\""), "Long|0");
    }

    #[test]
    fn int_div_and_mod_range_check_their_operands_not_just_the_result() {
        // `254 Mod "22147483647"` is error 6 even though the answer is 254:
        // the operand is not a Long. Checking only the result let it through.
        assert_eq!(
            run("    Dim a, b\n    a = 254\n    b = \"22147483647\"\n    F = (a Mod b)"),
            "ERR|6"
        );
        assert_eq!(
            run("    Dim a, b\n    a = 254\n    b = \"22147483647\"\n    F = (a \\ b)"),
            "ERR|6"
        );
        assert_eq!(
            run("    Dim a, b\n    a = 3000000000#\n    b = 3\n    F = (a Mod b)"),
            "ERR|6"
        );
        // Operands that do fit a Long still work.
        assert_eq!(
            run("    Dim a, b\n    a = 254\n    b = 2147483647\n    F = (a Mod b)"),
            "Long|254"
        );
        assert_eq!(
            run("    Dim a, b\n    a = 40000\n    b = 3\n    F = (a Mod b)"),
            "Long|1"
        );
        assert_eq!(
            run("    Dim a, b\n    a = 40000\n    b = 3\n    F = (a \\ b)"),
            "Long|13333"
        );
    }

    #[test]
    fn a_negative_base_with_a_fractional_exponent_is_an_error() {
        // Excel raises error 5 rather than returning NaN.
        assert_eq!(expr("(-1) ^ 1.5"), "ERR|5");
        assert_eq!(expr("(-8) ^ (1 / 3)"), "ERR|5");
        // Integral exponents are fine.
        assert_eq!(expr("(-2) ^ 2"), "Double|4");
        assert_eq!(expr("(-2) ^ 3"), "Double|-8");
    }

    #[test]
    fn select_case_matches_a_numeric_case_against_a_string_subject() {
        // `Select Case "10"` matches `Case 10`, but `Select Case ""` does not
        // match `Case 0` -- the numeric-constant rule, not an error.
        let body = |x: &str| {
            format!(
                "    Dim r\n    Select Case {x}\n    Case 0\n        r = \"zero\"\n    \
                     Case 10\n        r = \"ten\"\n    Case Else\n        r = \"else\"\n    \
                     End Select\n    F = r"
            )
        };
        assert_eq!(run(&body("\"10\"")), "String|ten");
        assert_eq!(run(&body("\"\"")), "String|else");
    }

    #[test]
    fn a_for_counter_is_left_at_the_value_that_failed_the_test() {
        assert_eq!(
            run("    Dim c\n    For c = 1 To 3\n    Next c\n    F = c"),
            "Integer|4"
        );
        assert_eq!(
            run("    Dim c\n    For c = 1 To 3 Step 2\n    Next c\n    F = c"),
            "Integer|5"
        );
        // A loop that never runs leaves the counter at its start value.
        assert_eq!(
            run("    Dim c\n    For c = 5 To 1\n    Next c\n    F = c"),
            "Integer|5"
        );
        assert_eq!(
            run("    Dim c\n    For c = 3 To 1 Step -1\n    Next c\n    F = c"),
            "Integer|0"
        );
        // Exit For leaves it at the value the body was running with.
        assert_eq!(
            run("    Dim c\n    For c = 1 To 3\n        Exit For\n    Next c\n    F = c"),
            "Integer|1"
        );
    }

    #[test]
    fn count_arguments_round_rather_than_truncate() {
        // Space(2.6) is three spaces, not two.
        assert_eq!(expr("Len(Space(2.6))"), "Long|3");
        assert_eq!(expr("Space(-1)"), "ERR|5");
        assert_eq!(expr("String(-1, \"x\")"), "ERR|5");
        assert_eq!(expr("Left(\"abc\", -1)"), "ERR|5");
        assert_eq!(expr("Right(\"abc\", 99)"), "String|abc");
        assert_eq!(expr("InStr(0, \"abc\", \"b\")"), "ERR|5");
        assert_eq!(expr("String(2, 65)"), "String|AA");
    }

    // ---- out of scope ---------------------------------------------------

    #[test]
    fn host_object_access_errors_rather_than_silently_doing_nothing() {
        // The refusal that matters: a macro that skips a line it cannot
        // understand and then reports success is wrong in the worst way.
        // These run with no workbook attached, which is what `visi macro run`
        // over a bare `.bas` file does.
        for body in [
            "    F = Range(\"A1\").Value",
            "    F = ThisWorkbook.Name",
            "    F = Worksheets(1).Name",
            "    F = Application.WorksheetFunction.Sum(1, 2)",
            "    Dim c\n    For Each c In r\n    Next",
        ] {
            let out = run(body);
            assert!(out.starts_with("ERR|438"), "{body:?} gave {out}");
        }
    }

    #[test]
    fn a_member_of_a_non_object_is_error_424() {
        // Not 438: the construct *is* supported, the value just is not an
        // object. VBA calls this "Object required", and distinguishing it
        // from "not implemented" is the difference between a macro bug and a
        // gap in this interpreter.
        assert_eq!(run("    With x\n        F = .a\n    End With"), "ERR|424");
        assert_eq!(expr("x.Name"), "ERR|424");
        assert_eq!(expr("x Is Nothing"), "ERR|424");
    }

    #[test]
    fn an_unknown_function_is_reported_not_ignored() {
        assert_eq!(expr("NoSuchFunction(1)"), "ERR|35");
    }

    #[test]
    fn class_module_instantiation_properties_and_methods() {
        let class_src = "Attribute VB_Name = \"Person\"\n\
                         Private m_name As String\n\
                         Public Property Get Name() As String\n\
                             Name = m_name\n\
                         End Property\n\
                         Public Property Let Name(val As String)\n\
                             m_name = val\n\
                         End Property\n\
                         Public Function Greet() As String\n\
                             Greet = \"Hello, \" & Me.Name\n\
                         End Function\n";

        let main_src = "Attribute VB_Name = \"Main\"\n\
                        Function Test()\n\
                            Dim p As Person\n\
                            Set p = New Person\n\
                            p.Name = \"Alice\"\n\
                            Test = p.Greet() & \"|\" & TypeName(p) & \"|\" & (TypeOf p Is Person) & \"|\" & (TypeOf p Is Object)\n\
                        End Function\n";

        let p_cls = VbaModule {
            name: "Person".to_string(),
            kind: VbaModuleKind::Class,
            source: class_src.to_string(),
            bound_sheet_id: None,
            prefix_bytes: Vec::new(),
            cached_compressed_source: None,
            module_cookie: 0,
        };
        let p_main = VbaModule {
            name: "Main".to_string(),
            kind: VbaModuleKind::Standard,
            source: main_src.to_string(),
            bound_sheet_id: None,
            prefix_bytes: Vec::new(),
            cached_compressed_source: None,
            module_cookie: 0,
        };

        let mut interp = Interpreter::from_modules(vec![p_cls, p_main], Some("Main"));
        let res = interp.run("Test", Vec::new()).unwrap();
        assert_eq!(
            res,
            Variant::Str("Hello, Alice|Person|True|True".to_string())
        );
    }

    #[test]
    fn class_module_lifecycle_and_auto_new() {
        let class_src = "Attribute VB_Name = \"Counter\"\n\
                         Public Value As Long\n\
                         Private Sub Class_Initialize()\n\
                             Value = 100\n\
                         End Sub\n\
                         Private Sub Class_Terminate()\n\
                             Value = 0\n\
                         End Sub\n";

        let main_src = "Attribute VB_Name = \"Main\"\n\
                        Function TestAutoNew()\n\
                            Dim c As New Counter\n\
                            Dim v1 As Long, v2 As Long\n\
                            v1 = c.Value\n\
                            c.Value = 200\n\
                            Set c = Nothing\n\
                            v2 = c.Value\n\
                            TestAutoNew = v1 & \"|\" & v2\n\
                        End Function\n";

        let p_cls = VbaModule {
            name: "Counter".to_string(),
            kind: VbaModuleKind::Class,
            source: class_src.to_string(),
            bound_sheet_id: None,
            prefix_bytes: Vec::new(),
            cached_compressed_source: None,
            module_cookie: 0,
        };
        let p_main = VbaModule {
            name: "Main".to_string(),
            kind: VbaModuleKind::Standard,
            source: main_src.to_string(),
            bound_sheet_id: None,
            prefix_bytes: Vec::new(),
            cached_compressed_source: None,
            module_cookie: 0,
        };

        let mut interp = Interpreter::from_modules(vec![p_cls, p_main], Some("Main"));
        let res = interp.run("TestAutoNew", Vec::new()).unwrap();
        assert_eq!(res, Variant::Str("100|100".to_string()));
    }

    #[test]
    fn class_default_member_dispatch() {
        let class_src = "Attribute VB_Name = \"Bag\"\n\
                         Private m_val As Long\n\
                         Public Property Get Item(idx As Long) As Long\n\
                             Attribute Item.VB_UserMemId = 0\n\
                             Item = m_val * idx\n\
                         End Property\n\
                         Public Property Let Item(idx As Long, val As Long)\n\
                             Attribute Item.VB_UserMemId = 0\n\
                             m_val = val + idx\n\
                         End Property\n";

        let main_src = "Attribute VB_Name = \"Main\"\n\
                        Function TestDefault()\n\
                            Dim b As Bag\n\
                            Set b = New Bag\n\
                            b(2) = 10\n\
                            TestDefault = b(3)\n\
                        End Function\n";

        let p_cls = VbaModule {
            name: "Bag".to_string(),
            kind: VbaModuleKind::Class,
            source: class_src.to_string(),
            bound_sheet_id: None,
            prefix_bytes: Vec::new(),
            cached_compressed_source: None,
            module_cookie: 0,
        };
        let p_main = VbaModule {
            name: "Main".to_string(),
            kind: VbaModuleKind::Standard,
            source: main_src.to_string(),
            bound_sheet_id: None,
            prefix_bytes: Vec::new(),
            cached_compressed_source: None,
            module_cookie: 0,
        };

        let mut interp = Interpreter::from_modules(vec![p_cls, p_main], Some("Main"));
        let res = interp.run("TestDefault", Vec::new()).unwrap();
        // m_val = 10 + 2 = 12; b(3) = 12 * 3 = 36
        assert_eq!(res, Variant::Integer(36));
    }

    #[test]
    fn custom_events_and_with_events() {
        let emitter_src = "Attribute VB_Name = \"Emitter\"\n\
                           Public Event OnChange(ByRef num As Long)\n\
                           Public Sub Trigger(n As Long)\n\
                               RaiseEvent OnChange(n)\n\
                           End Sub\n";

        let listener_src = "Attribute VB_Name = \"Listener\"\n\
                            Public Received As Long\n\
                            Public WithEvents em As Emitter\n\
                            Private Sub em_OnChange(ByRef num As Long)\n\
                                Received = num * 2\n\
                                num = num + 1\n\
                            End Sub\n\
                            Public Function TestEvent()\n\
                                Set em = New Emitter\n\
                                Dim x As Long\n\
                                x = 21\n\
                                em.Trigger x\n\
                                TestEvent = Received & \"|\" & x\n\
                            End Function\n";

        let p_em = VbaModule {
            name: "Emitter".to_string(),
            kind: VbaModuleKind::Class,
            source: emitter_src.to_string(),
            bound_sheet_id: None,
            prefix_bytes: Vec::new(),
            cached_compressed_source: None,
            module_cookie: 0,
        };
        let p_lis = VbaModule {
            name: "Listener".to_string(),
            kind: VbaModuleKind::Standard,
            source: listener_src.to_string(),
            bound_sheet_id: None,
            prefix_bytes: Vec::new(),
            cached_compressed_source: None,
            module_cookie: 0,
        };

        let mut interp = Interpreter::from_modules(vec![p_em, p_lis], Some("Listener"));
        let res = interp.run("TestEvent", Vec::new()).unwrap();
        assert_eq!(res, Variant::Str("42|21".to_string()));
    }

    #[test]
    fn host_worksheet_change_events() {
        let mut wb = crate::core::WorkbookManager::new_empty().unwrap();
        wb.ensure_vba_project().unwrap();
        let sheet_id = wb.sheets[0].id;

        let sheet1_src = "Attribute VB_Name = \"Sheet1\"\n\
                          Private Sub Worksheet_Change(ByVal Target As Range)\n\
                              If Target.Address = \"$A$1\" Then\n\
                                  Application.EnableEvents = False\n\
                                  Range(\"B1\").Value = Target.Value * 10\n\
                                  Application.EnableEvents = True\n\
                              End If\n\
                          End Sub\n";

        let main_src = "Attribute VB_Name = \"Main\"\n\
                        Sub TriggerChange()\n\
                            Range(\"A1\").Value = 5\n\
                        End Sub\n";

        wb.add_vba_module(
            "Sheet1".to_string(),
            VbaModuleKind::Document,
            sheet1_src.to_string(),
            Some(sheet_id),
        )
        .unwrap();

        wb.add_vba_module(
            "Main".to_string(),
            VbaModuleKind::Standard,
            main_src.to_string(),
            None,
        )
        .unwrap();

        let res = wb.run_macro(Some("Main"), "TriggerChange", &[]).unwrap();
        assert!(res.mutated);
        assert_eq!(
            wb.sheets[0].get_display_string(&crate::core::CellRef::new(0, 0)),
            "5"
        );
        assert_eq!(
            wb.sheets[0].get_display_string(&crate::core::CellRef::new(0, 1)),
            "50"
        );
    }

    #[test]
    fn open_events_execution() {
        let mut wb = crate::core::WorkbookManager::new_empty().unwrap();
        wb.ensure_vba_project().unwrap();

        let thisworkbook_src = "Attribute VB_Name = \"ThisWorkbook\"\n\
                                Private Sub Workbook_Open()\n\
                                    Range(\"A1\").Value = \"Opened\"\n\
                                End Sub\n\
                                Private Sub Workbook_BeforeClose(Cancel As Boolean)\n\
                                    Cancel = True\n\
                                End Sub\n";

        let mod_src = "Attribute VB_Name = \"Module1\"\n\
                       Public Sub Auto_Open()\n\
                           Range(\"A2\").Value = \"Auto\"\n\
                       End Sub\n";

        wb.add_vba_module(
            "ThisWorkbook".to_string(),
            VbaModuleKind::Document,
            thisworkbook_src.to_string(),
            None,
        )
        .unwrap();

        wb.add_vba_module(
            "Module1".to_string(),
            VbaModuleKind::Standard,
            mod_src.to_string(),
            None,
        )
        .unwrap();

        let res = wb.run_open_events().unwrap();
        assert!(res.mutated);
        assert_eq!(
            wb.sheets[0].get_display_string(&crate::core::CellRef::new(0, 0)),
            "Opened"
        );
        assert_eq!(
            wb.sheets[0].get_display_string(&crate::core::CellRef::new(1, 0)),
            "Auto"
        );
    }
}