drawland-core 0.5.0

Maps drawn for pen plotters: OSM features to a layered SVG. No I/O.
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
//! The graph a profile script builds (`drawland-script`), and its JSON form:
//! named nodes in four typed sections, the draws, and the composition.
//!
//! ```json
//! { "output": { "width": "6in", "height": "4in", "scale": "1:10000" },
//!   "$features": { "bldg_1": { "tiles_select": "buildings", "at": [3, 14] } },
//!   "$areas": { "polygons_2": { "tools_polygons": "$features.bldg_1", "at": [4, 19] } },
//!   "$lines": { "rings_3": { "tools_rings": "$areas.polygons_2", "at": [5, 15] } },
//!   "draw": [{ "id": "bldg_ring", "from": "$lines.rings_3", "stroke": "solid", "at": [6, 1] }],
//!   "compose": { "order": ["bldg_ring"] } }
//! ```
//!
//! A node refers to another by `$section.name`; the section is its type.
//! Operations are namespaced: `tools_*` (this module), `osm_*` / `tiles_*` /
//! `engine_*` (sources: Overpass, vector tiles, the output, the ocean) and
//! `module_*` (compiled recipes such as roads, whose outputs are drawn as
//! `roads.outlines`). `at` is where the script made the node; errors about it
//! carry that line and column.
//!
//! Loading is strict: unknown sections, operations and names are errors at
//! load, never halfway through a render.

use crate::profile::{FillSpec, StrokeSpec};
use crate::select::{Selector, TagMatch, TagTest};
use crate::units::Mm;
use serde::de::{self, Deserializer, MapAccess, Visitor};
use serde::{Deserialize, Serialize};
use serde_json::Value;
use std::collections::{BTreeMap, BTreeSet};
use std::fmt;

// ---------------------------------------------------------------------------
// Names
// ---------------------------------------------------------------------------

/// Which section a name lives in. The section is the type.
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub enum Section {
    Features,
    Areas,
    Lines,
    Fills,
}

impl Section {
    pub const ALL: [Section; 4] = [Section::Features, Section::Areas, Section::Lines, Section::Fills];

    pub fn key(self) -> &'static str {
        match self {
            Section::Features => "features",
            Section::Areas => "areas",
            Section::Lines => "lines",
            Section::Fills => "fills",
        }
    }
}

impl fmt::Display for Section {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        f.write_str(self.key())
    }
}

/// A reference such as `$areas.river` or `$fills.hatch`.
#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct Name {
    pub section: Section,
    pub name: String,
}

impl Name {
    /// Parse `$<section>.<name>`. Anything else (a bare word)
    /// is not a reference the grammar resolver understands.
    pub fn parse(text: &str) -> Result<Name, String> {
        let rest = text.strip_prefix('$').ok_or_else(|| format!("{text:?} is not a $section.name reference"))?;
        let (section, name) = rest
            .split_once('.')
            .ok_or_else(|| format!("{text:?} has no section (expected $section.name)"))?;
        let section = Section::ALL
            .into_iter()
            .find(|s| s.key() == section)
            .ok_or_else(|| format!("unknown section {section:?} in {text:?}"))?;
        if name.is_empty() {
            return Err(format!("{text:?} has an empty name"));
        }
        Ok(Name { section, name: name.to_string() })
    }
}

impl fmt::Display for Name {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        write!(f, "${}.{}", self.section.key(), self.name)
    }
}

/// An SVG group id: a label, not a variable, so it carries no marker.
#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord)]
pub struct Id(pub String);

// ---------------------------------------------------------------------------
// Operations
// ---------------------------------------------------------------------------

/// A tag filter, as `osm_select: { building: true, highway: [primary] }`.
pub type Select = Vec<(String, TagMatch)>;

/// A vector tile selection, as `tiles_select: [buildings, landcover:park]`:
/// terramask presets and `layer:class` rules, a class or a subclass by name.
#[derive(Debug, Clone, PartialEq)]
pub struct TileSelect {
    /// As written.
    pub items: Vec<String>,
    pub filter: terramask::Filter,
}

/// Where a `data_select` reads its features.
#[derive(Debug, Clone, PartialEq)]
pub enum DataSource {
    /// A GeoJSON URL or file path, for the host to read.
    Url(String),
    /// GeoJSON the profile wrote out itself.
    Inline(Value),
    /// Plain JSON with positions in it (a transit API, a feed), read by the
    /// host like a GeoJSON URL and turned into points by [`JsonSource`].
    Json(JsonSource),
}

impl DataSource {
    /// The URL or path the host reads, when there is one.
    pub fn url(&self) -> Option<&str> {
        match self {
            DataSource::Url(u) => Some(u),
            DataSource::Json(j) => Some(&j.url),
            DataSource::Inline(_) => None,
        }
    }
}

/// `features.json(url, { items, lat, lng })`: dot-paths into the reply — the
/// array of items (empty: the reply is the array), and each item's latitude
/// and longitude (numbers, or numbers written as text).
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct JsonSource {
    pub url: String,
    #[serde(default)]
    pub items: String,
    pub lat: String,
    pub lng: String,
}

/// `tools_where`: the features of `of` whose tags pass every test, as
/// `{ of: $features.b, tags: { render_height: { min: 20, max: 40 } } }`.
#[derive(Debug, Clone, PartialEq)]
pub struct Where {
    pub of: Name,
    pub tags: Vec<(String, TagTest)>,
}

/// A compiled module, reading `from` when given, else every OSM feature.
#[derive(Debug, Clone, PartialEq)]
pub struct Module {
    pub name: String,
    pub from: Option<Name>,
    pub roads: crate::themes::RoadOptions,
}

/// Buffer a shape by a distance, positive or negative.
#[derive(Debug, Clone, PartialEq)]
pub struct Grow {
    pub of: Name,
    pub by: Mm,
}

/// An area moved across the page by `by` mm (x right, y down): a shadow
/// cast off what casts it.
#[derive(Debug, Clone, PartialEq)]
pub struct Move {
    pub of: Name,
    pub by: [Mm; 2],
}

/// A disc of radius `by` around every point of a feature set (mapped trees),
/// merged into one area. Lines and polygons in the set are ignored.
#[derive(Debug, Clone, PartialEq)]
pub struct Around {
    pub of: Name,
    pub by: Mm,
}

/// Geometry written by the profile: `points` are mm offsets from `at`, in
/// page axes (x right, y down), turned clockwise by `rotate` degrees. `at` is
/// a place on the ground or a point on the page.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct Shape {
    pub at: ShapeAt,
    pub points: Vec<[f64; 2]>,
    #[serde(default)]
    pub rotate: f64,
    /// Lines only: join the last point back to the first.
    #[serde(default)]
    pub closed: bool,
}

#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(untagged)]
pub enum ShapeAt {
    Geo { lat: f64, lng: f64 },
    Page([PagePos; 2]),
}

/// A page coordinate: a length, or `"50%"` of the page's width (x) or height (y).
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(untagged)]
pub enum PagePos {
    Mm(Mm),
    Percent(String),
}

/// A line of text written by the profile, centred on `at`; `size` is the
/// capital height.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct Text {
    pub at: ShapeAt,
    pub text: String,
    pub size: Mm,
    #[serde(default)]
    pub font: crate::text::LabelFont,
    #[serde(default)]
    pub rotate: f64,
    /// `areas.text` with an outline font: keep the letters' counters (the
    /// holes in A, B, O) open, for a fill inside the letters; closed by
    /// default, for a mask.
    #[serde(default, rename = "openCounters", skip_serializing_if = "std::ops::Not::not")]
    pub open_counters: bool,
}

/// `"50%"` as a fraction, 0.5.
pub fn percent(s: &str) -> Option<f64> {
    s.trim().strip_suffix('%')?.trim().parse::<f64>().ok().map(|p| p / 100.0)
}

/// How `tools_buffer_lines` ends each stroke.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum LineBufferCap {
    #[default]
    Round,
    Flat,
}

/// Buffer lines by a half-width, merged into one area. Caps and joins are round
/// unless `cap` is `flat` (butt caps; joins stay round).
#[derive(Debug, Clone, PartialEq)]
pub struct BufferLines {
    pub lines: Name,
    pub by: Mm,
    pub cap: LineBufferCap,
}

/// Close the thin gaps between `of` and the edges of `within` (tile polygons
/// that stop just short of the card border); `gap_mm` is the widest closed.
#[derive(Debug, Clone, PartialEq)]
pub struct ExtendToFrame {
    pub of: Name,
    pub within: Name,
    pub gap_mm: Option<Mm>,
}

/// `tools_terrain`: pen-and-ink terrain in an area, drawn by burin from the
/// elevation under the output.
#[derive(Debug, Clone, PartialEq)]
pub struct Terrain {
    /// The area to draw in, or `None` for the whole output.
    pub in_area: Option<Name>,
    /// The colour at each dash, as burin writes one: a hex colour, or a tree.
    pub color: Option<serde_json::Value>,
    /// The line width at each dash, as a multiple of the pen.
    pub width: Option<serde_json::Value>,
    /// The field the streamlines run along, degrees.
    pub angle: f64,
    /// What to call the layer; `terrain` without one.
    pub layer: Option<String>,
    /// Style parameters, as burin names them.
    pub style: serde_json::Map<String, serde_json::Value>,
    /// Draw the shore (the zero contour) as well.
    pub shore: bool,
    /// The heights a fill keeps to, as burin writes them: `elevMin`, `elevMax`
    /// and the depths. Empty for streamlines, which cover the ground they can.
    pub band: serde_json::Map<String, serde_json::Value>,
    /// What to draw: streamlines along the slope, or a fill of the band.
    pub draw: TerrainDraw,
}

/// What a `tools_terrain` def draws.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum TerrainDraw {
    /// Pen-and-ink hatching along the slope; the default.
    #[default]
    Lines,
    /// A flat fill of the band: what a contour belt between two heights is.
    Fill,
    /// Stippling, denser where the shading is darker.
    Dots,
}

/// `tools_burin`: a whole burin document, built by burin's own language inside
/// a draw.land profile, drawn by the engine from the elevation under the
/// output. The atlas is burin's own JSON — the same thing `burin.draw()`
/// yields at burin's front ends — so no vocabulary is repeated here.
#[derive(Debug, Clone, PartialEq, Default)]
pub struct Burin {
    /// The burin atlas, as `burin.json()` writes it: batches and water passes.
    pub atlas: serde_json::Value,
    /// The area the drawing is kept to, or `None` for the whole output.
    pub in_area: Option<Name>,
    /// Regions batches name in `within` / `outside`, by name, in output mm.
    pub regions: std::collections::BTreeMap<String, Name>,
    /// Where the water is, in output mm: burin's water mask. `None` lets burin
    /// guess it from the elevation (at or below 0.5 m).
    pub water: Option<Name>,
    /// What to call the layer; `burin` without one.
    pub layer: Option<String>,
}

#[derive(Debug, Clone, PartialEq)]
pub struct Difference {
    pub base: Name,
    /// Named defs to subtract (empty when `cut_rule` is used).
    pub cut: Vec<Name>,
    /// `cut: { tools_rings: $areas.a }` — a rule written on the line.
    pub cut_rule: Option<Box<Op>>,
}

/// What `tools_union` / `tools_join` read.
#[derive(Debug, Clone, PartialEq)]
pub enum UnionRules {
    /// `tools_union: [$areas.a, $areas.b]`
    Refs(Vec<Name>),
    /// `tools_union: $areas.a` — one reference, `list: false`
    Ref(Name),
}

#[derive(Debug, Clone, PartialEq)]
pub struct Intersect {
    pub base: Name,
    /// A named def (empty when `keep_rule` is used).
    pub keep: Option<Name>,
    pub keep_rule: Option<Box<Op>>,
}

#[derive(Debug, Clone, PartialEq)]
pub struct Rings {
    pub of: Name,
    pub exterior_only: bool,
}

#[derive(Debug, Clone, PartialEq)]
pub struct ClipLines {
    pub lines: Name,
    pub within: Name,
    pub invert: bool,
}

/// Read strokes or the covered area from a `$lines` labels def, optionally
/// one rule bucket (`rule: "park"` matches `modules.labels` `rules[].id`).
#[derive(Debug, Clone, PartialEq)]
pub struct LabelPick {
    pub of: Name,
    pub rule: Option<String>,
    /// Only the places' dots (`marker`), not the letters.
    pub dots: bool,
}

/// `tools_labels`: the names of `from`, placed so that none covers another,
/// as the pen strokes of their letters. What the letters cover is read from
/// it by `tools_label_area` / `tools_label_lines`.
#[derive(Debug, Clone, PartialEq)]
pub struct Labels {
    /// Placed together, so no set's labels cover another's.
    pub from: Vec<Name>,
    pub in_area: Option<Name>,
    /// An area the letters keep off (the lines of a transit map); a place's
    /// point and dot may still sit on it.
    pub avoid: Option<Name>,
    pub style: crate::labels::Style,
}

/// `tools_graticule` (lines) / `tools_graticule_area` (an area): an atlas
/// plate's meridians and parallels round the page rectangle `in` (its
/// bounds), through the output's projection. `part` picks what comes out.
#[derive(Debug, Clone, PartialEq)]
pub struct Graticule {
    pub in_area: Name,
    pub look: GraticuleLook,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum GraticulePart {
    /// Lines: the meridians and parallels, cut to `in`.
    Grid,
    /// Lines: the degree labels round the border; as an area, what they cover.
    Labels,
    /// An area: the border's inked keys.
    Keys,
}

#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct GraticuleLook {
    pub part: GraticulePart,
    /// Minutes of arc between lines, and between labels.
    pub step: f64,
    /// Minutes of arc per key of the border; 0, none.
    #[serde(default)]
    pub ticks: f64,
    /// The key band's width, just outside `in`.
    #[serde(default)]
    pub band: Mm,
    /// Paper between the band and the labels.
    #[serde(default)]
    pub gap: Mm,
    /// The labels' capital height.
    #[serde(default = "graticule_size")]
    pub size: Mm,
    #[serde(default)]
    pub font: crate::text::LabelFont,
}

fn graticule_size() -> Mm {
    Mm(1.8)
}

/// A penfill run. `per: feature` runs one pattern per polygon instead of one
/// on the union. `content` fills the area with lines made elsewhere (burin's,
/// or any `$lines`), cut to it, instead of a pattern. `motif` is lines drawn
/// elsewhere (`lines.text`, `lines.shape`) used as the pattern's motif: the
/// runner centres them on the origin and hands them to penfill as polylines.
#[derive(Debug, Clone, PartialEq)]
pub struct Fill {
    pub in_area: Name,
    pub per_feature: bool,
    pub content: Option<Name>,
    pub motif: Option<Name>,
    pub spec: FillSpec,
}

/// One operation. Every variant names the section it produces.
#[derive(Debug, Clone, PartialEq)]
pub enum Op {
    // ---- feature sets ----------------------------------------------------
    Select(Selector),
    TileSelect(TileSelect),
    /// `data_select: "<url or path>"`, or `data_select: { geojson: {…} }`:
    /// every feature of a GeoJSON dataset, read by the host (see
    /// [`Grammar::datasets`]) or written in the profile.
    DataSelect(DataSource),
    /// `terrain_select: { contours: {…} }` or `{ soundings: {…} }`: features
    /// made from the elevation, their heights as tags (see [`crate::contours`]).
    TerrainSelect(crate::contours::TerrainSelect),
    Where(Where),

    // ---- areas -----------------------------------------------------------
    Polygons(Name),
    Union(UnionRules),
    Difference(Difference),
    Intersect(Intersect),
    FillHoles(Name),
    Grow(Grow),
    Move(Move),
    Around(Around),
    /// A closed shape written by the profile.
    Shape(Shape),
    /// What a profile's text covers.
    TextArea(Text),
    /// An atlas graticule's keys, or its labels' cover.
    GraticuleArea(Graticule),
    BufferLines(BufferLines),
    /// What the letters of a `$lines` labels def cover.
    LabelArea(LabelPick),
    /// What a fill covers on paper (its clearings left out, its overflow
    /// in), to mask other layers with.
    FillCover(Fill),
    /// The output rectangle.
    Frame,
    ExtendToFrame(ExtendToFrame),

    // ---- lines -----------------------------------------------------------
    Rings(Rings),
    Lines(Name),
    Segments(Name),
    Dedupe(Name),
    Merge(Name),
    Join(UnionRules),
    ClipLines(ClipLines),
    /// A line written by the profile.
    Path(Shape),
    /// Text written by the profile, as pen strokes.
    Text(Text),
    /// An atlas graticule: its lines, or its degree labels.
    Graticule(Graticule),
    /// Pen-and-ink terrain, drawn by burin from the elevation.
    Terrain(Terrain),
    /// A height or depth band of the elevation, as an area (`areas.band`): the
    /// fill burin would draw for `draw: "fill"`, closed into polygons.
    TerrainBand(Terrain),
    /// A whole burin document, drawn from the elevation.
    Burin(Burin),
    /// Names on the map, as pen strokes.
    Labels(Labels),
    /// Strokes from a labels def, or one of its rule buckets.
    LabelLines(LabelPick),

    // ---- fills (lines, produced by penfill) -------------------------------
    Fill(Fill),

    // ---- compiled modules (roads) ----------------------------------------
    /// Publishes named outputs (`roads.area`, `roads.outlines`, …).
    Module(Module),
}

impl Clip {
    pub fn auto() -> Clip {
        Clip::Auto
    }
}

impl Op {
    /// What a def holding this operation defines.
    pub fn section(&self) -> Section {
        match self {
            Op::Select(_) | Op::TileSelect(_) | Op::DataSelect(_) | Op::TerrainSelect(_) | Op::Where(_) => Section::Features,
            Op::Polygons(_)
            | Op::Union(_)
            | Op::Difference(_)
            | Op::Intersect(_)
            | Op::FillHoles(_)
            | Op::Grow(_)
            | Op::Move(_)
            | Op::Around(_)
            | Op::Shape(_)
            | Op::TextArea(_)
            | Op::GraticuleArea(_)
            | Op::BufferLines(_)
            | Op::LabelArea(_)
            | Op::FillCover(_)
            | Op::Frame
            | Op::ExtendToFrame(_)
            | Op::TerrainBand(_) => Section::Areas,
            Op::Path(_)
            | Op::Text(_)
            | Op::Graticule(_)
            | Op::Rings(_)
            | Op::Lines(_)
            | Op::Segments(_)
            | Op::Dedupe(_)
            | Op::Merge(_)
            | Op::Join(_)
            | Op::ClipLines(_)
            | Op::Terrain(_)
            | Op::Burin(_)
            | Op::Labels(_)
            | Op::LabelLines(_) => Section::Lines,
            Op::Fill(_) => Section::Fills,
            // A module is called from $areas: its headline output is an area,
            // and the rest are reached by output name (`roads.outlines`).
            Op::Module(_) => Section::Areas,
        }
    }

    /// The names this operation reads.
    pub fn refs(&self) -> Vec<Name> {
        match self {
            Op::Select(_) | Op::TileSelect(_) | Op::DataSelect(_) | Op::TerrainSelect(_) | Op::Frame | Op::Shape(_) | Op::Path(_) | Op::Text(_) | Op::TextArea(_) => vec![],
            Op::Module(m) => m.from.iter().cloned().collect(),
            Op::Polygons(n) | Op::FillHoles(n) | Op::Dedupe(n) | Op::Merge(n) | Op::Lines(n) | Op::Segments(n) => {
                vec![n.clone()]
            }
            Op::Union(UnionRules::Refs(ns)) | Op::Join(UnionRules::Refs(ns)) => ns.clone(),
            Op::Union(UnionRules::Ref(n)) | Op::Join(UnionRules::Ref(n)) => vec![n.clone()],
            Op::Difference(d) => std::iter::once(d.base.clone())
                .chain(d.cut.iter().cloned())
                .chain(d.cut_rule.as_deref().map(Op::refs).unwrap_or_default())
                .collect(),
            Op::Intersect(i) => std::iter::once(i.base.clone())
                .chain(i.keep.iter().cloned())
                .chain(i.keep_rule.as_deref().map(Op::refs).unwrap_or_default())
                .collect(),
            Op::Grow(g) => vec![g.of.clone()],
            Op::Move(m) => vec![m.of.clone()],
            Op::Around(a) => vec![a.of.clone()],
            Op::BufferLines(b) => vec![b.lines.clone()],
            Op::ExtendToFrame(e) => vec![e.of.clone(), e.within.clone()],
            Op::Where(w) => vec![w.of.clone()],
            Op::Rings(r) => vec![r.of.clone()],
            Op::ClipLines(c) => vec![c.lines.clone(), c.within.clone()],
            Op::Terrain(t) | Op::TerrainBand(t) => t.in_area.iter().cloned().collect(),
            Op::Burin(b) => b
                .in_area
                .iter()
                .cloned()
                .chain(b.regions.values().cloned())
                .chain(b.water.iter().cloned())
                .collect(),
            Op::Labels(l) => l.from.iter().chain(l.in_area.iter()).chain(l.avoid.iter()).cloned().collect(),
            Op::Graticule(g) | Op::GraticuleArea(g) => vec![g.in_area.clone()],
            Op::LabelLines(p) | Op::LabelArea(p) => vec![p.of.clone()],
            Op::Fill(f) | Op::FillCover(f) => {
                std::iter::once(f.in_area.clone()).chain(f.content.iter().cloned()).chain(f.motif.iter().cloned()).collect()
            }
        }
    }

    /// Same rule shape and the same inputs: the only difference is where the
    /// inputs live (a named def vs. on the line).
    pub fn same_semantics(&self, other: &Op) -> bool {
        match (self, other) {
            (Op::Polygons(a), Op::Polygons(b)) => a == b,
            (Op::Union(a), Op::Union(b)) => a == b,
            (Op::Difference(a), Op::Difference(b)) => a.base == b.base && a.cut.len() == b.cut.len(),
            (Op::Intersect(a), Op::Intersect(b)) => a.base == b.base && a.keep == b.keep,
            (Op::FillHoles(a), Op::FillHoles(b)) => a == b,
            (Op::LabelArea(a), Op::LabelArea(b)) => a == b,
            (Op::LabelLines(a), Op::LabelLines(b)) => a == b,
            (Op::Grow(a), Op::Grow(b)) => a.of == b.of,
            (Op::Around(a), Op::Around(b)) => a == b,
            (Op::BufferLines(a), Op::BufferLines(b)) => a.lines == b.lines && a.by == b.by && a.cap == b.cap,
            (Op::Rings(a), Op::Rings(b)) => a.of == b.of,
            (Op::Lines(a), Op::Lines(b)) => a == b,
            (Op::Segments(a), Op::Segments(b)) => a == b,
            (Op::Dedupe(a), Op::Dedupe(b)) => a == b,
            (Op::Merge(a), Op::Merge(b)) => a == b,
            (Op::Join(a), Op::Join(b)) => a == b,
            (Op::ClipLines(a), Op::ClipLines(b)) => a.lines == b.lines,
            // A selection, an engine source or a module cannot be inlined in v3.
            _ => false,
        }
    }
}

/// Where a script wrote something: line and column, from 1. Written as
/// `line 12 column 5`, the form the web editor's markers read.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
pub struct At(pub u32, pub u32);

impl fmt::Display for At {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        write!(f, "line {} column {}", self.0, self.1)
    }
}

/// `what`, followed by ` (line 12 column 5)` when the script position is known.
pub fn located(what: &str, at: Option<At>) -> String {
    match at {
        Some(at) => format!("{what} ({at})"),
        None => what.to_string(),
    }
}

/// A def: the name you chose, and the one operation it runs.
#[derive(Debug, Clone, PartialEq)]
pub struct Def {
    pub name: String,
    pub op: Op,
    pub at: Option<At>,
}

impl Def {
    /// The reference other defs use to reach this one.
    pub fn reference(&self) -> Name {
        Name { section: self.op.section(), name: self.name.clone() }
    }

    /// The reference, with the script line that made it.
    pub fn label(&self) -> String {
        located(&self.reference().to_string(), self.at)
    }
}

// ---------------------------------------------------------------------------
// draw: and compose:
// ---------------------------------------------------------------------------

#[derive(Debug, Clone, PartialEq)]
pub struct Draw {
    /// SVG group id. `None` falls back to the def name (`fills_hatch`).
    pub id: Option<String>,
    pub from: Target,
    pub stroke: Option<StrokeSpec>,
    pub at: Option<At>,
}

impl Draw {
    /// The group name this entry writes: explicit `id`, else the def reference
    /// with `$` dropped and the dot turned into an underscore.
    pub fn group(&self) -> String {
        match &self.id {
            Some(id) => id.clone(),
            None => match &self.from.module {
                Some(m) => format!("{m}_{}", self.from.name.name),
                None => format!("{}_{}", self.from.name.section.key(), self.from.name.name),
            },
        }
    }
}

#[derive(Debug, Clone, PartialEq)]
pub struct Mask {
    pub from: Target,
    pub occludes: Vec<Id>,
    pub at: Option<At>,
}

#[derive(Debug, Clone, Default, PartialEq)]
pub enum Clip {
    #[default]
    Auto,
    None,
    /// Subtract exactly these areas.
    Areas(Vec<Name>),
}

#[derive(Debug, Clone, PartialEq, Default)]
pub struct Compose {
    /// Bottom-most first. Empty means the order of `draw`.
    pub order: Vec<Id>,
    pub masks: Vec<(String, Mask)>,
    pub clip: BTreeMap<Id, Clip>,
    pub clip_default: Clip,
    pub optimize: Vec<crate::optimize::OptimizeStep>,
}

// ---------------------------------------------------------------------------
// The profile
// ---------------------------------------------------------------------------

#[derive(Debug, Clone, PartialEq)]
pub struct Grammar {
    /// A name for the profile, carried with it when shared; nothing draws it.
    pub title: Option<String>,
    pub output: crate::profile::OutputSpec,
    /// Sections in the order they were written, each with its defs.
    pub sections: Vec<(Section, Vec<Def>)>,
    pub draw: Vec<Draw>,
    pub compose: Compose,
    /// A screen's layers, bottom first (`paint(...)`): what covers the grid
    /// when the output is a screen (`output.screen`).
    pub paint: Vec<crate::paint::Paint>,
    /// Other places drawn into rectangles of this page (`view(...)`), under
    /// the page's own groups. Each is a whole graph with its own output.
    pub views: Vec<View>,
}

/// A view: another place, at its own scale, drawn into a rectangle of the
/// page. Its graph's `output` is the place and the rectangle's size; `at` is
/// the rectangle's top-left corner on the page, in mm. A page mask whose
/// `occludes` names the view's `id` cuts every stroke of it.
#[derive(Debug, Clone, PartialEq)]
pub struct View {
    pub id: String,
    pub at: (f64, f64),
    pub grammar: Box<Grammar>,
    /// One colour for every stroke of the view, whatever its style asks: the
    /// view is then one group of its own, named `id` — one pen.
    pub ink: Option<String>,
}

impl View {
    /// The place the view shows, as `(lng, lat)`.
    pub fn center(&self) -> (f64, f64) {
        (self.grammar.output.lng.unwrap_or(0.0), self.grammar.output.lat.unwrap_or(0.0))
    }
}

impl Grammar {
    /// The `tools_terrain` defs, in file order: what the host reads the
    /// elevation for.
    pub fn terrains(&self) -> Vec<&Terrain> {
        self.all_defs()
            .filter_map(|d| match &d.op {
                Op::Terrain(t) | Op::TerrainBand(t) => Some(t),
                _ => None,
            })
            .collect()
    }

    /// The `tools_burin` defs: whole burin documents the engine draws.
    pub fn burins(&self) -> Vec<&Burin> {
        self.all_defs()
            .filter_map(|d| match &d.op {
                Op::Burin(b) => Some(b),
                _ => None,
            })
            .collect()
    }

    /// Whether any def draws the elevation — terrain, or a burin document.
    /// What turns the terrain fetch on.
    pub fn draws_terrain(&self) -> bool {
        !self.terrains().is_empty()
            || !self.burins().is_empty()
            || self.all_defs().any(|d| matches!(d.op, Op::TerrainSelect(_)))
    }

    pub fn defs(&self, section: Section) -> &[Def] {
        self.sections
            .iter()
            .find(|(s, _)| *s == section)
            .map(|(_, d)| d.as_slice())
            .unwrap_or(&[])
    }

    /// Every def, in section order.
    pub fn all_defs(&self) -> impl Iterator<Item = &Def> {
        self.sections.iter().flat_map(|(_, defs)| defs.iter())
    }

    /// This graph with only what it shows: the defs that no `draw`, `paint`,
    /// mask or clip reads, directly or through other defs, left out, so
    /// nothing is fetched or computed for them (terrain no layer reads asks
    /// for no elevation, a tile layer none reads for no tiles). Views keep
    /// their own graphs whole.
    pub fn reached(mut self) -> Grammar {
        let target = |t: &Target| match &t.module {
            Some(m) => self.module(m).map(Def::reference),
            None => Some(t.name.clone()),
        };
        let mut todo: Vec<Name> = self
            .draw
            .iter()
            .map(|d| &d.from)
            .chain(self.paint.iter().map(|p| &p.from))
            .chain(self.compose.masks.iter().map(|(_, m)| &m.from))
            .filter_map(target)
            .collect();
        for clip in self.compose.clip.values().chain([&self.compose.clip_default]) {
            if let Clip::Areas(names) = clip {
                todo.extend(names.iter().cloned());
            }
        }
        let mut reached = BTreeSet::new();
        while let Some(name) = todo.pop() {
            if let Some(def) = self.find(&name) {
                if reached.insert(name) {
                    todo.extend(def.op.refs());
                }
            }
        }
        for (_, defs) in &mut self.sections {
            defs.retain(|d| reached.contains(&d.reference()));
        }
        self
    }

    pub fn find(&self, name: &Name) -> Option<&Def> {
        self.defs(name.section).iter().find(|d| d.name == name.name)
    }

    /// The def holding `module_<module>`, if the profile calls one.
    pub fn module(&self, module: &str) -> Option<&Def> {
        self.all_defs().find(|d| matches!(&d.op, Op::Module(m) if m.name == module))
    }

    /// The SVG group each draw entry writes.
    pub fn groups(&self) -> Vec<String> {
        self.draw.iter().map(Draw::group).collect()
    }

    /// Every OSM key the profile can select on: what Overpass must fetch.
    ///
    /// Modules read tags the profile never names (`module_roads` needs
    /// `highway`), so they contribute their keys too, unless they read a
    /// feature set of their own (`from`). Empty: the profile needs no
    /// Overpass at all.
    pub fn osm_keys(&self) -> Vec<String> {
        let mut keys: Vec<String> = Vec::new();
        fn add(keys: &mut Vec<String>, k: &str) {
            if !keys.iter().any(|x| x == k) {
                keys.push(k.to_string());
            }
        }
        let defs: Vec<&Def> = self.all_defs().collect();
        for def in defs {
            match &def.op {
                Op::Select(sel) => sel.keys().for_each(|k| add(&mut keys, k)),
                Op::Module(Module { name, from: None, .. }) => {
                    crate::themes::osm_keys(name).iter().for_each(|k| add(&mut keys, k))
                }
                _ => {}
            }
        }
        keys
    }

    /// Every `tiles_select` item: what to read from the vector tiles.
    pub fn tile_selectors(&self) -> Vec<String> {
        let mut out: Vec<String> = Vec::new();
        for def in self.all_defs() {
            if let Op::TileSelect(t) = &def.op {
                out.extend(t.items.iter().filter(|i| !out.contains(i)).cloned().collect::<Vec<_>>());
            }
        }
        out
    }

    /// Whether the profile reads open-sea polygons from the vector tiles.
    pub fn draws_ocean(&self) -> bool {
        self.tile_selectors().iter().any(|s| s == "ocean")
    }

    /// Every `data_select` source, a URL or a file path, in order: the
    /// GeoJSON the host must read and pass as `Inputs::data`.
    pub fn datasets(&self) -> Vec<String> {
        let mut out: Vec<String> = Vec::new();
        for def in self.all_defs() {
            if let Some(src) = match &def.op {
                Op::DataSelect(d) => d.url(),
                _ => None,
            } {
                if !out.iter().any(|o| o == src) {
                    out.push(src.to_string());
                }
            }
        }
        out
    }

    /// SVG files named by a fill `source`, for the host to read.
    pub fn source_files(&self) -> Vec<String> {
        let mut out = Vec::new();
        for def in self.defs(Section::Fills) {
            if let Op::Fill(f) = &def.op {
                if let Some(src) = &f.spec.source {
                    if !out.contains(&src.file) {
                        out.push(src.file.clone());
                    }
                }
            }
        }
        out
    }
}

// ---------------------------------------------------------------------------
// Deserialization
// ---------------------------------------------------------------------------

#[derive(Debug, thiserror::Error)]
pub enum GrammarError {
    #[error("graph JSON: {0}")]
    Json(String),
    #[error("profile: {0}")]
    Invalid(String),
}

/// Raw shape: sections as written, before validation.
#[derive(Debug, Deserialize)]
#[serde(deny_unknown_fields)]
struct Raw {
    #[serde(default)]
    title: Option<String>,
    output: crate::profile::OutputSpec,
    #[serde(default, rename = "$features", deserialize_with = "ordered_defs")]
    features: Vec<(String, RawOp)>,
    #[serde(default, rename = "$areas", deserialize_with = "ordered_defs")]
    areas: Vec<(String, RawOp)>,
    #[serde(default, rename = "$lines", deserialize_with = "ordered_defs")]
    lines: Vec<(String, RawOp)>,
    #[serde(default, rename = "$fills", deserialize_with = "ordered_defs")]
    fills: Vec<(String, RawOp)>,
    /// Recognised so the error is clear, not "unknown field".
    #[serde(default)]
    draw: Vec<RawDraw>,
    #[serde(default)]
    compose: RawCompose,
    #[serde(default)]
    paint: Vec<RawPaint>,
    #[serde(default)]
    views: Vec<RawView>,
}

#[derive(Debug, Deserialize)]
#[serde(deny_unknown_fields)]
struct RawPaint {
    id: String,
    from: String,
    #[serde(default)]
    fill: Option<Value>,
    #[serde(default)]
    line: Option<Value>,
    #[serde(default)]
    text: Option<Value>,
    #[serde(default)]
    halo: crate::paint::Halo,
    #[serde(default)]
    minzoom: Option<f64>,
    #[serde(default)]
    maxzoom: Option<f64>,
    #[serde(default)]
    filter: Option<Value>,
    #[serde(default)]
    at: Option<At>,
}

#[derive(Debug, Deserialize)]
#[serde(deny_unknown_fields)]
struct RawView {
    id: String,
    at: [f64; 2],
    graph: Value,
    #[serde(default)]
    ink: Option<String>,
}


/// `Vec<(String, T)>` from a YAML/JSON **mapping**, keeping the written order.
/// Used for the `$sections` (def name → operation) and for `compose.masks`.
fn ordered_defs<'de, D: Deserializer<'de>>(d: D) -> Result<Vec<(String, RawOp)>, D::Error> {
    ordered_map(d)
}

fn ordered_masks<'de, D: Deserializer<'de>>(d: D) -> Result<Vec<(String, RawMask)>, D::Error> {
    ordered_map(d)
}

fn ordered_map<'de, D, T>(d: D) -> Result<Vec<(String, T)>, D::Error>
where
    D: Deserializer<'de>,
    T: serde::de::DeserializeOwned,
{
    struct V<T>(std::marker::PhantomData<T>);
    impl<'de, T: serde::de::DeserializeOwned> Visitor<'de> for V<T> {
        type Value = Vec<(String, T)>;
        fn expecting(&self, f: &mut fmt::Formatter) -> fmt::Result {
            f.write_str("a mapping of name to value")
        }
        fn visit_map<A: MapAccess<'de>>(self, mut map: A) -> Result<Self::Value, A::Error> {
            let mut out = Vec::new();
            while let Some((k, v)) = map.next_entry::<String, T>()? {
                out.push((k, v));
            }
            Ok(out)
        }
        /// `$features:` with nothing under it is an empty section, not an error.
        fn visit_unit<E: de::Error>(self) -> Result<Self::Value, E> {
            Ok(Vec::new())
        }
    }
    d.deserialize_any(V(std::marker::PhantomData))
}

#[derive(Debug, Deserialize)]
#[serde(deny_unknown_fields)]
struct RawDraw {
    #[serde(default)]
    id: Option<String>,
    from: String,
    #[serde(default)]
    stroke: Option<StrokeSpec>,
    #[serde(default)]
    at: Option<At>,
}

#[derive(Debug, Default, Deserialize)]
#[serde(deny_unknown_fields)]
struct RawCompose {
    #[serde(default)]
    order: Vec<String>,
    #[serde(default, deserialize_with = "ordered_masks")]
    masks: Vec<(String, RawMask)>,
    #[serde(default)]
    clip: ClipBlock,
    #[serde(default)]
    optimize: Vec<RawOptimizeStep>,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct RawOptimizeStep {
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub layers: Vec<String>,
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub except: Vec<String>,
    #[serde(flatten)]
    pub op: crate::optimize::OptimizeOp,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub at: Option<At>,
}

#[derive(Debug, Default, Deserialize)]
#[serde(deny_unknown_fields)]
struct ClipBlock {
    #[serde(default)]
    default: Option<ClipValue>,
}

#[derive(Debug, Clone, Deserialize)]
#[serde(untagged)]
enum ClipValue {
    Keyword(String),
    List(Vec<String>),
}

#[derive(Debug, Deserialize)]
#[serde(deny_unknown_fields)]
struct RawMask {
    from: String,
    #[serde(default)]
    occludes: Vec<String>,
    #[serde(default)]
    at: Option<At>,
}

/// One operation, as a single-key mapping. The key picks the variant; a def
/// with several keys is an error (one operation per def).
/// `at: [line, column]` may sit next to the operation key: where the script
/// made the def.
#[derive(Debug)]
struct RawOp(BTreeMap<String, Value>, Option<At>);

impl<'de> Deserialize<'de> for RawOp {
    fn deserialize<D: Deserializer<'de>>(d: D) -> Result<Self, D::Error> {
        struct V;
        impl<'de> Visitor<'de> for V {
            type Value = RawOp;
            fn expecting(&self, f: &mut fmt::Formatter) -> fmt::Result {
                f.write_str("a mapping with exactly one operation key")
            }
            fn visit_map<A: MapAccess<'de>>(self, mut map: A) -> Result<RawOp, A::Error> {
                let mut entries = BTreeMap::new();
                let mut at = None;
                while let Some((k, v)) = map.next_entry::<String, Value>()? {
                    if k == "at" {
                        at = Some(serde_json::from_value(v).map_err(de::Error::custom)?);
                    } else {
                        entries.insert(k, v);
                    }
                }
                if entries.len() != 1 {
                    let keys: Vec<&str> = entries.keys().map(String::as_str).collect();
                    return Err(de::Error::custom(format!(
                        "a def takes exactly one operation, found {}: {}",
                        entries.len(),
                        keys.join(", ")
                    )));
                }
                Ok(RawOp(entries, at))
            }
            /// `def: name` with no body (an alias style) is not supported here.
            fn visit_str<E: de::Error>(self, v: &str) -> Result<RawOp, E> {
                Err(de::Error::custom(format!(
                    "expected an operation, found the bare name {v:?}; write `tools_union: [{v}]` or a real op"
                )))
            }
        }
        d.deserialize_any(V)
    }
}

/// Peak at the operation key without consuming the rest.
fn only_op(raw: RawOp) -> Result<(String, Value), String> {
    let (k, v) = raw.0.into_iter().next().ok_or("empty operation")?;
    Ok((k, v))
}

fn json<T: serde::de::DeserializeOwned>(value: &Value, what: &str) -> Result<T, GrammarError> {
    serde_json::from_value(value.clone()).map_err(|e| GrammarError::Invalid(format!("{what}: {e}")))
}

/// Tests write graphs as YAML, the op form's shortest spelling; the engine
/// itself reads only JSON.
#[cfg(test)]
pub(crate) fn from_yaml(text: &str) -> Result<Grammar, GrammarError> {
    let value: Value = serde_saphyr::from_str(text).map_err(|e| GrammarError::Json(e.to_string()))?;
    Grammar::from_json(&value.to_string())
}

fn build(raw: Raw) -> Result<Grammar, GrammarError> {
    let mut sections: Vec<(Section, Vec<Def>)> = Vec::new();
    for (section, entries) in [
        (Section::Features, raw.features),
        (Section::Areas, raw.areas),
        (Section::Lines, raw.lines),
        (Section::Fills, raw.fills),
    ] {
        if entries.is_empty() {
            continue;
        }
        let mut seen = BTreeSet::new();
        let mut defs = Vec::new();
        for (name, raw_op) in entries {
            if !seen.insert(name.clone()) {
                return Err(GrammarError::Invalid(format!("${}.{} is defined twice", section, name)));
            }
            let at = raw_op.1;
            let op = parse_op(raw_op, section).map_err(|e| match e {
                GrammarError::Invalid(m) => GrammarError::Invalid(located(&format!("${section}.{name}: {m}"), at)),
                other => other,
            })?;
            defs.push(Def { name, op, at });
        }
        sections.push((section, defs));
    }

    let draw = raw
        .draw
        .into_iter()
        .map(|d| {
            Ok(Draw {
                from: parse_output(&d.from)?,
                id: d.id,
                stroke: d.stroke,
                at: d.at,
            })
        })
        .collect::<Result<Vec<_>, GrammarError>>()?;

    let mut masks = Vec::new();
    for (name, m) in raw.compose.masks {
        masks.push((
            name,
            Mask {
                from: parse_output(&m.from)?,
                occludes: m.occludes.into_iter().map(Id).collect(),
                at: m.at,
            },
        ));
    }

    let clip_default = match &raw.compose.clip.default {
        None => Clip::Auto,
        Some(ClipValue::Keyword(k)) => match k.as_str() {
            "auto" => Clip::Auto,
            "none" => Clip::None,
            other => {
                return Err(GrammarError::Invalid(format!(
                    "clip default {other:?} is unknown: write auto, none, or a list of $areas.*"
                )))
            }
        },
        Some(ClipValue::List(names)) => Clip::Areas(
            names
                .iter()
                .map(|n| refname(n))
                .collect::<Result<Vec<_>, _>>()?,
        ),
    };

    let optimize = raw
        .compose
        .optimize
        .into_iter()
        .map(|s| crate::optimize::OptimizeStep {
            layers: s.layers.into_iter().map(Id).collect(),
            except: s.except.into_iter().map(Id).collect(),
            op: s.op,
            at: s.at,
        })
        .collect();

    let compose = Compose {
        order: raw.compose.order.into_iter().map(Id).collect(),
        masks,
        clip: BTreeMap::new(),
        clip_default,
        optimize,
    };

    let views = raw
        .views
        .into_iter()
        .map(|v| {
            let inner: Raw = serde_json::from_value(v.graph).map_err(|e| GrammarError::Json(format!("views.{}: {e}", v.id)))?;
            let grammar = build(inner).map_err(|e| GrammarError::Invalid(format!("view {}: {e}", v.id)))?;
            Ok(View { id: v.id, at: (v.at[0], v.at[1]), grammar: Box::new(grammar), ink: v.ink })
        })
        .collect::<Result<Vec<_>, GrammarError>>()?;
    let paint = raw
        .paint
        .into_iter()
        .map(|p| {
            let from = parse_output(&p.from)?;
            // Lines and features have a look by default; an area says its fill.
            let kind = if from.module.is_some() { Section::Lines } else { from.name.section };
            let (key, body) = match (p.fill, p.line, p.text) {
                (Some(f), None, None) => ("fill", f),
                (None, Some(l), None) => ("line", l),
                (None, None, Some(t)) => ("text", t),
                (None, None, None) if kind == Section::Lines => ("line", serde_json::json!({})),
                (None, None, None) if kind == Section::Features => ("text", serde_json::json!({})),
                _ => {
                    return Err(GrammarError::Invalid(located(
                        &format!("paint {:?}: one of fill, line or text", p.id),
                        p.at,
                    )))
                }
            };
            let fail = |m: String| GrammarError::Invalid(located(&format!("paint {:?}: {m}", p.id), p.at));
            let look = crate::paint::Style::new(key, body).map_err(fail)?;
            let shown = crate::paint::Shown::new(p.minzoom, p.maxzoom, p.filter).map_err(fail)?;
            Ok(crate::paint::Paint { id: p.id, from, look, shown, halo: p.halo, at: p.at })
        })
        .collect::<Result<Vec<_>, GrammarError>>()?;
    let mut output = raw.output;
    output.fit_screen().map_err(GrammarError::Invalid)?;
    let grammar = Grammar { title: raw.title, output, sections, draw, compose, paint, views };
    validate(&grammar)?;
    Ok(grammar)
}

fn not_a_reference(text: String) -> GrammarError {
    GrammarError::Invalid(format!("{text:?} is not a $section.name reference"))
}

/// `$lines.x`, `$fills.x`, or `roads.outlines` (a module output).
fn parse_output(text: &str) -> Result<Target, GrammarError> {
    if let Some(rest) = text.strip_prefix('$') {
        return Ok(Target { module: None, name: refname(&format!("${rest}"))? });
    }
    match text.split_once('.') {
        Some((module, name)) if !name.is_empty() => {
            Ok(Target { module: Some(module.to_string()), name: Name { section: Section::Lines, name: name.to_string() } })
        }
        _ => Err(GrammarError::Invalid(format!(
            "{text:?} is not a reference: write $lines.x, $fills.x or <module>.<output>"
        ))),
    }
}

fn refname(text: &str) -> Result<Name, GrammarError> {
    Name::parse(text).map_err(|_| not_a_reference(text.to_string()))
}

/// A draw/`from` target: `$lines.x` / `$fills.x`, or `roads.outlines` (a module
/// output, which has no `$` because the engine produced it).
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Target {
    /// `None` = a `$section.name` def; `Some(module)` = a module output.
    pub module: Option<String>,
    pub name: Name,
}

fn parse_op(raw: RawOp, section: Section) -> Result<Op, GrammarError> {
    let (key, value) = only_op(raw).map_err(GrammarError::Invalid)?;
    let target = match key.as_str() {
        "osm_select" | "tiles_select" | "data_select" | "terrain_select" | "tools_where" => Section::Features,
        "tools_polygons" | "tools_union" | "tools_difference" | "tools_intersect" | "tools_fill_holes"
        | "tools_fill_cover" | "tools_grow" | "tools_move" | "tools_around" | "tools_shape" | "tools_text_area" | "tools_buffer_lines" | "tools_label_area" | "tools_graticule_area" | "tools_extend_to_frame" | "tools_terrain_band" | "engine_frame" => {
            Section::Areas
        }
        "tools_rings" | "tools_lines" | "tools_segments" | "tools_dedupe" | "tools_merge" | "tools_join"
        | "tools_clip" | "tools_path" | "tools_text" | "tools_terrain" | "tools_burin" | "tools_labels" | "tools_label_lines" | "tools_graticule" => Section::Lines,
        "tools_fill" => Section::Fills,
        other => {
            if let Some(rest) = other.strip_prefix("module_") {
                let mut obj = value.as_object().cloned().ok_or_else(|| {
                    GrammarError::Json(format!("{key}: expected an object"))
                })?;
                let from_val = obj.remove("from");
                let from = match from_val {
                    Some(Value::String(s)) => Some(refname(&s)?),
                    Some(v) => return Err(GrammarError::Json(format!("{key}.from: expected a string, got {v}"))),
                    None => None,
                };
                if let Some(f) = &from {
                    if f.section != Section::Features {
                        return Err(GrammarError::Invalid(format!("{key}.from is {f}, but it must be a $features set")));
                    }
                }
                let roads: crate::themes::RoadOptions = json(&Value::Object(obj), &key)?;
                roads.validate().map_err(GrammarError::Invalid)?;
                return Ok(Op::Module(Module { name: rest.to_string(), from, roads }));
            }
            if let Some(rest) = other.strip_prefix("primitives_") {
                return Err(GrammarError::Invalid(format!(
                    "primitives_{rest} is not defined in this build"
                )));
            }
            return Err(GrammarError::Invalid(format!("unknown operation {other:?}")));
        }
    };
    if target != section {
        return Err(GrammarError::Invalid(format!(
            "{key} produces {target}, but it is written under ${section}"
        )));
    }
    let _ = target;
    let op = match key.as_str() {
        "osm_select" => Op::Select(parse_selector(&value)?),
        "tiles_select" => Op::TileSelect(parse_tile_select(&value)?),
        "terrain_select" => {
            let t: crate::contours::TerrainSelect = json(&value, "terrain_select")?;
            t.validate().map_err(GrammarError::Invalid)?;
            Op::TerrainSelect(t)
        }
        "data_select" => match &value {
            Value::String(s) if !s.trim().is_empty() => Op::DataSelect(DataSource::Url(s.trim().to_string())),
            Value::Object(o) if o.len() == 1 && o.get("geojson").is_some_and(Value::is_object) => {
                let gj = o["geojson"].clone();
                crate::geojson::features_of(&gj).map_err(|e| GrammarError::Invalid(format!("data_select: {e}")))?;
                Op::DataSelect(DataSource::Inline(gj))
            }
            Value::Object(o) if o.len() == 1 && o.get("json").is_some_and(Value::is_object) => {
                let js: JsonSource = serde_json::from_value(o["json"].clone())
                    .map_err(|e| GrammarError::Invalid(format!("data_select.json: {e}")))?;
                if js.url.trim().is_empty() || js.lat.is_empty() || js.lng.is_empty() {
                    return Err(GrammarError::Invalid("data_select.json needs a url, and the lat and lng paths".into()));
                }
                Op::DataSelect(DataSource::Json(js))
            }
            _ => return Err(GrammarError::Invalid("data_select is a URL, a file path, { geojson: {…} } or { json: { url, items, lat, lng } }".into())),
        },
        "tools_where" => Op::Where(parse_where(&value)?),
        "engine_frame" => Op::Frame,
        "tools_polygons" => Op::Polygons(name_ref(&value, "tools_polygons")?),
        "tools_union" => Op::Union(union_rules(&value, "tools_union")?),
        "tools_difference" => {
            #[derive(Deserialize)]
            struct Raw {
                base: String,
                cut: OneOrMany,
            }
            let raw: Raw = json(&value, "tools_difference")?;
            let (cut, cut_rule) = cut_rules(&raw.cut.into_vec(), "tools_difference.cut")?;
            Op::Difference(Difference { base: refname(&raw.base)?, cut, cut_rule })
        }
        "tools_intersect" => {
            #[derive(Deserialize)]
            struct Raw {
                base: String,
                #[serde(default)]
                keep: Option<String>,
                #[serde(default)]
                keep_rule: Option<RawOp>,
            }
            let raw: Raw = json(&value, "tools_intersect")?;
            if raw.keep.is_some() == raw.keep_rule.is_some() {
                return Err(GrammarError::Invalid(
                    "tools_intersect needs exactly one of `keep: $areas.x` or `keep_rule: { ... }`".into(),
                ));
            }
            let keep_rule = match raw.keep_rule {
                Some(op) => Some(Box::new(parse_op(op, Section::Areas)?)),
                None => None,
            };
            Op::Intersect(Intersect {
                base: refname(&raw.base)?,
                keep: raw.keep.as_deref().map(refname).transpose()?,
                keep_rule,
            })
        }
        "tools_fill_holes" => Op::FillHoles(name_ref(&value, "tools_fill_holes")?),
        "tools_label_area" => Op::LabelArea(parse_label_pick(&value, "tools_label_area")?),
        "tools_label_lines" => Op::LabelLines(parse_label_pick(&value, "tools_label_lines")?),
        "tools_move" => {
            #[derive(Deserialize)]
            #[serde(deny_unknown_fields)]
            struct Raw {
                of: String,
                by: [Mm; 2],
            }
            let raw: Raw = json(&value, "tools_move")?;
            Op::Move(Move { of: refname(&raw.of)?, by: raw.by })
        }
        "tools_grow" => {
            #[derive(Deserialize)]
            #[serde(deny_unknown_fields)]
            struct Raw {
                of: String,
                by: Mm,
            }
            let raw: Raw = json(&value, "tools_grow")?;
            Op::Grow(Grow { of: refname(&raw.of)?, by: raw.by })
        }
        "tools_around" => {
            #[derive(Deserialize)]
            #[serde(deny_unknown_fields)]
            struct Raw {
                of: String,
                by: Mm,
            }
            let raw: Raw = json(&value, "tools_around")?;
            let of = refname(&raw.of)?;
            if of.section != Section::Features {
                return Err(GrammarError::Invalid("tools_around: of must be $features".into()));
            }
            Op::Around(Around { of, by: raw.by })
        }
        "tools_shape" | "tools_path" => {
            let shape: Shape = json(&value, &key)?;
            if let ShapeAt::Page(xy) = &shape.at {
                for p in xy {
                    if let PagePos::Percent(s) = p {
                        if percent(s).is_none() {
                            return Err(GrammarError::Invalid(format!("{key}.at: {s:?} is not a length or a percentage")));
                        }
                    }
                }
            }
            if shape.points.len() < if key == "tools_shape" { 3 } else { 2 } {
                return Err(GrammarError::Invalid(format!("{key}: too few points")));
            }
            if key == "tools_shape" { Op::Shape(shape) } else { Op::Path(shape) }
        }
        "tools_text" | "tools_text_area" => {
            let text: Text = json(&value, &key)?;
            crate::text::validate_label_font(&text.font).map_err(GrammarError::Invalid)?;
            if key == "tools_text" { Op::Text(text) } else { Op::TextArea(text) }
        }
        "tools_buffer_lines" => {
            #[derive(Deserialize)]
            #[serde(deny_unknown_fields)]
            struct Raw {
                lines: String,
                by: Mm,
                #[serde(default)]
                cap: LineBufferCap,
            }
            let raw: Raw = json(&value, "tools_buffer_lines")?;
            Op::BufferLines(BufferLines { lines: refname(&raw.lines)?, by: raw.by, cap: raw.cap })
        }
        "tools_extend_to_frame" => {
            #[derive(Deserialize)]
            #[serde(deny_unknown_fields)]
            struct Raw {
                of: String,
                within: String,
                // Read and ignored: saved graphs still carry it.
                #[serde(rename = "min_height_frac")]
                _min_height_frac: Option<f64>,
                gap_mm: Option<Mm>,
            }
            let raw: Raw = json(&value, "tools_extend_to_frame")?;
            Op::ExtendToFrame(ExtendToFrame {
                of: refname(&raw.of)?,
                within: refname(&raw.within)?,
                gap_mm: raw.gap_mm,
            })
        }
        "tools_terrain" | "tools_terrain_band" => {
            #[derive(Deserialize)]
            #[serde(deny_unknown_fields)]
            struct Raw {
                #[serde(default)]
                in_area: Option<String>,
                #[serde(default)]
                color: Option<serde_json::Value>,
                #[serde(default)]
                width: Option<serde_json::Value>,
                #[serde(default)]
                angle: Option<f64>,
                #[serde(default)]
                layer: Option<String>,
                #[serde(default)]
                shore: Option<bool>,
                #[serde(default)]
                style: Option<serde_json::Map<String, serde_json::Value>>,
                #[serde(default)]
                r#where: Option<serde_json::Map<String, serde_json::Value>>,
                #[serde(default)]
                draw: Option<String>,
            }
            let raw: Raw = json(&value, "tools_terrain")?;
            let band = key.as_str() == "tools_terrain_band";
            let t = Terrain {
                in_area: raw.in_area.as_deref().map(refname).transpose()?,
                color: raw.color,
                width: raw.width,
                angle: raw.angle.unwrap_or(0.0),
                layer: raw.layer,
                style: raw.style.unwrap_or_default(),
                shore: raw.shore.unwrap_or(false),
                band: raw.r#where.unwrap_or_default(),
                draw: match raw.draw.as_deref() {
                    None | Some("lines") => TerrainDraw::Lines,
                    Some("fill") => TerrainDraw::Fill,
                    Some("dots") => TerrainDraw::Dots,
                    Some(other) => {
                        return Err(GrammarError::Invalid(format!(
                            "tools_terrain draws lines, a fill or dots, not {other:?}"
                        )))
                    }
                },
            };
            if band {
                Op::TerrainBand(Terrain { draw: TerrainDraw::Fill, ..t })
            } else {
                Op::Terrain(t)
            }
        }
        "tools_burin" => {
            #[derive(Deserialize)]
            #[serde(deny_unknown_fields)]
            struct Raw {
                /// The atlas, as `burin.json()` writes it: a list, or the JSON
                /// string of one (the library hands a string).
                atlas: Value,
                #[serde(default)]
                in_area: Option<String>,
                #[serde(default)]
                regions: std::collections::BTreeMap<String, String>,
                #[serde(default)]
                water: Option<String>,
                #[serde(default)]
                layer: Option<String>,
            }
            let raw: Raw = json(&value, "tools_burin")?;
            let regions = raw
                .regions
                .into_iter()
                .map(|(name, r)| {
                    let n = refname(&r)?;
                    if n.section != Section::Areas {
                        return Err(GrammarError::Invalid(format!(
                            "tools_burin.regions.{name} must be an area, not {n}"
                        )));
                    }
                    Ok((name, n))
                })
                .collect::<Result<_, _>>()?;
            let atlas = match raw.atlas {
                Value::String(text) => {
                    serde_json::from_str(&text).map_err(|e| GrammarError::Invalid(format!("tools_burin atlas: {e}")))?
                }
                other => other,
            };
            if !atlas.is_array() {
                return Err(GrammarError::Invalid("tools_burin atlas is a list of batches and water passes".into()));
            }
            Op::Burin(Burin {
                atlas,
                in_area: raw.in_area.as_deref().map(refname).transpose()?,
                regions,
                water: raw.water.as_deref().map(refname).transpose()?,
                layer: raw.layer,
            })
        }
        "tools_graticule" | "tools_graticule_area" => {
            let mut body = match value {
                Value::Object(m) => m,
                _ => return Err(GrammarError::Invalid(format!("{key} takes {{ in, part, step, ... }}"))),
            };
            let in_area = match body.remove("in") {
                Some(Value::String(s)) => refname(&s)?,
                _ => return Err(GrammarError::Invalid(format!("{key} needs in: an $areas reference"))),
            };
            if in_area.section != Section::Areas {
                return Err(GrammarError::Invalid(format!("{key}.in is {in_area}, but it reads an $areas def")));
            }
            let look: GraticuleLook = json(&Value::Object(body), &key)?;
            crate::text::validate_label_font(&look.font).map_err(GrammarError::Invalid)?;
            if !(look.step > 0.0) {
                return Err(GrammarError::Invalid(format!("{key}.step is minutes of arc, more than 0")));
            }
            let fits = match look.part {
                GraticulePart::Grid => key == "tools_graticule",
                GraticulePart::Keys => key == "tools_graticule_area",
                GraticulePart::Labels => true,
            };
            if !fits {
                return Err(GrammarError::Invalid(format!("{key}: part {:?} is not drawn by it", look.part)));
            }
            let g = Graticule { in_area, look };
            if key == "tools_graticule" { Op::Graticule(g) } else { Op::GraticuleArea(g) }
        }
        "tools_labels" => {
            let mut body = match value {
                Value::Object(m) => m,
                _ => return Err(GrammarError::Invalid("tools_labels takes { from, ...style }".into())),
            };
            let from: Vec<Name> = match body.remove("from") {
                Some(Value::String(s)) => vec![refname(&s)?],
                Some(Value::Array(items)) if !items.is_empty() => items
                    .iter()
                    .map(|v| v.as_str().ok_or_else(|| not_a_reference(v.to_string())).and_then(refname))
                    .collect::<Result<_, _>>()?,
                _ => return Err(GrammarError::Invalid("tools_labels needs from: $features.x or a list of them".into())),
            };
            if let Some(f) = from.iter().find(|f| f.section != Section::Features) {
                return Err(GrammarError::Invalid(format!("tools_labels.from has {f}, but it reads $features sets")));
            }
            let mut area_ref = |key: &str| -> Result<Option<Name>, GrammarError> {
                match body.remove(key) {
                    None => Ok(None),
                    Some(Value::String(s)) => {
                        let n = refname(&s)?;
                        if n.section != Section::Areas {
                            return Err(GrammarError::Invalid(format!("tools_labels.{key} is {n}, but it reads an $areas def")));
                        }
                        Ok(Some(n))
                    }
                    Some(_) => Err(GrammarError::Invalid(format!("tools_labels.{key} expects an $areas reference"))),
                }
            };
            let in_area = area_ref("in")?;
            let avoid = area_ref("avoid")?;
            let style: crate::labels::Style = json(&Value::Object(body), "tools_labels")?;
            crate::labels::validate_style(&style).map_err(GrammarError::Invalid)?;
            Op::Labels(Labels { from, in_area, avoid, style })
        }
        "tools_rings" => match &value {
            Value::String(s) => Op::Rings(Rings { of: refname(s)?, exterior_only: false }),
            _ => {
                #[derive(Deserialize)]
                #[serde(deny_unknown_fields)]
                struct Raw {
                    of: String,
                    #[serde(default)]
                    exterior_only: bool,
                }
                let raw: Raw = json(&value, "tools_rings")?;
                Op::Rings(Rings { of: refname(&raw.of)?, exterior_only: raw.exterior_only })
            }
        },
        "tools_lines" => Op::Lines(name_ref(&value, "tools_lines")?),
        "tools_segments" => Op::Segments(name_ref(&value, "tools_segments")?),
        "tools_dedupe" => Op::Dedupe(name_ref(&value, "tools_dedupe")?),
        "tools_merge" => Op::Merge(name_ref(&value, "tools_merge")?),
        "tools_join" => Op::Join(union_rules(&value, "tools_join")?),
        "tools_clip" => {
            #[derive(Deserialize)]
            #[serde(deny_unknown_fields)]
            struct Raw {
                lines: String,
                within: String,
                #[serde(default)]
                invert: bool,
            }
            let raw: Raw = json(&value, "tools_clip")?;
            Op::ClipLines(ClipLines { lines: refname(&raw.lines)?, within: refname(&raw.within)?, invert: raw.invert })
        }
        "tools_fill" | "tools_fill_cover" => {
            // The v3 toolkit writes `pattern:` (dots, waves, zigzag…), the spec
            // calls it `generator:`; one rename and the rest is FillSpec.
            #[derive(Deserialize)]
            struct Raw {
                #[serde(rename = "in")]
                in_area: String,
                #[serde(default)]
                per: Option<String>,
                #[serde(default)]
                pattern: Option<String>,
                #[serde(default)]
                content: Option<String>,
                #[serde(flatten)]
                spec: FillSpec,
            }
            let mut raw: Raw = json(&value, &key)?;
            if let Some(pattern) = raw.pattern.take() {
                if raw.spec.generator.is_none() {
                    raw.spec.generator = Some(pattern);
                }
            }
            let per_feature = match raw.per.as_deref() {
                None => false,
                Some("feature") => true,
                Some(other) => {
                    return Err(GrammarError::Invalid(format!(
                        "tools_fill: per: {other:?} is unknown (only `per: feature`)"
                    )))
                }
            };
            let content = raw.content.as_deref().map(refname).transpose()?;
            if content.as_ref().is_some_and(|c| c.section != Section::Lines) {
                return Err(GrammarError::Invalid("tools_fill: content must be $lines".into()));
            }
            // A motif given as `$lines.…` is a reference, resolved when the fill
            // runs; polylines or a symbol name stay in the spec as they are.
            let motif = match raw.spec.options.get("motif") {
                Some(Value::String(s)) if s.starts_with('$') => {
                    let name = refname(s)?;
                    if name.section != Section::Lines {
                        return Err(GrammarError::Invalid("tools_fill: motif must be $lines, polylines or a symbol name".into()));
                    }
                    raw.spec.options.remove("motif");
                    Some(name)
                }
                _ => None,
            };
            let fill = Fill { in_area: refname(&raw.in_area)?, per_feature, content, motif, spec: raw.spec };
            if key == "tools_fill" {
                Op::Fill(fill)
            } else if fill.per_feature || fill.content.is_some() {
                return Err(GrammarError::Invalid("tools_fill_cover takes a pattern, not per or content".into()));
            } else {
                Op::FillCover(fill)
            }
        }
        _ => unreachable!("keys are matched above"),
    };
    Ok(op)
}

/// `tools_difference.cut`: a list of references, or one inline rule.
fn cut_rules(items: &[String], what: &str) -> Result<(Vec<Name>, Option<Box<Op>>), GrammarError> {
    if items.is_empty() {
        return Err(GrammarError::Invalid(format!("{what} needs at least one input")));
    }
    if items.len() == 1 {
        if let Ok(op) = serde_json::from_str::<RawOp>(&items[0]) {
            return Err(GrammarError::Invalid(format!(
                "{what}: inline rules are not supported yet; define it under $areas and use $areas.name ({op:?})"
            )));
        }
    }
    Ok((items.iter().map(|s| refname(s)).collect::<Result<_, _>>()?, None))
}

fn name_ref(value: &Value, op: &str) -> Result<Name, GrammarError> {
    let s: String = json(value, op)?;
    refname(&s)
}

fn parse_label_pick(value: &Value, op: &str) -> Result<LabelPick, GrammarError> {
    match value {
        Value::String(s) => {
            let of = refname(s)?;
            if of.section != Section::Lines {
                return Err(GrammarError::Invalid(format!("{op} reads {of}, but labels live under $lines")));
            }
            Ok(LabelPick { of, rule: None, dots: false })
        }
        _ => {
            #[derive(Deserialize)]
            #[serde(deny_unknown_fields)]
            struct Raw {
                of: String,
                #[serde(default)]
                rule: Option<String>,
                #[serde(default)]
                dots: bool,
            }
            let raw: Raw = json(value, op)?;
            let of = refname(&raw.of)?;
            if of.section != Section::Lines {
                return Err(GrammarError::Invalid(format!("{op}.of is {of}, but labels live under $lines")));
            }
            Ok(LabelPick { of, rule: raw.rule, dots: raw.dots })
        }
    }
}

fn label_pick_json(pick: &LabelPick) -> Value {
    use serde_json::json;
    match (&pick.rule, pick.dots) {
        (None, false) => Value::String(pick.of.to_string()),
        (rule, false) => json!({ "of": pick.of.to_string(), "rule": rule }),
        (None, true) => json!({ "of": pick.of.to_string(), "dots": true }),
        (rule, true) => json!({ "of": pick.of.to_string(), "rule": rule, "dots": true }),
    }
}

/// `tools_union`: a list of references, or one reference with `list: false`.
fn union_rules(value: &Value, op: &str) -> Result<UnionRules, GrammarError> {
    #[derive(Deserialize)]
    #[serde(deny_unknown_fields)]
    struct Raw {
        #[serde(default)]
        refs: Vec<String>,
        #[serde(default, rename = "ref")]
        single: Option<String>,
        #[serde(default)]
        list: Option<bool>,
        #[serde(default)]
        rule: Option<RawOp>,
    }
    match value {
        // The plain form: `tools_union: [{ tools_polygons: ... }, ...]`
        Value::Array(items) => {
            if items.is_empty() {
                return Err(GrammarError::Invalid(format!("{op} needs at least one input")));
            }
            Ok(UnionRules::Refs(inline_list(items, op)?))
        }
        Value::String(s) => Ok(UnionRules::Ref(refname(s)?)),
        Value::Object(_) => {
            let raw: Raw = json(value, op)?;
            if let Some(rule) = raw.rule {
                let parsed = parse_op(rule, Section::Areas)?;
                if parsed.section() != Section::Areas {
                    return Err(GrammarError::Invalid(format!(
                        "{op}: `rule` must produce an area"
                    )));
                }
                return Ok(UnionRules::Refs(parsed.refs()));
            }
            match (raw.single, raw.list, raw.refs.is_empty()) {
                (Some(s), Some(false), true) => Ok(UnionRules::Ref(refname(&s)?)),
                (Some(s), _, true) => Ok(UnionRules::Ref(refname(&s)?)),
                (None, _, false) => Ok(UnionRules::Refs(
                    raw.refs.iter().map(|s| refname(s)).collect::<Result<_, _>>()?,
                )),
                _ => Err(GrammarError::Invalid(format!(
                    "{op} needs a list of references (or `list: false` with one)"
                ))),
            }
        }
        other => Err(GrammarError::Invalid(format!("{op}: unexpected {other}"))),
    }
}

/// A list that may contain `$refs` and/or one inline rule.
/// v3 allows exactly one form: if a rule is present it must be the only item.
fn inline_list(items: &[Value], op: &str) -> Result<Vec<Name>, GrammarError> {
    let mut refs = Vec::new();
    let mut rules = 0usize;
    for item in items {
        match item {
            Value::String(s) => refs.push(refname(s)?),
            Value::Object(_) => rules += 1,
            other => return Err(GrammarError::Invalid(format!("{op}: unexpected item {other}"))),
        }
    }
    if rules > 1 || (rules == 1 && !refs.is_empty()) {
        return Err(GrammarError::Invalid(format!(
            "{op}: write one inline rule, or a list of $refs, not both"
        )));
    }
    Ok(refs)
}

#[derive(Debug, Deserialize)]
#[serde(untagged)]
enum OneOrMany {
    One(String),
    Many(Vec<String>),
}

impl OneOrMany {
    fn into_vec(self) -> Vec<String> {
        match self {
            OneOrMany::One(s) => vec![s],
            OneOrMany::Many(v) => v,
        }
    }
}

fn parse_tile_select(value: &Value) -> Result<TileSelect, GrammarError> {
    let items: Vec<String> = json::<OneOrMany>(value, "tiles_select")?
        .into_vec()
        .iter()
        .flat_map(|s| s.split(|c: char| c.is_whitespace()).map(str::to_string).collect::<Vec<_>>())
        .filter(|s| !s.is_empty())
        .collect();
    if items.is_empty() {
        return Err(GrammarError::Invalid("tiles_select needs a preset or a layer:class rule".into()));
    }
    let filter = terramask::Filter::parse(&items).map_err(|e| GrammarError::Invalid(format!("tiles_select: {e}")))?;
    Ok(TileSelect { items, filter })
}

fn parse_where(value: &Value) -> Result<Where, GrammarError> {
    #[derive(Deserialize)]
    #[serde(deny_unknown_fields)]
    struct Raw {
        of: String,
        tags: serde_json::Map<String, Value>,
    }
    let raw: Raw = json(value, "tools_where")?;
    let of = refname(&raw.of)?;
    if of.section != Section::Features {
        return Err(GrammarError::Invalid(format!("tools_where.of is {of}, but it must be a $features set")));
    }
    if raw.tags.is_empty() {
        return Err(GrammarError::Invalid("tools_where needs at least one tag".into()));
    }
    let tags = crate::select::parse_tag_tests(raw.tags).map_err(|e| GrammarError::Invalid(format!("tools_where: {e}")))?;
    Ok(Where { of, tags })
}

fn parse_selector(value: &Value) -> Result<Selector, GrammarError> {
    #[derive(Deserialize)]
    struct Raw {
        #[serde(flatten)]
        any: BTreeMap<String, OneOrManyOrBool>,
        #[serde(default)]
        except: BTreeMap<String, OneOrManyOrBool>,
        #[serde(default)]
        underground: bool,
    }
    #[derive(Deserialize)]
    #[serde(untagged)]
    enum OneOrManyOrBool {
        Bool(bool),
        One(String),
        Many(Vec<String>),
    }
    impl OneOrManyOrBool {
        fn to_match(&self) -> TagMatch {
            match self {
                OneOrManyOrBool::Bool(p) => TagMatch::Present(*p),
                OneOrManyOrBool::One(v) => TagMatch::Values(vec![v.clone()]),
                OneOrManyOrBool::Many(vs) => TagMatch::Values(vs.clone()),
            }
        }
    }
    let raw: Raw = json(value, "osm_select")?;
    if raw.any.is_empty() {
        return Err(GrammarError::Invalid("osm_select needs at least one tag".into()));
    }
    Ok(Selector {
        any: raw.any.iter().map(|(k, v)| (k.clone(), v.to_match())).collect(),
        except: raw.except.iter().map(|(k, v)| (k.clone(), v.to_match())).collect(),
        underground: raw.underground,
    })
}

// ---------------------------------------------------------------------------
// JSON: the graph saved and loaded
// ---------------------------------------------------------------------------

/// One operation from its JSON form, `{ "tools_union": ["$areas.a"] }`, as
/// the def it will be in `section`.
pub fn op_from_json(section: Section, op: Value) -> Result<Op, GrammarError> {
    let Value::Object(map) = op else {
        return Err(GrammarError::Invalid(format!("an operation is an object, not {op}")));
    };
    let raw = RawOp(map.into_iter().collect(), None);
    if raw.0.len() != 1 {
        return Err(GrammarError::Invalid("an operation has exactly one key".into()));
    }
    parse_op(raw, section)
}

fn tag_json(m: &TagMatch) -> Value {
    match m {
        TagMatch::Present(p) => Value::Bool(*p),
        TagMatch::Values(vs) if vs.len() == 1 => Value::String(vs[0].clone()),
        TagMatch::Values(vs) => vs.iter().cloned().map(Value::String).collect(),
    }
}

fn refs_json(names: &[Name]) -> Value {
    names.iter().map(|n| Value::String(n.to_string())).collect()
}

/// The JSON form [`op_from_json`] reads back.
pub fn op_to_json(op: &Op) -> Value {
    use serde_json::json;
    let union = |u: &UnionRules| match u {
        UnionRules::Refs(ns) => refs_json(ns),
        UnionRules::Ref(n) => Value::String(n.to_string()),
    };
    let (key, value) = match op {
        Op::Select(sel) => {
            let mut body: serde_json::Map<String, Value> =
                sel.any.iter().map(|(k, m)| (k.clone(), tag_json(m))).collect();
            if !sel.except.is_empty() {
                body.insert("except".into(), sel.except.iter().map(|(k, m)| (k.clone(), tag_json(m))).collect());
            }
            if sel.underground {
                body.insert("underground".into(), Value::Bool(true));
            }
            ("osm_select", Value::Object(body))
        }
        Op::TileSelect(t) => ("tiles_select", t.items.iter().cloned().map(Value::String).collect()),
        Op::DataSelect(DataSource::Url(src)) => ("data_select", Value::String(src.clone())),
        Op::TerrainSelect(t) => ("terrain_select", serde_json::to_value(t).unwrap_or(Value::Null)),
        Op::DataSelect(DataSource::Inline(gj)) => ("data_select", json!({ "geojson": gj })),
        Op::DataSelect(DataSource::Json(js)) => ("data_select", json!({ "json": js })),
        Op::Where(w) => {
            let tags: serde_json::Map<String, Value> = w
                .tags
                .iter()
                .map(|(k, t)| {
                    let v = match t {
                        TagTest::Match(m) => tag_json(m),
                        TagTest::Range { min, max } => {
                            let mut r = serde_json::Map::new();
                            if let Some(lo) = min {
                                r.insert("min".into(), json!(lo));
                            }
                            if let Some(hi) = max {
                                r.insert("max".into(), json!(hi));
                            }
                            Value::Object(r)
                        }
                    };
                    (k.clone(), v)
                })
                .collect();
            ("tools_where", json!({ "of": w.of.to_string(), "tags": tags }))
        }
        Op::Polygons(n) => ("tools_polygons", Value::String(n.to_string())),
        Op::Union(u) => ("tools_union", union(u)),
        Op::Difference(d) => ("tools_difference", json!({ "base": d.base.to_string(), "cut": refs_json(&d.cut) })),
        Op::Intersect(i) => (
            "tools_intersect",
            json!({ "base": i.base.to_string(), "keep": i.keep.as_ref().map(Name::to_string) }),
        ),
        Op::FillHoles(n) => ("tools_fill_holes", Value::String(n.to_string())),
        Op::LabelArea(p) => ("tools_label_area", label_pick_json(p)),
        Op::LabelLines(p) => ("tools_label_lines", label_pick_json(p)),
        Op::Terrain(t) | Op::TerrainBand(t) => {
            let mut body = serde_json::Map::new();
            if let Some(a) = &t.in_area {
                body.insert("in_area".into(), Value::String(a.to_string()));
            }
            if let Some(c) = &t.color {
                body.insert("color".into(), c.clone());
            }
            if let Some(w) = &t.width {
                body.insert("width".into(), w.clone());
            }
            if t.angle != 0.0 {
                body.insert("angle".into(), json!(t.angle));
            }
            if let Some(l) = &t.layer {
                body.insert("layer".into(), Value::String(l.clone()));
            }
            if t.shore {
                body.insert("shore".into(), Value::Bool(true));
            }
            if !t.style.is_empty() {
                body.insert("style".into(), Value::Object(t.style.clone()));
            }
            if !t.band.is_empty() {
                body.insert("where".into(), Value::Object(t.band.clone()));
            }
            match t.draw {
                TerrainDraw::Lines => {}
                TerrainDraw::Fill => {
                    body.insert("draw".into(), Value::String("fill".into()));
                }
                TerrainDraw::Dots => {
                    body.insert("draw".into(), Value::String("dots".into()));
                }
            }
            (if matches!(op, Op::TerrainBand(_)) { "tools_terrain_band" } else { "tools_terrain" }, Value::Object(body))
        }
        Op::Burin(b) => {
            let mut body = serde_json::Map::new();
            body.insert("atlas".into(), b.atlas.clone());
            if let Some(a) = &b.in_area {
                body.insert("in_area".into(), Value::String(a.to_string()));
            }
            if !b.regions.is_empty() {
                body.insert(
                    "regions".into(),
                    Value::Object(
                        b.regions
                            .iter()
                            .map(|(k, v)| (k.clone(), Value::String(v.to_string())))
                            .collect(),
                    ),
                );
            }
            if let Some(w) = &b.water {
                body.insert("water".into(), Value::String(w.to_string()));
            }
            if let Some(l) = &b.layer {
                body.insert("layer".into(), Value::String(l.clone()));
            }
            ("tools_burin", Value::Object(body))
        }
        Op::Graticule(g) | Op::GraticuleArea(g) => {
            let mut body = serde_json::to_value(&g.look).unwrap_or_else(|_| json!({}));
            body["in"] = Value::String(g.in_area.to_string());
            (if matches!(op, Op::Graticule(_)) { "tools_graticule" } else { "tools_graticule_area" }, body)
        }
        Op::Labels(l) => {
            let mut body = serde_json::to_value(&l.style).unwrap_or_else(|_| json!({}));
            body["from"] = refs_json(&l.from);
            if let Some(a) = &l.in_area {
                body["in"] = Value::String(a.to_string());
            }
            if let Some(a) = &l.avoid {
                body["avoid"] = Value::String(a.to_string());
            }
            ("tools_labels", body)
        }
        Op::Grow(g) => ("tools_grow", json!({ "of": g.of.to_string(), "by": g.by })),
        Op::Move(m) => ("tools_move", json!({ "of": m.of.to_string(), "by": [m.by[0], m.by[1]] })),
        Op::Around(a) => ("tools_around", json!({ "of": a.of.to_string(), "by": a.by })),
        Op::Shape(s) => ("tools_shape", serde_json::to_value(s).unwrap_or_default()),
        Op::Path(s) => ("tools_path", serde_json::to_value(s).unwrap_or_default()),
        Op::Text(t) => ("tools_text", serde_json::to_value(t).unwrap_or_default()),
        Op::TextArea(t) => ("tools_text_area", serde_json::to_value(t).unwrap_or_default()),
        Op::BufferLines(b) => {
            let mut body = serde_json::Map::from_iter([
                ("lines".into(), Value::String(b.lines.to_string())),
                ("by".into(), json!(b.by)),
            ]);
            if b.cap == LineBufferCap::Flat {
                body.insert("cap".into(), json!("flat"));
            }
            ("tools_buffer_lines", Value::Object(body))
        }
        Op::Frame => ("engine_frame", json!({})),
        Op::ExtendToFrame(e) => (
            "tools_extend_to_frame",
            json!({
                "of": e.of.to_string(),
                "within": e.within.to_string(),
                "gap_mm": e.gap_mm,
            }),
        ),
        Op::Rings(r) => ("tools_rings", json!({ "of": r.of.to_string(), "exterior_only": r.exterior_only })),
        Op::Lines(n) => ("tools_lines", Value::String(n.to_string())),
        Op::Segments(n) => ("tools_segments", Value::String(n.to_string())),
        Op::Dedupe(n) => ("tools_dedupe", Value::String(n.to_string())),
        Op::Merge(n) => ("tools_merge", Value::String(n.to_string())),
        Op::Join(u) => ("tools_join", union(u)),
        Op::ClipLines(c) => (
            "tools_clip",
            json!({ "lines": c.lines.to_string(), "within": c.within.to_string(), "invert": c.invert }),
        ),
        Op::Fill(f) => {
            let mut body = serde_json::to_value(&f.spec).unwrap_or_else(|_| json!({}));
            body["in"] = Value::String(f.in_area.to_string());
            if f.per_feature {
                body["per"] = Value::String("feature".into());
            }
            if let Some(c) = &f.content {
                body["content"] = Value::String(c.to_string());
            }
            if let Some(m) = &f.motif {
                body["motif"] = Value::String(m.to_string());
            }
            ("tools_fill", body)
        }
        Op::FillCover(f) => {
            let mut body = serde_json::to_value(&f.spec).unwrap_or_else(|_| json!({}));
            body["in"] = Value::String(f.in_area.to_string());
            if let Some(m) = &f.motif {
                body["motif"] = Value::String(m.to_string());
            }
            ("tools_fill_cover", body)
        }
        Op::Module(m) => {
            let key = format!("module_{}", m.name);
            let mut body = serde_json::to_value(&m.roads).unwrap_or_else(|_| json!({}));
            if let Some(from) = &m.from {
                if let Some(obj) = body.as_object_mut() {
                    obj.insert("from".into(), Value::String(from.to_string()));
                }
            }
            return json!({ key: body });
        }
    };
    json!({ key: value })
}

impl Target {
    fn to_json(&self) -> Value {
        match &self.module {
            Some(m) => Value::String(format!("{m}.{}", self.name.name)),
            None => Value::String(self.name.to_string()),
        }
    }
}

impl Grammar {
    /// The graph as JSON: what a script built, for presets, `--dump-graph`
    /// and the page's worker. [`Grammar::from_json`] reads it back.
    pub fn to_json(&self) -> Value {
        use serde_json::json;
        let mut out = serde_json::Map::new();
        if let Some(t) = &self.title {
            out.insert("title".into(), Value::String(t.clone()));
        }
        out.insert("output".into(), serde_json::to_value(&self.output).unwrap_or(Value::Null));
        for (section, defs) in &self.sections {
            let body: serde_json::Map<String, Value> = defs
                .iter()
                .map(|d| {
                    let mut op = op_to_json(&d.op);
                    if let Some(at) = d.at {
                        op["at"] = json!(at);
                    }
                    (d.name.clone(), op)
                })
                .collect();
            out.insert(format!("${}", section.key()), Value::Object(body));
        }
        let draw: Vec<Value> = self
            .draw
            .iter()
            .map(|d| {
                let mut v = json!({ "from": d.from.to_json() });
                if let Some(id) = &d.id {
                    v["id"] = json!(id);
                }
                if let Some(s) = &d.stroke {
                    v["stroke"] = json!(s);
                }
                if let Some(at) = d.at {
                    v["at"] = json!(at);
                }
                v
            })
            .collect();
        out.insert("draw".into(), Value::Array(draw));
        if !self.paint.is_empty() {
            let paint: Vec<Value> = self
                .paint
                .iter()
                .map(|p| {
                    let mut v = json!({ "id": p.id, "from": p.from.to_json() });
                    v[p.look.key()] = p.look.to_json();
                    if !p.halo.is_none() {
                        v["halo"] = json!(p.halo);
                    }
                    if let Some(z) = p.shown.minzoom {
                        v["minzoom"] = json!(z);
                    }
                    if let Some(z) = p.shown.maxzoom {
                        v["maxzoom"] = json!(z);
                    }
                    if let Some((f, _)) = &p.shown.filter {
                        v["filter"] = f.clone();
                    }
                    if let Some(at) = p.at {
                        v["at"] = json!(at);
                    }
                    v
                })
                .collect();
            out.insert("paint".into(), Value::Array(paint));
        }
        let masks: serde_json::Map<String, Value> = self
            .compose
            .masks
            .iter()
            .map(|(name, m)| {
                let mut v = json!({
                    "from": m.from.to_json(),
                    "occludes": m.occludes.iter().map(|i| i.0.clone()).collect::<Vec<_>>(),
                });
                if let Some(at) = m.at {
                    v["at"] = json!(at);
                }
                (name.clone(), v)
            })
            .collect();
        let clip = match &self.compose.clip_default {
            Clip::Auto => json!("auto"),
            Clip::None => json!("none"),
            Clip::Areas(ns) => refs_json(ns),
        };
        let mut compose_obj = json!({
            "order": self.compose.order.iter().map(|i| i.0.clone()).collect::<Vec<_>>(),
            "masks": masks,
            "clip": { "default": clip },
        });
        if !self.compose.optimize.is_empty() {
            let opt: Vec<Value> = self
                .compose
                .optimize
                .iter()
                .map(|s| {
                    let raw = RawOptimizeStep {
                        layers: s.layers.iter().map(|i| i.0.clone()).collect(),
                        except: s.except.iter().map(|i| i.0.clone()).collect(),
                        op: s.op.clone(),
                        at: s.at,
                    };
                    serde_json::to_value(raw).unwrap()
                })
                .collect();
            compose_obj["optimize"] = Value::Array(opt);
        }
        out.insert("compose".into(), compose_obj);
        if !self.views.is_empty() {
            let views: Vec<Value> =
                self.views
                    .iter()
                    .map(|v| {
                        let mut o = json!({ "id": v.id, "at": [v.at.0, v.at.1], "graph": v.grammar.to_json() });
                        if let Some(ink) = &v.ink {
                            o["ink"] = json!(ink);
                        }
                        o
                    })
                    .collect();
            out.insert("views".into(), Value::Array(views));
        }
        Value::Object(out)
    }

    pub fn from_json(text: &str) -> Result<Grammar, GrammarError> {
        let raw: Raw = serde_json::from_str(text).map_err(|e| GrammarError::Json(e.to_string()))?;
        build(raw)
    }
}

// ---------------------------------------------------------------------------
// Validation
// ---------------------------------------------------------------------------

fn validate_label_pick(g: &Grammar, def: &Def, pick: &LabelPick) -> Result<(), GrammarError> {
    let labels = g.find(&pick.of).ok_or_else(|| {
        GrammarError::Invalid(format!("{} reads {}, which is not defined", def.label(), pick.of))
    })?;
    if !matches!(&labels.op, Op::Labels(_)) {
        return Err(GrammarError::Invalid(format!("{} reads {}, which is not a labels def", def.label(), pick.of)));
    }
    if let Some(rule) = &pick.rule {
        let Op::Labels(l) = &labels.op else { unreachable!() };
        if !l.style.rule_ids().iter().any(|id| id == rule) {
            return Err(GrammarError::Invalid(format!(
                "{}: rule {:?} is not a labels.rules[].id on {}",
                def.label(),
                rule,
                pick.of
            )));
        }
    }
    Ok(())
}

/// What each paint entry paints is defined and fits its look: an area is
/// filled, lines are lined, features are named. Ids are unique.
fn validate_paint(g: &Grammar) -> Result<(), GrammarError> {
    let mut ids = BTreeSet::new();
    for p in &g.paint {
        let fail = |m: String| GrammarError::Invalid(located(&format!("paint {:?}: {m}", p.id), p.at));
        if !ids.insert(p.id.as_str()) {
            return Err(fail("the id is painted twice".into()));
        }
        let kind = match &p.from.module {
            Some(m) => {
                if g.module(m).is_none() {
                    return Err(fail(format!("nothing calls module {m}")));
                }
                Section::Lines
            }
            None => {
                if g.find(&p.from.name).is_none() {
                    return Err(fail(format!("from {}: no such def", p.from.name)));
                }
                p.from.name.section
            }
        };
        let wants = match (p.look.key(), kind) {
            ("fill", Section::Areas) | ("line", Section::Lines) | ("text", Section::Features) => None,
            (_, Section::Fills) => Some("a fill's strokes are for paper: paint its area with a fill pattern instead".to_string()),
            ("fill", _) => Some(format!("fill paints an area, not ${kind}")),
            ("line", _) => Some(format!("line paints lines, not ${kind}")),
            _ => Some(format!("text names features, not ${kind}")),
        };
        // An area or lines are geometry made from features, their tags gone:
        // only names read them.
        if p.look.key() != "text" && p.look.reads().or(p.shown.reads()).feature {
            return Err(fail(format!(
                "{} reads a feature's tags ([\"get\", …]), which only names keep: split the features with features.where before they become {}",
                p.look.key(),
                if p.look.key() == "fill" { "an area" } else { "lines" }
            )));
        }
        if let Some(m) = wants {
            return Err(fail(m));
        }
    }
    if let Some(screen) = g.output.screen {
        let (own, other, medium) = match screen.kind {
            crate::paint::ScreenKind::Bitmap => ("px", "ch", "a bitmap counts pixels"),
            crate::paint::ScreenKind::Text => ("ch", "px", "a text screen counts characters"),
        };
        for p in &g.paint {
            if let Some(u) = p.look.units().iter().find(|u| **u != own) {
                let why = if *u == other { format!("{u} is the other screen's unit") } else { format!("{u} measures paper") };
                return Err(GrammarError::Invalid(located(&format!("paint {:?}: {why}; {medium}: write {own}, or a bare number", p.id), p.at)));
            }
        }
    }
    if !g.paint.is_empty() && g.output.screen.is_none() {
        return Err(GrammarError::Invalid("paint covers a screen: give the output one, output({ screen: { kind, width, height } })".into()));
    }
    Ok(())
}

/// Every reference defined in the right section, draw ids unique, order and
/// masks naming draw ids, no loops.
pub fn validate(g: &Grammar) -> Result<(), GrammarError> {
    // Every reference must exist, in the right section.
    for def in g.all_defs() {
        for r in def.op.refs() {
            if g.find(&r).is_none() {
                return Err(GrammarError::Invalid(format!(
                    "{} refers to {r}, which is not defined under ${}",
                    def.label(),
                    r.section
                )));
            }
        }
        if let Op::LabelArea(pick) | Op::LabelLines(pick) = &def.op {
            validate_label_pick(g, def, pick)?;
        }
    }
    // A draw must point at line output: $lines, $fills, or a module output.
    for d in &g.draw {
        if d.from.module.is_some() {
            continue; // e.g. roads.outlines: the module owns the name
        }
        if !matches!(d.from.name.section, Section::Lines | Section::Fills) {
            return Err(GrammarError::Invalid(located(
                &format!("draw from {} needs $lines or $fills, not ${}", d.from.name, d.from.name.section),
                d.at,
            )));
        }
        if g.find(&d.from.name).is_none() {
            return Err(GrammarError::Invalid(format!("draw from {}: no such def", d.from.name)));
        }
    }
    validate_paint(g)?;
    let mut groups: BTreeSet<String> = BTreeSet::new();
    for d in &g.draw {
        if !groups.insert(d.group()) {
            return Err(GrammarError::Invalid(located(
                &format!("two draw entries write the same SVG group id {:?}", d.group()),
                d.at,
            )));
        }
    }
    // Order and occludes must name draw groups.
    for id in &g.compose.order {
        if !groups.contains(&id.0) {
            return Err(GrammarError::Invalid(format!("compose.order names {:?}, which is not a draw id", id.0)));
        }
    }
    for (name, mask) in &g.compose.masks {
        if mask.from.module.is_some() {
            // e.g. roads.area: an area published by a module.
        } else if mask.from.name.section != Section::Areas {
            return Err(GrammarError::Invalid(located(
                &format!("masks.{name}.from is {}, but a mask must be an area", mask.from.name),
                mask.at,
            )));
        } else if g.find(&mask.from.name).is_none() {
            return Err(GrammarError::Invalid(located(
                &format!("masks.{name}.from: no such def {}", mask.from.name),
                mask.at,
            )));
        }
        for id in &mask.occludes {
            if !groups.contains(&id.0) && !g.views.iter().any(|v| v.id == id.0) {
                return Err(GrammarError::Invalid(located(
                    &format!("masks.{name}.occludes names {:?}, which is not a draw id", id.0),
                    mask.at,
                )));
            }
        }
    }
    for (id, clip) in &g.compose.clip {
        if !groups.contains(&id.0) {
            return Err(GrammarError::Invalid(format!("compose.clip names {:?}, which is not a draw id", id.0)));
        }
        if let Clip::Areas(names) = clip {
            for n in names {
                if n.section != Section::Areas || g.find(n).is_none() {
                    return Err(GrammarError::Invalid(format!("compose.clip[{:?}]: {n} is not an area def", id.0)));
                }
            }
        }
    }
    for step in &g.compose.optimize {
        for id in &step.layers {
            if !groups.contains(&id.0) {
                return Err(GrammarError::Invalid(located(
                    &format!("compose.{} names {:?}, which is not a draw id", step.op.name(), id.0),
                    step.at,
                )));
            }
        }
        for id in &step.except {
            if !groups.contains(&id.0) {
                return Err(GrammarError::Invalid(located(
                    &format!("compose.{} except names {:?}, which is not a draw id", step.op.name(), id.0),
                    step.at,
                )));
            }
        }
    }
    // No loops across defs.
    if let Some(cycle) = find_cycle(g) {
        return Err(GrammarError::Invalid(format!("loop between defs: {}", cycle.join(" → "))));
    }
    Ok(())
}

fn find_cycle(g: &Grammar) -> Option<Vec<String>> {
    #[derive(Clone, Copy, PartialEq)]
    enum Mark {
        Open,
        Done,
    }
    fn visit(
        g: &Grammar,
        name: &Name,
        marks: &mut BTreeMap<Name, Mark>,
        path: &mut Vec<Name>,
    ) -> Option<Vec<String>> {
        match marks.get(name) {
            Some(Mark::Done) => return None,
            Some(Mark::Open) => {
                let at = path.iter().position(|p| p == name).unwrap_or(0);
                let mut loop_names: Vec<String> = path[at..].iter().map(Name::to_string).collect();
                loop_names.push(name.to_string());
                return Some(loop_names);
            }
            None => {}
        }
        marks.insert(name.clone(), Mark::Open);
        path.push(name.clone());
        if let Some(def) = g.find(name) {
            for r in def.op.refs() {
                if let Some(cycle) = visit(g, &r, marks, path) {
                    return Some(cycle);
                }
            }
        }
        path.pop();
        marks.insert(name.clone(), Mark::Done);
        None
    }

    let mut marks = BTreeMap::new();
    let mut path = Vec::new();
    for def in g.all_defs() {
        if !marks.contains_key(&def.reference()) {
            if let Some(cycle) = visit(g, &def.reference(), &mut marks, &mut path) {
                return Some(cycle);
            }
        }
    }
    None
}

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

    /// The example profile, trimmed to the parts the grammar must accept.
    const YAML: &str = r#"
output: { width: 6in, height: 4in, scale: "1:10000" }

$features:
  garden: { osm_select: { leisure: garden } }
  bldg:   { osm_select: { building: true } }

$areas:
  garden:     { tools_polygons: $features.garden }
  parks:      { tools_union: [$areas.garden] }
  parks_ext:  { tools_fill_holes: $areas.parks }
  footprints: { tools_polygons: $features.bldg }
  dissolved:  { tools_union: [$areas.footprints] }
  inner_band: { tools_grow: { of: $areas.dissolved, by: -0.1mm } }
  wet:        { tools_union: [$areas.garden] }

$lines:
  parks_edge: { tools_rings: { of: $areas.parks_ext, exterior_only: true } }
  bldg_lines: { tools_segments: $features.bldg }
  bldg_dedupe: { tools_dedupe: $lines.bldg_lines }
  walls:      { tools_clip: { lines: $lines.bldg_dedupe, within: $areas.inner_band } }

$fills:
  hatch: { tools_fill: { in: $areas.footprints, per: feature, pattern: zigzag, spacing: 0.5mm, angle: 45 } }

draw:
  - { id: parks_ring, from: $lines.parks_edge, stroke: { style: dash, dash: 0.45mm, gap: 0.40mm } }
  - { from: $fills.hatch }
  - { id: bldg_wall, from: $lines.walls, stroke: solid }

compose:
  order: [parks_ring, fills_hatch, bldg_wall]
  masks:
    bldg_cover: { from: $areas.dissolved, occludes: [parks_ring] }
  clip:
    default: auto
"#;

    /// The tests below write only the part under test; the output is boilerplate.
    fn parse(text: &str) -> Result<Grammar, GrammarError> {
        let body = if text.contains("output:") {
            text.to_string()
        } else {
            format!("output: {{ width: 100mm, height: 50mm }}\n{text}")
        };
        from_yaml(&body)
    }

    #[test]
    fn parses_the_example_and_types_its_sections() {
        let g = parse(YAML).unwrap();
        assert_eq!(g.defs(Section::Features).len(), 2);
        assert_eq!(g.defs(Section::Areas).len(), 7);
        assert_eq!(g.defs(Section::Lines).len(), 4);
        assert_eq!(g.defs(Section::Fills).len(), 1);
        let dissolved = Name::parse("$areas.dissolved").unwrap();
        assert_eq!(g.find(&dissolved).unwrap().op.section(), Section::Areas);
    }

    #[test]
    fn a_title_is_optional_and_kept_as_written() {
        assert_eq!(parse(YAML).unwrap().title, None);
        let g = parse(&format!("title: \"Parks: and buildings\"\n{YAML}")).unwrap();
        assert_eq!(g.title.as_deref(), Some("Parks: and buildings"));
    }

    #[test]
    fn ids_fall_back_to_the_def_name() {
        let g = parse(YAML).unwrap();
        assert_eq!(g.groups(), vec!["parks_ring", "fills_hatch", "bldg_wall"]);
    }

    #[test]
    fn a_reference_must_exist_and_carry_its_section() {
        let bad = "$areas:\n  a: { tools_polygons: $features.nope }\n";
        assert!(matches!(parse(bad), Err(GrammarError::Invalid(m)) if m.contains("$features.nope")));
        let bad = "$areas:\n  a: { tools_polygons: $lines.nope }\n";
        assert!(matches!(parse(bad), Err(GrammarError::Invalid(m)) if m.contains("$lines.nope")));
    }

    #[test]
    fn an_operation_must_match_its_section() {
        // tools_rings makes lines; under $areas it is an error.
        let bad = "$areas:\n  a: { tools_rings: $areas.b }\n";
        assert!(matches!(
            parse(bad),
            Err(GrammarError::Invalid(m)) if m.contains("lines") && m.contains("areas")
        ));
    }

    #[test]
    fn draw_needs_line_output_and_masks_need_areas() {
        let base = "$features:\n  f: { osm_select: { building: true } }\n\
                    $areas:\n  a: { tools_polygons: $features.f }\n\
                    $lines:\n  l: { tools_rings: $areas.a }\n";
        // draw from an area: refused
        assert!(parse(&format!("{base}draw:\n  - {{ from: $areas.a }}\n")).is_err());
        // mask from a line set: refused
        let text = format!("{base}draw:\n  - {{ from: $lines.l }}\ncompose:\n  masks:\n    m: {{ from: $lines.l }}\n");
        assert!(matches!(parse(&text), Err(GrammarError::Invalid(m)) if m.contains("must be an area")));
    }

    #[test]
    fn a_screen_is_painted_by_what_each_entry_paints() {
        let screen = "output: { screen: { kind: text, width: 80, height: 24 } }\n";
        let base = format!(
            "{screen}$features:\n  f: {{ osm_select: {{ building: true }} }}\n\
             $areas:\n  a: {{ tools_polygons: $features.f }}\n\
             $lines:\n  l: {{ tools_rings: $areas.a }}\n"
        );
        let g = parse(&format!(
            "{base}paint:\n  - {{ id: blocks, from: $areas.a, fill: {{ chars: [\"~ \", \" ~\"], color: \"#36c\" }} }}\n\
             \x20 - {{ id: walls, from: $lines.l, line: {{ style: box }}, halo: [1, 0] }}\n\
             \x20 - {{ id: names, from: $features.f, text: {{ marker: \"*\" }} }}\n"
        ))
        .unwrap();
        // The screen's size is counted in characters, a row two of them tall.
        assert_eq!((g.output.width.0, g.output.height.0), (80.0, 48.0));
        assert_eq!(g.paint.len(), 3);
        assert_eq!(g.paint[1].halo, crate::paint::Halo(1, 0));
        // Back through JSON, the same graph.
        let again = Grammar::from_json(&g.to_json().to_string()).unwrap();
        assert_eq!(again.paint, g.paint);
        assert_eq!(again.output, g.output);
        // An area is filled, not lined; a pattern must be one there is.
        let wrong = parse(&format!("{base}paint:\n  - {{ id: x, from: $areas.a, line: {{}} }}\n"));
        assert!(matches!(&wrong, Err(GrammarError::Invalid(m)) if m.contains("line paints lines")), "{wrong:?}");
        let unknown = parse(&format!("{base}paint:\n  - {{ id: x, from: $areas.a, fill: {{ pattern: plaid }} }}\n"));
        assert!(matches!(unknown, Err(GrammarError::Invalid(m)) if m.contains("plaid")));
        // Paper has no paint.
        let paper = parse("$areas:\n  a: { engine_frame: {} }\npaint:\n  - { id: x, from: $areas.a, fill: { pattern: solid } }\n");
        assert!(matches!(paper, Err(GrammarError::Invalid(m)) if m.contains("give the output one")));
    }

    #[test]
    fn loops_and_unknown_operations_are_load_errors() {
        let looped = "$areas:\n  a: { tools_union: [$areas.b] }\n  b: { tools_grow: { of: $areas.a, by: 1mm } }\n";
        assert!(matches!(parse(looped), Err(GrammarError::Invalid(m)) if m.contains("loop")));
        let unknown = "$areas:\n  a: { tools_bogus: 1 }\n";
        assert!(matches!(parse(unknown), Err(GrammarError::Invalid(m)) if m.contains("unknown operation")));
    }

    #[test]
    fn one_operation_per_def() {
        let two = "$areas:\n  a: { tools_polygons: $areas.b, engine_frame: {} }\n  b: { engine_frame: {} }\n";
        assert!(matches!(parse(two), Err(GrammarError::Json(m)) if m.contains("exactly one operation")));
    }

    #[test]
    fn modules_are_recorded_and_bad_references_named() {
        let module = "$lines:\n  roads: { module_roads: {} }\n";
        let g = parse(module).unwrap();
        assert_eq!(
            g.defs(Section::Lines)[0].op,
            Op::Module(Module { name: "roads".into(), from: None, roads: Default::default() })
        );
        let bad_ref = "$areas:\n  a: { tools_union: [dense] }\n";
        assert!(matches!(parse(bad_ref), Err(GrammarError::Invalid(m)) if m.contains("\"dense\" is not a $section.name reference")));
        let bad_len = "$fills:\n  f: { tools_fill: { in: $areas.a, spacing: dense } }\n$areas:\n  a: { engine_frame: {} }\n";
        assert!(parse(bad_len).is_err());
    }

    #[test]
    fn tile_selections_and_modules_reading_them() {
        let text = "$features:\n  bldg: { tiles_select: buildings }\n  ways: { tiles_select: [roads, \"paths\"] }\n  sea: { tiles_select: ocean }\n\
                    $areas:\n  roads: { module_roads: { from: $features.ways } }\n";
        let g = parse(text).unwrap();
        assert_eq!(g.tile_selectors(), ["buildings", "roads", "paths", "ocean"]);
        assert!(g.osm_keys().is_empty(), "nothing reads Overpass");
        assert!(g.draws_ocean());
        assert_eq!(g.find(&Name::parse("$areas.roads").unwrap()).unwrap().op.refs(), [Name::parse("$features.ways").unwrap()]);
        let osm = parse("$areas:\n  roads: { module_roads: {} }\n").unwrap();
        assert!(osm.osm_keys().contains(&"highway".to_string()) && osm.tile_selectors().is_empty());
        assert!(matches!(parse("$features:\n  a: { tiles_select: forrest }\n"), Err(GrammarError::Invalid(m)) if m.contains("preset")));
        assert!(parse("$areas:\n  r: { module_roads: { from: $areas.r } }\n").is_err());
        assert!(parse("$areas:\n  r: { module_roads: { form: $features.x } }\n").is_err());
    }

    #[test]
    fn duplicate_names_and_extra_keys_are_refused() {
        let dup = r#"{ "output": {}, "$areas": { "a": { "engine_frame": {} }, "a": { "engine_frame": {} } } }"#;
        assert!(matches!(Grammar::from_json(dup), Err(GrammarError::Invalid(m)) if m.contains("defined twice")));
        let extra = "$areas:\n  a: { engine_frame: {}, note: hi }\n";
        assert!(parse(extra).is_err());
    }

    #[test]
    fn the_graph_round_trips_through_json() {
        let g = parse(YAML).unwrap();
        let json = g.to_json().to_string();
        let back = Grammar::from_json(&json).unwrap();
        assert_eq!(back, g);
        assert_eq!(back.to_json().to_string(), json);
    }

    #[test]
    fn script_positions_ride_along_and_label_errors() {
        let mut g = parse(YAML).unwrap();
        g.sections[1].1[0].at = Some(At(12, 5));
        let back = Grammar::from_json(&g.to_json().to_string()).unwrap();
        assert_eq!(back.sections[1].1[0].at, Some(At(12, 5)));
        assert_eq!(back.sections[1].1[0].label(), "$areas.garden (line 12 column 5)");
        let mut bad = g.to_json();
        bad["$areas"]["garden"]["tools_polygons"] = Value::String("$features.nope".into());
        let err = Grammar::from_json(&bad.to_string()).unwrap_err().to_string();
        assert!(err.contains("line 12 column 5"), "{err}");
    }

    #[test]
    fn label_area_accepts_a_rule_bucket_object() {
        let text = r#"{
          "output": { "width": "100mm", "height": "50mm" },
          "$features": { "p": { "tiles_select": ["parks"] } },
          "$lines": { "names": { "tools_labels": { "from": ["$features.p"], "rules": [{ "id": "park", "tags": { "class": "park" } }] } } },
          "$areas": { "park": { "tools_label_area": { "of": "$lines.names", "rule": "park" } } }
        }"#;
        let g = Grammar::from_json(text).unwrap();
        let def = g.defs(Section::Areas).iter().find(|d| d.name == "park").unwrap();
        let Op::LabelArea(pick) = &def.op else { panic!("label area") };
        assert_eq!(pick.rule.as_deref(), Some("park"));
    }
}