rpic-core 0.6.2

Core engine for rpic: lexer, parser, geometry, and SVG/PNG/PDF backends for the pic graphics language.
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
//! Recursive-descent parser for the pic drawing core.
//!
//! Follows dpic's `grammar.txt`. Implemented: pictures (`.PS … .PE`), primitives
//! with the full attribute set, positions (pairs, places, corners, ordinals,
//! `between`, `± shifts`), expressions with proper precedence, `[ … ]` blocks,
//! `{ … }` groups, labels, assignments, macros, includes, conditionals, loops,
//! `print` and `exec`.

use crate::ast::*;
use crate::diagnostic::{Diagnostic, Span};
use crate::lexer::{LexError, Spanned, lex, lex_named};
use crate::token::*;

/// A parse error with source location. `file` (via [`ParseError::span`]) is
/// `None` for the user's own input, or the `copy` include / library name the
/// position is relative to.
#[derive(Debug, Clone, PartialEq)]
pub struct ParseError {
    pub msg: String,
    pub line: u32,
    pub col: u32,
    pub end_col: u32,
    file: Option<std::sync::Arc<str>>,
    detail: Box<ParseErrorDetail>,
}

#[derive(Debug, Clone, PartialEq)]
struct ParseErrorDetail {
    kind: String,
    found: Option<String>,
    expected: Option<String>,
    hint: Option<String>,
}

impl std::fmt::Display for ParseError {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match &self.file {
            Some(file) => write!(f, "{}:{}:{}: {}", file, self.line, self.col, self.msg),
            None => write!(f, "{}:{}: {}", self.line, self.col, self.msg),
        }
    }
}

impl ParseError {
    fn new(msg: impl Into<String>, span: Span) -> Self {
        Self {
            msg: msg.into(),
            line: span.line,
            col: span.col,
            end_col: span.end_col,
            file: span.file,
            detail: Box::new(ParseErrorDetail {
                kind: "parse".into(),
                found: None,
                expected: None,
                hint: None,
            }),
        }
    }

    fn expected(expected: impl Into<String>, found: impl Into<String>, span: Span) -> Self {
        let expected = expected.into();
        let found = found.into();
        Self {
            msg: format!("expected {expected}, found {found}"),
            line: span.line,
            col: span.col,
            end_col: span.end_col,
            file: span.file,
            detail: Box::new(ParseErrorDetail {
                kind: "expected_token".into(),
                found: Some(found),
                expected: Some(expected),
                hint: None,
            }),
        }
    }

    /// Override the diagnostic kind (crate-internal builder).
    pub(crate) fn with_kind(mut self, kind: impl Into<String>) -> Self {
        self.detail.kind = kind.into();
        self
    }

    /// The error's source span, including which source it refers to.
    pub fn span(&self) -> Span {
        Span::new(self.line, self.col, self.end_col).in_file(self.file.clone())
    }

    pub fn diagnostic(&self) -> Diagnostic {
        let mut d = Diagnostic::new(self.detail.kind.clone(), self.msg.clone()).at(self.span());
        d.found = self.detail.found.clone();
        d.expected = self.detail.expected.clone();
        d.hint = self.detail.hint.clone();
        d
    }
}

impl From<LexError> for ParseError {
    fn from(e: LexError) -> Self {
        ParseError {
            msg: e.msg,
            line: e.line,
            col: e.col,
            end_col: e.end_col,
            file: e.file,
            detail: Box::new(ParseErrorDetail {
                kind: e.kind,
                found: None,
                expected: None,
                hint: None,
            }),
        }
    }
}

/// Parse a full source string into a [`Picture`] with no filesystem context.
/// `copy "file"` includes are unavailable (they require a base directory).
pub fn parse(src: &str) -> Result<Picture, ParseError> {
    parse_in_dir(src, None)
}

/// Parse pic source, resolving `copy "file"` includes relative to `base`
/// with the default (unrestricted) include policy.
pub fn parse_in_dir(src: &str, base: Option<&Path>) -> Result<Picture, ParseError> {
    parse_with_prelude(
        src,
        IncludeCtx::unrestricted(base.map(|p| p.to_path_buf())),
        false,
        false,
    )
}

/// Parse pic source with optional preludes: `circuits` loads the embedded
/// circuit-element library and `texlabels` injects `texlabels = 1` — the
/// library equivalents of the CLI `-c` / `-t` flags. Each prelude is lexed
/// as its own named source unit (not text glued in front of `src`), so every
/// diagnostic position stays relative to the source it belongs to: the user's
/// own input reports user lines, and library problems name the library.
pub fn parse_with_prelude(
    src: &str,
    includes: IncludeCtx,
    circuits: bool,
    texlabels: bool,
) -> Result<Picture, ParseError> {
    let mut toks: Vec<Spanned> = Vec::new();
    if circuits {
        splice_unit(&mut toks, lex_named(crate::CIRCUITS, "circuits")?);
    }
    if texlabels {
        // Initializer only — the source stays sovereign (`texlabels = 0` wins).
        splice_unit(&mut toks, lex_named("texlabels = 1\n", "<texlabels>")?);
    }
    let src = strip_backend_preamble(src);
    toks.extend(lex(&src)?);
    let (toks, macros) = preprocess(toks, &includes)?;
    let mut pic = Parser::new(toks).parse_picture()?;
    pic.macros = macros;
    pic.includes = includes;
    Ok(pic)
}

/// Append a lexed prelude unit ahead of the tokens that follow: drop its
/// `Eof` and guarantee a trailing `Newline` so the units stay statement-
/// separated (equivalent to the `\n` the old string-prepending inserted).
fn splice_unit(out: &mut Vec<Spanned>, mut unit: Vec<Spanned>) {
    if matches!(unit.last().map(|s| &s.tok), Some(Token::Eof)) {
        unit.pop();
    }
    if !matches!(unit.last().map(|s| &s.tok), Some(Token::Newline)) {
        let (line, file) = unit
            .last()
            .map(|s| (s.line, s.file.clone()))
            .unwrap_or((1, None));
        unit.push(Spanned::new(Token::Newline, line, 1).with_file(file));
    }
    out.extend(unit);
}

/// Parse a deferred body (the raw tokens of an `if`/`for` block) with the macro
/// table in scope, expanding macro calls (and `copy` includes) along this
/// executed path. Used by the evaluator so dead branches and recursive macros
/// are never parsed.
pub fn parse_body_tokens(
    toks: &[Spanned],
    macros: &mut Macros,
    includes: &IncludeCtx,
) -> Result<Vec<Stmt>, ParseError> {
    let before = body_macro_frame(toks).unwrap_or_else(|| macros.clone());
    let mut m = before.clone();
    let mut input = toks.to_vec();
    input.push(Spanned::new(Token::Eof, 0, 0));
    let expanded = expand(&input, &mut m, 0, includes)?;
    propagate_macro_changes(macros, &before, &m);
    let mut p = Parser::new(expanded);
    p.parse_elementlist(&[])
}

fn body_macro_frame(toks: &[Spanned]) -> Option<Macros> {
    toks.iter()
        .find_map(|s| s.macro_frame.as_ref().map(|m| m.as_ref().clone()))
}

fn propagate_macro_changes(macros: &mut Macros, before: &Macros, after: &Macros) {
    for name in before.keys() {
        if !after.contains_key(name) {
            macros.remove(name);
        }
    }
    for (name, body) in after {
        if before.get(name) != Some(body) {
            macros.insert(name.clone(), body.clone());
        }
    }
}

/// Parse pic source produced by `exec`, applying the caller's macro argument
/// frame before normal macro expansion.
pub(crate) fn parse_exec_source(
    src: &str,
    macros: &Macros,
    includes: &IncludeCtx,
    arg_frame: Option<&[Vec<Spanned>]>,
) -> Result<Vec<Stmt>, ParseError> {
    let mut toks = lex(src)?;
    if let Some(args) = arg_frame {
        toks = substitute(&toks, args);
    }
    let mut m = macros.clone();
    let expanded = expand(&toks, &mut m, 0, includes)?;
    let mut p = Parser::new(expanded);
    p.parse_elementlist(&[])
}

pub(crate) fn parse_stringexpr_tokens(
    toks: &[Spanned],
    macros: &mut Macros,
    includes: &IncludeCtx,
) -> Result<StringExpr, ParseError> {
    let mut input = toks.to_vec();
    input.push(Spanned::new(Token::Eof, 0, 0));
    let expanded = expand(&input, macros, 0, includes)?;
    let mut p = Parser::new(expanded);
    p.skip_newlines();
    let expr = p.parse_stringexpr()?;
    p.skip_newlines();
    if !p.at(&Token::Eof) {
        return p.err(format!("unexpected {:?} after string expression", p.cur()));
    }
    Ok(expr)
}

// ---- backend preamble filter ----------------------------------------------

/// Drop non-SVG backend snippets commonly embedded in dpic examples.
///
/// These TeX/PSTricks preambles are meaningful to other backends, but for rpic's
/// SVG output they should be tolerated as no-ops. Replacing ignored lines with
/// empty lines keeps subsequent diagnostics on the original line numbers.
fn strip_backend_preamble(src: &str) -> String {
    let mut out = String::with_capacity(src.len());
    let mut in_verbatimtex = false;
    let mut in_string = false;
    let mut in_raw_sh = false;

    for line in src.lines() {
        let trimmed = line.trim_start();
        if in_verbatimtex {
            out.push('\n');
            if starts_word(trimmed, "etex") {
                in_verbatimtex = false;
            }
            continue;
        }

        if in_raw_sh {
            out.push_str(line);
            out.push('\n');
            in_raw_sh = line_continues(line);
            continue;
        }

        if !in_string && starts_word(trimmed, "verbatimtex") {
            in_verbatimtex = true;
            out.push('\n');
        } else if !in_string && is_ignored_backend_line(trimmed) {
            out.push('\n');
        } else {
            out.push_str(line);
            out.push('\n');
            if starts_word(trimmed, "sh") {
                in_raw_sh = line_continues(line);
            } else {
                in_string = update_string_state(line, in_string);
            }
        }
    }
    out
}

fn line_continues(line: &str) -> bool {
    line.trim_end_matches([' ', '\t', '\r']).ends_with('\\')
}

fn update_string_state(line: &str, mut in_string: bool) -> bool {
    let mut slashes = 0usize;
    for c in line.chars() {
        if c == '\\' {
            slashes += 1;
            continue;
        }
        if c == '"' && slashes.is_multiple_of(2) {
            in_string = !in_string;
        }
        slashes = 0;
    }
    in_string
}

fn is_ignored_backend_line(trimmed: &str) -> bool {
    trimmed.starts_with("\\global") || trimmed.starts_with("\\psset")
}

fn starts_word(s: &str, word: &str) -> bool {
    let Some(rest) = s.strip_prefix(word) else {
        return false;
    };
    !rest
        .chars()
        .next()
        .is_some_and(|c| c.is_alphanumeric() || c == '_')
}

// ---- macro preprocessor ----------------------------------------------------
//
// Handles `define name { body }` (brace-delimited) with `$1..$9` argument
// substitution at the token level, before parsing. Invocations `name(a, b)` (or
// bare `name`) are replaced by the body with arguments spliced in; the result is
// re-expanded so macros may call macros. `undef name` removes a definition.

use std::collections::HashMap;
use std::path::Path;

fn preprocess(
    input: Vec<Spanned>,
    includes: &IncludeCtx,
) -> Result<(Vec<Spanned>, Macros), ParseError> {
    let mut macros: Macros = builtin_unit_macros();
    let out = expand(&input, &mut macros, 0, includes)?;
    Ok((out, macros))
}

/// dpic's absolute-unit suffix macros (`11bp__` → `11*(scale/72)`), predefined so
/// examples that use them without `copy`ing dpictools still work. A user
/// `define` of the same name overrides these.
fn builtin_unit_macros() -> Macros {
    let defs = [
        ("bp__", "*(scale/72)"),       // Adobe big point
        ("pt__", "*(scale/72.27)"),    // TeX point
        ("pc__", "*(12*scale/72.27)"), // pica
        ("in__", "*scale"),            // inch
        ("cm__", "*(scale/2.54)"),     // centimetre
        ("mm__", "*(scale/25.4)"),     // millimetre
        ("px__", "*(scale/96)"),       // pixel (96 dpi)
    ];
    let mut m = Macros::new();
    for (name, body) in defs {
        if let Ok(toks) = lex(body) {
            let body_toks: Vec<Spanned> =
                toks.into_iter().filter(|s| s.tok != Token::Eof).collect();
            m.insert(name.to_string(), body_toks);
        }
    }
    m
}

fn loc(toks: &[Spanned], i: usize) -> Span {
    toks.get(i)
        .map(|s| s.span())
        .unwrap_or_else(|| Span::new(0, 0, 0))
}

fn expand(
    toks: &[Spanned],
    macros: &mut HashMap<String, Vec<Spanned>>,
    depth: usize,
    includes: &IncludeCtx,
) -> Result<Vec<Spanned>, ParseError> {
    if depth > 64 {
        return Err(ParseError::new(
            "macro expansion too deep (recursive define?)",
            Span::new(0, 0, 0),
        ));
    }
    let mut out = Vec::new();
    let mut i = 0;
    while i < toks.len() {
        match &toks[i].tok {
            Token::Kw(Kw::Define) => {
                let span = loc(toks, i);
                i += 1;
                let name = match toks.get(i).map(|s| &s.tok) {
                    Some(Token::Name(n)) | Some(Token::Label(n)) => n.clone(),
                    _ => {
                        return Err(ParseError::new(
                            "define: expected a macro name",
                            span.clone(),
                        ));
                    }
                };
                i += 1;
                // the macro body delimiter may begin on a following line
                while toks.get(i).map(|s| &s.tok) == Some(&Token::Newline) {
                    i += 1;
                }
                let Some(delim) = toks.get(i).map(|s| s.tok.clone()) else {
                    return Err(ParseError::new(
                        "define: expected a body delimiter",
                        span.clone(),
                    ));
                };
                let body = if delim == Token::LeftBrace {
                    i += 1; // past `{`
                    let start = i;
                    let mut bd = 1;
                    while i < toks.len() && bd > 0 {
                        match &toks[i].tok {
                            Token::LeftBrace => bd += 1,
                            Token::RightBrace => {
                                bd -= 1;
                                if bd == 0 {
                                    break;
                                }
                            }
                            _ => {}
                        }
                        i += 1;
                    }
                    if bd != 0 {
                        return Err(ParseError::new(
                            "define: unterminated `{` body",
                            span.clone(),
                        ));
                    }
                    let body = trim_edge_newlines(&toks[start..i]);
                    i += 1; // past `}`
                    body
                } else {
                    if matches!(delim, Token::Eof | Token::Newline) {
                        let span = loc(toks, i);
                        return Err(ParseError::new(
                            "define: expected a body delimiter",
                            span.clone(),
                        ));
                    }
                    i += 1; // past delimiter
                    let start = i;
                    while i < toks.len() && toks[i].tok != delim {
                        i += 1;
                    }
                    if i >= toks.len() {
                        return Err(ParseError::new(
                            "define: unterminated delimited body",
                            span.clone(),
                        ));
                    }
                    let body = trim_edge_newlines(&toks[start..i]);
                    i += 1; // past closing delimiter
                    body
                };
                macros.insert(name, body);
            }
            Token::Kw(Kw::Undef) => {
                i += 1;
                if let Some(Token::Name(n)) | Some(Token::Label(n)) = toks.get(i).map(|s| &s.tok) {
                    macros.remove(n);
                }
                i += 1;
            }
            // `if`/`for` bodies are copied verbatim (macro calls inside are not
            // expanded here): they are expanded lazily, by the evaluator, only
            // along the branch/iteration that actually runs. The condition/range
            // is still expanded so macros there work.
            Token::Kw(Kw::If) => {
                let if_tok = toks[i].clone();
                out.push(toks[i].clone());
                i += 1;
                let Some(te) = find_kw_depth0(toks, i, Kw::Then) else {
                    continue; // malformed; let the parser report it
                };
                let cond = expand(&toks[i..te], macros, depth + 1, includes)?;
                if let Some((then_body, after_then)) = read_braced_body(toks, te + 1)? {
                    let mut j = after_then;
                    while matches!(toks.get(j).map(|s| &s.tok), Some(Token::Newline)) {
                        j += 1;
                    }
                    let else_body =
                        if matches!(toks.get(j).map(|s| &s.tok), Some(Token::Kw(Kw::Else))) {
                            read_braced_body(toks, j + 1)?
                        } else {
                            None
                        };
                    if let Some(take_then) = static_truth(&cond) {
                        let after_static = else_body
                            .as_ref()
                            .map(|(_, after)| *after)
                            .unwrap_or(after_then);
                        out.pop(); // discard the speculative `if`
                        if take_then {
                            out.extend(expand(&then_body, macros, depth + 1, includes)?);
                            i = after_static;
                        } else if let Some((body, after)) = else_body {
                            out.extend(expand(&body, macros, depth + 1, includes)?);
                            i = after;
                        } else {
                            i = after_then;
                        }
                        continue;
                    }
                }
                *out.last_mut().unwrap() = if_tok;
                out.extend(cond);
                out.push(toks[te].clone()); // `then`
                i = copy_braced(toks, te + 1, &mut out, macros)?;
                // optional `else { … }` (possibly across newlines)
                let mut j = i;
                while matches!(toks.get(j).map(|s| &s.tok), Some(Token::Newline)) {
                    j += 1;
                }
                if matches!(toks.get(j).map(|s| &s.tok), Some(Token::Kw(Kw::Else))) {
                    out.push(toks[j].clone());
                    i = copy_braced(toks, j + 1, &mut out, macros)?;
                }
            }
            Token::Kw(Kw::For) => {
                out.push(toks[i].clone());
                i += 1;
                let Some(de) = find_kw_depth0(toks, i, Kw::Do) else {
                    continue;
                };
                out.extend(expand(&toks[i..de], macros, depth + 1, includes)?);
                out.push(toks[de].clone()); // `do`
                i = copy_braced(toks, de + 1, &mut out, macros)?;
            }
            Token::Name(n) | Token::Label(n) if macros.contains_key(n) => {
                let body = macros.get(n).unwrap().clone();
                i += 1;
                let args = if toks.get(i).map(|s| &s.tok) == Some(&Token::Lparen) {
                    i += 1;
                    let (a, ni) = read_args(toks, i)?;
                    i = ni;
                    a
                } else {
                    Vec::new()
                };
                let sub = substitute(&body, &args);
                let expanded = expand(&sub, macros, depth + 1, includes)?;
                out.extend(expanded);
            }
            // `copy "file"` splices another pic file's (expanded) tokens inline.
            Token::Kw(Kw::Copy) => {
                let span = loc(toks, i);
                i += 1;
                let Some(Token::Str(fname)) = toks.get(i).map(|s| &s.tok) else {
                    return Err(ParseError::new(
                        "copy: expected a quoted file name (only `copy \"file\"` is supported)",
                        span.clone(),
                    ));
                };
                let fname = fname.clone();
                i += 1;
                let inc = include_file(includes, &fname, macros, depth, span)?;
                out.extend(inc);
            }
            _ => {
                out.push(toks[i].clone());
                i += 1;
            }
        }
    }
    Ok(out)
}

/// Read comma-separated argument token-lists after a `(` (index `i` is just past
/// it), returning the args and the index after the matching `)`.
fn read_args(toks: &[Spanned], mut i: usize) -> Result<(Vec<Vec<Spanned>>, usize), ParseError> {
    let mut args: Vec<Vec<Spanned>> = Vec::new();
    let mut cur: Vec<Spanned> = Vec::new();
    let mut depth = 0i32;
    loop {
        let Some(s) = toks.get(i) else {
            return Err(ParseError::new(
                "unterminated macro arguments",
                Span::new(0, 0, 0),
            ));
        };
        match &s.tok {
            Token::Lparen | Token::LeftBrack | Token::LeftBrace => {
                depth += 1;
                cur.push(s.clone());
                i += 1;
            }
            Token::Rparen if depth == 0 => {
                i += 1;
                trim_trailing_newlines(&mut cur);
                if !cur.is_empty() || !args.is_empty() {
                    args.push(cur);
                }
                break;
            }
            Token::Rparen | Token::RightBrack | Token::RightBrace => {
                depth -= 1;
                cur.push(s.clone());
                i += 1;
            }
            Token::Comma if depth == 0 => {
                trim_trailing_newlines(&mut cur);
                args.push(std::mem::take(&mut cur));
                i += 1;
            }
            Token::Newline if depth == 0 && cur.is_empty() => {
                i += 1;
            }
            _ => {
                cur.push(s.clone());
                i += 1;
            }
        }
    }
    Ok((args, i))
}

fn trim_trailing_newlines(toks: &mut Vec<Spanned>) {
    while matches!(toks.last().map(|s| &s.tok), Some(Token::Newline)) {
        toks.pop();
    }
}

/// Drop leading and trailing `Newline` tokens (used for macro bodies, where the
/// newlines around a multi-line `{ … }` are formatting, not structure).
fn trim_edge_newlines(toks: &[Spanned]) -> Vec<Spanned> {
    let mut start = 0;
    let mut end = toks.len();
    while start < end && toks[start].tok == Token::Newline {
        start += 1;
    }
    while end > start && toks[end - 1].tok == Token::Newline {
        end -= 1;
    }
    toks[start..end].to_vec()
}

/// Replace `$k` argument tokens in a macro body with the k-th argument's tokens.
fn substitute(body: &[Spanned], args: &[Vec<Spanned>]) -> Vec<Spanned> {
    let mut out = Vec::new();
    let mut i = 0;
    while i < body.len() {
        if matches!(body[i].tok, Token::Kw(Kw::Define))
            && let Some((define, next)) = copy_define_verbatim(body, i)
        {
            out.extend(define);
            i = next;
            continue;
        }

        if let Some((pasted, next)) = paste_adjacent_args(body, args, i) {
            out.push(pasted.with_arg_frame(args));
            i = next;
            continue;
        }

        let s = &body[i];
        match &s.tok {
            Token::Arg(k) => {
                if let Some(a) = args.get((*k as usize).wrapping_sub(1)) {
                    out.extend(a.iter().cloned().map(|s| s.with_arg_frame(args)));
                }
            }
            // `$+` is the number of arguments passed to this macro
            Token::ArgCount => out.push(
                Spanned::new(Token::Float(args.len() as f64), s.line, s.col).with_arg_frame(args),
            ),
            // `$n` is also substituted inside string literals (the `"$1"==""`
            // default-argument idiom, sprintf templates like `"$2%g"`, …).
            Token::Str(text) if text.contains('$') => {
                out.push(
                    Spanned::new(Token::Str(subst_in_string(text, args)), s.line, s.col)
                        .with_arg_frame(args),
                );
            }
            _ => out.push(s.clone().with_arg_frame(args)),
        }
        i += 1;
    }
    out
}

fn copy_define_verbatim(body: &[Spanned], start: usize) -> Option<(Vec<Spanned>, usize)> {
    let mut name_idx = start + 1;
    while matches!(body.get(name_idx).map(|s| &s.tok), Some(Token::Newline)) {
        name_idx += 1;
    }
    if !matches!(
        body.get(name_idx).map(|s| &s.tok),
        Some(Token::Name(_)) | Some(Token::Label(_))
    ) {
        return None;
    }

    let mut out = Vec::new();
    let mut i = start;
    while let Some(s) = body.get(i) {
        out.push(s.clone());
        i += 1;
        if matches!(s.tok, Token::LeftBrace) {
            break;
        }
    }

    if !matches!(out.last().map(|s| &s.tok), Some(Token::LeftBrace)) {
        return None;
    }

    let mut depth = 1i32;
    while let Some(s) = body.get(i) {
        match &s.tok {
            Token::LeftBrace => depth += 1,
            Token::RightBrace => depth -= 1,
            _ => {}
        }
        out.push(s.clone());
        i += 1;
        if depth == 0 {
            return Some((out, i));
        }
    }
    None
}

fn paste_adjacent_args(
    body: &[Spanned],
    args: &[Vec<Spanned>],
    start: usize,
) -> Option<(Spanned, usize)> {
    let first = body.get(start)?;
    let Token::Arg(k) = &first.tok else {
        return None;
    };

    let mut text = arg_text(*k, args);
    let mut count = 1usize;
    let mut end = start + 1;
    let mut prev = first;
    while let Some(next) = body.get(end) {
        let Token::Arg(k) = &next.tok else {
            break;
        };
        if !adjacent_arg_tokens(prev, next) {
            break;
        }
        text.push_str(&arg_text(*k, args));
        count += 1;
        prev = next;
        end += 1;
    }

    if count < 2 || text.is_empty() {
        return None;
    }

    Some((tokenize_pasted_arg_text(&text, first.line, first.col), end))
}

fn arg_text(k: u32, args: &[Vec<Spanned>]) -> String {
    args.get((k as usize).wrapping_sub(1))
        .map(|a| tokens_to_text(a))
        .unwrap_or_default()
}

fn adjacent_arg_tokens(left: &Spanned, right: &Spanned) -> bool {
    left.line == right.line && arg_end_col(left) == Some(right.col)
}

fn arg_end_col(s: &Spanned) -> Option<u32> {
    let Token::Arg(k) = &s.tok else {
        return None;
    };
    Some(s.col + 1 + k.to_string().len() as u32)
}

fn tokenize_pasted_arg_text(text: &str, line: u32, col: u32) -> Spanned {
    if let Ok(toks) = lex(text)
        && toks.len() == 2
        && matches!(toks[1].tok, Token::Eof)
    {
        return Spanned::new(toks[0].tok.clone(), line, col);
    }

    let tok = if text.chars().next().is_some_and(|c| c.is_ascii_uppercase()) {
        Token::Label(text.to_string())
    } else {
        Token::Name(text.to_string())
    };
    Spanned::new(tok, line, col)
}

/// Replace `$n` references inside a string literal with the textual form of the
/// n-th macro argument (empty if missing).
fn subst_in_string(text: &str, args: &[Vec<Spanned>]) -> String {
    let chars: Vec<char> = text.chars().collect();
    let mut out = String::new();
    let mut i = 0;
    while i < chars.len() {
        if chars[i] == '$' && chars.get(i + 1) == Some(&'+') {
            out.push_str(&args.len().to_string());
            i += 2;
        } else if chars[i] == '$' && chars.get(i + 1).is_some_and(|c| c.is_ascii_digit()) {
            let mut j = i + 1;
            let mut num = String::new();
            while j < chars.len() && chars[j].is_ascii_digit() {
                num.push(chars[j]);
                j += 1;
            }
            if let Ok(k) = num.parse::<usize>()
                && k >= 1
                && let Some(a) = args.get(k - 1)
            {
                out.push_str(&tokens_to_text(a));
            }
            i = j;
        } else {
            out.push(chars[i]);
            i += 1;
        }
    }
    out
}

/// Best-effort textual rendering of an argument token list, for `$n` splicing
/// inside string literals.
fn tokens_to_text(toks: &[Spanned]) -> String {
    let mut s = String::new();
    for t in toks {
        match &t.tok {
            Token::Float(v) => s.push_str(&format!("{v}")),
            Token::Str(t) => s.push_str(t),
            Token::Name(n) | Token::Label(n) => s.push_str(n),
            Token::Lparen => s.push('('),
            Token::Rparen => s.push(')'),
            Token::LeftBrack => s.push('['),
            Token::RightBrack => s.push(']'),
            Token::LeftBrace => s.push('{'),
            Token::RightBrace => s.push('}'),
            Token::Comma => s.push(','),
            Token::Colon => s.push(':'),
            Token::Dot => s.push('.'),
            Token::Plus => s.push('+'),
            Token::Minus => s.push('-'),
            Token::Mult => s.push('*'),
            Token::Div => s.push('/'),
            Token::Percent => s.push('%'),
            Token::Dollar => s.push('$'),
            Token::Backslash => s.push('\\'),
            Token::DotX => s.push_str(".x"),
            Token::DotY => s.push_str(".y"),
            Token::DotPS => s.push_str(".PS"),
            Token::DotPE => s.push_str(".PE"),
            Token::Corner(c) => s.push_str(corner_text(*c)),
            Token::Param(p) => s.push_str(param_text(*p)),
            Token::LineType(l) => s.push_str(line_type_text(*l)),
            Token::TextPos(p) => s.push_str(text_pos_text(*p)),
            Token::Arrow(a) => s.push_str(arrow_text(*a)),
            Token::Dir(d) => s.push_str(dir_text(*d)),
            Token::Prim(p) => s.push_str(prim_text(*p)),
            Token::Color(c) => s.push_str(color_text(*c)),
            _ => {}
        }
    }
    s
}

fn corner_text(c: Corner) -> &'static str {
    match c {
        Corner::N => ".n",
        Corner::S => ".s",
        Corner::E => ".e",
        Corner::W => ".w",
        Corner::Ne => ".ne",
        Corner::Se => ".se",
        Corner::Nw => ".nw",
        Corner::Sw => ".sw",
        Corner::Start => ".start",
        Corner::End => ".end",
        Corner::Center => ".c",
    }
}

fn param_text(p: Param) -> &'static str {
    match p {
        Param::Height => ".ht",
        Param::Width => ".wid",
        Param::Radius => ".rad",
        Param::Diameter => ".diam",
        Param::Thickness => ".thick",
        Param::Length => ".len",
    }
}

fn line_type_text(l: LineType) -> &'static str {
    match l {
        LineType::Solid => "solid",
        LineType::Dotted => "dotted",
        LineType::Dashed => "dashed",
        LineType::Invis => "invis",
    }
}

fn text_pos_text(p: TextPos) -> &'static str {
    match p {
        TextPos::Center => "center",
        TextPos::Ljust => "ljust",
        TextPos::Rjust => "rjust",
        TextPos::Above => "above",
        TextPos::Below => "below",
    }
}

fn arrow_text(a: Arrow) -> &'static str {
    match a {
        Arrow::Left => "<-",
        Arrow::Right => "->",
        Arrow::Double => "<->",
    }
}

fn dir_text(d: Dir) -> &'static str {
    match d {
        Dir::Up => "up",
        Dir::Down => "down",
        Dir::Right => "right",
        Dir::Left => "left",
    }
}

fn prim_text(p: Prim) -> &'static str {
    match p {
        Prim::Box => "box",
        Prim::Circle => "circle",
        Prim::Ellipse => "ellipse",
        Prim::Arc => "arc",
        Prim::Line => "line",
        Prim::Arrow => "arrow",
        Prim::Move => "move",
        Prim::Spline => "spline",
    }
}

fn color_text(c: Color) -> &'static str {
    match c {
        Color::Colored => "color",
        Color::Outlined => "outlined",
        Color::Shaded => "shaded",
    }
}

fn kw_text(k: Kw) -> &'static str {
    match k {
        Kw::Ht => "ht",
        Kw::Wid => "wid",
        Kw::Rad => "rad",
        Kw::Diam => "diam",
        Kw::Thick => "thick",
        Kw::Scaled => "scaled",
        Kw::From => "from",
        Kw::To => "to",
        Kw::At => "at",
        Kw::With => "with",
        Kw::By => "by",
        Kw::Then => "then",
        Kw::Continue => "continue",
        Kw::Chop => "chop",
        Kw::Same => "same",
        Kw::Cw => "cw",
        Kw::Ccw => "ccw",
        Kw::Of => "of",
        Kw::The => "the",
        Kw::Way => "way",
        Kw::Between => "between",
        Kw::And => "and",
        Kw::Here => "Here",
        Kw::Last => "last",
        Kw::Fill => "fill",
        Kw::Nth => "ordinal suffix",
        Kw::Print => "print",
        Kw::Copy => "copy",
        Kw::Reset => "reset",
        Kw::Exec => "exec",
        Kw::Sh => "sh",
        Kw::Command => "command",
        Kw::Define => "define",
        Kw::Undef => "undef",
        Kw::Rand => "rand",
        Kw::If => "if",
        Kw::Else => "else",
        Kw::For => "for",
        Kw::Do => "do",
        Kw::Sprintf => "sprintf",
        Kw::Animate => "animate",
        Kw::After => "after",
        Kw::Delay => "delay",
    }
}

fn token_text(t: &Token) -> String {
    match t {
        Token::Float(v) => fmt_float(*v),
        Token::Str(s) => format!("\"{s}\""),
        Token::Name(s) | Token::Label(s) => format!("`{s}`"),
        Token::Arg(n) => format!("${n}"),
        Token::ArgCount => "$+".into(),
        Token::Dollar => "$".into(),
        Token::Backslash => "\\".into(),
        Token::Newline => "end of line".into(),
        Token::DotPS => ".PS".into(),
        Token::DotPE => ".PE".into(),
        Token::Eof => "end of input".into(),
        Token::Lt => "<".into(),
        Token::Lparen => "(".into(),
        Token::Rparen => ")".into(),
        Token::Mult => "*".into(),
        Token::Plus => "+".into(),
        Token::Minus => "-".into(),
        Token::Div => "/".into(),
        Token::Percent => "%".into(),
        Token::Caret => "^".into(),
        Token::Not => "!".into(),
        Token::AndAnd => "&&".into(),
        Token::OrOr => "||".into(),
        Token::Ampersand => "&".into(),
        Token::Comma => ",".into(),
        Token::Colon => ":".into(),
        Token::LeftBrack => "[".into(),
        Token::RightBrack => "]".into(),
        Token::LeftBrace => "{".into(),
        Token::RightBrace => "}".into(),
        Token::Dot => ".".into(),
        Token::Block => "[]".into(),
        Token::LeftQuote => "`".into(),
        Token::RightQuote => "'".into(),
        Token::Eq => "=".into(),
        Token::ColonEq => ":=".into(),
        Token::PlusEq => "+=".into(),
        Token::MinusEq => "-=".into(),
        Token::MultEq => "*=".into(),
        Token::DivEq => "/=".into(),
        Token::RemEq => "%=".into(),
        Token::EqEq => "==".into(),
        Token::Neq => "!=".into(),
        Token::Ge => ">=".into(),
        Token::Le => "<=".into(),
        Token::Gt => ">".into(),
        Token::DotX => ".x".into(),
        Token::DotY => ".y".into(),
        Token::Kw(k) => kw_text(*k).into(),
        Token::Corner(c) => corner_text(*c).into(),
        Token::Param(p) => format!(".{}", param_text(*p)),
        Token::Func1(f) => format!("{f:?}").to_ascii_lowercase(),
        Token::Func2(f) => format!("{f:?}").to_ascii_lowercase(),
        Token::LineType(l) => line_type_text(*l).into(),
        Token::TextPos(p) => text_pos_text(*p).into(),
        Token::Arrow(a) => arrow_text(*a).into(),
        Token::Dir(d) => dir_text(*d).into(),
        Token::Prim(p) => prim_text(*p).into(),
        Token::Color(c) => color_text(*c).into(),
        Token::EnvVar(e) => format!("{e:?}").to_ascii_lowercase(),
    }
}

fn fmt_float(v: f64) -> String {
    let mut s = v.to_string();
    if s.ends_with(".0") {
        s.truncate(s.len() - 2);
    }
    s
}

fn suggest_object(word: &str) -> Option<&'static str> {
    const WORDS: &[&str] = &[
        "arc", "arrow", "box", "brace", "circle", "dot", "ellipse", "line", "move", "spline",
    ];
    crate::diagnostic::closest(word, WORDS)
}

/// Read and tokenize a `copy "file"` include, returning its expanded tokens
/// (with the trailing `Eof` removed so it splices cleanly mid-stream). The
/// included file resolves nested `copy`s relative to its own directory.
fn include_file(
    includes: &IncludeCtx,
    fname: &str,
    macros: &mut HashMap<String, Vec<Spanned>>,
    depth: usize,
    span: Span,
) -> Result<Vec<Spanned>, ParseError> {
    let mkerr = |msg: String| ParseError::new(msg, span.clone());
    let denied = |why: &str| {
        ParseError::new(format!("copy \"{fname}\": {why}"), span.clone())
            .with_kind("include_denied")
    };
    // `copy "circuits"` is a reserved target: it loads the embedded native
    // circuit-element library — the in-source spelling of `-c`, usable even
    // where file includes are not (wasm, compile_json with no base dir). It
    // shadows any real file literally named `circuits`. Skipped when the
    // library is already loaded (`-c` plus an explicit copy): `__resistor`
    // is one of its own defines.
    if fname == "circuits" {
        if macros.contains_key("__resistor") {
            return Ok(Vec::new());
        }
        let toks = lex_named(crate::CIRCUITS, "circuits")?;
        let mut expanded = expand(&toks, macros, depth + 1, includes)?;
        if matches!(expanded.last().map(|s| &s.tok), Some(Token::Eof)) {
            expanded.pop();
        }
        return Ok(expanded);
    }
    if includes.policy == IncludePolicy::Deny {
        return Err(denied(
            "filesystem includes are disabled by the include policy",
        ));
    }
    let p = Path::new(fname);
    if p.is_absolute() && includes.policy == IncludePolicy::SandboxedToBase {
        return Err(denied(
            "absolute paths are not allowed by the include policy",
        ));
    }
    let path = if p.is_absolute() {
        p.to_path_buf()
    } else {
        match includes.dir.as_deref() {
            Some(b) => b.join(p),
            None => {
                return Err(mkerr(format!(
                    "copy \"{fname}\": file includes require a file path (unavailable here)"
                )));
            }
        }
    };
    if includes.policy == IncludePolicy::SandboxedToBase {
        // Canonicalize (resolving `..` and symlinks) and require the result
        // to stay inside the fence root. A fence that failed to resolve at
        // setup fails closed. The error names the path as written, never the
        // resolved location.
        let inside = includes
            .fence
            .as_deref()
            .is_some_and(|fence| std::fs::canonicalize(&path).is_ok_and(|c| c.starts_with(fence)));
        if !inside {
            return Err(denied("path resolves outside the include base directory"));
        }
    }
    let content =
        std::fs::read_to_string(&path).map_err(|e| mkerr(format!("copy \"{fname}\": {e}")))?;
    let toks = lex_named(&content, fname)?;
    let inc_base = path.parent().map(|d| d.to_path_buf());
    let inc_ctx = includes.child(inc_base);
    let mut expanded = expand(&toks, macros, depth + 1, &inc_ctx)?;
    if matches!(expanded.last().map(|s| &s.tok), Some(Token::Eof)) {
        expanded.pop();
    }
    Ok(expanded)
}

/// Find the next occurrence of keyword `kw` at bracket-depth 0 from `start`.
fn find_kw_depth0(toks: &[Spanned], start: usize, kw: Kw) -> Option<usize> {
    let mut depth = 0i32;
    for (off, s) in toks[start..].iter().enumerate() {
        match &s.tok {
            Token::Lparen | Token::LeftBrace | Token::LeftBrack => depth += 1,
            Token::Rparen | Token::RightBrace | Token::RightBrack => {
                depth -= 1;
                if depth < 0 {
                    return None;
                }
            }
            Token::Kw(k) if *k == kw && depth == 0 => return Some(start + off),
            _ => {}
        }
    }
    None
}

/// Copy a brace-delimited block verbatim into `out` (including any nested
/// braces), skipping/copying leading newlines. Returns the index past the `}`.
fn copy_braced(
    toks: &[Spanned],
    mut i: usize,
    out: &mut Vec<Spanned>,
    macros: &HashMap<String, Vec<Spanned>>,
) -> Result<usize, ParseError> {
    while matches!(toks.get(i).map(|s| &s.tok), Some(Token::Newline)) {
        out.push(toks[i].clone());
        i += 1;
    }
    if !matches!(toks.get(i).map(|s| &s.tok), Some(Token::LeftBrace)) {
        return Ok(i); // no body; the parser will report the problem
    }
    let mut depth = 0i32;
    let mut tagged_body = false;
    while let Some(s) = toks.get(i) {
        let mut s = s.clone();
        let outer_left_brace = depth == 0 && matches!(s.tok, Token::LeftBrace);
        match &s.tok {
            Token::LeftBrace => depth += 1,
            Token::RightBrace => {
                out.push(s);
                i += 1;
                depth -= 1;
                if depth == 0 {
                    return Ok(i);
                }
                continue;
            }
            _ => {}
        }
        if depth == 1 && !outer_left_brace && !tagged_body {
            s = s.with_macro_frame(macros);
            tagged_body = true;
        }
        out.push(s);
        i += 1;
    }
    Err(ParseError::new("unterminated `{` body", Span::new(0, 0, 0)))
}

fn read_braced_body(
    toks: &[Spanned],
    mut i: usize,
) -> Result<Option<(Vec<Spanned>, usize)>, ParseError> {
    while matches!(toks.get(i).map(|s| &s.tok), Some(Token::Newline)) {
        i += 1;
    }
    if !matches!(toks.get(i).map(|s| &s.tok), Some(Token::LeftBrace)) {
        return Ok(None);
    }
    i += 1;
    let start = i;
    let mut depth = 1i32;
    while let Some(s) = toks.get(i) {
        match &s.tok {
            Token::LeftBrace => depth += 1,
            Token::RightBrace => {
                depth -= 1;
                if depth == 0 {
                    return Ok(Some((toks[start..i].to_vec(), i + 1)));
                }
            }
            _ => {}
        }
        i += 1;
    }
    Err(ParseError::new("unterminated `{` body", Span::new(0, 0, 0)))
}

fn static_truth(toks: &[Spanned]) -> Option<bool> {
    let toks = trim_trailing_eof(toks);
    match toks {
        [
            Spanned {
                tok: Token::Float(v),
                ..
            },
        ] => Some(*v != 0.0),
        [
            Spanned {
                tok: Token::Not, ..
            },
            Spanned {
                tok: Token::Float(v),
                ..
            },
        ] => Some(*v == 0.0),
        [a, op, b] => match op.tok {
            Token::EqEq | Token::Neq => {
                if let (Some(lhs), Some(rhs)) = (static_string(a), static_string(b)) {
                    return Some(if matches!(op.tok, Token::EqEq) {
                        lhs == rhs
                    } else {
                        lhs != rhs
                    });
                }
                if let (Some(lhs), Some(rhs)) = (static_number(a), static_number(b)) {
                    return Some(if matches!(op.tok, Token::EqEq) {
                        (lhs - rhs).abs() < f64::EPSILON
                    } else {
                        (lhs - rhs).abs() >= f64::EPSILON
                    });
                }
                None
            }
            _ => None,
        },
        [a, op, b, op2, c] if matches!(op2.tok, Token::Plus) => {
            let lhs = static_string(a)?;
            let mut rhs = static_string(b)?;
            rhs.push_str(&static_string(c)?);
            match op.tok {
                Token::EqEq => Some(lhs == rhs),
                Token::Neq => Some(lhs != rhs),
                _ => None,
            }
        }
        _ => None,
    }
}

fn trim_trailing_eof(toks: &[Spanned]) -> &[Spanned] {
    if matches!(toks.last().map(|s| &s.tok), Some(Token::Eof)) {
        &toks[..toks.len() - 1]
    } else {
        toks
    }
}

fn static_string(s: &Spanned) -> Option<String> {
    match &s.tok {
        Token::Str(v) => Some(v.clone()),
        _ => None,
    }
}

fn static_number(s: &Spanned) -> Option<f64> {
    match &s.tok {
        Token::Float(v) => Some(*v),
        Token::Name(n) | Token::Label(n) => dpic_backend_constant(n),
        _ => None,
    }
}

fn dpic_backend_constant(name: &str) -> Option<f64> {
    match name {
        "optMFpic" => Some(0.0),
        "optMpost" => Some(1.0),
        "optPDF" => Some(2.0),
        "optPGF" => Some(3.0),
        "optPict2e" => Some(4.0),
        "optPS" => Some(5.0),
        "optPSfrag" => Some(6.0),
        "optPSTricks" => Some(7.0),
        "optSVG" | "dpicopt" => Some(8.0),
        "optTeX" => Some(9.0),
        "opttTeX" => Some(10.0),
        "optxfig" => Some(11.0),
        _ => None,
    }
}

type PResult<T> = Result<T, ParseError>;

fn is_assign_op(t: &Token) -> bool {
    matches!(
        t,
        Token::Eq
            | Token::ColonEq
            | Token::PlusEq
            | Token::MinusEq
            | Token::MultEq
            | Token::DivEq
            | Token::RemEq
    )
}

struct Parser {
    toks: Vec<Spanned>,
    idx: usize,
}

impl Parser {
    fn new(toks: Vec<Spanned>) -> Self {
        Parser { toks, idx: 0 }
    }

    // ---- cursor helpers ----------------------------------------------------

    fn cur(&self) -> &Token {
        &self.toks[self.idx].tok
    }
    fn cur_span(&self) -> Span {
        self.toks[self.idx].span()
    }
    fn peek(&self, n: usize) -> &Token {
        self.toks
            .get(self.idx + n)
            .map(|s| &s.tok)
            .unwrap_or(&Token::Eof)
    }
    fn at(&self, t: &Token) -> bool {
        self.cur() == t
    }
    fn bump(&mut self) -> Token {
        let t = self.toks[self.idx].tok.clone();
        if self.idx + 1 < self.toks.len() {
            self.idx += 1;
        }
        t
    }
    fn eat(&mut self, t: &Token) -> bool {
        if self.at(t) {
            self.bump();
            true
        } else {
            false
        }
    }
    fn expect(&mut self, t: &Token) -> PResult<()> {
        if self.eat(t) {
            Ok(())
        } else {
            self.expected_here(token_text(t))
        }
    }
    fn err<T>(&self, msg: impl Into<String>) -> PResult<T> {
        let s = &self.toks[self.idx];
        Err(ParseError::new(msg, s.span()))
    }
    fn expected_here<T>(&self, expected: impl Into<String>) -> PResult<T> {
        let s = &self.toks[self.idx];
        Err(ParseError::expected(expected, token_text(&s.tok), s.span()))
    }
    fn expected_object<T>(&self) -> PResult<T> {
        let s = &self.toks[self.idx];
        let mut e = ParseError::expected("an object", token_text(&s.tok), s.span());
        if let Token::Name(name) | Token::Label(name) = &s.tok
            && let Some(hint) = suggest_object(name)
        {
            e.detail.hint = Some(format!("did you mean `{hint}`?"));
        }
        Err(e)
    }
    fn at_kw(&self, k: Kw) -> bool {
        matches!(self.cur(), Token::Kw(x) if *x == k)
    }
    fn eat_kw(&mut self, k: Kw) -> bool {
        if self.at_kw(k) {
            self.bump();
            true
        } else {
            false
        }
    }
    fn skip_newlines(&mut self) {
        while self.at(&Token::Newline) {
            self.bump();
        }
    }

    // ---- top level ---------------------------------------------------------

    fn parse_picture(&mut self) -> PResult<Picture> {
        // `.PS`/`.PE` are treated as markers that may appear anywhere; statements
        // (including `animate`) are collected across them up to EOF. The first
        // `.PS` may carry optional width/height.
        let (mut width, mut height) = (None, None);
        let mut seen_ps = false;
        let mut stmts = Vec::new();
        loop {
            self.skip_newlines();
            match self.cur() {
                Token::Eof => break,
                Token::DotPS => {
                    self.bump();
                    if !seen_ps && self.starts_scalar() {
                        width = Some(self.parse_expr()?);
                        if self.starts_scalar() {
                            height = Some(self.parse_expr()?);
                        }
                    }
                    seen_ps = true;
                    while !self.at(&Token::Newline) && !self.at(&Token::Eof) {
                        self.bump();
                    }
                    continue;
                }
                Token::DotPE => {
                    self.bump();
                    continue;
                }
                _ => {}
            }
            stmts.push(self.parse_element()?);
            if !self.at(&Token::Newline)
                && !self.at(&Token::Eof)
                && !self.at(&Token::DotPE)
                && !self.at(&Token::DotPS)
            {
                return self.err(format!("unexpected {:?} after statement", self.cur()));
            }
        }
        Ok(Picture {
            width,
            height,
            stmts,
            macros: HashMap::new(),
            includes: IncludeCtx::default(),
        })
    }

    /// Parse elements until one of `terminators` (or EOF) is the current token.
    fn parse_elementlist(&mut self, terminators: &[Token]) -> PResult<Vec<Stmt>> {
        let mut stmts = Vec::new();
        loop {
            self.skip_newlines();
            if self.at(&Token::Eof) || terminators.iter().any(|t| self.at(t)) {
                break;
            }
            let s = self.parse_element()?;
            stmts.push(s);
            // a statement must end at a newline, a terminator, or EOF
            if !self.at(&Token::Newline)
                && !self.at(&Token::Eof)
                && !terminators.iter().any(|t| self.at(t))
            {
                return self.err(format!("unexpected {:?} after statement", self.cur()));
            }
        }
        Ok(stmts)
    }

    // ---- statements --------------------------------------------------------

    fn parse_element(&mut self) -> PResult<Stmt> {
        // A `%`-led line is a comment convention in some source documents (pic
        // proper uses `#`). `%` is never valid at statement start, so skip the
        // line as a no-op.
        if self.at(&Token::Percent) {
            while !self.at(&Token::Newline) && !self.at(&Token::Eof) {
                self.bump();
            }
            return Ok(Stmt::Print(PrintItem::Str(StringExpr::Lit(String::new()))));
        }

        // rpic animation directive.
        if self.at_kw(Kw::Animate) {
            return Ok(Stmt::Animate(self.parse_animate()?));
        }

        // rpic `class <place> "name"` statement (extension). Contextual:
        // `class = 2` stays an assignment and `class` remains usable as a
        // variable, mirroring how `animate` targets are referenced.
        if matches!(self.cur(), Token::Name(n) if n == "class")
            && !is_assign_op(self.peek(1))
            && !matches!(self.peek(1), Token::LeftBrack)
        {
            self.bump();
            let target = self.parse_place()?;
            let class = self.parse_stringexpr()?;
            return Ok(Stmt::Class { target, class });
        }

        // control constructs
        match self.cur() {
            Token::Kw(Kw::If) => return self.parse_if(),
            Token::Kw(Kw::For) => return self.parse_for(),
            Token::Kw(Kw::Print) => return self.parse_print(),
            Token::Kw(Kw::Exec) => return self.parse_exec(),
            Token::Kw(Kw::Reset) => return self.parse_reset(),
            _ => {}
        }

        // `define`/`undef` are handled by the macro preprocessor before parsing;
        // reaching here means a non-brace form we don't support.
        if let Token::Kw(k) = self.cur() {
            match k {
                Kw::Define | Kw::Undef => {
                    return self.err("only the `define name { body }` macro form is supported");
                }
                // Policy (docs/raw-backend-policy in dpic-compat-audit.md):
                // `command` raw backend text is never injected into the SVG
                // output, and `sh` is never executed — both are tolerated as
                // true no-ops so dpic sources keep compiling. The lexer already
                // skipped their raw argument text.
                Kw::Command | Kw::Sh => {
                    self.bump();
                    return Ok(Stmt::Group(Vec::new()));
                }
                Kw::Copy => {
                    return self.err("`copy` is not supported yet (planned milestone)");
                }
                _ => {}
            }
        }

        // `{ … }` grouping
        if self.eat(&Token::LeftBrace) {
            let stmts = self.parse_elementlist(&[Token::RightBrace])?;
            self.expect(&Token::RightBrace)?;
            return Ok(Stmt::Group(stmts));
        }

        // Labelled element: `Label [suffix] : (object | position)`
        if matches!(self.cur(), Token::Label(_)) && self.label_colon_ahead() {
            let label = self.parse_label()?;
            self.expect(&Token::Colon)?;
            if self.at_object_start() {
                let object = self.parse_object()?;
                return Ok(Stmt::Object {
                    label: Some(label),
                    object,
                });
            } else {
                let pos = self.parse_label_position()?;
                return Ok(Stmt::Place { label, pos });
            }
        }

        // Assignment: `name [suffix] op …` or `envvar op …`
        if self.at_assignment_start() {
            return Ok(Stmt::Assign(self.parse_assignlist()?));
        }

        // Bare direction change.
        if let Token::Dir(d) = self.cur() {
            let d = *d;
            // Only a standalone direction (next token ends the statement).
            if matches!(self.peek(1), Token::Newline | Token::Eof) {
                self.bump();
                return Ok(Stmt::Direction(d));
            }
        }

        // Otherwise: an unlabelled object.
        let object = self.parse_object()?;
        Ok(Stmt::Object {
            label: None,
            object,
        })
    }

    fn parse_if(&mut self) -> PResult<Stmt> {
        self.expect_kw(Kw::If)?;
        let cond = self.parse_expr()?;
        self.expect_kw(Kw::Then)?;
        let then_body = self.capture_braced()?;
        // optional `else { … }`, possibly across newlines (which otherwise end
        // the statement)
        let save = self.idx;
        self.skip_newlines();
        let else_body = if self.eat_kw(Kw::Else) {
            Some(self.capture_braced()?)
        } else {
            self.idx = save;
            None
        };
        Ok(Stmt::If {
            cond,
            then_body,
            else_body,
        })
    }

    fn parse_for(&mut self) -> PResult<Stmt> {
        self.expect_kw(Kw::For)?;
        let var = match self.bump() {
            Token::Name(s) | Token::Label(s) => s,
            other => return self.err(format!("expected loop variable, found {other:?}")),
        };
        let subscript = if self.eat(&Token::LeftBrack) {
            let e = self.parse_subscript()?;
            self.expect(&Token::RightBrack)?;
            Some(e)
        } else {
            None
        };
        match self.bump() {
            Token::Eq | Token::ColonEq => {}
            other => return self.err(format!("expected `=` in for, found {other:?}")),
        }
        let from = self.parse_expr()?;
        self.expect_kw(Kw::To)?;
        let to = self.parse_expr()?;
        let mut by = Expr::Num(1.0);
        let mut mult = false;
        if self.eat_kw(Kw::By) {
            mult = self.eat(&Token::Mult);
            by = self.parse_expr()?;
        }
        self.expect_kw(Kw::Do)?;
        let body = self.capture_braced()?;
        Ok(Stmt::For {
            var,
            subscript,
            from,
            to,
            by,
            mult,
            body,
        })
    }

    /// Capture a brace-delimited block as raw tokens (excluding the braces),
    /// for deferred parsing by the evaluator. Assumes the body follows.
    fn capture_braced(&mut self) -> PResult<Body> {
        self.skip_newlines();
        self.expect(&Token::LeftBrace)?;
        let start = self.idx;
        let mut depth = 1i32;
        loop {
            match self.cur() {
                Token::LeftBrace => depth += 1,
                Token::RightBrace => {
                    depth -= 1;
                    if depth == 0 {
                        break;
                    }
                }
                Token::Eof => return self.err("unterminated `{` body"),
                _ => {}
            }
            self.bump();
        }
        let body = self.toks[start..self.idx].to_vec();
        self.expect(&Token::RightBrace)?;
        Ok(body)
    }

    fn parse_print(&mut self) -> PResult<Stmt> {
        self.expect_kw(Kw::Print)?;
        let item = if self.at_string_start() {
            PrintItem::Str(self.parse_stringexpr()?)
        } else {
            PrintItem::Expr(self.parse_expr()?)
        };
        Ok(Stmt::Print(item))
    }

    fn parse_exec(&mut self) -> PResult<Stmt> {
        let arg_frame = self.toks[self.idx].arg_frame.clone();
        self.expect_kw(Kw::Exec)?;
        let command = self.parse_stringexpr()?;
        Ok(Stmt::Exec { command, arg_frame })
    }

    fn parse_reset(&mut self) -> PResult<Stmt> {
        self.expect_kw(Kw::Reset)?;
        let mut list = Vec::new();
        if let Token::EnvVar(v) = self.cur() {
            list.push(*v);
            self.bump();
            while self.eat(&Token::Comma) {
                match self.cur() {
                    Token::EnvVar(v) => {
                        list.push(*v);
                        self.bump();
                    }
                    other => {
                        return self.err(format!("expected environment variable, found {other:?}"));
                    }
                }
            }
        }
        Ok(Stmt::Reset(list))
    }

    fn at_string_start(&self) -> bool {
        self.token_starts_string_at(0)
    }

    fn parse_animate(&mut self) -> PResult<Animate> {
        self.expect_kw(Kw::Animate)?;
        let target = self.parse_place()?;
        self.expect_kw(Kw::With)?;
        let effect_span = Some(self.cur_span());
        let effect = self.parse_stringexpr()?;
        let mut duration = None;
        let mut timing = Timing::Sequential;
        let mut delay = None;
        loop {
            if self.eat_kw(Kw::For) {
                duration = Some(self.parse_expr()?);
            } else if self.eat_kw(Kw::At) {
                timing = Timing::At(self.parse_expr()?);
            } else if self.eat_kw(Kw::After) {
                timing = Timing::After(self.parse_place()?);
            } else if self.eat_kw(Kw::Delay) {
                delay = Some(self.parse_expr()?);
            } else {
                break;
            }
        }
        Ok(Animate {
            target,
            effect,
            effect_span,
            duration,
            timing,
            delay,
        })
    }

    /// True if the current `Label` is followed by `:` (allowing a `[suffix]`).
    fn label_colon_ahead(&self) -> bool {
        match self.peek(1) {
            Token::Colon => true,
            Token::LeftBrack => {
                // scan past a balanced [ … ] suffix to find ':'
                let mut depth = 0;
                let mut i = self.idx + 1;
                while i < self.toks.len() {
                    match &self.toks[i].tok {
                        Token::LeftBrack => depth += 1,
                        Token::RightBrack => {
                            depth -= 1;
                            if depth == 0 {
                                return matches!(
                                    self.toks.get(i + 1).map(|s| &s.tok),
                                    Some(Token::Colon)
                                );
                            }
                        }
                        Token::Newline | Token::Eof => return false,
                        _ => {}
                    }
                    i += 1;
                }
                false
            }
            _ => false,
        }
    }

    fn at_object_start(&self) -> bool {
        matches!(
            self.cur(),
            Token::Prim(_)
                | Token::LeftBrack
                | Token::Block
                | Token::Str(_)
                | Token::Arg(_)
                | Token::Kw(Kw::Sprintf)
        ) || matches!(self.cur(), Token::Name(n) if n == "brace" || n == "dot")
    }

    fn at_assignment_start(&self) -> bool {
        match self.cur() {
            Token::Name(_) | Token::Label(_) => self.assignment_op_after_var_ref(),
            Token::EnvVar(_) => is_assign_op(self.peek(1)),
            _ => false,
        }
    }

    fn assignment_op_after_var_ref(&self) -> bool {
        let mut i = self.idx + 1;
        if matches!(self.toks.get(i).map(|s| &s.tok), Some(Token::LeftBrack)) {
            i += 1;
            let mut depth = 1i32;
            while let Some(tok) = self.toks.get(i).map(|s| &s.tok) {
                match tok {
                    Token::LeftBrack => depth += 1,
                    Token::RightBrack => {
                        depth -= 1;
                        if depth == 0 {
                            i += 1;
                            break;
                        }
                    }
                    Token::Eof | Token::Newline if depth > 0 => return false,
                    _ => {}
                }
                i += 1;
            }
            if depth != 0 {
                return false;
            }
        }
        self.toks.get(i).is_some_and(|s| is_assign_op(&s.tok))
    }

    fn parse_label(&mut self) -> PResult<Label> {
        let name = match self.bump() {
            Token::Label(s) => s,
            other => return self.err(format!("expected label, found {other:?}")),
        };
        let subscript = if self.eat(&Token::LeftBrack) {
            let e = self.parse_subscript()?;
            self.expect(&Token::RightBrack)?;
            Some(e)
        } else {
            None
        };
        Ok(Label { name, subscript })
    }

    fn parse_assignlist(&mut self) -> PResult<Vec<Assignment>> {
        let mut list = vec![self.parse_assignment()?];
        while self.eat(&Token::Comma) {
            list.push(self.parse_assignment()?);
        }
        Ok(list)
    }

    fn parse_assignment(&mut self) -> PResult<Assignment> {
        let target = match self.cur().clone() {
            Token::Name(name) | Token::Label(name) => {
                self.bump();
                let sub = if self.eat(&Token::LeftBrack) {
                    let e = self.parse_subscript()?;
                    self.expect(&Token::RightBrack)?;
                    Some(e)
                } else {
                    None
                };
                AssignTarget::Var(name, sub)
            }
            Token::EnvVar(v) => {
                self.bump();
                AssignTarget::Env(v)
            }
            other => return self.err(format!("expected assignment target, found {other:?}")),
        };
        let op = match self.bump() {
            Token::Eq => AssignOp::Set,
            Token::ColonEq => AssignOp::ColonSet,
            Token::PlusEq => AssignOp::Add,
            Token::MinusEq => AssignOp::Sub,
            Token::MultEq => AssignOp::Mul,
            Token::DivEq => AssignOp::Div,
            Token::RemEq => AssignOp::Rem,
            other => return self.err(format!("expected assignment operator, found {other:?}")),
        };
        let value = self.parse_expr()?;
        Ok(Assignment { target, op, value })
    }

    fn parse_subscript(&mut self) -> PResult<Expr> {
        let mut items = vec![self.parse_expr()?];
        while self.eat(&Token::Comma) {
            items.push(self.parse_expr()?);
        }
        if items.len() == 1 {
            Ok(items.pop().unwrap())
        } else {
            Ok(Expr::Index(items))
        }
    }

    // ---- objects & attributes ---------------------------------------------

    fn parse_object(&mut self) -> PResult<Object> {
        let mut attrs = Vec::new();
        // a bare string expression (literal, `$arg`, sprintf, concatenation)
        // places a text-only object.
        if self.at_string_start() {
            attrs.push(Attr::Text(self.parse_stringexpr()?));
            while let Some(a) = self.parse_attr(false, false, false, false)? {
                attrs.push(a);
            }
            return Ok(Object {
                kind: ObjectKind::Text,
                attrs,
            });
        }
        let kind = match self.cur().clone() {
            Token::Prim(p) => {
                self.bump();
                ObjectKind::Primitive(p)
            }
            Token::Block => {
                self.bump();
                ObjectKind::Empty
            }
            Token::Name(n) if n == "brace" => {
                self.bump();
                ObjectKind::Brace
            }
            Token::Name(n) if n == "dot" => {
                self.bump();
                ObjectKind::Dot
            }
            Token::LeftBrack => {
                self.bump();
                let stmts = self.parse_elementlist(&[Token::RightBrack])?;
                self.expect(&Token::RightBrack)?;
                ObjectKind::Block(stmts)
            }
            Token::Str(s) => {
                self.bump();
                attrs.push(Attr::Text(self.continue_string(StringExpr::Lit(s))?));
                ObjectKind::Text
            }
            Token::Kw(Kw::Continue) => {
                self.bump();
                ObjectKind::Continue
            }
            Token::Name(_) | Token::Label(_) => return self.expected_object(),
            _ => return self.expected_here("an object"),
        };
        // `spline <expr> <linespec>`: dpic's documented exception to the bare
        // distance rule — the expression right after `spline` is a tension
        // parameter, not a length. Parse it here so the attribute loop below
        // doesn't read it as `Attr::Dist`.
        if matches!(kind, ObjectKind::Primitive(Prim::Spline)) && self.spline_tension_ahead() {
            attrs.push(Attr::SplineTension(self.parse_expr()?));
        }
        let allow_fit = matches!(
            kind,
            ObjectKind::Primitive(Prim::Box | Prim::Circle | Prim::Ellipse)
        );
        let allow_brace = matches!(kind, ObjectKind::Brace);
        let allow_dot_fill = matches!(kind, ObjectKind::Dot);
        let allow_hatch = matches!(
            kind,
            ObjectKind::Primitive(
                Prim::Box
                    | Prim::Circle
                    | Prim::Ellipse
                    | Prim::Line
                    | Prim::Arrow
                    | Prim::Spline
                    | Prim::Arc
            )
        );
        let allow_close = matches!(kind, ObjectKind::Primitive(Prim::Line));
        while let Some(a) = self.parse_attr(
            allow_fit,
            allow_brace,
            allow_hatch || allow_dot_fill,
            allow_close,
        )? {
            attrs.push(a);
        }
        Ok(Object { kind, attrs })
    }

    /// True if the next token begins a bare scalar expression — the leading
    /// tension argument of `spline <expr>` — rather than a linespec keyword
    /// (`from`/`to`/`up`/`then`/…) or another attribute.
    fn spline_tension_ahead(&self) -> bool {
        matches!(
            self.cur(),
            Token::Float(_)
                | Token::Lparen
                | Token::EnvVar(_)
                | Token::Func1(_)
                | Token::Func2(_)
                | Token::Name(_)
                | Token::Minus
                | Token::Plus
                | Token::Kw(Kw::Rand)
        )
    }

    fn parse_attr(
        &mut self,
        allow_fit: bool,
        allow_brace: bool,
        allow_hatch: bool,
        allow_close: bool,
    ) -> PResult<Option<Attr>> {
        // any string expression (literal, sprintf, $arg, concatenation) is text
        if self.at_string_start() {
            return Ok(Some(Attr::Text(self.parse_stringexpr()?)));
        }
        let attr = match self.cur().clone() {
            Token::Kw(Kw::Ht) => {
                self.bump();
                Attr::Dim(DimKind::Ht, self.parse_expr()?)
            }
            Token::Kw(Kw::Wid) => {
                self.bump();
                Attr::Dim(DimKind::Wid, self.parse_expr()?)
            }
            Token::Kw(Kw::Rad) => {
                self.bump();
                Attr::Dim(DimKind::Rad, self.parse_expr()?)
            }
            Token::Kw(Kw::Diam) => {
                self.bump();
                Attr::Dim(DimKind::Diam, self.parse_expr()?)
            }
            Token::Kw(Kw::Thick) => {
                self.bump();
                Attr::Dim(DimKind::Thick, self.parse_expr()?)
            }
            Token::Kw(Kw::Scaled) => {
                self.bump();
                Attr::Dim(DimKind::Scaled, self.parse_expr()?)
            }
            Token::Dir(d) => {
                self.bump();
                Attr::Direction(
                    d,
                    self.opt_attr_expr(allow_fit, allow_brace, allow_hatch, allow_close)?,
                )
            }
            Token::LineType(lt) => {
                self.bump();
                Attr::LineStyle(
                    lt,
                    self.opt_attr_expr(allow_fit, allow_brace, allow_hatch, allow_close)?,
                )
            }
            Token::Kw(Kw::Chop) => {
                self.bump();
                Attr::Chop(self.opt_attr_expr(allow_fit, allow_brace, allow_hatch, allow_close)?)
            }
            Token::Kw(Kw::Fill) => {
                self.bump();
                Attr::Fill(self.opt_attr_expr(allow_fit, allow_brace, allow_hatch, allow_close)?)
            }
            Token::Arrow(a) => {
                self.bump();
                Attr::Arrowhead(
                    a,
                    self.opt_attr_expr(allow_fit, allow_brace, allow_hatch, allow_close)?,
                )
            }
            Token::Kw(Kw::Then) => {
                self.bump();
                Attr::Then
            }
            Token::Kw(Kw::Cw) => {
                self.bump();
                Attr::Cw
            }
            Token::Kw(Kw::Ccw) => {
                self.bump();
                Attr::Ccw
            }
            Token::Kw(Kw::Same) => {
                self.bump();
                Attr::Same
            }
            Token::Kw(Kw::Continue) => {
                self.bump();
                Attr::Continue
            }
            Token::Kw(Kw::From) => {
                self.bump();
                Attr::From(self.parse_position()?)
            }
            Token::Kw(Kw::To) => {
                self.bump();
                Attr::To(self.parse_position()?)
            }
            Token::Kw(Kw::At) => {
                self.bump();
                Attr::At(self.parse_position()?)
            }
            Token::Kw(Kw::By) => {
                self.bump();
                Attr::By(self.parse_position()?)
            }
            Token::Kw(Kw::With) => {
                self.bump();
                let anchor = if self.eat(&Token::Dot) {
                    WithAnchor::Place(self.parse_place()?)
                } else if let Token::Corner(c) = self.cur() {
                    let c = *c;
                    self.bump();
                    WithAnchor::Corner(c)
                } else if self.at(&Token::Lparen) {
                    self.bump();
                    let x = self.parse_expr()?;
                    self.expect(&Token::Comma)?;
                    let y = self.parse_expr()?;
                    self.expect(&Token::Rparen)?;
                    WithAnchor::Pair(x, y)
                } else {
                    WithAnchor::Plain
                };
                self.expect_kw(Kw::At)?;
                Attr::With {
                    anchor,
                    at: self.parse_position()?,
                }
            }
            Token::TextPos(tp) => {
                self.bump();
                Attr::TextPos(tp)
            }
            Token::Color(c) => {
                self.bump();
                // a colour may be a quoted string or a bareword name (e.g.
                // `shaded Custom`, `outlined red`).
                let s = match self.cur().clone() {
                    Token::Name(n) | Token::Label(n) => {
                        self.bump();
                        StringExpr::Lit(n)
                    }
                    _ => self.parse_stringexpr()?,
                };
                Attr::Color(c, s)
            }
            Token::Name(n) if allow_fit && n == "fit" => {
                self.bump();
                Attr::Fit
            }
            Token::Name(n) if allow_hatch && n == "hatch" => {
                self.bump();
                Attr::Hatch(HatchKind::Single)
            }
            Token::Name(n) if allow_hatch && n == "crosshatch" => {
                self.bump();
                Attr::Hatch(HatchKind::Cross)
            }
            Token::Name(n) if allow_hatch && n == "hatchangle" => {
                self.bump();
                Attr::HatchAngle(self.parse_expr()?)
            }
            Token::Name(n) if allow_hatch && n == "hatchsep" => {
                self.bump();
                Attr::HatchSep(self.parse_expr()?)
            }
            Token::Name(n) if allow_hatch && (n == "hatchwid" || n == "hatchwidth") => {
                self.bump();
                Attr::HatchWidth(self.parse_expr()?)
            }
            Token::Name(n) if allow_hatch && n == "hatchcolor" => {
                self.bump();
                let s = match self.cur().clone() {
                    Token::Name(n) | Token::Label(n) => {
                        self.bump();
                        StringExpr::Lit(n)
                    }
                    _ => self.parse_stringexpr()?,
                };
                Attr::HatchColor(s)
            }
            Token::Name(n) if allow_hatch && n == "gradient" => {
                self.bump();
                let from = self.parse_color_like()?;
                let to = self.parse_color_like()?;
                Attr::Gradient(from, to)
            }
            Token::Name(n) if allow_hatch && n == "gradientangle" => {
                self.bump();
                Attr::GradientAngle(self.parse_expr()?)
            }
            Token::Name(n) if n == "opacity" => {
                self.bump();
                Attr::Opacity(self.parse_expr()?)
            }
            Token::Name(n) if allow_close && n == "close" => {
                self.bump();
                Attr::Close
            }
            Token::Name(n) if allow_brace && n == "bracepos" => {
                self.bump();
                Attr::BracePos(self.parse_expr()?)
            }
            Token::Name(n) if allow_brace && n == "labeloffset" => {
                self.bump();
                Attr::BraceLabelOffset(self.parse_expr()?)
            }
            Token::Name(n) if n == "behind" => {
                self.bump();
                Attr::Behind(self.parse_place()?)
            }
            Token::Name(n) if n == "class" => {
                self.bump();
                Attr::Class(self.parse_stringexpr()?)
            }
            // a bare expression distance with no direction word, e.g. `move 1`,
            // `move -0.1`, `spline x` (length in the prevailing direction)
            Token::Float(_)
            | Token::Lparen
            | Token::EnvVar(_)
            | Token::Func1(_)
            | Token::Func2(_)
            | Token::Name(_)
            | Token::Minus
            | Token::Plus
            | Token::Kw(Kw::Rand) => {
                let span = self.cur_span();
                Attr::Dist(self.parse_expr()?, Some(span))
            }
            _ if self.place_is_scalar_ahead() => {
                let span = self.cur_span();
                Attr::Dist(self.parse_expr()?, Some(span))
            }
            _ => return Ok(None),
        };
        Ok(Some(attr))
    }

    fn expect_kw(&mut self, k: Kw) -> PResult<()> {
        if self.eat_kw(k) {
            Ok(())
        } else {
            self.expected_here(kw_text(k))
        }
    }

    // ---- string expressions ------------------------------------------------

    fn parse_stringexpr(&mut self) -> PResult<StringExpr> {
        let first = self.parse_string_atom()?;
        self.continue_string(first)
    }

    /// Continue a string expression with trailing `+ string` parts.
    fn continue_string(&mut self, first: StringExpr) -> PResult<StringExpr> {
        let mut e = first;
        while self.at(&Token::Plus) && self.string_after_plus() {
            self.bump();
            let rhs = self.parse_string_atom()?;
            e = StringExpr::Concat(Box::new(e), Box::new(rhs));
        }
        Ok(e)
    }

    fn string_after_plus(&self) -> bool {
        self.token_starts_string_at(1)
    }

    fn token_starts_string_at(&self, offset: usize) -> bool {
        match self.toks.get(self.idx + offset).map(|s| &s.tok) {
            Some(Token::Str(_) | Token::Arg(_) | Token::Kw(Kw::Sprintf)) => true,
            Some(Token::Name(n)) if n == "svg_font" => {
                matches!(
                    self.toks.get(self.idx + offset + 1).map(|s| &s.tok),
                    Some(Token::Lparen)
                )
            }
            _ => false,
        }
    }

    fn parse_string_atom(&mut self) -> PResult<StringExpr> {
        match self.cur().clone() {
            Token::Str(s) => {
                self.bump();
                Ok(StringExpr::Lit(s))
            }
            Token::Arg(n) => {
                self.bump();
                Ok(StringExpr::Arg(n))
            }
            Token::Kw(Kw::Sprintf) => {
                self.bump();
                self.expect(&Token::Lparen)?;
                let fmt = self.parse_stringexpr()?;
                let mut args = Vec::new();
                while self.eat(&Token::Comma) {
                    args.push(self.parse_expr()?);
                }
                self.expect(&Token::Rparen)?;
                Ok(StringExpr::Sprintf(Box::new(fmt), args))
            }
            Token::Name(n) if n == "svg_font" && matches!(self.peek(1), Token::Lparen) => {
                self.bump();
                self.expect(&Token::Lparen)?;
                let mut args = Vec::new();
                if !self.at(&Token::Rparen) {
                    args.push(self.parse_expr()?);
                    while self.eat(&Token::Comma) {
                        args.push(self.parse_expr()?);
                    }
                }
                self.expect(&Token::Rparen)?;
                Ok(StringExpr::SvgFont(args))
            }
            other => self.err(format!("expected a string, found {other:?}")),
        }
    }

    // ---- positions ---------------------------------------------------------

    fn parse_label_position(&mut self) -> PResult<Position> {
        let save = self.idx;
        if let Ok(x) = self.parse_expr()
            && self.eat(&Token::Comma)
        {
            let y = self.parse_expr()?;
            return Ok(Position::Pair(x, y));
        }
        self.idx = save;
        self.parse_position()
    }

    /// Positions support vector arithmetic; `+`/`-` are the lowest precedence.
    fn parse_position(&mut self) -> PResult<Position> {
        let mut left = self.parse_pos_mul()?;
        loop {
            let sign = if self.at(&Token::Plus) {
                Sign::Plus
            } else if self.at(&Token::Minus) {
                Sign::Minus
            } else {
                break;
            };
            self.bump();
            let right = self.parse_pos_mul()?;
            left = Position::Sum(sign, Box::new(left), Box::new(right));
        }
        Ok(left)
    }

    /// Scaling a position by a scalar: `p * s`, `p / s` (binds tighter than ±).
    fn parse_pos_mul(&mut self) -> PResult<Position> {
        let mut left = self.parse_pos_primary()?;
        loop {
            if self.eat(&Token::Mult) {
                left = Position::Scale(Box::new(left), self.parse_unary()?, false);
            } else if self.eat(&Token::Div) {
                left = Position::Scale(Box::new(left), self.parse_unary()?, true);
            } else {
                break;
            }
        }
        Ok(left)
    }

    fn parse_pos_primary(&mut self) -> PResult<Position> {
        // A fraction-led interpolation — `frac between A and B`, `frac <p,p>`, or
        // `frac of the way between A and B`. The fraction can be parenthesised
        // (e.g. `(X/Y) between A and B`), so try it before the `(`/place branches.
        if let Some(p) = self.try_fraction()? {
            return Ok(p);
        }
        // `( … )`: coordinate pair `(x,y)` of scalar expressions, a
        // parenthesised position, or `(pos, pos)` — x of the first, y of the
        // second. Try a scalar pair first so components that are themselves
        // parenthesised scalars (e.g. `((a*g)*cos(t), …)`) parse correctly.
        if self.eat(&Token::Lparen) {
            let save = self.idx;
            // Prefer parsing the contents as position(s) — handles `(A, B.c)`,
            // `(pos, pos)`, `(2,3)`, `(0.5 between A and B)`. If that fails, the
            // contents are scalar coordinate expressions that the position
            // grammar can't represent alone (e.g. `((a*g)*cos t, (a*g)*sin t)`).
            if let Ok(p1) = self.parse_position() {
                let p = if self.eat(&Token::Comma) {
                    let p2 = self.parse_position()?;
                    Position::Place(Location::ParenPair(Box::new(p1), Box::new(p2)))
                } else {
                    p1 // drop the redundant parentheses
                };
                self.expect(&Token::Rparen)?;
                return Ok(p);
            }
            self.idx = save;
            let e1 = self.parse_add()?;
            self.expect(&Token::Comma)?;
            let e2 = self.parse_add()?;
            self.expect(&Token::Rparen)?;
            return Ok(Position::Pair(e1, e2));
        }
        // A leading place is point-valued UNLESS it is a scalar accessor
        // (`place.x` / `.y` / `.attr`), which begins an `(expr, expr)` pair.
        if self.at_place_start() && !self.place_is_scalar_ahead() {
            return Ok(Position::Place(Location::Place(self.parse_place()?)));
        }
        // expression-led coordinate pair `x, y` (interpolation handled above)
        let e1 = self.parse_add()?;
        if self.eat(&Token::Comma) {
            let e2 = self.parse_add()?;
            return Ok(Position::Pair(e1, e2));
        }
        self.err("expected `,`, `between`, or `of the way between` in position")
    }

    /// Try to parse `frac (between | <p,p> | of the way between)`; if the leading
    /// expression isn't followed by an interpolation, backtrack and return `None`
    /// so the caller can parse a plain place / pair / parenthesised position.
    fn try_fraction(&mut self) -> PResult<Option<Position>> {
        let save = self.idx;
        let Ok(frac) = self.parse_add() else {
            self.idx = save;
            return Ok(None);
        };
        let mk = |frac, a, b, of_the_way| {
            Ok(Some(Position::Between {
                frac: Box::new(frac),
                a: Box::new(a),
                b: Box::new(b),
                of_the_way,
            }))
        };
        if self.eat(&Token::Lt) {
            let a = self.parse_position()?;
            self.expect(&Token::Comma)?;
            let b = self.parse_position()?;
            self.expect(&Token::Gt)?;
            return mk(frac, a, b, false);
        }
        let of_the_way = if self.at_kw(Kw::Of) {
            self.eat_kw(Kw::Of);
            if !(self.eat_kw(Kw::The) && self.eat_kw(Kw::Way) && self.eat_kw(Kw::Between)) {
                self.idx = save;
                return Ok(None);
            }
            true
        } else if self.eat_kw(Kw::Between) {
            false
        } else {
            self.idx = save;
            return Ok(None);
        };
        let a = self.parse_position()?;
        self.expect_kw(Kw::And)?;
        let b = self.parse_position()?;
        mk(frac, a, b, of_the_way)
    }

    /// Lookahead: does the upcoming place end in a scalar accessor
    /// (`.x` / `.y` / `.attr`)? If so it is a number, not a point. Non-consuming.
    fn place_is_scalar_ahead(&mut self) -> bool {
        let save = self.idx;
        let parsed = self.parse_place().is_ok();
        let scalar = parsed && matches!(self.cur(), Token::DotX | Token::DotY | Token::Param(_));
        self.idx = save;
        scalar
    }

    fn at_place_start(&self) -> bool {
        match self.cur() {
            Token::Label(_) | Token::Block | Token::Corner(_) => true,
            Token::Kw(Kw::Last) | Token::Kw(Kw::Here) => true,
            Token::Float(_) => matches!(self.peek(1), Token::Kw(Kw::Nth)),
            // `{expr}th …` / `` `expr`th … `` ordinal counts (only valid as a
            // place in position/expression context, never a group here)
            Token::LeftBrace | Token::LeftQuote => true,
            _ => false,
        }
    }

    fn parse_place(&mut self) -> PResult<Place> {
        // `corner [of] placename`
        if let Token::Corner(c) = self.cur() {
            let c = *c;
            self.bump();
            self.eat_kw(Kw::Of);
            let inner = self.parse_place()?;
            return Ok(Place::CornerOf(c, Box::new(inner)));
        }

        let mut place = self.parse_place_base()?;

        // trailing `.corner`, `.label`, `.nth primobj`
        loop {
            if let Token::Corner(c) = self.cur() {
                let c = *c;
                self.bump();
                place = Place::Corner(Box::new(place), c);
            } else if self.at(&Token::Dot) {
                self.bump();
                let rhs = self.parse_place_base()?;
                place = Place::Member(Box::new(place), Box::new(rhs));
            } else {
                break;
            }
        }
        Ok(place)
    }

    fn parse_place_base(&mut self) -> PResult<Place> {
        match self.cur().clone() {
            Token::Kw(Kw::Here) => {
                self.bump();
                Ok(Place::Here)
            }
            Token::Label(name) => {
                let span = Some(self.cur_span());
                self.bump();
                let subscript = if self.eat(&Token::LeftBrack) {
                    let e = self.parse_subscript()?;
                    self.expect(&Token::RightBrack)?;
                    Some(Box::new(e))
                } else {
                    None
                };
                Ok(Place::Name {
                    name,
                    subscript,
                    span,
                })
            }
            Token::Kw(Kw::Last) | Token::Float(_) | Token::LeftBrace | Token::LeftQuote => {
                let span = Some(self.cur_span());
                let count = self.parse_nth()?;
                // A type keyword may follow (`last box`); without one, this is an
                // untyped reference to the most recent object of any kind
                // (`last`, `last.c`, `2nd last.n`).
                let obj = if self.at_primobj() {
                    self.parse_primobj()?
                } else {
                    PrimObj::Any
                };
                Ok(Place::Nth { count, obj, span })
            }
            other => self.err(format!("expected a place, found {other:?}")),
        }
    }

    fn parse_nth(&mut self) -> PResult<Nth> {
        if self.eat_kw(Kw::Last) {
            return Ok(Nth::Last);
        }
        // ncount ordinal [last]
        let e = self.parse_ncount()?;
        self.expect_kw(Kw::Nth)?;
        let from_last = self.eat_kw(Kw::Last);
        Ok(Nth::Count(Box::new(e), from_last))
    }

    /// An ordinal count: a number, `` `expr' ``, or `{ expr }` (grammar:
    /// `ncount`). Must NOT recurse into the general expression grammar on a
    /// bare number, or `2nd` would re-enter place parsing.
    fn parse_ncount(&mut self) -> PResult<Expr> {
        match self.cur().clone() {
            Token::Float(v) => {
                self.bump();
                Ok(Expr::Num(v))
            }
            Token::LeftBrace => {
                self.bump();
                let e = self.parse_expr()?;
                self.expect(&Token::RightBrace)?;
                Ok(e)
            }
            Token::LeftQuote => {
                self.bump();
                let e = self.parse_expr()?;
                self.expect(&Token::RightQuote)?;
                Ok(e)
            }
            other => self.err(format!("expected an ordinal count, found {other:?}")),
        }
    }

    /// Whether the current token can begin a primitive-object type keyword
    /// (`box`, `[`, a string, …) — i.e. an explicit type after `last`/ordinal.
    fn at_primobj(&self) -> bool {
        matches!(
            self.cur(),
            Token::Prim(_) | Token::Block | Token::Str(_) | Token::LeftBrack
        ) || matches!(self.cur(), Token::Name(n) if n == "brace")
    }

    fn parse_primobj(&mut self) -> PResult<PrimObj> {
        match self.cur().clone() {
            Token::Prim(p) => {
                self.bump();
                Ok(PrimObj::Prim(p))
            }
            Token::Name(n) if n == "brace" => {
                self.bump();
                Ok(PrimObj::Brace)
            }
            Token::Block => {
                self.bump();
                Ok(PrimObj::Block)
            }
            Token::Str(s) => {
                self.bump();
                Ok(PrimObj::Str(s))
            }
            Token::LeftBrack => {
                self.bump();
                self.expect(&Token::RightBrack)?;
                Ok(PrimObj::EmptyBrack)
            }
            other => self.err(format!("expected a primitive object, found {other:?}")),
        }
    }

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

    fn opt_expr(&mut self) -> PResult<Option<Expr>> {
        if self.starts_scalar() || self.place_is_scalar_ahead() {
            Ok(Some(self.parse_expr()?))
        } else {
            Ok(None)
        }
    }

    /// A color argument: a bare name (`red`), a label-cased name, or any
    /// string expression — the same grammar `hatchcolor` accepts.
    fn parse_color_like(&mut self) -> PResult<StringExpr> {
        match self.cur().clone() {
            Token::Name(n) | Token::Label(n) => {
                self.bump();
                Ok(StringExpr::Lit(n))
            }
            _ => self.parse_stringexpr(),
        }
    }

    fn opt_attr_expr(
        &mut self,
        allow_fit: bool,
        allow_brace: bool,
        allow_hatch: bool,
        allow_close: bool,
    ) -> PResult<Option<Expr>> {
        if self.contextual_attr_ahead(allow_fit, allow_brace, allow_hatch, allow_close) {
            Ok(None)
        } else {
            self.opt_expr()
        }
    }

    fn contextual_attr_ahead(
        &self,
        allow_fit: bool,
        allow_brace: bool,
        allow_hatch: bool,
        allow_close: bool,
    ) -> bool {
        matches!(
            self.cur(),
            Token::Name(n)
                if (allow_fit && n == "fit")
                    || (allow_hatch
                        && matches!(
                            n.as_str(),
                            "hatch"
                                | "crosshatch"
                                | "hatchangle"
                                | "hatchsep"
                                | "hatchwid"
                                | "hatchwidth"
                                | "hatchcolor"
                                | "gradient"
                                | "gradientangle"
                        ))
                    || n == "opacity"
                    || (allow_brace && matches!(n.as_str(), "bracepos" | "labeloffset"))
                    || n == "behind"
                    || n == "class"
                    || (allow_close && n == "close")
        )
    }

    fn starts_scalar(&self) -> bool {
        matches!(
            self.cur(),
            Token::Float(_)
                | Token::Name(_)
                | Token::EnvVar(_)
                | Token::Lparen
                | Token::Minus
                | Token::Plus
                | Token::Not
                | Token::Func1(_)
                | Token::Func2(_)
                | Token::Kw(Kw::Rand)
                | Token::ArgCount
        )
    }

    fn parse_expr(&mut self) -> PResult<Expr> {
        self.parse_or()
    }

    fn parse_or(&mut self) -> PResult<Expr> {
        let mut e = self.parse_and()?;
        while self.eat(&Token::OrOr) {
            let r = self.parse_and()?;
            e = Expr::Bin(BinOp::Or, Box::new(e), Box::new(r));
        }
        Ok(e)
    }

    fn parse_and(&mut self) -> PResult<Expr> {
        let mut e = self.parse_cmp()?;
        while self.eat(&Token::AndAnd) {
            let r = self.parse_cmp()?;
            e = Expr::Bin(BinOp::And, Box::new(e), Box::new(r));
        }
        Ok(e)
    }

    fn parse_cmp(&mut self) -> PResult<Expr> {
        let mut e = self.parse_add()?;
        loop {
            let op = match self.cur() {
                Token::EqEq => BinOp::Eq,
                Token::Neq => BinOp::Ne,
                Token::Lt => BinOp::Lt,
                Token::Le => BinOp::Le,
                Token::Gt => BinOp::Gt,
                Token::Ge => BinOp::Ge,
                _ => break,
            };
            self.bump();
            let r = self.parse_add()?;
            e = Expr::Bin(op, Box::new(e), Box::new(r));
        }
        Ok(e)
    }

    fn parse_add(&mut self) -> PResult<Expr> {
        let mut e = self.parse_mul()?;
        loop {
            let op = match self.cur() {
                Token::Plus => BinOp::Add,
                Token::Minus => BinOp::Sub,
                _ => break,
            };
            self.bump();
            let r = self.parse_mul()?;
            e = Expr::Bin(op, Box::new(e), Box::new(r));
        }
        Ok(e)
    }

    fn parse_mul(&mut self) -> PResult<Expr> {
        let mut e = self.parse_unary()?;
        loop {
            let op = match self.cur() {
                Token::Mult => BinOp::Mul,
                Token::Div => BinOp::Div,
                Token::Percent => BinOp::Mod,
                _ => break,
            };
            self.bump();
            let r = self.parse_unary()?;
            e = Expr::Bin(op, Box::new(e), Box::new(r));
        }
        Ok(e)
    }

    fn parse_unary(&mut self) -> PResult<Expr> {
        let op = match self.cur() {
            Token::Minus => Some(UnOp::Neg),
            Token::Plus => Some(UnOp::Pos),
            Token::Not => Some(UnOp::Not),
            _ => None,
        };
        if let Some(op) = op {
            self.bump();
            let e = self.parse_unary()?;
            Ok(Expr::Unary(op, Box::new(e)))
        } else {
            self.parse_pow()
        }
    }

    fn parse_pow(&mut self) -> PResult<Expr> {
        let base = self.parse_primary()?;
        if self.eat(&Token::Caret) {
            let exp = self.parse_unary()?; // right-associative
            Ok(Expr::Bin(BinOp::Pow, Box::new(base), Box::new(exp)))
        } else {
            Ok(base)
        }
    }

    /// Lookahead from just inside a `(`: is the matching `)` immediately followed
    /// by `.x` or `.y`? (Used to read `( position ).x` as a coordinate.)
    fn paren_followed_by_dot_xy(&self) -> bool {
        let mut depth = 1i32;
        let mut i = self.idx;
        while let Some(s) = self.toks.get(i) {
            match &s.tok {
                Token::Lparen => depth += 1,
                Token::Rparen => {
                    depth -= 1;
                    if depth == 0 {
                        return matches!(
                            self.toks.get(i + 1).map(|t| &t.tok),
                            Some(Token::DotX | Token::DotY)
                        );
                    }
                }
                Token::Eof => return false,
                _ => {}
            }
            i += 1;
        }
        false
    }

    fn parse_primary(&mut self) -> PResult<Expr> {
        // place-derived scalars: location.x / location.y / place.attr
        if self.at_place_start() && self.place_is_scalar_ahead() {
            return self.parse_place_scalar();
        }
        // a string operand (only meaningful as an `==`/`!=` operand)
        if self.at_string_start() {
            return Ok(Expr::Str(self.parse_stringexpr()?));
        }
        match self.cur().clone() {
            Token::Float(v) => {
                self.bump();
                Ok(Expr::Num(v))
            }
            Token::Name(name) | Token::Label(name) => {
                self.bump();
                let subscript = if self.eat(&Token::LeftBrack) {
                    let e = self.parse_subscript()?;
                    self.expect(&Token::RightBrack)?;
                    Some(Box::new(e))
                } else {
                    None
                };
                Ok(Expr::Var(name, subscript))
            }
            Token::EnvVar(v) => {
                self.bump();
                Ok(Expr::Env(v))
            }
            Token::Lparen => {
                self.bump();
                // embedded assignment `( name = expr )` yields the assigned value
                if matches!(self.cur(), Token::Name(_) | Token::Label(_))
                    && self.assignment_op_after_var_ref()
                {
                    let name = match self.bump() {
                        Token::Name(n) | Token::Label(n) => n,
                        _ => unreachable!(),
                    };
                    let subscript = if self.eat(&Token::LeftBrack) {
                        let e = self.parse_subscript()?;
                        self.expect(&Token::RightBrack)?;
                        Some(Box::new(e))
                    } else {
                        None
                    };
                    self.bump(); // `=`
                    let v = self.parse_expr()?;
                    self.expect(&Token::Rparen)?;
                    return Ok(Expr::Assign(name, subscript, Box::new(v)));
                }
                // `( position ).x` / `.y` — a coordinate of a parenthesised
                // position (e.g. `(A - B).x`, `($1-($2)).y`). Chosen by lookahead
                // for a trailing `.x`/`.y`, since `(A - B)` alone parses as scalar
                // (labels read as variables).
                if self.paren_followed_by_dot_xy() {
                    let pos = self.parse_position()?;
                    self.expect(&Token::Rparen)?;
                    let loc = Location::Paren(Box::new(pos));
                    return Ok(if self.eat(&Token::DotX) {
                        Expr::DotX(loc)
                    } else {
                        self.expect(&Token::DotY)?;
                        Expr::DotY(loc)
                    });
                }
                // a plain scalar group `( expr )`
                let e = self.parse_expr()?;
                self.expect(&Token::Rparen)?;
                Ok(e)
            }
            // `$+` outside any macro invocation: zero arguments
            Token::ArgCount => {
                self.bump();
                Ok(Expr::Num(0.0))
            }
            Token::Func1(f) => {
                self.bump();
                self.expect(&Token::Lparen)?;
                let e = self.parse_expr()?;
                self.expect(&Token::Rparen)?;
                Ok(Expr::Func1(f, Box::new(e)))
            }
            Token::Func2(f) => {
                self.bump();
                self.expect(&Token::Lparen)?;
                let a = self.parse_expr()?;
                self.expect(&Token::Comma)?;
                let b = self.parse_expr()?;
                self.expect(&Token::Rparen)?;
                Ok(Expr::Func2(f, Box::new(a), Box::new(b)))
            }
            Token::Kw(Kw::Rand) => {
                self.bump();
                self.expect(&Token::Lparen)?;
                let arg = if self.at(&Token::Rparen) {
                    None
                } else {
                    Some(Box::new(self.parse_expr()?))
                };
                self.expect(&Token::Rparen)?;
                Ok(Expr::Rand(arg))
            }
            other => self.err(format!("expected an expression, found {other:?}")),
        }
    }

    /// Parse a place followed by `.x` / `.y` / `.attr` to yield a scalar.
    fn parse_place_scalar(&mut self) -> PResult<Expr> {
        let place = self.parse_place()?;
        match self.cur().clone() {
            Token::DotX => {
                self.bump();
                Ok(Expr::DotX(Location::Place(place)))
            }
            Token::DotY => {
                self.bump();
                Ok(Expr::DotY(Location::Place(place)))
            }
            Token::Param(p) => {
                self.bump();
                Ok(Expr::PlaceAttr(place, p))
            }
            other => self.err(format!(
                "a place is not a number here; expected `.x`, `.y`, or an attribute, found {other:?}"
            )),
        }
    }
}

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

    fn pic(src: &str) -> Picture {
        parse(src).unwrap_or_else(|e| panic!("parse error: {e}"))
    }

    #[test]
    fn kernighan_pipeline() {
        let p = pic(r#".PS
ellipse "document"
arrow
box "PIC"
arrow
box "TBL/EQN" "(optional)" dashed
arrow
box "TROFF"
arrow
ellipse "typesetter"
.PE
"#);
        assert_eq!(p.stmts.len(), 9);
        // the dashed box with two strings
        if let Stmt::Object { object, .. } = &p.stmts[4] {
            assert_eq!(object.kind, ObjectKind::Primitive(Prim::Box));
            let texts = object
                .attrs
                .iter()
                .filter(|a| matches!(a, Attr::Text(_)))
                .count();
            assert_eq!(texts, 2);
            assert!(
                object
                    .attrs
                    .iter()
                    .any(|a| matches!(a, Attr::LineStyle(LineType::Dashed, _)))
            );
        } else {
            panic!("expected object");
        }
    }

    #[test]
    fn box_with_dims_and_at() {
        let p = pic("box ht 0.3 wid 0.5 at 0.25,0.15");
        let Stmt::Object { object, .. } = &p.stmts[0] else {
            panic!()
        };
        assert!(matches!(object.attrs[0], Attr::Dim(DimKind::Ht, _)));
        assert!(matches!(object.attrs[1], Attr::Dim(DimKind::Wid, _)));
        assert!(matches!(object.attrs[2], Attr::At(Position::Pair(_, _))));
    }

    #[test]
    fn behind_parses_as_contextual_extension_attribute() {
        let p = pic("A: box\nbox behind A");
        let Stmt::Object { object, .. } = &p.stmts[1] else {
            panic!()
        };
        let Some(Attr::Behind(Place::Name {
            name, subscript, ..
        })) = object.attrs.last()
        else {
            panic!("expected behind attribute");
        };
        assert_eq!(name, "A");
        assert!(subscript.is_none());

        let p = pic("behind = 2\nbox wid behind");
        assert_eq!(p.stmts.len(), 2);
        assert!(matches!(p.stmts[0], Stmt::Assign(_)));
    }

    #[test]
    fn fit_parses_as_contextual_extension_attribute() {
        let p = pic("box \"long label\" fit");
        let Stmt::Object { object, .. } = &p.stmts[0] else {
            panic!()
        };
        assert!(object.attrs.iter().any(|a| matches!(a, Attr::Fit)));

        let p = pic("fit = 2\nbox wid fit");
        assert_eq!(p.stmts.len(), 2);
        assert!(matches!(p.stmts[0], Stmt::Assign(_)));

        let p = pic("fit = 2\nline fit");
        let Stmt::Object { object, .. } = &p.stmts[1] else {
            panic!()
        };
        assert!(matches!(object.attrs[0], Attr::Dist(_, _)));
    }

    #[test]
    fn hatch_parses_as_contextual_extension_attribute() {
        let p = pic("box hatch hatchangle 30 hatchsep .05 hatchwid 1.2 hatchcolor red");
        let Stmt::Object { object, .. } = &p.stmts[0] else {
            panic!()
        };
        assert!(
            object
                .attrs
                .iter()
                .any(|a| matches!(a, Attr::Hatch(HatchKind::Single)))
        );
        assert!(
            object
                .attrs
                .iter()
                .any(|a| matches!(a, Attr::HatchAngle(_)))
        );
        assert!(object.attrs.iter().any(|a| matches!(a, Attr::HatchSep(_))));
        assert!(
            object
                .attrs
                .iter()
                .any(|a| matches!(a, Attr::HatchWidth(_)))
        );
        assert!(
            object
                .attrs
                .iter()
                .any(|a| matches!(a, Attr::HatchColor(_)))
        );

        let p = pic("hatch = 2\nbox wid hatch");
        assert_eq!(p.stmts.len(), 2);
        assert!(matches!(p.stmts[0], Stmt::Assign(_)));
        let Stmt::Object { object, .. } = &p.stmts[1] else {
            panic!()
        };
        assert!(matches!(object.attrs[0], Attr::Dim(DimKind::Wid, _)));
    }

    #[test]
    fn opacity_parses_as_contextual_extension_attribute() {
        let p = pic("box opacity 0.5");
        let Stmt::Object { object, .. } = &p.stmts[0] else {
            panic!()
        };
        assert!(object.attrs.iter().any(|a| matches!(a, Attr::Opacity(_))));

        let p = pic("opacity = 2\nbox wid opacity");
        assert_eq!(p.stmts.len(), 2);
        assert!(matches!(p.stmts[0], Stmt::Assign(_)));
        let Stmt::Object { object, .. } = &p.stmts[1] else {
            panic!()
        };
        assert!(matches!(object.attrs[0], Attr::Dim(DimKind::Wid, _)));
    }

    #[test]
    fn close_parses_as_contextual_line_extension_attribute() {
        let p = pic("line right then up close");
        let Stmt::Object { object, .. } = &p.stmts[0] else {
            panic!()
        };
        assert!(object.attrs.iter().any(|a| matches!(a, Attr::Close)));

        let p = pic("close = 2\nbox wid close");
        assert_eq!(p.stmts.len(), 2);
        assert!(matches!(p.stmts[0], Stmt::Assign(_)));
        let Stmt::Object { object, .. } = &p.stmts[1] else {
            panic!()
        };
        assert!(matches!(object.attrs[0], Attr::Dim(DimKind::Wid, _)));
    }

    #[test]
    fn gradient_parses_as_contextual_extension_attribute() {
        let p = pic("box gradient \"steelblue\" white gradientangle 45");
        let Stmt::Object { object, .. } = &p.stmts[0] else {
            panic!()
        };
        assert!(object.attrs.iter().any(|a| matches!(a, Attr::Gradient(..))));
        assert!(
            object
                .attrs
                .iter()
                .any(|a| matches!(a, Attr::GradientAngle(_)))
        );

        // contextual fallback: `gradient` stays usable as a variable
        let p = pic("gradient = 2\nbox wid gradient");
        assert!(matches!(p.stmts[0], Stmt::Assign(_)));
        let Stmt::Object { object, .. } = &p.stmts[1] else {
            panic!()
        };
        assert!(matches!(object.attrs[0], Attr::Dim(DimKind::Wid, _)));
    }

    #[test]
    fn class_parses_inline_and_statement_forms() {
        let p = pic("box class \"critical\"");
        let Stmt::Object { object, .. } = &p.stmts[0] else {
            panic!()
        };
        assert!(object.attrs.iter().any(|a| matches!(a, Attr::Class(_))));

        let p = pic("A: box\nclass A \"hot\"\nclass last box \"cold\"");
        assert!(matches!(p.stmts[1], Stmt::Class { .. }));
        assert!(matches!(p.stmts[2], Stmt::Class { .. }));

        // contextual fallbacks: assignment and expression use survive
        let p = pic("class = 2\nbox wid class");
        assert!(matches!(p.stmts[0], Stmt::Assign(_)));
        let Stmt::Object { object, .. } = &p.stmts[1] else {
            panic!()
        };
        assert!(matches!(object.attrs[0], Attr::Dim(DimKind::Wid, _)));
    }

    #[test]
    fn brace_parses_as_contextual_extension_object() {
        let p = pic(
            "A: box\nB: box\nbrace from A.e to B.w down \"group\" wid .2 bracepos .4 labeloffset .1",
        );
        let Stmt::Object { object, .. } = &p.stmts[2] else {
            panic!()
        };
        assert_eq!(object.kind, ObjectKind::Brace);
        assert!(object.attrs.iter().any(|a| matches!(a, Attr::From(_))));
        assert!(object.attrs.iter().any(|a| matches!(a, Attr::To(_))));
        assert!(
            object
                .attrs
                .iter()
                .any(|a| matches!(a, Attr::Direction(Dir::Down, None)))
        );
        assert!(object.attrs.iter().any(|a| matches!(a, Attr::Text(_))));
        assert!(object.attrs.iter().any(|a| matches!(a, Attr::BracePos(_))));
        assert!(
            object
                .attrs
                .iter()
                .any(|a| matches!(a, Attr::BraceLabelOffset(_)))
        );

        let p = pic("brace = 2\nline right brace");
        assert!(matches!(p.stmts[0], Stmt::Assign(_)));
        let Stmt::Object { object, .. } = &p.stmts[1] else {
            panic!()
        };
        assert_eq!(object.kind, ObjectKind::Primitive(Prim::Line));

        let p = pic("brace from 0,0 to 1,0\nline from last brace.start to last brace.end");
        assert_eq!(p.stmts.len(), 2);
    }

    #[test]
    fn labeled_and_corners() {
        let p = pic("B1: box\narc -> from top of B1 to last box.ne");
        assert!(matches!(p.stmts[0], Stmt::Object { label: Some(_), .. }));
        let Stmt::Object { object, .. } = &p.stmts[1] else {
            panic!()
        };
        assert_eq!(object.kind, ObjectKind::Primitive(Prim::Arc));
        assert!(
            object
                .attrs
                .iter()
                .any(|a| matches!(a, Attr::Arrowhead(Arrow::Right, _)))
        );
        // from top of B1
        assert!(object.attrs.iter().any(|a| matches!(
            a,
            Attr::From(Position::Place(Location::Place(Place::CornerOf(
                Corner::N,
                _
            ))))
        )));
    }

    #[test]
    fn with_at_and_shift() {
        let p = pic("ellipse \"2\" with .nw at last ellipse.se + (0.1,0)");
        let Stmt::Object { object, .. } = &p.stmts[0] else {
            panic!()
        };
        let with = object
            .attrs
            .iter()
            .find(|a| matches!(a, Attr::With { .. }))
            .unwrap();
        let Attr::With { anchor, at } = with else {
            panic!()
        };
        assert_eq!(*anchor, WithAnchor::Corner(Corner::Nw));
        // `last ellipse.se + (0.1,0)` is a position sum
        assert!(matches!(at, Position::Sum(Sign::Plus, _, _)));
    }

    #[test]
    fn with_member_anchor_parses() {
        let p = pic("[ A: box ] with .A.c at Here");
        let Stmt::Object { object, .. } = &p.stmts[0] else {
            panic!()
        };
        let with = object
            .attrs
            .iter()
            .find(|a| matches!(a, Attr::With { .. }))
            .unwrap();
        let Attr::With { anchor, .. } = with else {
            panic!()
        };
        assert!(matches!(
            anchor,
            WithAnchor::Place(Place::Corner(inner, Corner::Center))
                if matches!(inner.as_ref(), Place::Name { name, .. } if name == "A")
        ));
    }

    #[test]
    fn expression_precedence() {
        // 2 + 3 * 4 ^ 2  ==  2 + (3 * (4^2)) = 50
        let p = pic("x = 2 + 3 * 4 ^ 2");
        let Stmt::Assign(list) = &p.stmts[0] else {
            panic!()
        };
        // structure: Add(2, Mul(3, Pow(4,2)))
        let Expr::Bin(BinOp::Add, _, rhs) = &list[0].value else {
            panic!("expected top-level add")
        };
        assert!(matches!(**rhs, Expr::Bin(BinOp::Mul, _, _)));
    }

    #[test]
    fn between_position() {
        let p = pic("arrow from 1/3 of the way between A.ne and A.se");
        let Stmt::Object { object, .. } = &p.stmts[0] else {
            panic!()
        };
        assert!(object.attrs.iter().any(|a| matches!(
            a,
            Attr::From(Position::Between {
                of_the_way: true,
                ..
            })
        )));
    }

    #[test]
    fn assignment_list_and_envvar() {
        let p = pic("boxht = 0.3; boxwid = 2 * boxht");
        assert_eq!(p.stmts.len(), 2);
        let Stmt::Assign(a0) = &p.stmts[0] else {
            panic!()
        };
        assert_eq!(a0[0].target, AssignTarget::Env(EnvVar::Boxht));
    }

    #[test]
    fn dpic_svg_font_stub_parses_as_string() {
        let p = pic("print svg_font(\"Times\", 12)");
        let Stmt::Print(PrintItem::Str(StringExpr::SvgFont(args))) = &p.stmts[0] else {
            panic!()
        };
        assert_eq!(args.len(), 2);
    }

    #[test]
    fn subscripted_variable_refs_parse() {
        let p = pic("P[1] = 2\nx = P[1]");
        let Stmt::Assign(a0) = &p.stmts[0] else {
            panic!()
        };
        assert!(matches!(&a0[0].target, AssignTarget::Var(name, Some(_)) if name == "P"));

        let Stmt::Assign(a1) = &p.stmts[1] else {
            panic!()
        };
        assert!(matches!(&a1[0].value, Expr::Var(name, Some(_)) if name == "P"));
    }

    #[test]
    fn block_object() {
        let p = pic("[ box; circle ] with .nw at Here");
        let Stmt::Object { object, .. } = &p.stmts[0] else {
            panic!()
        };
        let ObjectKind::Block(inner) = &object.kind else {
            panic!()
        };
        assert_eq!(inner.len(), 2);
    }

    #[test]
    fn diamond_line_with_then() {
        let p = pic("line up right then down right then down left then up left");
        let Stmt::Object { object, .. } = &p.stmts[0] else {
            panic!()
        };
        let thens = object
            .attrs
            .iter()
            .filter(|a| matches!(a, Attr::Then))
            .count();
        assert_eq!(thens, 3);
    }

    #[test]
    fn place_scalar_in_coord_pair() {
        // issue #3: (A.x, expr) must parse as an (expr,expr) pair, not a place
        let p = pic("A: box\n\"t\" at (A.x, A.y - 0.5)");
        let Stmt::Object { object, .. } = &p.stmts[1] else {
            panic!()
        };
        assert!(
            object
                .attrs
                .iter()
                .any(|a| matches!(a, Attr::At(Position::Pair(_, _))))
        );
        // a plain point place still parses as a place position
        let q = pic("A: box\nbox at A.ne");
        let Stmt::Object { object, .. } = &q.stmts[1] else {
            panic!()
        };
        assert!(object.attrs.iter().any(|a| matches!(
            a,
            Attr::At(Position::Place(Location::Place(Place::Corner(_, _))))
        )));
    }

    #[test]
    fn ignores_non_svg_backend_preambles() {
        let p = pic(r#".PS
verbatimtex
\global\def\foo#1{#1}
etex
\global\def\bar#1{#1}
\psset{arrowsize=4pt}
box
.PE
"#);
        assert_eq!(p.stmts.len(), 1);
        let Stmt::Object { object, .. } = &p.stmts[0] else {
            panic!()
        };
        assert_eq!(object.kind, ObjectKind::Primitive(Prim::Box));
    }

    #[test]
    fn backend_filter_keeps_global_lines_inside_strings() {
        let p = pic(
            "sh \"echo -n \\\"print \\\\\"\\\" > x\"\nif dpicopt==optPGF then { command \"cycle; \\\n\\global\\let\\dpicdraw=x\" } else { box }",
        );
        assert_eq!(p.stmts.len(), 2);
        let Stmt::Object { object, .. } = &p.stmts[1] else {
            panic!()
        };
        assert_eq!(object.kind, ObjectKind::Primitive(Prim::Box));
    }

    #[test]
    fn static_if_copy_defines_macros_before_following_statements() {
        let dir = std::env::temp_dir().join(format!("rpic_static_if_{}", std::process::id()));
        std::fs::create_dir_all(&dir).unwrap();
        std::fs::write(dir.join("macros.pic"), "define makebox { box wid $1 }\n").unwrap();
        std::fs::write(
            dir.join("inc.pic"),
            "define makecircle { circle rad 0.1 }\n",
        )
        .unwrap();
        let p = parse_in_dir(
            "if \"plotlib\" != \"1\" then { copy \"macros.pic\" }\ndefine choose { if \"$1\"==\"\" then { box } else { copy \"$1/inc.pic\" } }\nchoose(.)\nmakecircle()\nmakebox(0.4)",
            Some(dir.as_path()),
        )
        .unwrap_or_else(|e| panic!("parse error: {e}"));
        let _ = std::fs::remove_dir_all(&dir);
        assert_eq!(p.stmts.len(), 2);
        let Stmt::Object { object, .. } = &p.stmts[0] else {
            panic!()
        };
        assert_eq!(object.kind, ObjectKind::Primitive(Prim::Circle));
        let Stmt::Object { object, .. } = &p.stmts[1] else {
            panic!()
        };
        assert_eq!(object.kind, ObjectKind::Primitive(Prim::Box));
    }

    #[test]
    fn unsupported_control_is_clear() {
        // `copy "file"` with no filesystem context reports a clear file error
        let e = parse("copy \"x\"").unwrap_err();
        assert!(e.msg.contains("copy") && e.msg.contains("file"));
    }

    #[test]
    fn control_constructs_parse() {
        assert!(parse("for i = 1 to 3 do { box }").is_ok());
        assert!(parse("if 1 > 0 then { box } else { circle }").is_ok());
        assert!(parse("reset boxht, boxwid").is_ok());
        // define is consumed by the preprocessor and expanded
        let p = parse("define e { box }\ne\ne").unwrap();
        assert_eq!(p.stmts.len(), 2);
    }
}