endbasic-core 0.10.0

The EndBASIC programming language - core
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
// EndBASIC
// Copyright 2020 Julio Merino
//
// Licensed under the Apache License, Version 2.0 (the "License"); you may not
// use this file except in compliance with the License.  You may obtain a copy
// of the License at:
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
// WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.  See the
// License for the specific language governing permissions and limitations
// under the License.

//! Statement and expression parser for the EndBASIC language.

use crate::ast::*;
use crate::lexer::{Lexer, PeekableLexer, Token, TokenSpan};
use crate::reader::LineCol;
use std::cmp::Ordering;
use std::io;

/// Parser errors.
#[derive(Debug, thiserror::Error)]
pub enum Error {
    /// Bad syntax in the input program.
    #[error("{}:{}: {}", .0.line, .0.col, .1)]
    Bad(LineCol, String),

    /// I/O error while parsing the input program.
    #[error("read error")]
    Io(#[from] io::Error),
}

/// Result for parser return values.
pub type Result<T> = std::result::Result<T, Error>;

/// Transforms a `VarRef` into an unannotated name.
///
/// This is only valid for references that have no annotations in them.
fn vref_to_unannotated_string(vref: VarRef, pos: LineCol) -> Result<String> {
    if vref.ref_type() != VarType::Auto {
        return Err(Error::Bad(pos, format!("Type annotation not allowed in {}", vref)));
    }
    Ok(vref.take_name())
}

/// Operators that can appear within an expression.
///
/// The main difference between this and `lexer::Token` is that, in here, we differentiate the
/// meaning of a minus sign and separate it in its two variants: the 2-operand `Minus` and the
/// 1-operand `Negate`.
///
/// That said, this type also is the right place to abstract away operator-related logic to
/// implement the expression parsing algorithm, so it's not completely useless.
#[derive(Debug, Eq, PartialEq)]
enum ExprOp {
    LeftParen,

    Add,
    Subtract,
    Multiply,
    Divide,
    Modulo,
    Power,
    Negate,

    Equal,
    NotEqual,
    Less,
    LessEqual,
    Greater,
    GreaterEqual,

    And,
    Not,
    Or,
    Xor,

    ShiftLeft,
    ShiftRight,
}

impl ExprOp {
    /// Constructs a new operator based on a token, which must have a valid correspondence.
    fn from(t: Token) -> Self {
        match t {
            Token::Equal => ExprOp::Equal,
            Token::NotEqual => ExprOp::NotEqual,
            Token::Less => ExprOp::Less,
            Token::LessEqual => ExprOp::LessEqual,
            Token::Greater => ExprOp::Greater,
            Token::GreaterEqual => ExprOp::GreaterEqual,
            Token::Plus => ExprOp::Add,
            Token::Multiply => ExprOp::Multiply,
            Token::Divide => ExprOp::Divide,
            Token::Modulo => ExprOp::Modulo,
            Token::Exponent => ExprOp::Power,
            Token::And => ExprOp::And,
            Token::Or => ExprOp::Or,
            Token::Xor => ExprOp::Xor,
            Token::ShiftLeft => ExprOp::ShiftLeft,
            Token::ShiftRight => ExprOp::ShiftRight,
            Token::Minus => panic!("Ambiguous token; cannot derive ExprOp"),
            _ => panic!("Called on an non-operator"),
        }
    }

    /// Returns the priority of this operator.  The specific number's meaning is only valid when
    /// comparing it against other calls to this function.  Higher number imply higher priority.
    fn priority(&self) -> i8 {
        match self {
            ExprOp::LeftParen => 6,
            ExprOp::Power => 6,

            ExprOp::Negate => 5,
            ExprOp::Not => 5,

            ExprOp::Multiply => 4,
            ExprOp::Divide => 4,
            ExprOp::Modulo => 4,

            ExprOp::Add => 3,
            ExprOp::Subtract => 3,

            ExprOp::ShiftLeft => 2,
            ExprOp::ShiftRight => 2,

            ExprOp::Equal => 1,
            ExprOp::NotEqual => 1,
            ExprOp::Less => 1,
            ExprOp::LessEqual => 1,
            ExprOp::Greater => 1,
            ExprOp::GreaterEqual => 1,

            ExprOp::And => 0,
            ExprOp::Or => 0,
            ExprOp::Xor => 0,
        }
    }
}

/// Wrapper over an `ExprOp` to extend it with its position.
struct ExprOpSpan {
    /// The wrapped expression operation.
    op: ExprOp,

    /// The position where the operation appears in the input.
    pos: LineCol,
}

impl ExprOpSpan {
    /// Creates a new span from its parts.
    fn new(op: ExprOp, pos: LineCol) -> Self {
        Self { op, pos }
    }

    /// Pops operands from the `expr` stack, applies this operation, and pushes the result back.
    fn apply(&self, exprs: &mut Vec<Expr>) -> Result<()> {
        fn apply1(
            exprs: &mut Vec<Expr>,
            pos: LineCol,
            f: fn(Box<UnaryOpSpan>) -> Expr,
        ) -> Result<()> {
            if exprs.is_empty() {
                return Err(Error::Bad(pos, "Not enough values to apply operator".to_owned()));
            }
            let expr = exprs.pop().unwrap();
            exprs.push(f(Box::from(UnaryOpSpan { expr, pos })));
            Ok(())
        }

        fn apply2(
            exprs: &mut Vec<Expr>,
            pos: LineCol,
            f: fn(Box<BinaryOpSpan>) -> Expr,
        ) -> Result<()> {
            if exprs.len() < 2 {
                return Err(Error::Bad(pos, "Not enough values to apply operator".to_owned()));
            }
            let rhs = exprs.pop().unwrap();
            let lhs = exprs.pop().unwrap();
            exprs.push(f(Box::from(BinaryOpSpan { lhs, rhs, pos })));
            Ok(())
        }

        match self.op {
            ExprOp::Add => apply2(exprs, self.pos, Expr::Add),
            ExprOp::Subtract => apply2(exprs, self.pos, Expr::Subtract),
            ExprOp::Multiply => apply2(exprs, self.pos, Expr::Multiply),
            ExprOp::Divide => apply2(exprs, self.pos, Expr::Divide),
            ExprOp::Modulo => apply2(exprs, self.pos, Expr::Modulo),
            ExprOp::Power => apply2(exprs, self.pos, Expr::Power),

            ExprOp::Equal => apply2(exprs, self.pos, Expr::Equal),
            ExprOp::NotEqual => apply2(exprs, self.pos, Expr::NotEqual),
            ExprOp::Less => apply2(exprs, self.pos, Expr::Less),
            ExprOp::LessEqual => apply2(exprs, self.pos, Expr::LessEqual),
            ExprOp::Greater => apply2(exprs, self.pos, Expr::Greater),
            ExprOp::GreaterEqual => apply2(exprs, self.pos, Expr::GreaterEqual),

            ExprOp::And => apply2(exprs, self.pos, Expr::And),
            ExprOp::Or => apply2(exprs, self.pos, Expr::Or),
            ExprOp::Xor => apply2(exprs, self.pos, Expr::Xor),

            ExprOp::ShiftLeft => apply2(exprs, self.pos, Expr::ShiftLeft),
            ExprOp::ShiftRight => apply2(exprs, self.pos, Expr::ShiftRight),

            ExprOp::Negate => apply1(exprs, self.pos, Expr::Negate),
            ExprOp::Not => apply1(exprs, self.pos, Expr::Not),

            ExprOp::LeftParen => Ok(()),
        }
    }
}

/// Iterator over the statements of the language.
pub struct Parser<'a> {
    lexer: PeekableLexer<'a>,
}

impl<'a> Parser<'a> {
    /// Creates a new parser from the given readable.
    fn from(input: &'a mut dyn io::Read) -> Self {
        Self { lexer: Lexer::from(input).peekable() }
    }

    /// Expects the peeked token to be `t` and consumes it.  Otherwise, leaves the token in the
    /// stream and fails with error `err`.
    fn expect_and_consume<E: Into<String>>(&mut self, t: Token, err: E) -> Result<TokenSpan> {
        let peeked = self.lexer.peek()?;
        if peeked.token != t {
            return Err(Error::Bad(peeked.pos, err.into()));
        }
        Ok(self.lexer.consume_peeked())
    }

    /// Expects the peeked token to be `t` and consumes it.  Otherwise, leaves the token in the
    /// stream and fails with error `err`, pointing at `pos` as the original location of the
    /// problem.
    fn expect_and_consume_with_pos<E: Into<String>>(
        &mut self,
        t: Token,
        pos: LineCol,
        err: E,
    ) -> Result<()> {
        let peeked = self.lexer.peek()?;
        if peeked.token != t {
            return Err(Error::Bad(pos, err.into()));
        }
        self.lexer.consume_peeked();
        Ok(())
    }

    /// Reads statements until the `delim` keyword is found.  The delimiter is not consumed.
    fn parse_until(&mut self, delim: Token) -> Result<Vec<Statement>> {
        let mut stmts = vec![];
        loop {
            let peeked = self.lexer.peek()?;
            if peeked.token == delim {
                break;
            } else if peeked.token == Token::Eol {
                self.lexer.consume_peeked();
                continue;
            }
            match self.parse_one_safe()? {
                Some(stmt) => stmts.push(stmt),
                None => break,
            }
        }
        Ok(stmts)
    }

    /// Parses an assignment for the variable reference `vref` already read.
    fn parse_assignment(&mut self, vref: VarRef, vref_pos: LineCol) -> Result<Statement> {
        let expr = self.parse_required_expr("Missing expression in assignment")?;

        let next = self.lexer.peek()?;
        match &next.token {
            Token::Eof | Token::Eol | Token::Else => (),
            t => return Err(Error::Bad(next.pos, format!("Unexpected {} in assignment", t))),
        }
        Ok(Statement::Assignment(AssignmentSpan { vref, vref_pos, expr }))
    }

    /// Parses an assignment to the array `varref` with `subscripts`, both of which have already
    /// been read.
    fn parse_array_assignment(
        &mut self,
        vref: VarRef,
        vref_pos: LineCol,
        subscripts: Vec<Expr>,
    ) -> Result<Statement> {
        let expr = self.parse_required_expr("Missing expression in array assignment")?;

        let next = self.lexer.peek()?;
        match &next.token {
            Token::Eof | Token::Eol | Token::Else => (),
            t => return Err(Error::Bad(next.pos, format!("Unexpected {} in array assignment", t))),
        }
        Ok(Statement::ArrayAssignment(ArrayAssignmentSpan { vref, vref_pos, subscripts, expr }))
    }

    /// Parses a builtin call (things of the form `INPUT a`).
    fn parse_builtin_call(
        &mut self,
        vref: VarRef,
        vref_pos: LineCol,
        mut first: Option<Expr>,
    ) -> Result<Statement> {
        let mut name = vref_to_unannotated_string(vref, vref_pos)?;
        name.make_ascii_uppercase();

        let mut args = vec![];
        loop {
            let expr = self.parse_expr(first.take())?;

            let peeked = self.lexer.peek()?;
            match peeked.token {
                Token::Eof | Token::Eol | Token::Else => {
                    if expr.is_some() || !args.is_empty() {
                        args.push(ArgSpan { expr, sep: ArgSep::End, sep_pos: peeked.pos });
                    }
                    break;
                }
                Token::Semicolon => {
                    let peeked = self.lexer.consume_peeked();
                    args.push(ArgSpan { expr, sep: ArgSep::Short, sep_pos: peeked.pos });
                }
                Token::Comma => {
                    let peeked = self.lexer.consume_peeked();
                    args.push(ArgSpan { expr, sep: ArgSep::Long, sep_pos: peeked.pos });
                }
                Token::As => {
                    let peeked = self.lexer.consume_peeked();
                    args.push(ArgSpan { expr, sep: ArgSep::As, sep_pos: peeked.pos });
                }
                _ => {
                    return Err(Error::Bad(
                        peeked.pos,
                        "Expected comma, semicolon, or end of statement".to_owned(),
                    ))
                }
            }
        }
        Ok(Statement::BuiltinCall(BuiltinCallSpan { name, name_pos: vref_pos, args }))
    }

    /// Starts processing either an array reference or a builtin call and disambiguates between the
    /// two.
    fn parse_array_or_builtin_call(
        &mut self,
        vref: VarRef,
        vref_pos: LineCol,
    ) -> Result<Statement> {
        match self.lexer.peek()?.token {
            Token::LeftParen => {
                let left_paren = self.lexer.consume_peeked();
                let mut exprs = self.parse_comma_separated_exprs()?;
                match self.lexer.peek()?.token {
                    Token::Equal => {
                        self.lexer.consume_peeked();
                        self.parse_array_assignment(vref, vref_pos, exprs)
                    }
                    _ => {
                        if exprs.len() != 1 {
                            return Err(Error::Bad(
                                left_paren.pos,
                                "Expected expression".to_owned(),
                            ));
                        }
                        self.parse_builtin_call(vref, vref_pos, Some(exprs.remove(0)))
                    }
                }
            }
            _ => self.parse_builtin_call(vref, vref_pos, None),
        }
    }

    /// Parses a `DATA` statement.
    fn parse_data(&mut self) -> Result<Statement> {
        let mut values = vec![];
        loop {
            let peeked = self.lexer.peek()?;
            match peeked.token {
                Token::Eof | Token::Eol | Token::Else => {
                    values.push(None);
                    break;
                }
                _ => (),
            }

            let token_span = self.lexer.read()?;
            match token_span.token {
                Token::Boolean(b) => values.push(Some(Value::Boolean(b))),
                Token::Double(d) => values.push(Some(Value::Double(d))),
                Token::Integer(i) => values.push(Some(Value::Integer(i))),
                Token::Text(t) => values.push(Some(Value::Text(t))),

                Token::Minus => {
                    let token_span = self.lexer.read()?;
                    match token_span.token {
                        Token::Double(d) => values.push(Some(Value::Double(-d))),
                        Token::Integer(i) => values.push(Some(Value::Integer(-i))),
                        _ => {
                            return Err(Error::Bad(
                                token_span.pos,
                                "Expected number after -".to_owned(),
                            ))
                        }
                    }
                }

                Token::Eof | Token::Eol | Token::Else => {
                    panic!("Should not be consumed here; handled above")
                }

                Token::Comma => {
                    values.push(None);
                    continue;
                }

                t => {
                    return Err(Error::Bad(
                        token_span.pos,
                        format!("Unexpected {} in DATA statement", t),
                    ))
                }
            }

            let peeked = self.lexer.peek()?;
            match &peeked.token {
                Token::Eof | Token::Eol | Token::Else => {
                    break;
                }

                Token::Comma => {
                    self.lexer.consume_peeked();
                }

                t => {
                    return Err(Error::Bad(
                        peeked.pos,
                        format!("Expected comma after datum but found {}", t),
                    ))
                }
            }
        }
        Ok(Statement::Data(DataSpan { values }))
    }

    /// Parses the `AS typename` clause of a `DIM` statement.  The caller has already consumed the
    /// `AS` token.
    fn parse_dim_as(&mut self) -> Result<(VarType, LineCol)> {
        let peeked = self.lexer.peek()?;
        let (vtype, vtype_pos) = match peeked.token {
            Token::Eof | Token::Eol => (VarType::Integer, peeked.pos),
            Token::As => {
                self.lexer.consume_peeked();
                let token_span = self.lexer.read()?;
                match token_span.token {
                    Token::BooleanName => (VarType::Boolean, token_span.pos),
                    Token::DoubleName => (VarType::Double, token_span.pos),
                    Token::IntegerName => (VarType::Integer, token_span.pos),
                    Token::TextName => (VarType::Text, token_span.pos),
                    t => {
                        return Err(Error::Bad(
                            token_span.pos,
                            format!("Invalid type name {} in DIM AS statement", t),
                        ))
                    }
                }
            }
            _ => return Err(Error::Bad(peeked.pos, "Expected AS or end of statement".to_owned())),
        };

        let next = self.lexer.peek()?;
        match &next.token {
            Token::Eof | Token::Eol => (),
            t => return Err(Error::Bad(next.pos, format!("Unexpected {} in DIM statement", t))),
        }

        Ok((vtype, vtype_pos))
    }

    /// Parses a `DIM` statement.
    fn parse_dim(&mut self) -> Result<Statement> {
        let token_span = self.lexer.read()?;
        let vref = match token_span.token {
            Token::Symbol(vref) => vref,
            _ => {
                return Err(Error::Bad(
                    token_span.pos,
                    "Expected variable name after DIM".to_owned(),
                ))
            }
        };
        let name = vref_to_unannotated_string(vref, token_span.pos)?;
        let name_pos = token_span.pos;

        match self.lexer.peek()?.token {
            Token::LeftParen => {
                let peeked = self.lexer.consume_peeked();
                let dimensions = self.parse_comma_separated_exprs()?;
                if dimensions.is_empty() {
                    return Err(Error::Bad(
                        peeked.pos,
                        "Arrays require at least one dimension".to_owned(),
                    ));
                }
                let (subtype, subtype_pos) = self.parse_dim_as()?;
                Ok(Statement::DimArray(DimArraySpan {
                    name,
                    name_pos,
                    dimensions,
                    subtype,
                    subtype_pos,
                }))
            }
            _ => {
                let (vtype, vtype_pos) = self.parse_dim_as()?;
                Ok(Statement::Dim(DimSpan { name, name_pos, vtype, vtype_pos }))
            }
        }
    }

    /// Parses the `UNTIL` or `WHILE` clause of a `DO` loop.
    ///
    /// `part` is a string indicating where the clause is expected (either after `DO` or after
    /// `LOOP`).
    ///
    /// Returns the guard expression and a boolean indicating if this is an `UNTIL` clause.
    fn parse_do_guard(&mut self, part: &str) -> Result<Option<(Expr, bool)>> {
        let peeked = self.lexer.peek()?;
        match peeked.token {
            Token::Until => {
                self.lexer.consume_peeked();
                let expr = self.parse_required_expr("No expression in UNTIL clause")?;
                Ok(Some((expr, true)))
            }
            Token::While => {
                self.lexer.consume_peeked();
                let expr = self.parse_required_expr("No expression in WHILE clause")?;
                Ok(Some((expr, false)))
            }
            Token::Eof | Token::Eol => Ok(None),
            _ => {
                let token_span = self.lexer.consume_peeked();
                Err(Error::Bad(
                    token_span.pos,
                    format!("Expecting newline, UNTIL or WHILE after {}", part),
                ))
            }
        }
    }

    /// Parses a `DO` statement.
    fn parse_do(&mut self, do_pos: LineCol) -> Result<Statement> {
        let pre_guard = self.parse_do_guard("DO")?;
        self.expect_and_consume(Token::Eol, "Expecting newline after DO")?;

        let stmts = self.parse_until(Token::Loop)?;
        self.expect_and_consume_with_pos(Token::Loop, do_pos, "DO without LOOP")?;

        let post_guard = self.parse_do_guard("LOOP")?;

        let guard = match (pre_guard, post_guard) {
            (None, None) => DoGuard::Infinite,
            (Some((guard, true)), None) => DoGuard::PreUntil(guard),
            (Some((guard, false)), None) => DoGuard::PreWhile(guard),
            (None, Some((guard, true))) => DoGuard::PostUntil(guard),
            (None, Some((guard, false))) => DoGuard::PostWhile(guard),
            (Some(_), Some(_)) => {
                return Err(Error::Bad(
                    do_pos,
                    "DO loop cannot have pre and post guards at the same time".to_owned(),
                ))
            }
        };

        Ok(Statement::Do(DoSpan { guard, body: stmts }))
    }

    /// Advances until the next statement after failing to parse a `DO` statement.
    fn reset_do(&mut self) -> Result<()> {
        loop {
            match self.lexer.peek()?.token {
                Token::Eof => break,
                Token::Loop => {
                    self.lexer.consume_peeked();
                    loop {
                        match self.lexer.peek()?.token {
                            Token::Eof | Token::Eol => break,
                            _ => {
                                self.lexer.consume_peeked();
                            }
                        }
                    }
                    break;
                }
                _ => {
                    self.lexer.consume_peeked();
                }
            }
        }
        self.reset()
    }

    /// Parses a potential `END` statement but, if this corresponds to a statement terminator such
    /// as `END IF`, returns the token that followed `END`.
    fn maybe_parse_end(&mut self) -> Result<std::result::Result<Statement, Token>> {
        match self.lexer.peek()?.token {
            Token::If => Ok(Err(Token::If)),
            Token::Select => Ok(Err(Token::Select)),
            _ => {
                let code = self.parse_expr(None)?;
                Ok(Ok(Statement::End(EndSpan { code })))
            }
        }
    }

    /// Parses an `END` statement.
    fn parse_end(&mut self, pos: LineCol) -> Result<Statement> {
        match self.maybe_parse_end()? {
            Ok(stmt) => Ok(stmt),
            Err(token) => Err(Error::Bad(pos, format!("END {} without {}", token, token))),
        }
    }

    /// Parses an `EXIT DO` statement.
    fn parse_exit_do(&mut self, pos: LineCol) -> Result<Statement> {
        self.expect_and_consume(Token::Do, "Expecting DO after EXIT")?;
        Ok(Statement::ExitDo(ExitDoSpan { pos }))
    }

    /// Parses a variable list of comma-separated expressions.  The caller must have consumed the
    /// open parenthesis and we stop processing when we encounter the terminating parenthesis (and
    /// consume it).  We expect at least one expression.
    fn parse_comma_separated_exprs(&mut self) -> Result<Vec<Expr>> {
        let mut exprs = vec![];
        let first_pos = self.lexer.peek()?.pos;
        if let Some(expr) = self.parse_expr(None)? {
            // The first expression is optional to support calls to functions without arguments.
            exprs.push(expr);
        }

        loop {
            let peeked = self.lexer.peek()?;
            let pos = peeked.pos;
            match &peeked.token {
                Token::RightParen => {
                    self.lexer.consume_peeked();
                    break;
                }
                Token::Comma => {
                    self.lexer.consume_peeked();
                    if exprs.is_empty() {
                        // The first expression (parsed outside the loop) cannot be empty if we
                        // encounter more than one expression.
                        return Err(Error::Bad(first_pos, "Missing expression".to_owned()));
                    }
                    let expr = self.parse_required_expr("Missing expression")?;
                    exprs.push(expr);
                }
                t => return Err(Error::Bad(pos, format!("Unexpected {}", t))),
            }
        }

        Ok(exprs)
    }

    /// Parses an expression.
    ///
    /// Returns `None` if no expression was found.  This is necessary to treat the case of empty
    /// arguments to statements, as is the case in `PRINT a , , b`.
    ///
    /// If the caller has already processed a parenthesized term of an expression like
    /// `(first) + second`, then that term must be provided in `first`.
    ///
    /// This is an implementation of the Shunting Yard Algorithm by Edgar Dijkstra.
    fn parse_expr(&mut self, first: Option<Expr>) -> Result<Option<Expr>> {
        let mut exprs: Vec<Expr> = vec![];
        let mut op_spans: Vec<ExprOpSpan> = vec![];

        let mut need_operand = true; // Also tracks whether an upcoming minus is unary.
        if let Some(e) = first {
            exprs.push(e);
            need_operand = false;
        }

        loop {
            let mut handle_operand = |e, pos| {
                if !need_operand {
                    return Err(Error::Bad(pos, "Unexpected value in expression".to_owned()));
                }
                need_operand = false;
                exprs.push(e);
                Ok(())
            };

            // Stop processing if we encounter an expression separator, but don't consume it because
            // the caller needs to have access to it.
            match self.lexer.peek()?.token {
                Token::Eof
                | Token::Eol
                | Token::As
                | Token::Comma
                | Token::Else
                | Token::Semicolon
                | Token::Then
                | Token::To
                | Token::Step => break,
                Token::RightParen => {
                    if !op_spans.iter().any(|eos| eos.op == ExprOp::LeftParen) {
                        // We encountered an unbalanced parenthesis but we don't know if this is
                        // because we were called from within an argument list (in which case the
                        // caller consumed the opening parenthesis and is expecting to consume the
                        // closing parenthesis) or because we really found an invalid expression.
                        // Only the caller can know, so avoid consuming the token and exit.
                        break;
                    }
                }
                _ => (),
            };

            let ts = self.lexer.consume_peeked();
            match ts.token {
                Token::Boolean(value) => {
                    handle_operand(Expr::Boolean(BooleanSpan { value, pos: ts.pos }), ts.pos)?
                }
                Token::Double(value) => {
                    handle_operand(Expr::Double(DoubleSpan { value, pos: ts.pos }), ts.pos)?
                }
                Token::Integer(value) => {
                    handle_operand(Expr::Integer(IntegerSpan { value, pos: ts.pos }), ts.pos)?
                }
                Token::Text(value) => {
                    handle_operand(Expr::Text(TextSpan { value, pos: ts.pos }), ts.pos)?
                }
                Token::Symbol(vref) => {
                    handle_operand(Expr::Symbol(SymbolSpan { vref, pos: ts.pos }), ts.pos)?
                }

                Token::LeftParen => {
                    // If the last operand we encountered was a symbol, collapse it and the left
                    // parenthesis into the beginning of a function call.
                    match exprs.pop() {
                        Some(Expr::Symbol(span)) => {
                            if !need_operand {
                                exprs.push(Expr::Call(FunctionCallSpan {
                                    fref: span.vref,
                                    args: self.parse_comma_separated_exprs()?,
                                    pos: span.pos,
                                }));
                                need_operand = false;
                            } else {
                                // We popped out the last expression to see if it this left
                                // parenthesis started a function call... but it did not (it is a
                                // symbol following a parenthesis) so put both the expression and
                                // the token back.
                                op_spans.push(ExprOpSpan::new(ExprOp::LeftParen, ts.pos));
                                exprs.push(Expr::Symbol(span));
                                need_operand = true;
                            }
                        }
                        e => {
                            if let Some(e) = e {
                                // We popped out the last expression to see if this left
                                // parenthesis started a function call... but if it didn't, we have
                                // to put the expression back.
                                exprs.push(e);
                            }
                            if !need_operand {
                                return Err(Error::Bad(
                                    ts.pos,
                                    format!("Unexpected {} in expression", ts.token),
                                ));
                            }
                            op_spans.push(ExprOpSpan::new(ExprOp::LeftParen, ts.pos));
                            need_operand = true;
                        }
                    };
                }
                Token::RightParen => {
                    let mut found = false;
                    while let Some(eos) = op_spans.pop() {
                        eos.apply(&mut exprs)?;
                        if eos.op == ExprOp::LeftParen {
                            found = true;
                            break;
                        }
                    }
                    assert!(found, "Unbalanced parenthesis should have been handled above");
                    need_operand = false;
                }

                Token::Not => {
                    op_spans.push(ExprOpSpan::new(ExprOp::Not, ts.pos));
                    need_operand = true;
                }
                Token::Minus => {
                    let op;
                    if need_operand {
                        op = ExprOp::Negate;
                    } else {
                        op = ExprOp::Subtract;
                        while let Some(eos2) = op_spans.last() {
                            if eos2.op == ExprOp::LeftParen || eos2.op.priority() < op.priority() {
                                break;
                            }
                            let eos2 = op_spans.pop().unwrap();
                            eos2.apply(&mut exprs)?;
                        }
                    }
                    op_spans.push(ExprOpSpan::new(op, ts.pos));
                    need_operand = true;
                }

                Token::Equal
                | Token::NotEqual
                | Token::Less
                | Token::LessEqual
                | Token::Greater
                | Token::GreaterEqual
                | Token::Plus
                | Token::Multiply
                | Token::Divide
                | Token::Modulo
                | Token::Exponent
                | Token::And
                | Token::Or
                | Token::Xor
                | Token::ShiftLeft
                | Token::ShiftRight => {
                    let op = ExprOp::from(ts.token);
                    while let Some(eos2) = op_spans.last() {
                        if eos2.op == ExprOp::LeftParen || eos2.op.priority() < op.priority() {
                            break;
                        }
                        let eos2 = op_spans.pop().unwrap();
                        eos2.apply(&mut exprs)?;
                    }
                    op_spans.push(ExprOpSpan::new(op, ts.pos));
                    need_operand = true;
                }

                Token::Bad(e) => return Err(Error::Bad(ts.pos, e)),

                Token::Eof
                | Token::Eol
                | Token::As
                | Token::Comma
                | Token::Else
                | Token::Semicolon
                | Token::Then
                | Token::To
                | Token::Step => {
                    panic!("Field separators handled above")
                }

                Token::BooleanName
                | Token::Case
                | Token::Data
                | Token::Do
                | Token::Dim
                | Token::DoubleName
                | Token::Elseif
                | Token::End
                | Token::Error
                | Token::Exit
                | Token::For
                | Token::Gosub
                | Token::Goto
                | Token::If
                | Token::Is
                | Token::IntegerName
                | Token::Label(_)
                | Token::Loop
                | Token::Next
                | Token::On
                | Token::Resume
                | Token::Return
                | Token::Select
                | Token::TextName
                | Token::Until
                | Token::Wend
                | Token::While => {
                    return Err(Error::Bad(ts.pos, "Unexpected keyword in expression".to_owned()));
                }
            };
        }

        while let Some(eos) = op_spans.pop() {
            match eos.op {
                ExprOp::LeftParen => {
                    return Err(Error::Bad(eos.pos, "Unbalanced parenthesis".to_owned()))
                }
                _ => eos.apply(&mut exprs)?,
            }
        }

        if let Some(expr) = exprs.pop() {
            Ok(Some(expr))
        } else {
            Ok(None)
        }
    }

    /// Wrapper over `parse_expr` that requires an expression to be present and returns an error
    /// with `msg` otherwise.
    fn parse_required_expr(&mut self, msg: &'static str) -> Result<Expr> {
        let next_pos = self.lexer.peek()?.pos;
        match self.parse_expr(None)? {
            Some(expr) => Ok(expr),
            None => Err(Error::Bad(next_pos, msg.to_owned())),
        }
    }

    /// Parses a `GOSUB` statement.
    fn parse_gosub(&mut self) -> Result<Statement> {
        let token_span = self.lexer.read()?;
        match token_span.token {
            Token::Integer(i) => {
                let target = format!("{}", i);
                Ok(Statement::Gosub(GotoSpan { target, target_pos: token_span.pos }))
            }
            Token::Label(target) => {
                Ok(Statement::Gosub(GotoSpan { target, target_pos: token_span.pos }))
            }
            _ => Err(Error::Bad(token_span.pos, "Expected label name after GOSUB".to_owned())),
        }
    }

    /// Parses a `GOTO` statement.
    fn parse_goto(&mut self) -> Result<Statement> {
        let token_span = self.lexer.read()?;
        match token_span.token {
            Token::Integer(i) => {
                let target = format!("{}", i);
                Ok(Statement::Goto(GotoSpan { target, target_pos: token_span.pos }))
            }
            Token::Label(target) => {
                Ok(Statement::Goto(GotoSpan { target, target_pos: token_span.pos }))
            }
            _ => Err(Error::Bad(token_span.pos, "Expected label name after GOTO".to_owned())),
        }
    }

    /// Parses the branches of a uniline `IF` statement.
    fn parse_if_uniline(&mut self, branches: &mut Vec<IfBranchSpan>) -> Result<()> {
        debug_assert!(!branches.is_empty(), "Caller must populate the guard of the first branch");

        let mut has_else = false;
        let peeked = self.lexer.peek()?;
        match peeked.token {
            Token::Else => has_else = true,
            _ => {
                let stmt = self
                    .parse_uniline()?
                    .expect("The caller already checked for a non-empty token");
                branches[0].body.push(stmt);
            }
        }

        let peeked = self.lexer.peek()?;
        has_else |= peeked.token == Token::Else;

        if has_else {
            let else_span = self.lexer.consume_peeked();
            let expr = Expr::Boolean(BooleanSpan { value: true, pos: else_span.pos });
            branches.push(IfBranchSpan { guard: expr, body: vec![] });
            if let Some(stmt) = self.parse_uniline()? {
                branches[1].body.push(stmt);
            }
        }

        Ok(())
    }

    /// Parses the branches of a multiline `IF` statement.
    fn parse_if_multiline(
        &mut self,
        if_pos: LineCol,
        branches: &mut Vec<IfBranchSpan>,
    ) -> Result<()> {
        debug_assert!(!branches.is_empty(), "Caller must populate the guard of the first branch");

        let mut i = 0;
        let mut last = false;
        loop {
            let peeked = self.lexer.peek()?;
            match peeked.token {
                Token::Eol => {
                    self.lexer.consume_peeked();
                }

                Token::Elseif => {
                    if last {
                        return Err(Error::Bad(
                            peeked.pos,
                            "Unexpected ELSEIF after ELSE".to_owned(),
                        ));
                    }

                    self.lexer.consume_peeked();
                    let expr = self.parse_required_expr("No expression in ELSEIF statement")?;
                    self.expect_and_consume(Token::Then, "No THEN in ELSEIF statement")?;
                    self.expect_and_consume(Token::Eol, "Expecting newline after THEN")?;
                    branches.push(IfBranchSpan { guard: expr, body: vec![] });
                    i += 1;
                }

                Token::Else => {
                    if last {
                        return Err(Error::Bad(peeked.pos, "Duplicate ELSE after ELSE".to_owned()));
                    }

                    let else_span = self.lexer.consume_peeked();
                    self.expect_and_consume(Token::Eol, "Expecting newline after ELSE")?;

                    let expr = Expr::Boolean(BooleanSpan { value: true, pos: else_span.pos });
                    branches.push(IfBranchSpan { guard: expr, body: vec![] });
                    i += 1;

                    last = true;
                }

                Token::End => {
                    let token_span = self.lexer.consume_peeked();
                    match self.maybe_parse_end()? {
                        Ok(stmt) => {
                            branches[i].body.push(stmt);
                        }
                        Err(Token::If) => {
                            break;
                        }
                        Err(token) => {
                            return Err(Error::Bad(
                                token_span.pos,
                                format!("END {} without {}", token, token),
                            ));
                        }
                    }
                }

                _ => match self.parse_one_safe()? {
                    Some(stmt) => {
                        branches[i].body.push(stmt);
                    }
                    None => {
                        break;
                    }
                },
            }
        }

        self.expect_and_consume_with_pos(Token::If, if_pos, "IF without END IF")
    }

    /// Parses an `IF` statement.
    fn parse_if(&mut self, if_pos: LineCol) -> Result<Statement> {
        let expr = self.parse_required_expr("No expression in IF statement")?;
        self.expect_and_consume(Token::Then, "No THEN in IF statement")?;

        let mut branches = vec![IfBranchSpan { guard: expr, body: vec![] }];

        let peeked = self.lexer.peek()?;
        match peeked.token {
            Token::Eol | Token::Eof => self.parse_if_multiline(if_pos, &mut branches)?,
            _ => self.parse_if_uniline(&mut branches)?,
        }

        Ok(Statement::If(IfSpan { branches }))
    }

    /// Advances until the next statement after failing to parse an `IF` statement.
    fn reset_if(&mut self, if_pos: LineCol) -> Result<()> {
        loop {
            match self.lexer.peek()?.token {
                Token::Eof => break,
                Token::End => {
                    self.lexer.consume_peeked();
                    self.expect_and_consume_with_pos(Token::If, if_pos, "IF without END IF")?;
                    break;
                }
                _ => {
                    self.lexer.consume_peeked();
                }
            }
        }
        self.reset()
    }

    /// Extracts the optional `STEP` part of a `FOR` statement, with a default of 1.
    ///
    /// Returns the step as an expression, an `Ordering` value representing how the step value
    /// compares to zero, and whether the step is a double or not.
    fn parse_step(&mut self) -> Result<(Expr, Ordering, bool)> {
        let peeked = self.lexer.peek()?;
        match peeked.token {
            Token::Step => self.lexer.consume_peeked(),
            _ => {
                // The position we return here for the step isn't truly the right value, but given
                // that we know the hardcoded step of 1 is valid, the caller will not error out and
                // will not print the slightly invalid position.
                return Ok((
                    Expr::Integer(IntegerSpan { value: 1, pos: peeked.pos }),
                    Ordering::Greater,
                    false,
                ));
            }
        };

        let peeked = self.lexer.peek()?;
        match peeked.token {
            Token::Double(d) => {
                let peeked = self.lexer.consume_peeked();
                let sign = if d == 0.0 { Ordering::Equal } else { Ordering::Greater };
                Ok((Expr::Double(DoubleSpan { value: d, pos: peeked.pos }), sign, true))
            }
            Token::Integer(i) => {
                let peeked = self.lexer.consume_peeked();
                Ok((Expr::Integer(IntegerSpan { value: i, pos: peeked.pos }), i.cmp(&0), false))
            }
            Token::Minus => {
                self.lexer.consume_peeked();
                let peeked = self.lexer.peek()?;
                match peeked.token {
                    Token::Double(d) => {
                        let peeked = self.lexer.consume_peeked();
                        let sign = if d == 0.0 { Ordering::Equal } else { Ordering::Less };
                        Ok((Expr::Double(DoubleSpan { value: -d, pos: peeked.pos }), sign, true))
                    }
                    Token::Integer(i) => {
                        let peeked = self.lexer.consume_peeked();
                        Ok((
                            Expr::Integer(IntegerSpan { value: -i, pos: peeked.pos }),
                            (-i).cmp(&0),
                            false,
                        ))
                    }
                    _ => Err(Error::Bad(peeked.pos, "STEP needs a literal number".to_owned())),
                }
            }
            _ => Err(Error::Bad(peeked.pos, "STEP needs a literal number".to_owned())),
        }
    }

    /// Parses a `FOR` statement.
    fn parse_for(&mut self, for_pos: LineCol) -> Result<Statement> {
        let token_span = self.lexer.read()?;
        let iterator = match token_span.token {
            Token::Symbol(iterator) => match iterator.ref_type() {
                VarType::Auto | VarType::Double | VarType::Integer => iterator,
                _ => {
                    return Err(Error::Bad(
                        token_span.pos,
                        "Iterator name in FOR statement must be a numeric reference".to_owned(),
                    ))
                }
            },
            _ => {
                return Err(Error::Bad(
                    token_span.pos,
                    "No iterator name in FOR statement".to_owned(),
                ))
            }
        };
        let iterator_pos = token_span.pos;

        self.expect_and_consume(Token::Equal, "No equal sign in FOR statement")?;
        let start = self.parse_required_expr("No start expression in FOR statement")?;

        let to_span = self.expect_and_consume(Token::To, "No TO in FOR statement")?;
        let end = self.parse_required_expr("No end expression in FOR statement")?;

        let (step, step_sign, iter_double) = self.parse_step()?;
        let end_condition = match step_sign {
            Ordering::Greater => Expr::LessEqual(Box::from(BinaryOpSpan {
                lhs: Expr::Symbol(SymbolSpan { vref: iterator.clone(), pos: iterator_pos }),
                rhs: end,
                pos: to_span.pos,
            })),
            Ordering::Less => Expr::GreaterEqual(Box::from(BinaryOpSpan {
                lhs: Expr::Symbol(SymbolSpan { vref: iterator.clone(), pos: iterator_pos }),
                rhs: end,
                pos: to_span.pos,
            })),
            Ordering::Equal => {
                return Err(Error::Bad(
                    step.start_pos(),
                    "Infinite FOR loop; STEP cannot be 0".to_owned(),
                ))
            }
        };

        let next_value = Expr::Add(Box::from(BinaryOpSpan {
            lhs: Expr::Symbol(SymbolSpan { vref: iterator.clone(), pos: iterator_pos }),
            rhs: step,
            pos: to_span.pos,
        }));

        self.expect_and_consume(Token::Eol, "Expecting newline after FOR")?;

        let stmts = self.parse_until(Token::Next)?;
        self.expect_and_consume_with_pos(Token::Next, for_pos, "FOR without NEXT")?;

        Ok(Statement::For(ForSpan {
            iter: iterator,
            iter_pos: iterator_pos,
            iter_double,
            start,
            end: end_condition,
            next: next_value,
            body: stmts,
        }))
    }

    /// Advances until the next statement after failing to parse a `FOR` statement.
    fn reset_for(&mut self) -> Result<()> {
        loop {
            match self.lexer.peek()?.token {
                Token::Eof => break,
                Token::Next => {
                    self.lexer.consume_peeked();
                    break;
                }
                _ => {
                    self.lexer.consume_peeked();
                }
            }
        }
        self.reset()
    }

    /// Parses an `ON ERROR` statement.  Only `ON` has been consumed so far.
    fn parse_on(&mut self) -> Result<Statement> {
        self.expect_and_consume(Token::Error, "Expected ERROR after ON")?;

        let token_span = self.lexer.read()?;
        match token_span.token {
            Token::Goto => {
                let token_span = self.lexer.read()?;
                match token_span.token {
                    Token::Integer(i) if i == 0 => Ok(Statement::OnError(OnErrorSpan::Reset)),
                    Token::Integer(i) => Ok(Statement::OnError(OnErrorSpan::Goto(GotoSpan {
                        target: format!("{}", i),
                        target_pos: token_span.pos,
                    }))),
                    Token::Label(target) => Ok(Statement::OnError(OnErrorSpan::Goto(GotoSpan {
                        target,
                        target_pos: token_span.pos,
                    }))),
                    _ => Err(Error::Bad(
                        token_span.pos,
                        "Expected label name or 0 after ON ERROR GOTO".to_owned(),
                    )),
                }
            }
            Token::Resume => {
                self.expect_and_consume(Token::Next, "Expected NEXT after ON ERROR RESUME")?;
                Ok(Statement::OnError(OnErrorSpan::ResumeNext))
            }
            _ => {
                Err(Error::Bad(token_span.pos, "Expected GOTO or RESUME after ON ERROR".to_owned()))
            }
        }
    }

    /// Parses the guards after a `CASE` keyword.
    fn parse_case_guards(&mut self) -> Result<Vec<CaseGuardSpan>> {
        let mut guards = vec![];

        loop {
            let peeked = self.lexer.peek()?;
            match peeked.token {
                Token::Else => {
                    let token_span = self.lexer.consume_peeked();

                    if !guards.is_empty() {
                        return Err(Error::Bad(
                            token_span.pos,
                            "CASE ELSE must be on its own".to_owned(),
                        ));
                    }

                    let peeked = self.lexer.peek()?;
                    if peeked.token != Token::Eol && peeked.token != Token::Eof {
                        return Err(Error::Bad(
                            peeked.pos,
                            "Expected newline after CASE ELSE".to_owned(),
                        ));
                    }

                    break;
                }

                Token::Is => {
                    self.lexer.consume_peeked();

                    let token_span = self.lexer.read()?;
                    let rel_op = match token_span.token {
                        Token::Equal => CaseRelOp::Equal,
                        Token::NotEqual => CaseRelOp::NotEqual,
                        Token::Less => CaseRelOp::Less,
                        Token::LessEqual => CaseRelOp::LessEqual,
                        Token::Greater => CaseRelOp::Greater,
                        Token::GreaterEqual => CaseRelOp::GreaterEqual,
                        _ => {
                            return Err(Error::Bad(
                                token_span.pos,
                                "Expected relational operator".to_owned(),
                            ));
                        }
                    };

                    let expr =
                        self.parse_required_expr("Missing expression after relational operator")?;
                    guards.push(CaseGuardSpan::Is(rel_op, expr));
                }

                _ => {
                    let from_expr = self.parse_required_expr("Missing expression in CASE guard")?;

                    let peeked = self.lexer.peek()?;
                    match peeked.token {
                        Token::Eol | Token::Comma => {
                            guards.push(CaseGuardSpan::Is(CaseRelOp::Equal, from_expr));
                        }
                        Token::To => {
                            self.lexer.consume_peeked();
                            let to_expr = self
                                .parse_required_expr("Missing expression after TO in CASE guard")?;
                            guards.push(CaseGuardSpan::To(from_expr, to_expr));
                        }
                        _ => {
                            return Err(Error::Bad(
                                peeked.pos,
                                "Expected comma, newline, or TO after expression".to_owned(),
                            ));
                        }
                    }
                }
            }

            let peeked = self.lexer.peek()?;
            match peeked.token {
                Token::Eol => {
                    break;
                }
                Token::Comma => {
                    self.lexer.consume_peeked();
                }
                _ => {
                    return Err(Error::Bad(
                        peeked.pos,
                        "Expected comma, newline, or TO after expression".to_owned(),
                    ));
                }
            }
        }

        Ok(guards)
    }

    /// Parses a `SELECT` statement.
    fn parse_select(&mut self, select_pos: LineCol) -> Result<Statement> {
        self.expect_and_consume(Token::Case, "Expecting CASE after SELECT")?;

        let expr = self.parse_required_expr("No expression in SELECT CASE statement")?;
        self.expect_and_consume(Token::Eol, "Expecting newline after SELECT CASE")?;

        let mut cases = vec![];

        let mut i = 0;
        let mut last = false;
        let end_pos;
        loop {
            let peeked = self.lexer.peek()?;
            match peeked.token {
                Token::Eof => {
                    end_pos = peeked.pos;
                    break;
                }

                Token::Eol => {
                    self.lexer.consume_peeked();
                }

                Token::Case => {
                    let peeked = self.lexer.consume_peeked();
                    let guards = self.parse_case_guards()?;
                    self.expect_and_consume(Token::Eol, "Expecting newline after CASE")?;

                    let is_last = guards.is_empty();
                    if last {
                        if is_last {
                            return Err(Error::Bad(
                                peeked.pos,
                                "CASE ELSE must be unique".to_owned(),
                            ));
                        } else {
                            return Err(Error::Bad(peeked.pos, "CASE ELSE is not last".to_owned()));
                        }
                    }
                    last |= is_last;

                    cases.push(CaseSpan { guards, body: vec![] });
                    if cases.len() > 1 {
                        i += 1;
                    }
                }

                Token::End => {
                    let end_span = self.lexer.consume_peeked();
                    match self.maybe_parse_end()? {
                        Ok(stmt) => {
                            if cases.is_empty() {
                                return Err(Error::Bad(
                                    end_span.pos,
                                    "Expected CASE after SELECT CASE before any statement"
                                        .to_owned(),
                                ));
                            }

                            cases[i].body.push(stmt);
                        }
                        Err(Token::Select) => {
                            end_pos = end_span.pos;
                            break;
                        }
                        Err(token) => {
                            if cases.is_empty() {
                                return Err(Error::Bad(
                                    end_span.pos,
                                    "Expected CASE after SELECT CASE before any statement"
                                        .to_owned(),
                                ));
                            } else {
                                return Err(Error::Bad(
                                    end_span.pos,
                                    format!("END {} without {}", token, token),
                                ));
                            }
                        }
                    }
                }

                _ => {
                    if cases.is_empty() {
                        return Err(Error::Bad(
                            peeked.pos,
                            "Expected CASE after SELECT CASE before any statement".to_owned(),
                        ));
                    }

                    if let Some(stmt) = self.parse_one_safe()? {
                        cases[i].body.push(stmt);
                    }
                }
            }
        }

        self.expect_and_consume_with_pos(Token::Select, select_pos, "SELECT without END SELECT")?;

        Ok(Statement::Select(SelectSpan { expr, cases, end_pos }))
    }

    /// Advances until the next statement after failing to parse a `SELECT` statement.
    fn reset_select(&mut self, select_pos: LineCol) -> Result<()> {
        loop {
            match self.lexer.peek()?.token {
                Token::Eof => break,
                Token::End => {
                    self.lexer.consume_peeked();
                    self.expect_and_consume_with_pos(
                        Token::Select,
                        select_pos,
                        "SELECT without END SELECT",
                    )?;
                    break;
                }
                _ => {
                    self.lexer.consume_peeked();
                }
            }
        }
        self.reset()
    }

    /// Parses a `WHILE` statement.
    fn parse_while(&mut self, while_pos: LineCol) -> Result<Statement> {
        let expr = self.parse_required_expr("No expression in WHILE statement")?;
        self.expect_and_consume(Token::Eol, "Expecting newline after WHILE")?;

        let stmts = self.parse_until(Token::Wend)?;
        self.expect_and_consume_with_pos(Token::Wend, while_pos, "WHILE without WEND")?;

        Ok(Statement::While(WhileSpan { expr, body: stmts }))
    }

    /// Advances until the next statement after failing to parse a `WHILE` statement.
    fn reset_while(&mut self) -> Result<()> {
        loop {
            match self.lexer.peek()?.token {
                Token::Eof => break,
                Token::Wend => {
                    self.lexer.consume_peeked();
                    break;
                }
                _ => {
                    self.lexer.consume_peeked();
                }
            }
        }
        self.reset()
    }

    /// Extracts the next available uniline statement from the input stream, or `None` if none is
    /// available.
    ///
    /// The statement must be specifiable in a single line as part of a uniline `IF` statement, and
    /// we currently expect this to only be used while parsing an `IF`.
    ///
    /// On success, the stream is left in a position where the next statement can be extracted.
    /// On failure, the caller must advance the stream to the next statement by calling `reset`.
    fn parse_uniline(&mut self) -> Result<Option<Statement>> {
        let token_span = self.lexer.read()?;
        match token_span.token {
            Token::Data => Ok(Some(self.parse_data()?)),
            Token::End => Ok(Some(self.parse_end(token_span.pos)?)),
            Token::Eof | Token::Eol => Ok(None),
            Token::Exit => Ok(Some(self.parse_exit_do(token_span.pos)?)),
            Token::Gosub => Ok(Some(self.parse_gosub()?)),
            Token::Goto => Ok(Some(self.parse_goto()?)),
            Token::On => Ok(Some(self.parse_on()?)),
            Token::Return => Ok(Some(Statement::Return(ReturnSpan { pos: token_span.pos }))),
            Token::Symbol(vref) => {
                let peeked = self.lexer.peek()?;
                if peeked.token == Token::Equal {
                    self.lexer.consume_peeked();
                    Ok(Some(self.parse_assignment(vref, token_span.pos)?))
                } else {
                    Ok(Some(self.parse_array_or_builtin_call(vref, token_span.pos)?))
                }
            }
            Token::Bad(msg) => Err(Error::Bad(token_span.pos, msg)),
            t => Err(Error::Bad(token_span.pos, format!("Unexpected {} in uniline IF branch", t))),
        }
    }

    /// Extracts the next available statement from the input stream, or `None` if none is available.
    ///
    /// On success, the stream is left in a position where the next statement can be extracted.
    /// On failure, the caller must advance the stream to the next statement by calling `reset`.
    fn parse_one(&mut self) -> Result<Option<Statement>> {
        loop {
            match self.lexer.peek()?.token {
                Token::Eol => {
                    self.lexer.consume_peeked();
                }
                Token::Eof => return Ok(None),
                _ => break,
            }
        }
        let token_span = self.lexer.read()?;
        let res = match token_span.token {
            Token::Data => Ok(Some(self.parse_data()?)),
            Token::Dim => Ok(Some(self.parse_dim()?)),
            Token::Do => {
                let result = self.parse_do(token_span.pos);
                if result.is_err() {
                    self.reset_do()?;
                }
                Ok(Some(result?))
            }
            Token::End => Ok(Some(self.parse_end(token_span.pos)?)),
            Token::Eof => return Ok(None),
            Token::Eol => Ok(None),
            Token::Exit => Ok(Some(self.parse_exit_do(token_span.pos)?)),
            Token::If => {
                let result = self.parse_if(token_span.pos);
                if result.is_err() {
                    self.reset_if(token_span.pos)?;
                }
                Ok(Some(result?))
            }
            Token::For => {
                let result = self.parse_for(token_span.pos);
                if result.is_err() {
                    self.reset_for()?;
                }
                Ok(Some(result?))
            }
            Token::Gosub => {
                let result = self.parse_gosub();
                Ok(Some(result?))
            }
            Token::Goto => {
                let result = self.parse_goto();
                Ok(Some(result?))
            }
            Token::Integer(i) => {
                let name = format!("{}", i);
                // When we encounter a line number, we must return early to avoid looking for a line
                // ending given that the next statement may start after the label we found.
                return Ok(Some(Statement::Label(LabelSpan { name, name_pos: token_span.pos })));
            }
            Token::Label(name) => {
                // When we encounter a label, we must return early to avoid looking for a line
                // ending given that the next statement may start after the label we found.
                return Ok(Some(Statement::Label(LabelSpan { name, name_pos: token_span.pos })));
            }
            Token::On => Ok(Some(self.parse_on()?)),
            Token::Return => Ok(Some(Statement::Return(ReturnSpan { pos: token_span.pos }))),
            Token::Select => {
                let result = self.parse_select(token_span.pos);
                if result.is_err() {
                    self.reset_select(token_span.pos)?;
                }
                Ok(Some(result?))
            }
            Token::Symbol(vref) => {
                let peeked = self.lexer.peek()?;
                if peeked.token == Token::Equal {
                    self.lexer.consume_peeked();
                    Ok(Some(self.parse_assignment(vref, token_span.pos)?))
                } else {
                    Ok(Some(self.parse_array_or_builtin_call(vref, token_span.pos)?))
                }
            }
            Token::While => {
                let result = self.parse_while(token_span.pos);
                if result.is_err() {
                    self.reset_while()?;
                }
                Ok(Some(result?))
            }
            Token::Bad(msg) => return Err(Error::Bad(token_span.pos, msg)),
            t => return Err(Error::Bad(token_span.pos, format!("Unexpected {} in statement", t))),
        };

        let token_span = self.lexer.peek()?;
        match token_span.token {
            Token::Eof => (),
            Token::Eol => {
                self.lexer.consume_peeked();
            }
            _ => {
                return Err(Error::Bad(
                    token_span.pos,
                    format!("Expected newline but found {}", token_span.token),
                ))
            }
        };

        res
    }

    /// Advances until the next statement after failing to parse a single statement.
    fn reset(&mut self) -> Result<()> {
        loop {
            match self.lexer.peek()?.token {
                Token::Eof => break,
                Token::Eol => {
                    self.lexer.consume_peeked();
                    break;
                }
                _ => {
                    self.lexer.consume_peeked();
                }
            }
        }
        Ok(())
    }

    /// Extracts the next available statement from the input stream, or `None` if none is available.
    ///
    /// The stream is always left in a position where the next statement extraction can be tried.
    fn parse_one_safe(&mut self) -> Result<Option<Statement>> {
        let result = self.parse_one();
        if result.is_err() {
            self.reset()?;
        }
        result
    }
}

/// Extracts all statements from the input stream.
pub fn parse(input: &mut dyn io::Read) -> Result<Vec<Statement>> {
    let mut parser = Parser::from(input);
    let mut statements = vec![];
    while let Some(statement) = parser.parse_one_safe()? {
        statements.push(statement);
    }
    Ok(statements)
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::ast::VarType;

    /// Syntactic sugar to instantiate a `LineCol` for testing.
    fn lc(line: usize, col: usize) -> LineCol {
        LineCol { line, col }
    }

    /// Syntactic sugar to instantiate an `Expr::Boolean` for testing.
    fn expr_boolean(value: bool, line: usize, col: usize) -> Expr {
        Expr::Boolean(BooleanSpan { value, pos: LineCol { line, col } })
    }

    /// Syntactic sugar to instantiate an `Expr::Double` for testing.
    fn expr_double(value: f64, line: usize, col: usize) -> Expr {
        Expr::Double(DoubleSpan { value, pos: LineCol { line, col } })
    }

    /// Syntactic sugar to instantiate an `Expr::Integer` for testing.
    fn expr_integer(value: i32, line: usize, col: usize) -> Expr {
        Expr::Integer(IntegerSpan { value, pos: LineCol { line, col } })
    }

    /// Syntactic sugar to instantiate an `Expr::Text` for testing.
    fn expr_text<S: Into<String>>(value: S, line: usize, col: usize) -> Expr {
        Expr::Text(TextSpan { value: value.into(), pos: LineCol { line, col } })
    }

    /// Syntactic sugar to instantiate an `Expr::Symbol` for testing.
    fn expr_symbol(vref: VarRef, line: usize, col: usize) -> Expr {
        Expr::Symbol(SymbolSpan { vref, pos: LineCol { line, col } })
    }

    #[test]
    fn test_varref_to_unannotated_string() {
        assert_eq!(
            "print",
            &vref_to_unannotated_string(
                VarRef::new("print", VarType::Auto),
                LineCol { line: 0, col: 0 }
            )
            .unwrap()
        );

        assert_eq!(
            "7:6: Type annotation not allowed in print$",
            format!(
                "{}",
                &vref_to_unannotated_string(
                    VarRef::new("print", VarType::Text),
                    LineCol { line: 7, col: 6 }
                )
                .unwrap_err()
            )
        );
    }

    /// Runs the parser on the given `input` and expects the returned statements to match
    /// `exp_statements`.
    fn do_ok_test(input: &str, exp_statements: &[Statement]) {
        let mut input = input.as_bytes();
        let statements = parse(&mut input).expect("Parsing failed");
        assert_eq!(exp_statements, statements.as_slice());
    }

    /// Runs the parser on the given `input` and expects the `err` error message.
    fn do_error_test(input: &str, expected_err: &str) {
        let mut input = input.as_bytes();
        let mut parser = Parser::from(&mut input);
        assert_eq!(
            expected_err,
            format!("{}", parser.parse_one_safe().expect_err("Parsing did not fail"))
        );
        assert!(parser.parse_one_safe().unwrap().is_none());
    }

    /// Runs the parser on the given `input` and expects the `err` error message.
    ///
    /// Does not expect the parser to be reset to the next (EOF) statement.
    // TODO(jmmv): Need better testing to ensure the parser is reset to something that can be
    // parsed next.
    fn do_error_test_no_reset(input: &str, expected_err: &str) {
        let mut input = input.as_bytes();
        assert_eq!(
            expected_err,
            format!("{}", parse(&mut input).expect_err("Parsing did not fail"))
        );
    }

    #[test]
    fn test_empty() {
        do_ok_test("", &[]);
    }

    #[test]
    fn test_statement_separators() {
        do_ok_test(
            "a=1\nb=2:c=3:' A comment: that follows\nd=4",
            &[
                Statement::Assignment(AssignmentSpan {
                    vref: VarRef::new("a", VarType::Auto),
                    vref_pos: lc(1, 1),
                    expr: expr_integer(1, 1, 3),
                }),
                Statement::Assignment(AssignmentSpan {
                    vref: VarRef::new("b", VarType::Auto),
                    vref_pos: lc(2, 1),
                    expr: expr_integer(2, 2, 3),
                }),
                Statement::Assignment(AssignmentSpan {
                    vref: VarRef::new("c", VarType::Auto),
                    vref_pos: lc(2, 5),
                    expr: expr_integer(3, 2, 7),
                }),
                Statement::Assignment(AssignmentSpan {
                    vref: VarRef::new("d", VarType::Auto),
                    vref_pos: lc(3, 1),
                    expr: expr_integer(4, 3, 3),
                }),
            ],
        );
    }

    #[test]
    fn test_array_assignments() {
        do_ok_test(
            "a(1)=100\nfoo(2, 3)=\"text\"\nabc$ (5 + z, 6) = TRUE OR FALSE",
            &[
                Statement::ArrayAssignment(ArrayAssignmentSpan {
                    vref: VarRef::new("a", VarType::Auto),
                    vref_pos: lc(1, 1),
                    subscripts: vec![expr_integer(1, 1, 3)],
                    expr: expr_integer(100, 1, 6),
                }),
                Statement::ArrayAssignment(ArrayAssignmentSpan {
                    vref: VarRef::new("foo", VarType::Auto),
                    vref_pos: lc(2, 1),
                    subscripts: vec![expr_integer(2, 2, 5), expr_integer(3, 2, 8)],
                    expr: expr_text("text", 2, 11),
                }),
                Statement::ArrayAssignment(ArrayAssignmentSpan {
                    vref: VarRef::new("abc", VarType::Text),
                    vref_pos: lc(3, 1),
                    subscripts: vec![
                        Expr::Add(Box::from(BinaryOpSpan {
                            lhs: expr_integer(5, 3, 7),
                            rhs: expr_symbol(VarRef::new("z".to_owned(), VarType::Auto), 3, 11),
                            pos: lc(3, 9),
                        })),
                        expr_integer(6, 3, 14),
                    ],
                    expr: Expr::Or(Box::from(BinaryOpSpan {
                        lhs: expr_boolean(true, 3, 19),
                        rhs: expr_boolean(false, 3, 27),
                        pos: lc(3, 24),
                    })),
                }),
            ],
        );
    }

    #[test]
    fn test_array_assignment_errors() {
        do_error_test("a(", "1:3: Unexpected <<EOF>>");
        do_error_test("a()", "1:2: Expected expression");
        do_error_test("a() =", "1:6: Missing expression in array assignment");
        do_error_test("a() IF", "1:2: Expected expression");
        do_error_test("a() = 3 4", "1:9: Unexpected value in expression");
        do_error_test("a() = 3 THEN", "1:9: Unexpected THEN in array assignment");
        do_error_test("a(,) = 3", "1:3: Missing expression");
        do_error_test("a(2;3) = 3", "1:4: Unexpected ;");
        do_error_test("(2) = 3", "1:1: Unexpected ( in statement");
    }

    #[test]
    fn test_assignments() {
        do_ok_test(
            "a=1\nfoo$ = \"bar\"\nb$ = 3 + z",
            &[
                Statement::Assignment(AssignmentSpan {
                    vref: VarRef::new("a", VarType::Auto),
                    vref_pos: lc(1, 1),
                    expr: expr_integer(1, 1, 3),
                }),
                Statement::Assignment(AssignmentSpan {
                    vref: VarRef::new("foo", VarType::Text),
                    vref_pos: lc(2, 1),
                    expr: expr_text("bar", 2, 8),
                }),
                Statement::Assignment(AssignmentSpan {
                    vref: VarRef::new("b", VarType::Text),
                    vref_pos: lc(3, 1),
                    expr: Expr::Add(Box::from(BinaryOpSpan {
                        lhs: expr_integer(3, 3, 6),
                        rhs: expr_symbol(VarRef::new("z", VarType::Auto), 3, 10),
                        pos: lc(3, 8),
                    })),
                }),
            ],
        );
    }

    #[test]
    fn test_assignment_errors() {
        do_error_test("a =", "1:4: Missing expression in assignment");
        do_error_test("a = b 3", "1:7: Unexpected value in expression");
        do_error_test("a = b, 3", "1:6: Unexpected , in assignment");
        do_error_test("a = if 3", "1:5: Unexpected keyword in expression");
        do_error_test("true = 1", "1:1: Unexpected TRUE in statement");
    }

    #[test]
    fn test_builtin_calls() {
        do_ok_test(
            "PRINT a\nPRINT ; 3 , c$\nNOARGS\nNAME 3 AS 4",
            &[
                Statement::BuiltinCall(BuiltinCallSpan {
                    name: "PRINT".to_owned(),
                    name_pos: lc(1, 1),
                    args: vec![ArgSpan {
                        expr: Some(expr_symbol(VarRef::new("a", VarType::Auto), 1, 7)),
                        sep: ArgSep::End,
                        sep_pos: lc(1, 8),
                    }],
                }),
                Statement::BuiltinCall(BuiltinCallSpan {
                    name: "PRINT".to_owned(),
                    name_pos: lc(2, 1),
                    args: vec![
                        ArgSpan { expr: None, sep: ArgSep::Short, sep_pos: lc(2, 7) },
                        ArgSpan {
                            expr: Some(expr_integer(3, 2, 9)),
                            sep: ArgSep::Long,
                            sep_pos: lc(2, 11),
                        },
                        ArgSpan {
                            expr: Some(expr_symbol(VarRef::new("c", VarType::Text), 2, 13)),
                            sep: ArgSep::End,
                            sep_pos: lc(2, 15),
                        },
                    ],
                }),
                Statement::BuiltinCall(BuiltinCallSpan {
                    name: "NOARGS".to_owned(),
                    name_pos: lc(3, 1),
                    args: vec![],
                }),
                Statement::BuiltinCall(BuiltinCallSpan {
                    name: "NAME".to_owned(),
                    name_pos: lc(4, 1),
                    args: vec![
                        ArgSpan {
                            expr: Some(expr_integer(3, 4, 6)),
                            sep: ArgSep::As,
                            sep_pos: lc(4, 8),
                        },
                        ArgSpan {
                            expr: Some(expr_integer(4, 4, 11)),
                            sep: ArgSep::End,
                            sep_pos: lc(4, 12),
                        },
                    ],
                }),
            ],
        );
    }

    #[test]
    fn test_builtin_calls_and_array_references_disambiguation() {
        use Expr::*;

        do_ok_test(
            "PRINT(1)",
            &[Statement::BuiltinCall(BuiltinCallSpan {
                name: "PRINT".to_owned(),
                name_pos: lc(1, 1),
                args: vec![ArgSpan {
                    expr: Some(expr_integer(1, 1, 7)),
                    sep: ArgSep::End,
                    sep_pos: lc(1, 9),
                }],
            })],
        );

        do_ok_test(
            "PRINT(1), 2",
            &[Statement::BuiltinCall(BuiltinCallSpan {
                name: "PRINT".to_owned(),
                name_pos: lc(1, 1),
                args: vec![
                    ArgSpan {
                        expr: Some(expr_integer(1, 1, 7)),
                        sep: ArgSep::Long,
                        sep_pos: lc(1, 9),
                    },
                    ArgSpan {
                        expr: Some(expr_integer(2, 1, 11)),
                        sep: ArgSep::End,
                        sep_pos: lc(1, 12),
                    },
                ],
            })],
        );

        do_ok_test(
            "PRINT(1); 2",
            &[Statement::BuiltinCall(BuiltinCallSpan {
                name: "PRINT".to_owned(),
                name_pos: lc(1, 1),
                args: vec![
                    ArgSpan {
                        expr: Some(expr_integer(1, 1, 7)),
                        sep: ArgSep::Short,
                        sep_pos: lc(1, 9),
                    },
                    ArgSpan {
                        expr: Some(expr_integer(2, 1, 11)),
                        sep: ArgSep::End,
                        sep_pos: lc(1, 12),
                    },
                ],
            })],
        );

        do_ok_test(
            "PRINT(1);",
            &[Statement::BuiltinCall(BuiltinCallSpan {
                name: "PRINT".to_owned(),
                name_pos: lc(1, 1),
                args: vec![
                    ArgSpan {
                        expr: Some(expr_integer(1, 1, 7)),
                        sep: ArgSep::Short,
                        sep_pos: lc(1, 9),
                    },
                    ArgSpan { expr: None, sep: ArgSep::End, sep_pos: lc(1, 10) },
                ],
            })],
        );

        do_ok_test(
            "PRINT(1) + 2; 3",
            &[Statement::BuiltinCall(BuiltinCallSpan {
                name: "PRINT".to_owned(),
                name_pos: lc(1, 1),
                args: vec![
                    ArgSpan {
                        expr: Some(Add(Box::from(BinaryOpSpan {
                            lhs: expr_integer(1, 1, 7),
                            rhs: expr_integer(2, 1, 12),
                            pos: lc(1, 10),
                        }))),
                        sep: ArgSep::Short,
                        sep_pos: lc(1, 13),
                    },
                    ArgSpan {
                        expr: Some(expr_integer(3, 1, 15)),
                        sep: ArgSep::End,
                        sep_pos: lc(1, 16),
                    },
                ],
            })],
        );
    }

    #[test]
    fn test_builtin_calls_errors() {
        do_error_test("FOO 3 5\n", "1:7: Unexpected value in expression");
        do_error_test("INPUT$ a\n", "1:1: Type annotation not allowed in INPUT$");
        do_error_test("PRINT IF 1\n", "1:7: Unexpected keyword in expression");
        do_error_test("PRINT 3, IF 1\n", "1:10: Unexpected keyword in expression");
        do_error_test("PRINT 3 THEN\n", "1:9: Expected comma, semicolon, or end of statement");
        do_error_test("PRINT ()\n", "1:7: Expected expression");
        do_error_test("PRINT (2, 3)\n", "1:7: Expected expression");
        do_error_test("PRINT (2, 3); 4\n", "1:7: Expected expression");
    }

    #[test]
    fn test_data() {
        do_ok_test("DATA", &[Statement::Data(DataSpan { values: vec![None] })]);

        do_ok_test("DATA , ", &[Statement::Data(DataSpan { values: vec![None, None] })]);
        do_ok_test(
            "DATA , , ,",
            &[Statement::Data(DataSpan { values: vec![None, None, None, None] })],
        );

        do_ok_test(
            "DATA 1: DATA 2",
            &[
                Statement::Data(DataSpan { values: vec![Some(Value::Integer(1))] }),
                Statement::Data(DataSpan { values: vec![Some(Value::Integer(2))] }),
            ],
        );

        do_ok_test(
            "DATA TRUE, -3, 5.1, \"foo\"",
            &[Statement::Data(DataSpan {
                values: vec![
                    Some(Value::Boolean(true)),
                    Some(Value::Integer(-3)),
                    Some(Value::Double(5.1)),
                    Some(Value::Text("foo".to_owned())),
                ],
            })],
        );

        do_ok_test(
            "DATA , TRUE, , 3, , 5.1, , \"foo\",",
            &[Statement::Data(DataSpan {
                values: vec![
                    None,
                    Some(Value::Boolean(true)),
                    None,
                    Some(Value::Integer(3)),
                    None,
                    Some(Value::Double(5.1)),
                    None,
                    Some(Value::Text("foo".to_owned())),
                    None,
                ],
            })],
        );

        do_ok_test(
            "DATA -3, -5.1",
            &[Statement::Data(DataSpan {
                values: vec![Some(Value::Integer(-3)), Some(Value::Double(-5.1))],
            })],
        );
    }

    #[test]
    fn test_data_errors() {
        do_error_test("DATA + 2", "1:6: Unexpected + in DATA statement");
        do_error_test("DATA ;", "1:6: Unexpected ; in DATA statement");
        do_error_test("DATA 5 + 1", "1:8: Expected comma after datum but found +");
        do_error_test("DATA 5 ; 1", "1:8: Expected comma after datum but found ;");
        do_error_test("DATA -FALSE", "1:7: Expected number after -");
        do_error_test("DATA -\"abc\"", "1:7: Expected number after -");
        do_error_test("DATA -foo", "1:7: Expected number after -");
    }

    #[test]
    fn test_dim_default_type() {
        do_ok_test(
            "DIM i",
            &[Statement::Dim(DimSpan {
                name: "i".to_owned(),
                name_pos: lc(1, 5),
                vtype: VarType::Integer,
                vtype_pos: lc(1, 6),
            })],
        );
    }

    #[test]
    fn test_dim_as_simple_types() {
        do_ok_test(
            "DIM i AS BOOLEAN",
            &[Statement::Dim(DimSpan {
                name: "i".to_owned(),
                name_pos: lc(1, 5),
                vtype: VarType::Boolean,
                vtype_pos: lc(1, 10),
            })],
        );
        do_ok_test(
            "DIM i AS DOUBLE",
            &[Statement::Dim(DimSpan {
                name: "i".to_owned(),
                name_pos: lc(1, 5),
                vtype: VarType::Double,
                vtype_pos: lc(1, 10),
            })],
        );
        do_ok_test(
            "DIM i AS INTEGER",
            &[Statement::Dim(DimSpan {
                name: "i".to_owned(),
                name_pos: lc(1, 5),
                vtype: VarType::Integer,
                vtype_pos: lc(1, 10),
            })],
        );
        do_ok_test(
            "DIM i AS STRING",
            &[Statement::Dim(DimSpan {
                name: "i".to_owned(),
                name_pos: lc(1, 5),
                vtype: VarType::Text,
                vtype_pos: lc(1, 10),
            })],
        );
    }

    #[test]
    fn test_dim_consecutive() {
        do_ok_test(
            "DIM i\nDIM j AS BOOLEAN\nDIM k",
            &[
                Statement::Dim(DimSpan {
                    name: "i".to_owned(),
                    name_pos: lc(1, 5),
                    vtype: VarType::Integer,
                    vtype_pos: lc(1, 6),
                }),
                Statement::Dim(DimSpan {
                    name: "j".to_owned(),
                    name_pos: lc(2, 5),
                    vtype: VarType::Boolean,
                    vtype_pos: lc(2, 10),
                }),
                Statement::Dim(DimSpan {
                    name: "k".to_owned(),
                    name_pos: lc(3, 5),
                    vtype: VarType::Integer,
                    vtype_pos: lc(3, 6),
                }),
            ],
        );
    }

    #[test]
    fn test_dim_array() {
        use Expr::*;

        do_ok_test(
            "DIM i(10)",
            &[Statement::DimArray(DimArraySpan {
                name: "i".to_owned(),
                name_pos: lc(1, 5),
                dimensions: vec![expr_integer(10, 1, 7)],
                subtype: VarType::Integer,
                subtype_pos: lc(1, 10),
            })],
        );

        do_ok_test(
            "DIM foo(-5, 0) AS STRING",
            &[Statement::DimArray(DimArraySpan {
                name: "foo".to_owned(),
                name_pos: lc(1, 5),
                dimensions: vec![
                    Negate(Box::from(UnaryOpSpan { expr: expr_integer(5, 1, 10), pos: lc(1, 9) })),
                    expr_integer(0, 1, 13),
                ],
                subtype: VarType::Text,
                subtype_pos: lc(1, 19),
            })],
        );

        do_ok_test(
            "DIM foo(bar$() + 3, 8, -1)",
            &[Statement::DimArray(DimArraySpan {
                name: "foo".to_owned(),
                name_pos: lc(1, 5),
                dimensions: vec![
                    Add(Box::from(BinaryOpSpan {
                        lhs: Call(FunctionCallSpan {
                            fref: VarRef::new("bar", VarType::Text),
                            args: vec![],
                            pos: lc(1, 9),
                        }),
                        rhs: expr_integer(3, 1, 18),
                        pos: lc(1, 16),
                    })),
                    expr_integer(8, 1, 21),
                    Negate(Box::from(UnaryOpSpan { expr: expr_integer(1, 1, 25), pos: lc(1, 24) })),
                ],
                subtype: VarType::Integer,
                subtype_pos: lc(1, 27),
            })],
        );
    }

    #[test]
    fn test_dim_errors() {
        do_error_test("DIM", "1:4: Expected variable name after DIM");
        do_error_test("DIM 3", "1:5: Expected variable name after DIM");
        do_error_test("DIM AS", "1:5: Expected variable name after DIM");
        do_error_test("DIM foo 3", "1:9: Expected AS or end of statement");
        do_error_test("DIM a AS", "1:9: Invalid type name <<EOF>> in DIM AS statement");
        do_error_test("DIM a$ AS", "1:5: Type annotation not allowed in a$");
        do_error_test("DIM a AS 3", "1:10: Invalid type name 3 in DIM AS statement");
        do_error_test("DIM a AS INTEGER 3", "1:18: Unexpected 3 in DIM statement");

        do_error_test("DIM a()", "1:6: Arrays require at least one dimension");
        do_error_test("DIM a(,)", "1:7: Missing expression");
        do_error_test("DIM a(, 3)", "1:7: Missing expression");
        do_error_test("DIM a(3, )", "1:10: Missing expression");
        do_error_test("DIM a(3, , 4)", "1:10: Missing expression");
        do_error_test("DIM a(1) AS INTEGER 3", "1:21: Unexpected 3 in DIM statement");
    }

    #[test]
    fn test_do_until_empty() {
        do_ok_test(
            "DO UNTIL TRUE\nLOOP",
            &[Statement::Do(DoSpan {
                guard: DoGuard::PreUntil(expr_boolean(true, 1, 10)),
                body: vec![],
            })],
        );

        do_ok_test(
            "DO UNTIL FALSE\nREM foo\nLOOP",
            &[Statement::Do(DoSpan {
                guard: DoGuard::PreUntil(expr_boolean(false, 1, 10)),
                body: vec![],
            })],
        );
    }

    #[test]
    fn test_do_infinite_empty() {
        do_ok_test("DO\nLOOP", &[Statement::Do(DoSpan { guard: DoGuard::Infinite, body: vec![] })]);
    }

    #[test]
    fn test_do_pre_until_loops() {
        do_ok_test(
            "DO UNTIL TRUE\nA\nB\nLOOP",
            &[Statement::Do(DoSpan {
                guard: DoGuard::PreUntil(expr_boolean(true, 1, 10)),
                body: vec![make_bare_builtin_call("A", 2, 1), make_bare_builtin_call("B", 3, 1)],
            })],
        );
    }

    #[test]
    fn test_do_pre_while_loops() {
        do_ok_test(
            "DO WHILE TRUE\nA\nB\nLOOP",
            &[Statement::Do(DoSpan {
                guard: DoGuard::PreWhile(expr_boolean(true, 1, 10)),
                body: vec![make_bare_builtin_call("A", 2, 1), make_bare_builtin_call("B", 3, 1)],
            })],
        );
    }

    #[test]
    fn test_do_post_until_loops() {
        do_ok_test(
            "DO\nA\nB\nLOOP UNTIL TRUE",
            &[Statement::Do(DoSpan {
                guard: DoGuard::PostUntil(expr_boolean(true, 4, 12)),

                body: vec![make_bare_builtin_call("A", 2, 1), make_bare_builtin_call("B", 3, 1)],
            })],
        );
    }

    #[test]
    fn test_do_post_while_loops() {
        do_ok_test(
            "DO\nA\nB\nLOOP WHILE FALSE",
            &[Statement::Do(DoSpan {
                guard: DoGuard::PostWhile(expr_boolean(false, 4, 12)),
                body: vec![make_bare_builtin_call("A", 2, 1), make_bare_builtin_call("B", 3, 1)],
            })],
        );
    }

    #[test]
    fn test_do_nested() {
        let code = r#"
            DO WHILE TRUE
                A
                DO
                    B
                LOOP UNTIL FALSE
                C
            LOOP
        "#;
        do_ok_test(
            code,
            &[Statement::Do(DoSpan {
                guard: DoGuard::PreWhile(expr_boolean(true, 2, 22)),
                body: vec![
                    make_bare_builtin_call("A", 3, 17),
                    Statement::Do(DoSpan {
                        guard: DoGuard::PostUntil(expr_boolean(false, 6, 28)),
                        body: vec![make_bare_builtin_call("B", 5, 21)],
                    }),
                    make_bare_builtin_call("C", 7, 17),
                ],
            })],
        );
    }

    #[test]
    fn test_do_errors() {
        do_error_test("DO\n", "1:1: DO without LOOP");
        do_error_test("DO FOR\n", "1:4: Expecting newline, UNTIL or WHILE after DO");

        do_error_test("\n\nDO UNTIL TRUE\n", "3:1: DO without LOOP");
        do_error_test("\n\nDO WHILE TRUE\n", "3:1: DO without LOOP");
        do_error_test("DO UNTIL TRUE\nEND", "1:1: DO without LOOP");
        do_error_test("DO WHILE TRUE\nEND", "1:1: DO without LOOP");
        do_error_test("DO UNTIL TRUE\nEND\n", "1:1: DO without LOOP");
        do_error_test("DO WHILE TRUE\nEND\n", "1:1: DO without LOOP");
        do_error_test("DO UNTIL TRUE\nEND WHILE\n", "2:5: Unexpected keyword in expression");
        do_error_test("DO WHILE TRUE\nEND WHILE\n", "2:5: Unexpected keyword in expression");

        do_error_test("DO UNTIL\n", "1:9: No expression in UNTIL clause");
        do_error_test("DO WHILE\n", "1:9: No expression in WHILE clause");
        do_error_test("DO UNTIL TRUE", "1:14: Expecting newline after DO");
        do_error_test("DO WHILE TRUE", "1:14: Expecting newline after DO");

        do_error_test("DO\nLOOP UNTIL", "2:11: No expression in UNTIL clause");
        do_error_test("DO\nLOOP WHILE\n", "2:11: No expression in WHILE clause");

        do_error_test("DO UNTIL ,\nLOOP", "1:10: No expression in UNTIL clause");
        do_error_test("DO WHILE ,\nLOOP", "1:10: No expression in WHILE clause");

        do_error_test("DO\nLOOP UNTIL ,\n", "2:12: No expression in UNTIL clause");
        do_error_test("DO\nLOOP WHILE ,\n", "2:12: No expression in WHILE clause");

        do_error_test(
            "DO WHILE TRUE\nLOOP UNTIL FALSE",
            "1:1: DO loop cannot have pre and post guards at the same time",
        );
    }

    #[test]
    fn test_exit_do() {
        do_ok_test("  EXIT DO", &[Statement::ExitDo(ExitDoSpan { pos: lc(1, 3) })]);
    }

    #[test]
    fn test_exit_do_errors() {
        do_error_test("EXIT", "1:5: Expecting DO after EXIT");
        do_error_test("EXIT 5", "1:6: Expecting DO after EXIT");
    }

    /// Wrapper around `do_ok_test` to parse an expression.  Given that expressions alone are not
    /// valid statements, we have to put them in a statement to parse them.  In doing so, we can
    /// also put an extra statement after them to ensure we detect their end properly.
    fn do_expr_ok_test(input: &str, expr: Expr) {
        do_ok_test(
            &format!("PRINT {}, 1", input),
            &[Statement::BuiltinCall(BuiltinCallSpan {
                name: "PRINT".to_owned(),
                name_pos: lc(1, 1),
                args: vec![
                    ArgSpan {
                        expr: Some(expr),
                        sep: ArgSep::Long,
                        sep_pos: lc(1, 7 + input.len()),
                    },
                    ArgSpan {
                        expr: Some(expr_integer(1, 1, 6 + input.len() + 3)),
                        sep: ArgSep::End,
                        sep_pos: lc(1, 10 + input.len()),
                    },
                ],
            })],
        );
    }

    /// Wrapper around `do_error_test` to parse an expression.  Given that expressions alone are not
    /// valid statements, we have to put them in a statement to parse them.  In doing so, we can
    /// also put an extra statement after them to ensure we detect their end properly.
    fn do_expr_error_test(input: &str, msg: &str) {
        do_error_test(&format!("PRINT {}, 1", input), msg)
    }

    #[test]
    fn test_expr_literals() {
        do_expr_ok_test("TRUE", expr_boolean(true, 1, 7));
        do_expr_ok_test("FALSE", expr_boolean(false, 1, 7));
        do_expr_ok_test("5", expr_integer(5, 1, 7));
        do_expr_ok_test("\"some text\"", expr_text("some text", 1, 7));
    }

    #[test]
    fn test_expr_symbols() {
        do_expr_ok_test("foo", expr_symbol(VarRef::new("foo", VarType::Auto), 1, 7));
        do_expr_ok_test("bar$", expr_symbol(VarRef::new("bar", VarType::Text), 1, 7));
    }

    #[test]
    fn test_expr_parens() {
        use Expr::*;
        do_expr_ok_test("(1)", expr_integer(1, 1, 8));
        do_expr_ok_test("((1))", expr_integer(1, 1, 9));
        do_expr_ok_test(" ( ( 1 ) ) ", expr_integer(1, 1, 12));
        do_expr_ok_test(
            "3 * (2 + 5)",
            Multiply(Box::from(BinaryOpSpan {
                lhs: expr_integer(3, 1, 7),
                rhs: Add(Box::from(BinaryOpSpan {
                    lhs: expr_integer(2, 1, 12),
                    rhs: expr_integer(5, 1, 16),
                    pos: lc(1, 14),
                })),
                pos: lc(1, 9),
            })),
        );
        do_expr_ok_test(
            "(7) - (1) + (-2)",
            Add(Box::from(BinaryOpSpan {
                lhs: Subtract(Box::from(BinaryOpSpan {
                    lhs: expr_integer(7, 1, 8),
                    rhs: expr_integer(1, 1, 14),
                    pos: lc(1, 11),
                })),
                rhs: Negate(Box::from(UnaryOpSpan {
                    expr: expr_integer(2, 1, 21),
                    pos: lc(1, 20),
                })),
                pos: lc(1, 17),
            })),
        );
    }

    #[test]
    fn test_expr_arith_ops() {
        use Expr::*;
        let span = Box::from(BinaryOpSpan {
            lhs: expr_integer(1, 1, 7),
            rhs: expr_integer(2, 1, 11),
            pos: lc(1, 9),
        });
        do_expr_ok_test("1 + 2", Add(span.clone()));
        do_expr_ok_test("1 - 2", Subtract(span.clone()));
        do_expr_ok_test("1 * 2", Multiply(span.clone()));
        do_expr_ok_test("1 / 2", Divide(span.clone()));
        do_expr_ok_test("1 ^ 2", Power(span));
        let span = Box::from(BinaryOpSpan {
            lhs: expr_integer(1, 1, 7),
            rhs: expr_integer(2, 1, 13),
            pos: lc(1, 9),
        });
        do_expr_ok_test("1 MOD 2", Modulo(span));
    }

    #[test]
    fn test_expr_rel_ops() {
        use Expr::*;
        let span1 = Box::from(BinaryOpSpan {
            lhs: expr_integer(1, 1, 7),
            rhs: expr_integer(2, 1, 11),
            pos: lc(1, 9),
        });
        let span2 = Box::from(BinaryOpSpan {
            lhs: expr_integer(1, 1, 7),
            rhs: expr_integer(2, 1, 12),
            pos: lc(1, 9),
        });
        do_expr_ok_test("1 = 2", Equal(span1.clone()));
        do_expr_ok_test("1 <> 2", NotEqual(span2.clone()));
        do_expr_ok_test("1 < 2", Less(span1.clone()));
        do_expr_ok_test("1 <= 2", LessEqual(span2.clone()));
        do_expr_ok_test("1 > 2", Greater(span1));
        do_expr_ok_test("1 >= 2", GreaterEqual(span2));
    }

    #[test]
    fn test_expr_logical_ops() {
        use Expr::*;
        do_expr_ok_test(
            "1 AND 2",
            And(Box::from(BinaryOpSpan {
                lhs: expr_integer(1, 1, 7),
                rhs: expr_integer(2, 1, 13),
                pos: lc(1, 9),
            })),
        );
        do_expr_ok_test(
            "1 OR 2",
            Or(Box::from(BinaryOpSpan {
                lhs: expr_integer(1, 1, 7),
                rhs: expr_integer(2, 1, 12),
                pos: lc(1, 9),
            })),
        );
        do_expr_ok_test(
            "1 XOR 2",
            Xor(Box::from(BinaryOpSpan {
                lhs: expr_integer(1, 1, 7),
                rhs: expr_integer(2, 1, 13),
                pos: lc(1, 9),
            })),
        );
    }

    #[test]
    fn test_expr_logical_ops_not() {
        use Expr::*;
        do_expr_ok_test(
            "NOT TRUE",
            Not(Box::from(UnaryOpSpan { expr: expr_boolean(true, 1, 11), pos: lc(1, 7) })),
        );
        do_expr_ok_test(
            "NOT 6",
            Not(Box::from(UnaryOpSpan { expr: expr_integer(6, 1, 11), pos: lc(1, 7) })),
        );
        do_expr_ok_test(
            "NOT NOT TRUE",
            Not(Box::from(UnaryOpSpan {
                expr: Not(Box::from(UnaryOpSpan {
                    expr: expr_boolean(true, 1, 15),
                    pos: lc(1, 11),
                })),
                pos: lc(1, 7),
            })),
        );
        do_expr_ok_test(
            "1 - NOT 4",
            Subtract(Box::from(BinaryOpSpan {
                lhs: expr_integer(1, 1, 7),
                rhs: Not(Box::from(UnaryOpSpan { expr: expr_integer(4, 1, 15), pos: lc(1, 11) })),
                pos: lc(1, 9),
            })),
        );
    }

    #[test]
    fn test_expr_bitwise_ops() {
        use Expr::*;
        do_expr_ok_test(
            "1 << 2",
            ShiftLeft(Box::from(BinaryOpSpan {
                lhs: expr_integer(1, 1, 7),
                rhs: expr_integer(2, 1, 12),
                pos: lc(1, 9),
            })),
        );
        do_expr_ok_test(
            "1 >> 2",
            ShiftRight(Box::from(BinaryOpSpan {
                lhs: expr_integer(1, 1, 7),
                rhs: expr_integer(2, 1, 12),
                pos: lc(1, 9),
            })),
        );
    }

    #[test]
    fn test_expr_op_priorities() {
        use Expr::*;
        do_expr_ok_test(
            "3 * (2 + 5) = (3 + 1 = 2 OR 1 = 3 XOR FALSE * \"a\")",
            Equal(Box::from(BinaryOpSpan {
                lhs: Multiply(Box::from(BinaryOpSpan {
                    lhs: expr_integer(3, 1, 7),
                    rhs: Add(Box::from(BinaryOpSpan {
                        lhs: expr_integer(2, 1, 12),
                        rhs: expr_integer(5, 1, 16),
                        pos: lc(1, 14),
                    })),
                    pos: lc(1, 9),
                })),
                rhs: Xor(Box::from(BinaryOpSpan {
                    lhs: Or(Box::from(BinaryOpSpan {
                        lhs: Equal(Box::from(BinaryOpSpan {
                            lhs: Add(Box::from(BinaryOpSpan {
                                lhs: expr_integer(3, 1, 22),
                                rhs: expr_integer(1, 1, 26),
                                pos: lc(1, 24),
                            })),
                            rhs: expr_integer(2, 1, 30),
                            pos: lc(1, 28),
                        })),
                        rhs: Equal(Box::from(BinaryOpSpan {
                            lhs: expr_integer(1, 1, 35),
                            rhs: expr_integer(3, 1, 39),
                            pos: lc(1, 37),
                        })),
                        pos: lc(1, 32),
                    })),
                    rhs: Multiply(Box::from(BinaryOpSpan {
                        lhs: expr_boolean(false, 1, 45),
                        rhs: expr_text("a", 1, 53),
                        pos: lc(1, 51),
                    })),
                    pos: lc(1, 41),
                })),
                pos: lc(1, 19),
            })),
        );
        do_expr_ok_test(
            "-1 ^ 3",
            Negate(Box::from(UnaryOpSpan {
                expr: Power(Box::from(BinaryOpSpan {
                    lhs: expr_integer(1, 1, 8),
                    rhs: expr_integer(3, 1, 12),
                    pos: lc(1, 10),
                })),
                pos: lc(1, 7),
            })),
        );
        do_expr_ok_test(
            "-(1 ^ 3)",
            Negate(Box::from(UnaryOpSpan {
                expr: Power(Box::from(BinaryOpSpan {
                    lhs: expr_integer(1, 1, 9),
                    rhs: expr_integer(3, 1, 13),
                    pos: lc(1, 11),
                })),
                pos: lc(1, 7),
            })),
        );
        do_expr_ok_test(
            "(-1) ^ 3",
            Power(Box::from(BinaryOpSpan {
                lhs: Negate(Box::from(UnaryOpSpan { expr: expr_integer(1, 1, 9), pos: lc(1, 8) })),
                rhs: expr_integer(3, 1, 14),
                pos: lc(1, 12),
            })),
        );
        do_expr_ok_test(
            "1 ^ (-3)",
            Power(Box::from(BinaryOpSpan {
                lhs: expr_integer(1, 1, 7),
                rhs: Negate(Box::from(UnaryOpSpan {
                    expr: expr_integer(3, 1, 13),
                    pos: lc(1, 12),
                })),
                pos: lc(1, 9),
            })),
        );
        do_expr_ok_test(
            "0 <> 2 >> 1",
            NotEqual(Box::from(BinaryOpSpan {
                lhs: expr_integer(0, 1, 7),
                rhs: ShiftRight(Box::from(BinaryOpSpan {
                    lhs: expr_integer(2, 1, 12),
                    rhs: expr_integer(1, 1, 17),
                    pos: lc(1, 14),
                })),
                pos: lc(1, 9),
            })),
        );
    }

    #[test]
    fn test_expr_numeric_signs() {
        use Expr::*;

        do_expr_ok_test(
            "-a",
            Negate(Box::from(UnaryOpSpan {
                expr: expr_symbol(VarRef::new("a", VarType::Auto), 1, 8),
                pos: lc(1, 7),
            })),
        );

        do_expr_ok_test(
            "1 - -3",
            Subtract(Box::from(BinaryOpSpan {
                lhs: expr_integer(1, 1, 7),
                rhs: Negate(Box::from(UnaryOpSpan {
                    expr: expr_integer(3, 1, 12),
                    pos: lc(1, 11),
                })),
                pos: lc(1, 9),
            })),
        );
        do_expr_ok_test(
            "-1 - 3",
            Subtract(Box::from(BinaryOpSpan {
                lhs: Negate(Box::from(UnaryOpSpan { expr: expr_integer(1, 1, 8), pos: lc(1, 7) })),
                rhs: expr_integer(3, 1, 12),
                pos: lc(1, 10),
            })),
        );
        do_expr_ok_test(
            "5 + -1",
            Add(Box::from(BinaryOpSpan {
                lhs: expr_integer(5, 1, 7),
                rhs: Negate(Box::from(UnaryOpSpan {
                    expr: expr_integer(1, 1, 12),
                    pos: lc(1, 11),
                })),
                pos: lc(1, 9),
            })),
        );
        do_expr_ok_test(
            "-5 + 1",
            Add(Box::from(BinaryOpSpan {
                lhs: Negate(Box::from(UnaryOpSpan { expr: expr_integer(5, 1, 8), pos: lc(1, 7) })),
                rhs: expr_integer(1, 1, 12),
                pos: lc(1, 10),
            })),
        );
        do_expr_ok_test(
            "NOT -3",
            Not(Box::from(UnaryOpSpan {
                expr: Negate(Box::from(UnaryOpSpan {
                    expr: expr_integer(3, 1, 12),
                    pos: lc(1, 11),
                })),
                pos: lc(1, 7),
            })),
        );

        do_expr_ok_test(
            "1.0 - -3.5",
            Subtract(Box::from(BinaryOpSpan {
                lhs: expr_double(1.0, 1, 7),
                rhs: Negate(Box::from(UnaryOpSpan {
                    expr: expr_double(3.5, 1, 14),
                    pos: lc(1, 13),
                })),
                pos: lc(1, 11),
            })),
        );
        do_expr_ok_test(
            "5.12 + -0.50",
            Add(Box::from(BinaryOpSpan {
                lhs: expr_double(5.12, 1, 7),
                rhs: Negate(Box::from(UnaryOpSpan {
                    expr: expr_double(0.50, 1, 15),
                    pos: lc(1, 14),
                })),
                pos: lc(1, 12),
            })),
        );
        do_expr_ok_test(
            "NOT -3",
            Not(Box::from(UnaryOpSpan {
                expr: Negate(Box::from(UnaryOpSpan {
                    expr: expr_integer(3, 1, 12),
                    pos: lc(1, 11),
                })),
                pos: lc(1, 7),
            })),
        );
    }

    #[test]
    fn test_expr_functions_variadic() {
        use Expr::*;
        do_expr_ok_test(
            "zero()",
            Call(FunctionCallSpan {
                fref: VarRef::new("zero", VarType::Auto),
                args: vec![],
                pos: lc(1, 7),
            }),
        );
        do_expr_ok_test(
            "one%(1)",
            Call(FunctionCallSpan {
                fref: VarRef::new("one", VarType::Integer),
                args: vec![expr_integer(1, 1, 12)],
                pos: lc(1, 7),
            }),
        );
        do_expr_ok_test(
            "many$(3, \"x\", TRUE)",
            Call(FunctionCallSpan {
                fref: VarRef::new("many", VarType::Text),
                args: vec![
                    expr_integer(3, 1, 13),
                    expr_text("x", 1, 16),
                    expr_boolean(true, 1, 21),
                ],
                pos: lc(1, 7),
            }),
        );
    }

    #[test]
    fn test_expr_functions_nested() {
        use Expr::*;
        do_expr_ok_test(
            "consecutive(parenthesis())",
            Call(FunctionCallSpan {
                fref: VarRef::new("consecutive", VarType::Auto),
                args: vec![Call(FunctionCallSpan {
                    fref: VarRef::new("parenthesis", VarType::Auto),
                    args: vec![],
                    pos: lc(1, 19),
                })],
                pos: lc(1, 7),
            }),
        );
        do_expr_ok_test(
            "outer?(1, inner1(2, 3), 4, inner2(), 5)",
            Call(FunctionCallSpan {
                fref: VarRef::new("outer", VarType::Boolean),
                args: vec![
                    expr_integer(1, 1, 14),
                    Call(FunctionCallSpan {
                        fref: VarRef::new("inner1", VarType::Auto),
                        args: vec![expr_integer(2, 1, 24), expr_integer(3, 1, 27)],
                        pos: lc(1, 17),
                    }),
                    expr_integer(4, 1, 31),
                    Call(FunctionCallSpan {
                        fref: VarRef::new("inner2", VarType::Auto),
                        args: vec![],
                        pos: lc(1, 34),
                    }),
                    expr_integer(5, 1, 44),
                ],
                pos: lc(1, 7),
            }),
        );
    }

    #[test]
    fn test_expr_functions_and_ops() {
        use Expr::*;
        do_expr_ok_test(
            "b AND ask?(34 + 15, ask(1, FALSE), -5)",
            And(Box::from(BinaryOpSpan {
                lhs: expr_symbol(VarRef::new("b".to_owned(), VarType::Auto), 1, 7),
                rhs: Call(FunctionCallSpan {
                    fref: VarRef::new("ask", VarType::Boolean),
                    args: vec![
                        Add(Box::from(BinaryOpSpan {
                            lhs: expr_integer(34, 1, 18),
                            rhs: expr_integer(15, 1, 23),
                            pos: lc(1, 21),
                        })),
                        Call(FunctionCallSpan {
                            fref: VarRef::new("ask", VarType::Auto),
                            args: vec![expr_integer(1, 1, 31), expr_boolean(false, 1, 34)],
                            pos: lc(1, 27),
                        }),
                        Negate(Box::from(UnaryOpSpan {
                            expr: expr_integer(5, 1, 43),
                            pos: lc(1, 42),
                        })),
                    ],
                    pos: lc(1, 13),
                }),
                pos: lc(1, 9),
            })),
        );
    }

    #[test]
    fn test_expr_functions_not_confused_with_symbols() {
        use Expr::*;
        let iref = VarRef::new("i", VarType::Auto);
        let jref = VarRef::new("j", VarType::Auto);
        do_expr_ok_test(
            "i = 0 OR i = (j - 1)",
            Or(Box::from(BinaryOpSpan {
                lhs: Equal(Box::from(BinaryOpSpan {
                    lhs: expr_symbol(iref.clone(), 1, 7),
                    rhs: expr_integer(0, 1, 11),
                    pos: lc(1, 9),
                })),
                rhs: Equal(Box::from(BinaryOpSpan {
                    lhs: expr_symbol(iref, 1, 16),
                    rhs: Subtract(Box::from(BinaryOpSpan {
                        lhs: expr_symbol(jref, 1, 21),
                        rhs: expr_integer(1, 1, 25),
                        pos: lc(1, 23),
                    })),
                    pos: lc(1, 18),
                })),
                pos: lc(1, 13),
            })),
        );
    }

    #[test]
    fn test_expr_errors() {
        // Note that all column numbers in the errors below are offset by 6 (due to "PRINT ") as
        // that's what the do_expr_error_test function is prefixing to the given strings.

        do_expr_error_test("+3", "1:7: Not enough values to apply operator");
        do_expr_error_test("2 + * 3", "1:9: Not enough values to apply operator");
        do_expr_error_test("(2(3))", "1:9: Unexpected ( in expression");
        do_expr_error_test("((3)2)", "1:11: Unexpected value in expression");
        do_expr_error_test("2 3", "1:9: Unexpected value in expression");

        do_expr_error_test("(", "1:8: Missing expression");

        do_expr_error_test(")", "1:7: Expected comma, semicolon, or end of statement");
        do_expr_error_test("(()", "1:8: Missing expression");
        do_expr_error_test("())", "1:7: Expected expression");
        do_expr_error_test("3 + (2 + 1) + (4 - 5", "1:21: Unbalanced parenthesis");
        do_expr_error_test(
            "3 + 2 + 1) + (4 - 5)",
            "1:16: Expected comma, semicolon, or end of statement",
        );

        do_expr_error_test("foo(,)", "1:11: Missing expression");
        do_expr_error_test("foo(, 3)", "1:11: Missing expression");
        do_expr_error_test("foo(3, )", "1:14: Missing expression");
        do_expr_error_test("foo(3, , 4)", "1:14: Missing expression");
        // TODO(jmmv): These are not the best error messages...
        do_expr_error_test("(,)", "1:8: Missing expression");
        do_expr_error_test("(3, 4)", "1:7: Expected expression");
        do_expr_error_test("((), ())", "1:8: Missing expression");

        // TODO(jmmv): This succeeds because `PRINT` is interned as a `Token::Symbol` so the
        // expression parser sees it as a variable reference... but this should probably fail.
        // Would need to intern builtin call names as a separate token to catch this, but that
        // also means that the lexer must be aware of builtin call names upfront.
        use Expr::*;
        do_expr_ok_test(
            "1 + PRINT",
            Add(Box::from(BinaryOpSpan {
                lhs: expr_integer(1, 1, 7),
                rhs: expr_symbol(VarRef::new("PRINT", VarType::Auto), 1, 11),
                pos: lc(1, 9),
            })),
        );
    }

    #[test]
    fn test_expr_errors_due_to_keywords() {
        for kw in &[
            "BOOLEAN", "CASE", "DATA", "DIM", "DOUBLE", "ELSEIF", "END", "ERROR", "EXIT", "FOR",
            "GOSUB", "GOTO", "IF", "IS", "INTEGER", "LOOP", "NEXT", "ON", "RESUME", "RETURN",
            "SELECT", "STRING", "UNTIL", "WEND", "WHILE",
        ] {
            do_expr_error_test(
                &format!("2 + {} - 1", kw),
                "1:11: Unexpected keyword in expression",
            );
        }
    }

    #[test]
    fn test_if_empty_branches() {
        do_ok_test(
            "IF 1 THEN\nEND IF",
            &[Statement::If(IfSpan {
                branches: vec![IfBranchSpan { guard: expr_integer(1, 1, 4), body: vec![] }],
            })],
        );
        do_ok_test(
            "IF 1 THEN\nREM Some comment to skip over\n\nEND IF",
            &[Statement::If(IfSpan {
                branches: vec![IfBranchSpan { guard: expr_integer(1, 1, 4), body: vec![] }],
            })],
        );
        do_ok_test(
            "IF 1 THEN\nELSEIF 2 THEN\nEND IF",
            &[Statement::If(IfSpan {
                branches: vec![
                    IfBranchSpan { guard: expr_integer(1, 1, 4), body: vec![] },
                    IfBranchSpan { guard: expr_integer(2, 2, 8), body: vec![] },
                ],
            })],
        );
        do_ok_test(
            "IF 1 THEN\nELSEIF 2 THEN\nELSE\nEND IF",
            &[Statement::If(IfSpan {
                branches: vec![
                    IfBranchSpan { guard: expr_integer(1, 1, 4), body: vec![] },
                    IfBranchSpan { guard: expr_integer(2, 2, 8), body: vec![] },
                    IfBranchSpan { guard: expr_boolean(true, 3, 1), body: vec![] },
                ],
            })],
        );
        do_ok_test(
            "IF 1 THEN\nELSE\nEND IF",
            &[Statement::If(IfSpan {
                branches: vec![
                    IfBranchSpan { guard: expr_integer(1, 1, 4), body: vec![] },
                    IfBranchSpan { guard: expr_boolean(true, 2, 1), body: vec![] },
                ],
            })],
        );
    }

    /// Helper to instantiate a trivial `Statement::BuiltinCall` that has no arguments.
    fn make_bare_builtin_call(name: &str, line: usize, col: usize) -> Statement {
        Statement::BuiltinCall(BuiltinCallSpan {
            name: name.to_owned(),
            name_pos: LineCol { line, col },
            args: vec![],
        })
    }

    #[test]
    fn test_if_with_one_statement_or_empty_lines() {
        do_ok_test(
            "IF 1 THEN\nPRINT\nEND IF",
            &[Statement::If(IfSpan {
                branches: vec![IfBranchSpan {
                    guard: expr_integer(1, 1, 4),
                    body: vec![make_bare_builtin_call("PRINT", 2, 1)],
                }],
            })],
        );
        do_ok_test(
            "IF 1 THEN\nREM foo\nELSEIF 2 THEN\nPRINT\nEND IF",
            &[Statement::If(IfSpan {
                branches: vec![
                    IfBranchSpan { guard: expr_integer(1, 1, 4), body: vec![] },
                    IfBranchSpan {
                        guard: expr_integer(2, 3, 8),
                        body: vec![make_bare_builtin_call("PRINT", 4, 1)],
                    },
                ],
            })],
        );
        do_ok_test(
            "IF 1 THEN\nELSEIF 2 THEN\nELSE\n\nPRINT\nEND IF",
            &[Statement::If(IfSpan {
                branches: vec![
                    IfBranchSpan { guard: expr_integer(1, 1, 4), body: vec![] },
                    IfBranchSpan { guard: expr_integer(2, 2, 8), body: vec![] },
                    IfBranchSpan {
                        guard: expr_boolean(true, 3, 1),
                        body: vec![make_bare_builtin_call("PRINT", 5, 1)],
                    },
                ],
            })],
        );
        do_ok_test(
            "IF 1 THEN\n\n\nELSE\nPRINT\nEND IF",
            &[Statement::If(IfSpan {
                branches: vec![
                    IfBranchSpan { guard: expr_integer(1, 1, 4), body: vec![] },
                    IfBranchSpan {
                        guard: expr_boolean(true, 4, 1),
                        body: vec![make_bare_builtin_call("PRINT", 5, 1)],
                    },
                ],
            })],
        );
    }

    #[test]
    fn test_if_complex() {
        let code = r#"
            IF 1 THEN 'First branch
                A
                B
            ELSEIF 2 THEN 'Second branch
                C
                D
            ELSEIF 3 THEN 'Third branch
                E
                F
            ELSE 'Last branch
                G
                H
            END IF
        "#;
        do_ok_test(
            code,
            &[Statement::If(IfSpan {
                branches: vec![
                    IfBranchSpan {
                        guard: expr_integer(1, 2, 16),
                        body: vec![
                            make_bare_builtin_call("A", 3, 17),
                            make_bare_builtin_call("B", 4, 17),
                        ],
                    },
                    IfBranchSpan {
                        guard: expr_integer(2, 5, 20),
                        body: vec![
                            make_bare_builtin_call("C", 6, 17),
                            make_bare_builtin_call("D", 7, 17),
                        ],
                    },
                    IfBranchSpan {
                        guard: expr_integer(3, 8, 20),
                        body: vec![
                            make_bare_builtin_call("E", 9, 17),
                            make_bare_builtin_call("F", 10, 17),
                        ],
                    },
                    IfBranchSpan {
                        guard: expr_boolean(true, 11, 13),
                        body: vec![
                            make_bare_builtin_call("G", 12, 17),
                            make_bare_builtin_call("H", 13, 17),
                        ],
                    },
                ],
            })],
        );
    }

    #[test]
    fn test_if_with_interleaved_end_complex() {
        let code = r#"
            IF 1 THEN 'First branch
                A
                END
                B
            ELSEIF 2 THEN 'Second branch
                C
                END 8
                D
            ELSEIF 3 THEN 'Third branch
                E
                END
                F
            ELSE 'Last branch
                G
                END 5
                H
            END IF
        "#;
        do_ok_test(
            code,
            &[Statement::If(IfSpan {
                branches: vec![
                    IfBranchSpan {
                        guard: expr_integer(1, 2, 16),
                        body: vec![
                            make_bare_builtin_call("A", 3, 17),
                            Statement::End(EndSpan { code: None }),
                            make_bare_builtin_call("B", 5, 17),
                        ],
                    },
                    IfBranchSpan {
                        guard: expr_integer(2, 6, 20),
                        body: vec![
                            make_bare_builtin_call("C", 7, 17),
                            Statement::End(EndSpan {
                                code: Some(Expr::Integer(IntegerSpan { value: 8, pos: lc(8, 21) })),
                            }),
                            make_bare_builtin_call("D", 9, 17),
                        ],
                    },
                    IfBranchSpan {
                        guard: expr_integer(3, 10, 20),
                        body: vec![
                            make_bare_builtin_call("E", 11, 17),
                            Statement::End(EndSpan { code: None }),
                            make_bare_builtin_call("F", 13, 17),
                        ],
                    },
                    IfBranchSpan {
                        guard: expr_boolean(true, 14, 13),
                        body: vec![
                            make_bare_builtin_call("G", 15, 17),
                            Statement::End(EndSpan {
                                code: Some(Expr::Integer(IntegerSpan {
                                    value: 5,
                                    pos: lc(16, 21),
                                })),
                            }),
                            make_bare_builtin_call("H", 17, 17),
                        ],
                    },
                ],
            })],
        );
    }

    #[test]
    fn test_if_nested() {
        let code = r#"
            IF 1 THEN
                A
            ELSEIF 2 THEN
                IF 3 THEN
                    B
                END IF
            END IF
        "#;
        do_ok_test(
            code,
            &[Statement::If(IfSpan {
                branches: vec![
                    IfBranchSpan {
                        guard: expr_integer(1, 2, 16),
                        body: vec![make_bare_builtin_call("A", 3, 17)],
                    },
                    IfBranchSpan {
                        guard: expr_integer(2, 4, 20),
                        body: vec![Statement::If(IfSpan {
                            branches: vec![IfBranchSpan {
                                guard: expr_integer(3, 5, 20),
                                body: vec![make_bare_builtin_call("B", 6, 21)],
                            }],
                        })],
                    },
                ],
            })],
        );
    }

    #[test]
    fn test_if_errors() {
        do_error_test("IF\n", "1:3: No expression in IF statement");
        do_error_test("IF 3 + 1", "1:9: No THEN in IF statement");
        do_error_test("IF 3 + 1\n", "1:9: No THEN in IF statement");
        do_error_test("IF 3 + 1 PRINT foo\n", "1:10: Unexpected value in expression");
        do_error_test("IF 3 + 1\nPRINT foo\n", "1:9: No THEN in IF statement");
        do_error_test("IF 3 + 1 THEN", "1:1: IF without END IF");

        do_error_test("IF 1 THEN\n", "1:1: IF without END IF");
        do_error_test("IF 1 THEN\nELSEIF 1 THEN\n", "1:1: IF without END IF");
        do_error_test("IF 1 THEN\nELSE\n", "1:1: IF without END IF");
        do_error_test("REM\n   IF 1 THEN\n", "2:4: IF without END IF");

        do_error_test("IF 1 THEN\nELSEIF\n", "2:7: No expression in ELSEIF statement");
        do_error_test("IF 1 THEN\nELSEIF 3 + 1", "2:13: No THEN in ELSEIF statement");
        do_error_test("IF 1 THEN\nELSEIF 3 + 1\n", "2:13: No THEN in ELSEIF statement");
        do_error_test(
            "IF 1 THEN\nELSEIF 3 + 1 PRINT foo\n",
            "2:14: Unexpected value in expression",
        );
        do_error_test("IF 1 THEN\nELSEIF 3 + 1\nPRINT foo\n", "2:13: No THEN in ELSEIF statement");
        do_error_test("IF 1 THEN\nELSEIF 3 + 1 THEN", "2:18: Expecting newline after THEN");

        do_error_test("IF 1 THEN\nELSE", "2:5: Expecting newline after ELSE");
        do_error_test("IF 1 THEN\nELSE foo", "2:6: Expecting newline after ELSE");

        do_error_test("IF 1 THEN\nEND", "1:1: IF without END IF");
        do_error_test("IF 1 THEN\nEND\n", "1:1: IF without END IF");
        do_error_test("IF 1 THEN\nEND IF foo", "2:8: Expected newline but found foo");
        do_error_test("IF 1 THEN\nEND SELECT\n", "2:1: END SELECT without SELECT");
        do_error_test("IF 1 THEN\nEND SELECT\nEND IF\n", "2:1: END SELECT without SELECT");

        do_error_test(
            "IF 1 THEN\nELSE\nELSEIF 2 THEN\nEND IF",
            "3:1: Unexpected ELSEIF after ELSE",
        );
        do_error_test("IF 1 THEN\nELSE\nELSE\nEND IF", "3:1: Duplicate ELSE after ELSE");

        do_error_test_no_reset("ELSEIF 1 THEN\nEND IF", "1:1: Unexpected ELSEIF in statement");
        do_error_test_no_reset("ELSE 1\nEND IF", "1:1: Unexpected ELSE in statement");

        do_error_test("IF 1 THEN\nEND 3 IF", "2:7: Unexpected keyword in expression");
        do_error_test("END 3 IF", "1:7: Unexpected keyword in expression");
        do_error_test("END IF", "1:1: END IF without IF");

        do_error_test("IF TRUE THEN PRINT ELSE ELSE", "1:25: Unexpected ELSE in uniline IF branch");
    }

    #[test]
    fn test_if_uniline_then() {
        do_ok_test(
            "IF 1 THEN A",
            &[Statement::If(IfSpan {
                branches: vec![IfBranchSpan {
                    guard: expr_integer(1, 1, 4),
                    body: vec![make_bare_builtin_call("A", 1, 11)],
                }],
            })],
        );
    }

    #[test]
    fn test_if_uniline_then_else() {
        do_ok_test(
            "IF 1 THEN A ELSE B",
            &[Statement::If(IfSpan {
                branches: vec![
                    IfBranchSpan {
                        guard: expr_integer(1, 1, 4),
                        body: vec![make_bare_builtin_call("A", 1, 11)],
                    },
                    IfBranchSpan {
                        guard: expr_boolean(true, 1, 13),
                        body: vec![make_bare_builtin_call("B", 1, 18)],
                    },
                ],
            })],
        );
    }

    #[test]
    fn test_if_uniline_empty_then_else() {
        do_ok_test(
            "IF 1 THEN ELSE B",
            &[Statement::If(IfSpan {
                branches: vec![
                    IfBranchSpan { guard: expr_integer(1, 1, 4), body: vec![] },
                    IfBranchSpan {
                        guard: expr_boolean(true, 1, 11),
                        body: vec![make_bare_builtin_call("B", 1, 16)],
                    },
                ],
            })],
        );
    }

    #[test]
    fn test_if_uniline_then_empty_else() {
        do_ok_test(
            "IF 1 THEN A ELSE",
            &[Statement::If(IfSpan {
                branches: vec![
                    IfBranchSpan {
                        guard: expr_integer(1, 1, 4),
                        body: vec![make_bare_builtin_call("A", 1, 11)],
                    },
                    IfBranchSpan { guard: expr_boolean(true, 1, 13), body: vec![] },
                ],
            })],
        );
    }

    #[test]
    fn test_if_uniline_empty_then_empty_else() {
        do_ok_test(
            "IF 1 THEN ELSE",
            &[Statement::If(IfSpan {
                branches: vec![
                    IfBranchSpan { guard: expr_integer(1, 1, 4), body: vec![] },
                    IfBranchSpan { guard: expr_boolean(true, 1, 11), body: vec![] },
                ],
            })],
        );
    }

    /// Performs a test of a uniline if statement followed by a specific allowed statement type.
    ///
    /// `text` is the literal statement to append to the if statement, and `stmt` contains the
    /// expected parsed statement.  The expected positions for the parsed statement are line 1 and
    /// columns offset by 11 characters.
    fn do_if_uniline_allowed_test(text: &str, stmt: Statement) {
        do_ok_test(
            &format!("IF 1 THEN {}\nZ", text),
            &[
                Statement::If(IfSpan {
                    branches: vec![IfBranchSpan { guard: expr_integer(1, 1, 4), body: vec![stmt] }],
                }),
                make_bare_builtin_call("Z", 2, 1),
            ],
        );
    }

    #[test]
    fn test_if_uniline_allowed_data() {
        do_if_uniline_allowed_test("DATA", Statement::Data(DataSpan { values: vec![None] }));
    }

    #[test]
    fn test_if_uniline_allowed_end() {
        do_if_uniline_allowed_test(
            "END 8",
            Statement::End(EndSpan { code: Some(expr_integer(8, 1, 15)) }),
        );
    }

    #[test]
    fn test_if_uniline_allowed_exit() {
        do_if_uniline_allowed_test("EXIT DO", Statement::ExitDo(ExitDoSpan { pos: lc(1, 11) }));

        do_error_test("IF 1 THEN EXIT", "1:15: Expecting DO after EXIT");
    }

    #[test]
    fn test_if_uniline_allowed_gosub() {
        do_if_uniline_allowed_test(
            "GOSUB 10",
            Statement::Gosub(GotoSpan { target: "10".to_owned(), target_pos: lc(1, 17) }),
        );

        do_error_test("IF 1 THEN GOSUB", "1:16: Expected label name after GOSUB");
    }

    #[test]
    fn test_if_uniline_allowed_goto() {
        do_if_uniline_allowed_test(
            "GOTO 10",
            Statement::Goto(GotoSpan { target: "10".to_owned(), target_pos: lc(1, 16) }),
        );

        do_error_test("IF 1 THEN GOTO", "1:15: Expected label name after GOTO");
    }

    #[test]
    fn test_if_uniline_allowed_on_error() {
        do_if_uniline_allowed_test(
            "ON ERROR RESUME NEXT",
            Statement::OnError(OnErrorSpan::ResumeNext),
        );

        do_error_test("IF 1 THEN ON", "1:13: Expected ERROR after ON");
    }

    #[test]
    fn test_if_uniline_allowed_return() {
        do_if_uniline_allowed_test("RETURN", Statement::Return(ReturnSpan { pos: lc(1, 11) }));
    }

    #[test]
    fn test_if_uniline_allowed_assignment() {
        do_if_uniline_allowed_test(
            "a = 3",
            Statement::Assignment(AssignmentSpan {
                vref: VarRef::new("a", VarType::Auto),
                vref_pos: lc(1, 11),
                expr: expr_integer(3, 1, 15),
            }),
        );
    }

    #[test]
    fn test_if_uniline_allowed_array_assignment() {
        do_if_uniline_allowed_test(
            "a(3) = 5",
            Statement::ArrayAssignment(ArrayAssignmentSpan {
                vref: VarRef::new("a", VarType::Auto),
                vref_pos: lc(1, 11),
                subscripts: vec![expr_integer(3, 1, 13)],
                expr: expr_integer(5, 1, 18),
            }),
        );
    }

    #[test]
    fn test_if_uniline_allowed_builtin_call() {
        do_if_uniline_allowed_test(
            "a 0",
            Statement::BuiltinCall(BuiltinCallSpan {
                name: "A".to_owned(),
                name_pos: lc(1, 11),
                args: vec![ArgSpan {
                    expr: Some(expr_integer(0, 1, 13)),
                    sep: ArgSep::End,
                    sep_pos: lc(1, 14),
                }],
            }),
        );
    }

    #[test]
    fn test_if_uniline_unallowed_statements() {
        for t in ["DIM", "DO", "IF", "FOR", "10", "@label", "SELECT", "WHILE"] {
            do_error_test(
                &format!("IF 1 THEN {}", t),
                &format!("1:11: Unexpected {} in uniline IF branch", t),
            );
        }
    }

    #[test]
    fn test_for_empty() {
        let auto_iter = VarRef::new("i", VarType::Auto);
        do_ok_test(
            "FOR i = 1 TO 10\nNEXT",
            &[Statement::For(ForSpan {
                iter: auto_iter.clone(),
                iter_pos: lc(1, 5),
                iter_double: false,
                start: expr_integer(1, 1, 9),
                end: Expr::LessEqual(Box::from(BinaryOpSpan {
                    lhs: expr_symbol(auto_iter.clone(), 1, 5),
                    rhs: expr_integer(10, 1, 14),
                    pos: lc(1, 11),
                })),
                next: Expr::Add(Box::from(BinaryOpSpan {
                    lhs: expr_symbol(auto_iter, 1, 5),
                    rhs: expr_integer(1, 1, 16),
                    pos: lc(1, 11),
                })),
                body: vec![],
            })],
        );

        let typed_iter = VarRef::new("d", VarType::Double);
        do_ok_test(
            "FOR d# = 1.0 TO 10.2\nREM Nothing to do\nNEXT",
            &[Statement::For(ForSpan {
                iter: typed_iter.clone(),
                iter_pos: lc(1, 5),
                iter_double: false,
                start: expr_double(1.0, 1, 10),
                end: Expr::LessEqual(Box::from(BinaryOpSpan {
                    lhs: expr_symbol(typed_iter.clone(), 1, 5),
                    rhs: expr_double(10.2, 1, 17),
                    pos: lc(1, 14),
                })),
                next: Expr::Add(Box::from(BinaryOpSpan {
                    lhs: expr_symbol(typed_iter, 1, 5),
                    rhs: expr_integer(1, 1, 21),
                    pos: lc(1, 14),
                })),
                body: vec![],
            })],
        );
    }

    #[test]
    fn test_for_incrementing() {
        let iter = VarRef::new("i", VarType::Auto);
        do_ok_test(
            "FOR i = 0 TO 5\nA\nB\nNEXT",
            &[Statement::For(ForSpan {
                iter: iter.clone(),
                iter_pos: lc(1, 5),
                iter_double: false,
                start: expr_integer(0, 1, 9),
                end: Expr::LessEqual(Box::from(BinaryOpSpan {
                    lhs: expr_symbol(iter.clone(), 1, 5),
                    rhs: expr_integer(5, 1, 14),
                    pos: lc(1, 11),
                })),
                next: Expr::Add(Box::from(BinaryOpSpan {
                    lhs: expr_symbol(iter, 1, 5),
                    rhs: expr_integer(1, 1, 15),
                    pos: lc(1, 11),
                })),
                body: vec![make_bare_builtin_call("A", 2, 1), make_bare_builtin_call("B", 3, 1)],
            })],
        );
    }

    #[test]
    fn test_for_incrementing_with_step() {
        let iter = VarRef::new("i", VarType::Auto);
        do_ok_test(
            "FOR i = 0 TO 5 STEP 2\nA\nNEXT",
            &[Statement::For(ForSpan {
                iter: iter.clone(),
                iter_pos: lc(1, 5),
                iter_double: false,
                start: expr_integer(0, 1, 9),
                end: Expr::LessEqual(Box::from(BinaryOpSpan {
                    lhs: expr_symbol(iter.clone(), 1, 5),
                    rhs: expr_integer(5, 1, 14),
                    pos: lc(1, 11),
                })),
                next: Expr::Add(Box::from(BinaryOpSpan {
                    lhs: expr_symbol(iter, 1, 5),
                    rhs: expr_integer(2, 1, 21),
                    pos: lc(1, 11),
                })),
                body: vec![make_bare_builtin_call("A", 2, 1)],
            })],
        );

        let iter = VarRef::new("i", VarType::Auto);
        do_ok_test(
            "FOR i = 0 TO 5 STEP 2.5\nA\nNEXT",
            &[Statement::For(ForSpan {
                iter: iter.clone(),
                iter_pos: lc(1, 5),
                iter_double: true,
                start: expr_integer(0, 1, 9),
                end: Expr::LessEqual(Box::from(BinaryOpSpan {
                    lhs: expr_symbol(iter.clone(), 1, 5),
                    rhs: expr_integer(5, 1, 14),
                    pos: lc(1, 11),
                })),
                next: Expr::Add(Box::from(BinaryOpSpan {
                    lhs: expr_symbol(iter, 1, 5),
                    rhs: expr_double(2.5, 1, 21),
                    pos: lc(1, 11),
                })),
                body: vec![make_bare_builtin_call("A", 2, 1)],
            })],
        );
    }

    #[test]
    fn test_for_decrementing_with_step() {
        let iter = VarRef::new("i", VarType::Auto);
        do_ok_test(
            "FOR i = 5 TO 0 STEP -1\nA\nNEXT",
            &[Statement::For(ForSpan {
                iter: iter.clone(),
                iter_pos: lc(1, 5),
                iter_double: false,
                start: expr_integer(5, 1, 9),
                end: Expr::GreaterEqual(Box::from(BinaryOpSpan {
                    lhs: expr_symbol(iter.clone(), 1, 5),
                    rhs: expr_integer(0, 1, 14),
                    pos: lc(1, 11),
                })),
                next: Expr::Add(Box::from(BinaryOpSpan {
                    lhs: expr_symbol(iter, 1, 5),
                    rhs: expr_integer(-1, 1, 22),
                    pos: lc(1, 11),
                })),
                body: vec![make_bare_builtin_call("A", 2, 1)],
            })],
        );

        let iter = VarRef::new("i", VarType::Auto);
        do_ok_test(
            "FOR i = 5 TO 0 STEP -1.2\nA\nNEXT",
            &[Statement::For(ForSpan {
                iter: iter.clone(),
                iter_pos: lc(1, 5),
                iter_double: true,
                start: expr_integer(5, 1, 9),
                end: Expr::GreaterEqual(Box::from(BinaryOpSpan {
                    lhs: expr_symbol(iter.clone(), 1, 5),
                    rhs: expr_integer(0, 1, 14),
                    pos: lc(1, 11),
                })),
                next: Expr::Add(Box::from(BinaryOpSpan {
                    lhs: expr_symbol(iter, 1, 5),
                    rhs: expr_double(-1.2, 1, 22),
                    pos: lc(1, 11),
                })),
                body: vec![make_bare_builtin_call("A", 2, 1)],
            })],
        );
    }

    #[test]
    fn test_for_errors() {
        do_error_test("FOR\n", "1:4: No iterator name in FOR statement");
        do_error_test("FOR =\n", "1:5: No iterator name in FOR statement");
        do_error_test(
            "FOR a$\n",
            "1:5: Iterator name in FOR statement must be a numeric reference",
        );

        do_error_test("FOR d#\n", "1:7: No equal sign in FOR statement");
        do_error_test("FOR i 3\n", "1:7: No equal sign in FOR statement");
        do_error_test("FOR i = TO\n", "1:9: No start expression in FOR statement");
        do_error_test("FOR i = NEXT\n", "1:9: Unexpected keyword in expression");

        do_error_test("FOR i = 3 STEP\n", "1:11: No TO in FOR statement");
        do_error_test("FOR i = 3 TO STEP\n", "1:14: No end expression in FOR statement");
        do_error_test("FOR i = 3 TO NEXT\n", "1:14: Unexpected keyword in expression");

        do_error_test("FOR i = 3 TO 1 STEP a\n", "1:21: STEP needs a literal number");
        do_error_test("FOR i = 3 TO 1 STEP -a\n", "1:22: STEP needs a literal number");
        do_error_test("FOR i = 3 TO 1 STEP NEXT\n", "1:21: STEP needs a literal number");
        do_error_test("FOR i = 3 TO 1 STEP 0\n", "1:21: Infinite FOR loop; STEP cannot be 0");
        do_error_test("FOR i = 3 TO 1 STEP 0.0\n", "1:21: Infinite FOR loop; STEP cannot be 0");

        do_error_test("FOR i = 3 TO 1", "1:15: Expecting newline after FOR");
        do_error_test("FOR i = 1 TO 3 STEP 1", "1:22: Expecting newline after FOR");
        do_error_test("FOR i = 3 TO 1 STEP -1", "1:23: Expecting newline after FOR");

        do_error_test("    FOR i = 0 TO 10\nPRINT i\n", "1:5: FOR without NEXT");
    }

    #[test]
    fn test_gosub_ok() {
        do_ok_test(
            "GOSUB 10",
            &[Statement::Gosub(GotoSpan { target: "10".to_owned(), target_pos: lc(1, 7) })],
        );

        do_ok_test(
            "GOSUB @foo",
            &[Statement::Gosub(GotoSpan { target: "foo".to_owned(), target_pos: lc(1, 7) })],
        );
    }

    #[test]
    fn test_gosub_errors() {
        do_error_test("GOSUB\n", "1:6: Expected label name after GOSUB");
        do_error_test("GOSUB foo\n", "1:7: Expected label name after GOSUB");
        do_error_test("GOSUB \"foo\"\n", "1:7: Expected label name after GOSUB");
        do_error_test("GOSUB @foo, @bar\n", "1:11: Expected newline but found ,");
        do_error_test("GOSUB @foo, 3\n", "1:11: Expected newline but found ,");
    }

    #[test]
    fn test_goto_ok() {
        do_ok_test(
            "GOTO 10",
            &[Statement::Goto(GotoSpan { target: "10".to_owned(), target_pos: lc(1, 6) })],
        );

        do_ok_test(
            "GOTO @foo",
            &[Statement::Goto(GotoSpan { target: "foo".to_owned(), target_pos: lc(1, 6) })],
        );
    }

    #[test]
    fn test_goto_errors() {
        do_error_test("GOTO\n", "1:5: Expected label name after GOTO");
        do_error_test("GOTO foo\n", "1:6: Expected label name after GOTO");
        do_error_test("GOTO \"foo\"\n", "1:6: Expected label name after GOTO");
        do_error_test("GOTO @foo, @bar\n", "1:10: Expected newline but found ,");
        do_error_test("GOTO @foo, 3\n", "1:10: Expected newline but found ,");
    }

    #[test]
    fn test_label_own_line() {
        do_ok_test(
            "@foo\nPRINT",
            &[
                Statement::Label(LabelSpan { name: "foo".to_owned(), name_pos: lc(1, 1) }),
                make_bare_builtin_call("PRINT", 2, 1),
            ],
        );
    }

    #[test]
    fn test_label_before_statement() {
        do_ok_test(
            "@foo PRINT",
            &[
                Statement::Label(LabelSpan { name: "foo".to_owned(), name_pos: lc(1, 1) }),
                make_bare_builtin_call("PRINT", 1, 6),
            ],
        );
    }

    #[test]
    fn test_label_multiple_same_line() {
        do_ok_test(
            "@foo @bar",
            &[
                Statement::Label(LabelSpan { name: "foo".to_owned(), name_pos: lc(1, 1) }),
                Statement::Label(LabelSpan { name: "bar".to_owned(), name_pos: lc(1, 6) }),
            ],
        );
    }

    #[test]
    fn test_label_errors() {
        do_error_test("PRINT @foo", "1:7: Unexpected keyword in expression");
    }

    #[test]
    fn test_parse_on_error_ok() {
        do_ok_test("ON ERROR GOTO 0", &[Statement::OnError(OnErrorSpan::Reset)]);

        do_ok_test(
            "ON ERROR GOTO 10",
            &[Statement::OnError(OnErrorSpan::Goto(GotoSpan {
                target: "10".to_owned(),
                target_pos: lc(1, 15),
            }))],
        );

        do_ok_test(
            "ON ERROR GOTO @foo",
            &[Statement::OnError(OnErrorSpan::Goto(GotoSpan {
                target: "foo".to_owned(),
                target_pos: lc(1, 15),
            }))],
        );

        do_ok_test("ON ERROR RESUME NEXT", &[Statement::OnError(OnErrorSpan::ResumeNext)]);
    }

    #[test]
    fn test_parse_on_error_errors() {
        do_error_test("ON", "1:3: Expected ERROR after ON");
        do_error_test("ON NEXT", "1:4: Expected ERROR after ON");
        do_error_test("ON ERROR", "1:9: Expected GOTO or RESUME after ON ERROR");
        do_error_test("ON ERROR FOR", "1:10: Expected GOTO or RESUME after ON ERROR");

        do_error_test("ON ERROR RESUME", "1:16: Expected NEXT after ON ERROR RESUME");
        do_error_test("ON ERROR RESUME 3", "1:17: Expected NEXT after ON ERROR RESUME");
        do_error_test("ON ERROR RESUME NEXT 3", "1:22: Expected newline but found 3");

        do_error_test("ON ERROR GOTO", "1:14: Expected label name or 0 after ON ERROR GOTO");
        do_error_test("ON ERROR GOTO NEXT", "1:15: Expected label name or 0 after ON ERROR GOTO");
        do_error_test("ON ERROR GOTO 0 @a", "1:17: Expected newline but found @a");
    }

    #[test]
    fn test_select_empty() {
        do_ok_test(
            "SELECT CASE 7\nEND SELECT",
            &[Statement::Select(SelectSpan {
                expr: expr_integer(7, 1, 13),
                cases: vec![],
                end_pos: lc(2, 1),
            })],
        );

        do_ok_test(
            "SELECT CASE 5 - TRUE\n    \nEND SELECT",
            &[Statement::Select(SelectSpan {
                expr: Expr::Subtract(Box::from(BinaryOpSpan {
                    lhs: expr_integer(5, 1, 13),
                    rhs: expr_boolean(true, 1, 17),
                    pos: lc(1, 15),
                })),
                cases: vec![],
                end_pos: lc(3, 1),
            })],
        );
    }

    #[test]
    fn test_select_case_else_only() {
        do_ok_test(
            "SELECT CASE 7\nCASE ELSE\nA\nEND SELECT",
            &[Statement::Select(SelectSpan {
                expr: expr_integer(7, 1, 13),
                cases: vec![CaseSpan {
                    guards: vec![],
                    body: vec![make_bare_builtin_call("A", 3, 1)],
                }],
                end_pos: lc(4, 1),
            })],
        );
    }

    #[test]
    fn test_select_multiple_cases_without_else() {
        do_ok_test(
            "SELECT CASE 7\nCASE 1\nA\nCASE 2\nB\nEND SELECT",
            &[Statement::Select(SelectSpan {
                expr: expr_integer(7, 1, 13),
                cases: vec![
                    CaseSpan {
                        guards: vec![CaseGuardSpan::Is(CaseRelOp::Equal, expr_integer(1, 2, 6))],
                        body: vec![make_bare_builtin_call("A", 3, 1)],
                    },
                    CaseSpan {
                        guards: vec![CaseGuardSpan::Is(CaseRelOp::Equal, expr_integer(2, 4, 6))],
                        body: vec![make_bare_builtin_call("B", 5, 1)],
                    },
                ],
                end_pos: lc(6, 1),
            })],
        );
    }

    #[test]
    fn test_select_multiple_cases_with_else() {
        do_ok_test(
            "SELECT CASE 7\nCASE 1\nA\nCASE 2\nB\nCASE ELSE\nC\nEND SELECT",
            &[Statement::Select(SelectSpan {
                expr: expr_integer(7, 1, 13),
                cases: vec![
                    CaseSpan {
                        guards: vec![CaseGuardSpan::Is(CaseRelOp::Equal, expr_integer(1, 2, 6))],
                        body: vec![make_bare_builtin_call("A", 3, 1)],
                    },
                    CaseSpan {
                        guards: vec![CaseGuardSpan::Is(CaseRelOp::Equal, expr_integer(2, 4, 6))],
                        body: vec![make_bare_builtin_call("B", 5, 1)],
                    },
                    CaseSpan { guards: vec![], body: vec![make_bare_builtin_call("C", 7, 1)] },
                ],
                end_pos: lc(8, 1),
            })],
        );
    }

    #[test]
    fn test_select_multiple_cases_empty_bodies() {
        do_ok_test(
            "SELECT CASE 7\nCASE 1\n\nCASE 2\n\nCASE ELSE\n\nEND SELECT",
            &[Statement::Select(SelectSpan {
                expr: expr_integer(7, 1, 13),
                cases: vec![
                    CaseSpan {
                        guards: vec![CaseGuardSpan::Is(CaseRelOp::Equal, expr_integer(1, 2, 6))],
                        body: vec![],
                    },
                    CaseSpan {
                        guards: vec![CaseGuardSpan::Is(CaseRelOp::Equal, expr_integer(2, 4, 6))],
                        body: vec![],
                    },
                    CaseSpan { guards: vec![], body: vec![] },
                ],
                end_pos: lc(8, 1),
            })],
        );
    }

    #[test]
    fn test_select_multiple_cases_with_interleaved_end() {
        let code = r#"
            SELECT CASE 7
                CASE 1
                    A
                    END
                    B
                CASE 2 ' Second case.
                    C
                    END 8
                    D
                CASE ELSE
                    E
                    END
                    F
            END SELECT
        "#;
        do_ok_test(
            code,
            &[Statement::Select(SelectSpan {
                expr: expr_integer(7, 2, 25),
                cases: vec![
                    CaseSpan {
                        guards: vec![CaseGuardSpan::Is(CaseRelOp::Equal, expr_integer(1, 3, 22))],
                        body: vec![
                            make_bare_builtin_call("A", 4, 21),
                            Statement::End(EndSpan { code: None }),
                            make_bare_builtin_call("B", 6, 21),
                        ],
                    },
                    CaseSpan {
                        guards: vec![CaseGuardSpan::Is(CaseRelOp::Equal, expr_integer(2, 7, 22))],
                        body: vec![
                            make_bare_builtin_call("C", 8, 21),
                            Statement::End(EndSpan {
                                code: Some(Expr::Integer(IntegerSpan { value: 8, pos: lc(9, 25) })),
                            }),
                            make_bare_builtin_call("D", 10, 21),
                        ],
                    },
                    CaseSpan {
                        guards: vec![],
                        body: vec![
                            make_bare_builtin_call("E", 12, 21),
                            Statement::End(EndSpan { code: None }),
                            make_bare_builtin_call("F", 14, 21),
                        ],
                    },
                ],
                end_pos: lc(15, 13),
            })],
        );
    }

    #[test]
    fn test_select_case_guards_equals() {
        do_ok_test(
            "SELECT CASE 7: CASE 9, 10, FALSE: END SELECT",
            &[Statement::Select(SelectSpan {
                expr: expr_integer(7, 1, 13),
                cases: vec![CaseSpan {
                    guards: vec![
                        CaseGuardSpan::Is(CaseRelOp::Equal, expr_integer(9, 1, 21)),
                        CaseGuardSpan::Is(CaseRelOp::Equal, expr_integer(10, 1, 24)),
                        CaseGuardSpan::Is(CaseRelOp::Equal, expr_boolean(false, 1, 28)),
                    ],
                    body: vec![],
                }],
                end_pos: lc(1, 35),
            })],
        );
    }

    #[test]
    fn test_select_case_guards_is() {
        do_ok_test(
            "SELECT CASE 7: CASE IS = 1, IS <> 2, IS < 3, IS <= 4, IS > 5, IS >= 6: END SELECT",
            &[Statement::Select(SelectSpan {
                expr: expr_integer(7, 1, 13),
                cases: vec![CaseSpan {
                    guards: vec![
                        CaseGuardSpan::Is(CaseRelOp::Equal, expr_integer(1, 1, 26)),
                        CaseGuardSpan::Is(CaseRelOp::NotEqual, expr_integer(2, 1, 35)),
                        CaseGuardSpan::Is(CaseRelOp::Less, expr_integer(3, 1, 43)),
                        CaseGuardSpan::Is(CaseRelOp::LessEqual, expr_integer(4, 1, 52)),
                        CaseGuardSpan::Is(CaseRelOp::Greater, expr_integer(5, 1, 60)),
                        CaseGuardSpan::Is(CaseRelOp::GreaterEqual, expr_integer(6, 1, 69)),
                    ],
                    body: vec![],
                }],
                end_pos: lc(1, 72),
            })],
        );
    }

    #[test]
    fn test_select_case_guards_to() {
        do_ok_test(
            "SELECT CASE 7: CASE 1 TO 20, 10 TO 1: END SELECT",
            &[Statement::Select(SelectSpan {
                expr: expr_integer(7, 1, 13),
                cases: vec![CaseSpan {
                    guards: vec![
                        CaseGuardSpan::To(expr_integer(1, 1, 21), expr_integer(20, 1, 26)),
                        CaseGuardSpan::To(expr_integer(10, 1, 30), expr_integer(1, 1, 36)),
                    ],
                    body: vec![],
                }],
                end_pos: lc(1, 39),
            })],
        );
    }

    #[test]
    fn test_select_errors() {
        do_error_test("SELECT\n", "1:7: Expecting CASE after SELECT");
        do_error_test("SELECT CASE\n", "1:12: No expression in SELECT CASE statement");
        do_error_test("SELECT CASE 3 + 7", "1:18: Expecting newline after SELECT CASE");
        do_error_test("SELECT CASE 3 + 7 ,", "1:19: Expecting newline after SELECT CASE");
        do_error_test("SELECT CASE 3 + 7 IF", "1:19: Unexpected keyword in expression");

        do_error_test("SELECT CASE 1\n", "1:1: SELECT without END SELECT");

        do_error_test(
            "SELECT CASE 1\nEND",
            "2:1: Expected CASE after SELECT CASE before any statement",
        );
        do_error_test(
            "SELECT CASE 1\nEND IF",
            "2:1: Expected CASE after SELECT CASE before any statement",
        );
        do_error_test(
            "SELECT CASE 1\na = 1",
            "2:1: Expected CASE after SELECT CASE before any statement",
        );

        do_error_test(
            "SELECT CASE 1\nCASE 1",
            "2:7: Expected comma, newline, or TO after expression",
        );
        do_error_test("SELECT CASE 1\nCASE ELSE", "2:10: Expecting newline after CASE");

        do_error_test("SELECT CASE 1\nCASE ELSE\nEND", "1:1: SELECT without END SELECT");
        do_error_test("SELECT CASE 1\nCASE ELSE\nEND IF", "3:1: END IF without IF");

        do_error_test("SELECT CASE 1\nCASE ELSE\nCASE ELSE\n", "3:1: CASE ELSE must be unique");
        do_error_test("SELECT CASE 1\nCASE ELSE\nCASE 1\n", "3:1: CASE ELSE is not last");
    }

    #[test]
    fn test_select_case_errors() {
        fn do_case_error_test(cases: &str, exp_error: &str) {
            do_error_test(&format!("SELECT CASE 1\nCASE {}\n", cases), exp_error);
        }

        do_case_error_test("ELSE, ELSE", "2:10: Expected newline after CASE ELSE");
        do_case_error_test("ELSE, 7", "2:10: Expected newline after CASE ELSE");
        do_case_error_test("7, ELSE", "2:9: CASE ELSE must be on its own");

        do_case_error_test("IS 7", "2:9: Expected relational operator");
        do_case_error_test("IS AND", "2:9: Expected relational operator");
        do_case_error_test("IS END", "2:9: Expected relational operator");

        do_case_error_test("IS <>", "2:11: Missing expression after relational operator");
        do_case_error_test("IS <> IF", "2:12: Unexpected keyword in expression");

        do_case_error_test("", "2:6: Missing expression in CASE guard");
        do_case_error_test("2 + 5 TO", "2:14: Missing expression after TO in CASE guard");
        do_case_error_test("2 + 5 TO AS", "2:15: Missing expression after TO in CASE guard");
        do_case_error_test(
            "2 + 5 TO 8 AS",
            "2:17: Expected comma, newline, or TO after expression",
        );
    }

    #[test]
    fn test_while_empty() {
        do_ok_test(
            "WHILE 2 + 3\nWEND",
            &[Statement::While(WhileSpan {
                expr: Expr::Add(Box::from(BinaryOpSpan {
                    lhs: expr_integer(2, 1, 7),
                    rhs: expr_integer(3, 1, 11),
                    pos: lc(1, 9),
                })),
                body: vec![],
            })],
        );
        do_ok_test(
            "WHILE 5\n\nREM foo\n\nWEND\n",
            &[Statement::While(WhileSpan { expr: expr_integer(5, 1, 7), body: vec![] })],
        );
    }

    #[test]
    fn test_while_loops() {
        do_ok_test(
            "WHILE TRUE\nA\nB\nWEND",
            &[Statement::While(WhileSpan {
                expr: expr_boolean(true, 1, 7),
                body: vec![make_bare_builtin_call("A", 2, 1), make_bare_builtin_call("B", 3, 1)],
            })],
        );
    }

    #[test]
    fn test_while_nested() {
        let code = r#"
            WHILE TRUE
                A
                WHILE FALSE
                    B
                WEND
                C
            WEND
        "#;
        do_ok_test(
            code,
            &[Statement::While(WhileSpan {
                expr: expr_boolean(true, 2, 19),
                body: vec![
                    make_bare_builtin_call("A", 3, 17),
                    Statement::While(WhileSpan {
                        expr: expr_boolean(false, 4, 23),
                        body: vec![make_bare_builtin_call("B", 5, 21)],
                    }),
                    make_bare_builtin_call("C", 7, 17),
                ],
            })],
        );
    }

    #[test]
    fn test_while_errors() {
        do_error_test("WHILE\n", "1:6: No expression in WHILE statement");
        do_error_test("WHILE TRUE", "1:11: Expecting newline after WHILE");
        do_error_test("\n\nWHILE TRUE\n", "3:1: WHILE without WEND");
        do_error_test("WHILE TRUE\nEND", "1:1: WHILE without WEND");
        do_error_test("WHILE TRUE\nEND\n", "1:1: WHILE without WEND");
        do_error_test("WHILE TRUE\nEND WHILE\n", "2:5: Unexpected keyword in expression");

        do_error_test("WHILE ,\nWEND", "1:7: No expression in WHILE statement");
        do_error_test("WHILE ,\nEND", "1:7: No expression in WHILE statement");
    }
}