tilo-resource 0.5.2

The Tilo resource layer: typed, hierarchical app resources.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
//! A model type's storage contract as data.
//!
//! What a record does with its fields — read them, write them, compare them,
//! edit, check and describe them — is the same walk for every record, over
//! each field's own type. `#[derive(Model)]` describes a record as a table
//! of its fields ([`ResourceDesc`]) and three small functions reaching into it
//! (a field by position, the same mutably, and building one from its
//! fields), and every [`Model`] operation of a record is one function here,
//! compiled once into the runtime. A field's type is reached through
//! its [`ModelTable`]: the type's [`Model`] functions with the type erased,
//! built once per type, and for the types this crate defines, once.

use std::any::Any;
use std::marker::PhantomData;
use tilo_sort::CompactSort as _;

use automerge::{ObjId, ObjType, Value};

use crate::action::{ActionCx, Refusal};
use crate::delta::{Delta, Touch};
use crate::items::{ItemCollection, ItemSource, ItemText};
use crate::model::{Doc, Fresh, LocatedAt as _, Model, ModelError, Slot};
use crate::path::{Edit, EditOp, OpDescription, Segment};
use crate::resource::Place;

pub(crate) mod fresh;
mod item_paths;
pub use item_paths::{holds_nested_items, item_json, names_item, reads_item};

/// A value's fields made with the map holding it in one batch, and the
/// fields its `store` writes into it after, by position, with whether each
/// was made with the map ([`Fresh::Made`](crate::Fresh::Made)).
pub(crate) type Fields = (automerge::hydrate::Map, Vec<(usize, bool)>);

/// A model type's [`Model`] functions, its type erased. Each takes the table
/// it was reached through, which for a record carries its [`ResourceDesc`].
/// A value is handed over as `&dyn Any` of the type; a value made is put
/// into an `&mut dyn Any` of `Option` of the type.
#[allow(
    clippy::type_complexity,
    reason = "each field is one Model function, with the same parameters"
)]
pub struct ModelOps {
    pub(crate) to_json: fn(&ModelTable, &dyn Any) -> serde_json::Value,
    pub(crate) from_json:
        fn(&ModelTable, &serde_json::Value, &mut dyn Any) -> Result<(), ModelError>,
    pub(crate) load:
        fn(&ModelTable, &Doc, &Value<'_>, &ObjId, &mut dyn Any) -> Result<(), ModelError>,
    pub(crate) missing: fn(&ModelTable, &mut dyn Any) -> Result<(), ModelError>,
    /// Read the value anew in place: from what a slot holds, or its missing
    /// value when the slot holds nothing.
    pub(crate) reload:
        fn(&ModelTable, &mut dyn Any, &Doc, Option<(&Value<'_>, &ObjId)>) -> Result<(), ModelError>,
    pub(crate) store: fn(&ModelTable, &dyn Any, &mut Doc, Slot<'_>) -> Result<(), ModelError>,
    /// [`Model::fresh`].
    pub(crate) fresh: fn(&ModelTable, &dyn Any, automerge::TextEncoding) -> Fresh,
    pub(crate) stores_as: fn(&ModelTable, &dyn Any, &dyn Any) -> bool,
    pub(crate) store_changed:
        fn(&ModelTable, &dyn Any, &dyn Any, &mut Doc, Slot<'_>, &Delta) -> Result<(), ModelError>,
    pub(crate) refresh:
        fn(&ModelTable, &mut dyn Any, &Doc, &Value<'_>, &ObjId, &Delta) -> Result<(), ModelError>,
    pub(crate) read_whole: fn(&ModelTable, &mut dyn Any, &Doc) -> Result<(), ModelError>,
    pub(crate) edit: fn(
        &ModelTable,
        &mut Doc,
        Slot<'_>,
        &[Segment],
        &EditOp,
        &mut ActionCx,
    ) -> Result<(), ModelError>,
    pub(crate) diff: fn(&ModelTable, &dyn Any, &dyn Any, &[Segment], &mut Vec<Edit<()>>),
    pub(crate) collect_text: fn(&ModelTable, &dyn Any, &mut Vec<String>),
    pub(crate) check: fn(&ModelTable, &dyn Any) -> Result<(), Refusal>,
    pub(crate) get_at: for<'a> fn(&ModelTable, &'a dyn Any, &[Segment]) -> Option<&'a dyn Any>,
    pub(crate) label: fn(&ModelTable, &dyn Any) -> Option<String>,
    pub(crate) nested_collections: fn(&ModelTable, &dyn Any) -> Vec<ItemCollection>,
    pub(crate) op_coalesces:
        fn(&ModelTable, &[Segment], &serde_json::Value, &serde_json::Value) -> Option<bool>,
    pub(crate) op_continuable: fn(&ModelTable, &[Segment], &serde_json::Value) -> Option<bool>,
    pub(crate) op_describe:
        fn(&ModelTable, &[Segment], &serde_json::Value) -> Option<OpDescription>,
    pub(crate) op_lands: fn(&ModelTable, &dyn Any, &[Segment], &serde_json::Value) -> Option<Place>,
    pub(crate) op_schemas: fn(&ModelTable, &str, &mut Vec<(String, serde_json::Value)>),
    /// What an edit that writes a new value carries of the value's JSON
    /// form ([`crate::shape::without_absent`]).
    pub(crate) without_absent: fn(&ModelTable, serde_json::Value) -> serde_json::Value,
}

/// A model type as data: its erased [`Model`] functions, what it is (a
/// record's fields), and what it holds (a collection's items).
pub struct ModelTable {
    pub(crate) ops: &'static ModelOps,
    desc: Desc,
    /// Its [`Model::CHECKS`].
    pub checks: bool,
    /// Its [`Model::OPS`].
    pub has_ops: bool,
    /// Its [`Model::SCALAR`].
    pub scalar: bool,
}

/// What a type's table knows of its shape, beyond its functions.
#[derive(Clone, Copy)]
enum Desc {
    /// Its own functions do everything.
    Own,
    /// A record of fields.
    Record(&'static ResourceDesc),
    /// An `Option` of a value.
    Option(&'static OptionDesc),
    /// A collection of items.
    Collection(&'static crate::collection::CollectionDesc),
    /// An enum of unit variants.
    Unit(&'static UnitDesc),
    /// A value stored whole as JSON text.
    Json(&'static JsonDesc),
    /// A list of values.
    Vec(&'static VecDesc),
    /// A map of string keys.
    Map(&'static MapDesc),
    /// A set of elements stored as map keys.
    Set(&'static crate::storage::SetDesc),
}

impl ModelTable {
    pub(crate) const fn record(&self) -> Option<&'static ResourceDesc> {
        match self.desc {
            Desc::Record(record) => Some(record),
            _ => None,
        }
    }

    pub(crate) const fn collection(&self) -> Option<&'static crate::collection::CollectionDesc> {
        match self.desc {
            Desc::Collection(collection) => Some(collection),
            _ => None,
        }
    }

    /// The table of a collection.
    #[must_use]
    pub const fn of_collection(
        collection: &'static crate::collection::CollectionDesc,
        checks: bool,
        has_ops: bool,
    ) -> Self {
        Self {
            ops: &crate::collection::COLLECTION_OPS,
            desc: Desc::Collection(collection),
            checks,
            has_ops,
            scalar: false,
        }
    }

    pub(crate) const fn set(&self) -> Option<&'static crate::storage::SetDesc> {
        match self.desc {
            Desc::Set(set) => Some(set),
            _ => None,
        }
    }

    /// The table of a set.
    #[must_use]
    pub const fn of_set(set: &'static crate::storage::SetDesc, checks: bool) -> Self {
        Self {
            ops: &crate::storage::SET_OPS,
            desc: Desc::Set(set),
            checks,
            has_ops: false,
            scalar: false,
        }
    }

    const fn option(&self) -> Option<&'static OptionDesc> {
        match self.desc {
            Desc::Option(option) => Some(option),
            _ => None,
        }
    }

    /// Whether a value of this table's type holds a value of `target`'s:
    /// it is one, or a field of it is, an option's value, or an item of a
    /// collection of it, at any depth a record nests.
    pub(crate) fn holds(&'static self, target: &'static Self) -> bool {
        fn within(table: &'static ModelTable, target: &'static ModelTable, depth: u8) -> bool {
            if std::ptr::eq(table, target) {
                return true;
            }
            // Records nest a handful deep; a type that holds itself (a tree
            // of boxed nodes) is not walked without end.
            if depth >= 16 {
                return false;
            }
            if let Some(option) = table.option() {
                return within(option.inner, target, depth.saturating_add(1));
            }
            table.record().is_some_and(|record| {
                record.fields.iter().any(|field| {
                    within(field.table, target, depth.saturating_add(1))
                        || field.items.is_some_and(|items| {
                            within(items.item_table, target, depth.saturating_add(1))
                        })
                })
            })
        }
        within(self, target, 0)
    }
}

/// A collection type's [`ItemSource`] functions, its type erased.
pub struct ItemOps {
    item_collection: fn(&dyn Any, &'static str) -> Option<ItemCollection>,
    item_presence: fn(&dyn Any) -> usize,
    label_of_item: fn(&dyn Any, &crate::Id) -> Option<String>,
    item_texts: fn(&dyn Any, &'static str, &mut Vec<ItemText>),
    nested_items: fn(&dyn Any, &'static str, &mut Vec<ItemCollection>),
    /// The items, whatever their type.
    pub(crate) list: for<'a> fn(&'a dyn Any) -> Option<&'a dyn crate::collection::ItemList>,
    /// The items' type's table.
    pub(crate) item_table: &'static ModelTable,
}

/// A collection whose items are published: its items' type's table.
pub trait PublishedItems: crate::collection::ItemList + ItemSource + 'static {
    const ITEM_TABLE: &'static ModelTable;
}

/// One field of a record, as [`ResourceDesc`] lists it.
pub struct FieldDesc {
    /// The key it is stored under.
    pub key: &'static str,
    /// Its Rust name.
    pub name: &'static str,
    /// Its type's table.
    pub table: &'static ModelTable,
    /// Changed only by the record's verbs (`#[model(readonly)]`).
    pub readonly: bool,
    /// Read all of it whenever it is read (`#[model(whole)]`).
    pub whole: bool,
    /// Left unread by a view's reader until a view demands its item
    /// (`#[model(demanded)]`, [`for_view`]).
    pub demanded: bool,
    /// Its items, for a collection whose items are published.
    pub items: Option<&'static ItemOps>,
}

/// Read a record, boxed, from the map it is stored in.
pub type ReadResource = fn(&Doc, &ObjId) -> Result<Box<dyn Any>, ModelError>;

/// A record's own invariant (`#[model(check = path)]`).
pub struct OwnCheck {
    /// Check a record.
    pub check: fn(&dyn Any) -> Result<(), Refusal>,
    /// Read a record from the map it is stored in, to check it after an
    /// edit of one of its fields.
    pub read: ReadResource,
    /// What the check reads (`#[model(check_reads, check_items)]`); `None`
    /// when it may read anything, so every edit inside the record checks it.
    pub reads: Option<CheckReads>,
}

/// What a record's own check reads: an edit that touches none of it cannot
/// break the invariant, so the record is not read again to check it.
pub struct CheckReads {
    /// The keys of the fields it reads.
    pub fields: &'static [&'static str],
    /// The keys of the collections whose items it counts but does not read
    /// into: adding, removing or replacing an item touches it, an edit
    /// inside one does not.
    pub items: &'static [&'static str],
}

impl CheckReads {
    /// Whether an edit at `path` (from the record) can change what the
    /// check reads.
    #[must_use]
    pub fn touched_by(&self, path: &[Segment]) -> bool {
        match path.split_first() {
            Some((Segment::Field(key), rest)) => {
                self.fields.contains(&key.as_str())
                    || (self.items.contains(&key.as_str()) && rest.len() <= 1)
            }
            // The whole record, or a path it does not know: checked.
            None | Some(_) => true,
        }
    }
}

/// A record type as `#[derive(Model)]` describes it. See the [module
/// docs](self).
pub struct ResourceDesc {
    /// Its stored fields, in declaration order.
    pub fields: &'static [FieldDesc],
    /// The field at a position of a record.
    pub field: for<'a> fn(&'a dyn Any, usize) -> Option<&'a dyn Any>,
    /// The same, mutably.
    pub field_mut: for<'a> fn(&'a mut dyn Any, usize) -> Option<&'a mut dyn Any>,
    /// A record from its fields, in order, put into an `Option` of it.
    pub build: fn(&mut dyn FieldSource, &mut dyn Any) -> Result<(), ModelError>,
    /// An empty `Option` of the record, for [`Self::build`] to fill.
    pub empty: fn() -> Box<dyn Any>,
    /// The record in a filled `Option` of it.
    pub unwrap: fn(&dyn Any) -> Option<&dyn Any>,
    /// Move the record out of a filled `Option` (the second) over a record
    /// (the first).
    pub replace: fn(&mut dyn Any, &mut dyn Any) -> Result<(), ModelError>,
    /// Its own invariant.
    pub own_check: Option<OwnCheck>,
    /// The position of its `#[model(label)]` field.
    pub label: Option<usize>,
    /// The positions of the fields its label joins (`#[model(label = "..")]`).
    pub label_parts: &'static [usize],
    /// What names it, where its name is not a field's text as stored
    /// (`#[model(label = path)]`).
    pub label_with: Option<fn(&dyn Any) -> Option<String>>,
    /// Its type's name: what a deferred check is known by.
    pub name: fn() -> &'static str,
    /// Its stored shape.
    pub shape: crate::Shape,
    /// Its [`Model::CHECKS`].
    pub checks: bool,
    /// Its [`Model::OPS`].
    pub has_ops: bool,
}

/// Where a record being built takes its fields from, one after the other.
pub trait FieldSource {
    /// The next field's value, put into `out`, an `Option` of its type.
    fn next(&mut self, out: &mut dyn Any) -> Result<(), ModelError>;

    /// The field just read: read all of it (`#[model(whole)]`) and move on.
    fn read(&mut self, value: &mut dyn Any) -> Result<(), ModelError>;
}

/// The next field of `source`, a `T`.
pub fn take<T: 'static>(source: &mut dyn FieldSource) -> Result<T, ModelError> {
    let mut out: Option<T> = None;
    source.next(&mut out)?;
    let Some(mut value) = out else {
        return Err(mismatch());
    };
    source.read(&mut value)?;
    Ok(value)
}

/// The next field of `source`, a `T`, or what `repair` derives for it when
/// the document holds none: a field declared `#[model(default = ..)]`, so a
/// record missing it (written by an older app, or half-made by an edit that
/// raced its deletion) still reads, and the next whole write stores it.
pub fn take_or<T: 'static>(
    source: &mut dyn FieldSource,
    repair: impl FnOnce() -> T,
) -> Result<T, ModelError> {
    let mut out: Option<T> = None;
    match source.next(&mut out) {
        Ok(()) => {}
        Err(ModelError::Missing { .. }) => out = Some(repair()),
        Err(error) => return Err(error),
    }
    let Some(mut value) = out else {
        return Err(mismatch());
    };
    source.read(&mut value)?;
    Ok(value)
}

/// Put `value` into `out`, an `Option` of its type.
///
/// # Errors
/// When `out` is of another type.
pub fn put<T: 'static>(out: &mut dyn Any, value: T) -> Result<(), ModelError> {
    match out.downcast_mut::<Option<T>>() {
        Some(slot) => {
            *slot = Some(value);
            Ok(())
        }
        None => Err(mismatch()),
    }
}

/// An empty `Option` of `T`.
#[must_use]
pub fn empty_of<T: 'static>() -> Box<dyn Any> {
    Box::new(None::<T>)
}

/// The `T` in a filled `Option` of it.
#[must_use]
pub fn unwrap_of<T: 'static>(filled: &dyn Any) -> Option<&dyn Any> {
    match filled.downcast_ref::<Option<T>>()? {
        Some(value) => Some(value),
        None => None,
    }
}

/// Swap the `T` in `filled`, an `Option` of it, with `target`: `filled`
/// then holds what `target` held, dropped with it.
///
/// # Errors
/// When either is of another type, or `filled` is empty.
pub fn replace_of<T: 'static>(
    target: &mut dyn Any,
    filled: &mut dyn Any,
) -> Result<(), ModelError> {
    match (
        target.downcast_mut::<T>(),
        filled.downcast_mut::<Option<T>>(),
    ) {
        (Some(target), Some(Some(value))) => {
            std::mem::swap(target, value);
            Ok(())
        }
        _ => Err(mismatch()),
    }
}

/// A value handed to a table of another type: a bug in the caller.
#[inline(never)]
pub(crate) fn mismatch() -> ModelError {
    ModelError::invalid("a value of another type")
}

/// The table of `T`, from its own [`Model`] functions.
pub struct TableOf<T>(PhantomData<T>);

/// `TABLE` of a type this crate defines, inside its `impl Model`: built
/// here, once, rather than in every app holding a field of it.
#[doc(hidden)]
#[macro_export]
macro_rules! __own_table {
    ($ty:ty) => {
        const TABLE: &'static $crate::table::ModelTable = {
            static TABLE: $crate::table::ModelTable = $crate::table::TableOf::<$ty>::TABLE;
            &TABLE
        };
    };
}

impl<T: Model> TableOf<T> {
    /// `T`'s functions.
    pub const OPS: ModelOps = ModelOps {
        without_absent: crate::shape::kept_whole,
        to_json: to_json_of::<T>,
        from_json: from_json_of::<T>,
        load: load_of::<T>,
        missing: missing_of::<T>,
        reload: reload_of::<T>,
        store: store_of::<T>,
        fresh: fresh::fresh_of::<T>,
        stores_as: stores_as_of::<T>,
        store_changed: store_changed_of::<T>,
        refresh: refresh_of::<T>,
        read_whole: read_whole_of::<T>,
        edit: edit_of::<T>,
        diff: diff_of::<T>,
        collect_text: collect_text_of::<T>,
        check: if T::CHECKS { check_of::<T> } else { no_check },
        get_at: get_at_of::<T>,
        label: label_of::<T>,
        nested_collections: nested_collections_of::<T>,
        op_coalesces: if T::OPS {
            op_coalesces_of::<T>
        } else {
            no_coalesces
        },
        op_continuable: if T::OPS {
            op_continuable_of::<T>
        } else {
            no_continuable
        },
        op_describe: if T::OPS {
            op_describe_of::<T>
        } else {
            no_describe
        },
        op_lands: if T::OPS { op_lands_of::<T> } else { no_lands },
        op_schemas: if T::OPS {
            op_schemas_of::<T>
        } else {
            no_schemas
        },
    };

    /// `T`'s table.
    pub const TABLE: ModelTable = ModelTable {
        ops: &Self::OPS,
        desc: Desc::Own,
        checks: T::CHECKS,
        has_ops: T::OPS,
        scalar: T::SCALAR,
    };
}

fn to_json_of<T: Model>(_: &ModelTable, value: &dyn Any) -> serde_json::Value {
    value
        .downcast_ref::<T>()
        .map_or(serde_json::Value::Null, Model::to_json)
}

fn from_json_of<T: Model>(
    _: &ModelTable,
    value: &serde_json::Value,
    out: &mut dyn Any,
) -> Result<(), ModelError> {
    put(out, T::from_json(value)?)
}

fn load_of<T: Model>(
    _: &ModelTable,
    doc: &Doc,
    value: &Value<'_>,
    id: &ObjId,
    out: &mut dyn Any,
) -> Result<(), ModelError> {
    put(out, T::load(doc, value, id)?)
}

fn missing_of<T: Model>(_: &ModelTable, out: &mut dyn Any) -> Result<(), ModelError> {
    put(out, T::missing()?)
}

fn reload_of<T: Model>(
    _: &ModelTable,
    target: &mut dyn Any,
    doc: &Doc,
    slot: Option<(&Value<'_>, &ObjId)>,
) -> Result<(), ModelError> {
    let Some(target) = target.downcast_mut::<T>() else {
        return Err(mismatch());
    };
    *target = match slot {
        Some((value, id)) => T::load(doc, value, id)?,
        None => T::missing()?,
    };
    Ok(())
}

fn store_of<T: Model>(
    _: &ModelTable,
    value: &dyn Any,
    doc: &mut Doc,
    slot: Slot<'_>,
) -> Result<(), ModelError> {
    match value.downcast_ref::<T>() {
        Some(value) => value.store(doc, slot),
        None => Err(mismatch()),
    }
}

fn stores_as_of<T: Model>(_: &ModelTable, value: &dyn Any, before: &dyn Any) -> bool {
    match (value.downcast_ref::<T>(), before.downcast_ref::<T>()) {
        (Some(value), Some(before)) => value.stores_as(before),
        _ => false,
    }
}

fn store_changed_of<T: Model>(
    _: &ModelTable,
    value: &dyn Any,
    before: &dyn Any,
    doc: &mut Doc,
    slot: Slot<'_>,
    dirty: &Delta,
) -> Result<(), ModelError> {
    match (value.downcast_ref::<T>(), before.downcast_ref::<T>()) {
        (Some(value), Some(before)) => value.store_changed(before, doc, slot, dirty),
        _ => Err(mismatch()),
    }
}

fn refresh_of<T: Model>(
    _: &ModelTable,
    target: &mut dyn Any,
    doc: &Doc,
    value: &Value<'_>,
    id: &ObjId,
    delta: &Delta,
) -> Result<(), ModelError> {
    match target.downcast_mut::<T>() {
        Some(target) => target.refresh(doc, value, id, delta),
        None => Err(mismatch()),
    }
}

fn read_whole_of<T: Model>(
    _: &ModelTable,
    target: &mut dyn Any,
    doc: &Doc,
) -> Result<(), ModelError> {
    match target.downcast_mut::<T>() {
        Some(target) => target.read_whole(doc),
        None => Err(mismatch()),
    }
}

fn edit_of<T: Model>(
    _: &ModelTable,
    doc: &mut Doc,
    slot: Slot<'_>,
    path: &[Segment],
    op: &EditOp,
    cx: &mut ActionCx,
) -> Result<(), ModelError> {
    T::edit(doc, slot, path, op, cx)
}

fn diff_of<T: Model>(
    _: &ModelTable,
    before: &dyn Any,
    after: &dyn Any,
    path: &[Segment],
    out: &mut Vec<Edit<()>>,
) {
    if let (Some(before), Some(after)) = (before.downcast_ref::<T>(), after.downcast_ref::<T>()) {
        before.diff(after, path, out);
    }
}

fn collect_text_of<T: Model>(_: &ModelTable, value: &dyn Any, out: &mut Vec<String>) {
    if let Some(value) = value.downcast_ref::<T>() {
        value.collect_text(out);
    }
}

fn check_of<T: Model>(_: &ModelTable, value: &dyn Any) -> Result<(), Refusal> {
    value.downcast_ref::<T>().map_or(Ok(()), Model::check)
}

#[allow(
    clippy::unnecessary_wraps,
    reason = "a table function: every type's check returns a result"
)]
fn no_check(_: &ModelTable, _: &dyn Any) -> Result<(), Refusal> {
    Ok(())
}

fn label_of<T: Model>(_: &ModelTable, value: &dyn Any) -> Option<String> {
    value.downcast_ref::<T>()?.label()
}

fn nested_collections_of<T: Model>(_: &ModelTable, value: &dyn Any) -> Vec<ItemCollection> {
    value
        .downcast_ref::<T>()
        .map_or_else(Vec::new, Model::nested_collections)
}

/// No label, no collections inside: what a value of a type with neither
/// answers.
pub(crate) fn no_label(_: &ModelTable, _: &dyn Any) -> Option<String> {
    None
}

pub(crate) fn no_nested(_: &ModelTable, _: &dyn Any) -> Vec<ItemCollection> {
    Vec::new()
}

fn get_at_of<'a, T: Model>(
    _: &ModelTable,
    value: &'a dyn Any,
    path: &[Segment],
) -> Option<&'a dyn Any> {
    value.downcast_ref::<T>()?.get_at(path)
}

fn op_coalesces_of<T: Model>(
    _: &ModelTable,
    path: &[Segment],
    previous: &serde_json::Value,
    next: &serde_json::Value,
) -> Option<bool> {
    T::op_coalesces(path, previous, next)
}

fn no_coalesces(
    _: &ModelTable,
    _: &[Segment],
    _: &serde_json::Value,
    _: &serde_json::Value,
) -> Option<bool> {
    None
}

fn op_continuable_of<T: Model>(
    _: &ModelTable,
    path: &[Segment],
    op: &serde_json::Value,
) -> Option<bool> {
    T::op_continuable(path, op)
}

fn no_continuable(_: &ModelTable, _: &[Segment], _: &serde_json::Value) -> Option<bool> {
    None
}

fn op_describe_of<T: Model>(
    _: &ModelTable,
    path: &[Segment],
    op: &serde_json::Value,
) -> Option<OpDescription> {
    T::op_describe(path, op)
}

fn no_describe(_: &ModelTable, _: &[Segment], _: &serde_json::Value) -> Option<OpDescription> {
    None
}

fn op_lands_of<T: Model>(
    _: &ModelTable,
    value: &dyn Any,
    path: &[Segment],
    op: &serde_json::Value,
) -> Option<Place> {
    value.downcast_ref::<T>()?.op_lands(path, op)
}

fn no_lands(_: &ModelTable, _: &dyn Any, _: &[Segment], _: &serde_json::Value) -> Option<Place> {
    None
}

fn op_schemas_of<T: Model>(
    _: &ModelTable,
    prefix: &str,
    out: &mut Vec<(String, serde_json::Value)>,
) {
    T::op_schemas(prefix, out);
}

fn no_schemas(_: &ModelTable, _: &str, _: &mut Vec<(String, serde_json::Value)>) {}

/// The [`ItemOps`] of a collection type.
pub struct ItemOpsOf<C>(PhantomData<C>);

impl<C: PublishedItems> ItemOpsOf<C> {
    pub const OPS: ItemOps = ItemOps {
        list: |value| Some(value.downcast_ref::<C>()? as &dyn crate::collection::ItemList),
        item_table: C::ITEM_TABLE,
        item_collection: item_collection_of::<C>,
        item_presence: item_presence_of::<C>,
        label_of_item: label_of_item_of::<C>,
        item_texts: item_texts_of::<C>,
        nested_items: nested_items_of::<C>,
    };
}

fn item_collection_of<C: ItemSource + 'static>(
    value: &dyn Any,
    field: &'static str,
) -> Option<ItemCollection> {
    Some(value.downcast_ref::<C>()?.item_collection(field))
}

fn item_presence_of<C: ItemSource + 'static>(value: &dyn Any) -> usize {
    value
        .downcast_ref::<C>()
        .map_or(0, ItemSource::item_presence)
}

fn label_of_item_of<C: ItemSource + 'static>(value: &dyn Any, id: &crate::Id) -> Option<String> {
    value.downcast_ref::<C>()?.label_of_item(id)
}

fn item_texts_of<C: ItemSource + 'static>(
    value: &dyn Any,
    field: &'static str,
    found: &mut Vec<ItemText>,
) {
    if let Some(value) = value.downcast_ref::<C>() {
        value.item_texts(field, found);
    }
}

fn nested_items_of<C: ItemSource + 'static>(
    value: &dyn Any,
    field: &'static str,
    out: &mut Vec<ItemCollection>,
) {
    if let Some(value) = value.downcast_ref::<C>() {
        value.nested_items(field, out);
    }
}

/// The table of a `String` stored whole, last writer winning
/// (`#[model(atom)]`): an id or a name two people setting at once must not
/// interleave.
pub static ATOM_STRING: ModelTable = ModelTable {
    ops: &ATOM_STRING_OPS,
    desc: Desc::Own,
    checks: false,
    has_ops: false,
    scalar: true,
};

/// A type `#[model(atom)]` stores whole: one value, last writer wins, never
/// merged part by part. A colour, a name from a list or an encoded path
/// merged by character or element reads as no value at all.
pub trait Atomic: Model {
    /// The table the field is stored by.
    const ATOM: &'static ModelTable;
}

impl Atomic for String {
    const ATOM: &'static ModelTable = &ATOM_STRING;
}

/// `None` is an absent key, as for any `Option`; a present value is stored
/// whole.
impl<T: Atomic> Atomic for Option<T> {
    const ATOM: &'static ModelTable = &AtomOptionOf::<T>::TABLE;
}

/// The table of an optional atom.
struct AtomOptionOf<T>(PhantomData<T>);

impl<T: Atomic> AtomOptionOf<T> {
    const DESC: OptionDesc = OptionDesc {
        inner: T::ATOM,
        get: option_get::<T>,
        get_mut: option_get_mut::<T>,
        slot: option_slot::<T>,
        clear: option_clear::<T>,
        staged: (empty_of::<Option<T>>, unwrap_of::<Option<T>>),
    };

    const TABLE: ModelTable = ModelTable {
        ops: &OPTION_OPS,
        desc: Desc::Option(&Self::DESC),
        checks: false,
        has_ops: false,
        scalar: true,
    };
}

/// An id is one scalar already.
impl Atomic for crate::Id {
    const ATOM: &'static ModelTable = <Self as Model>::TABLE;
}

/// A list stored as one JSON text: a shape's points, not a list two people
/// edit item by item.
impl<T> Atomic for Vec<T>
where
    T: Model + serde::Serialize + serde::de::DeserializeOwned + PartialEq,
{
    const ATOM: &'static ModelTable = &ModelTable::of_json(&JsonOf::<Self>::COMPARED);
}

static ATOM_STRING_OPS: ModelOps = ModelOps {
    without_absent: crate::shape::kept_whole,
    to_json: atom_to_json,
    from_json: atom_from_json,
    load: atom_load,
    missing: atom_missing,
    reload: atom_reload,
    store: atom_store,
    fresh: |_, value, encoding| atom_of(value).map_or(Fresh::Store, |atom| atom.fresh(encoding)),
    stores_as: atom_stores_as,
    store_changed: atom_store_changed,
    refresh: atom_refresh,
    read_whole: atom_read_whole,
    edit: atom_edit,
    diff: atom_diff,
    collect_text: atom_collect_text,
    check: no_check,
    get_at: atom_get_at,
    label: no_label,
    nested_collections: no_nested,
    op_coalesces: no_coalesces,
    op_continuable: no_continuable,
    op_describe: no_describe,
    op_lands: no_lands,
    op_schemas: no_schemas,
};

fn atom_text(value: &dyn Any) -> Result<&String, ModelError> {
    value.downcast_ref::<String>().ok_or_else(mismatch)
}

fn atom_of(value: &dyn Any) -> Result<crate::Atom, ModelError> {
    Ok(crate::Atom(atom_text(value)?.clone()))
}

// What the record shows of the field is the `String`'s; what it stores is
// the `Atom`'s.

fn atom_to_json(_: &ModelTable, value: &dyn Any) -> serde_json::Value {
    atom_text(value).map_or(serde_json::Value::Null, Model::to_json)
}

fn atom_from_json(
    _: &ModelTable,
    value: &serde_json::Value,
    out: &mut dyn Any,
) -> Result<(), ModelError> {
    put(out, String::from_json(value)?)
}

fn atom_load(
    _: &ModelTable,
    doc: &Doc,
    value: &Value<'_>,
    id: &ObjId,
    out: &mut dyn Any,
) -> Result<(), ModelError> {
    put(out, crate::Atom::load(doc, value, id)?.0)
}

fn atom_missing(_: &ModelTable, out: &mut dyn Any) -> Result<(), ModelError> {
    put(out, crate::Atom::missing()?.0)
}

fn atom_reload(
    _: &ModelTable,
    target: &mut dyn Any,
    doc: &Doc,
    slot: Option<(&Value<'_>, &ObjId)>,
) -> Result<(), ModelError> {
    let Some(target) = target.downcast_mut::<String>() else {
        return Err(mismatch());
    };
    *target = match slot {
        Some((value, id)) => crate::Atom::load(doc, value, id)?.0,
        None => crate::Atom::missing()?.0,
    };
    Ok(())
}

fn atom_store(
    _: &ModelTable,
    value: &dyn Any,
    doc: &mut Doc,
    slot: Slot<'_>,
) -> Result<(), ModelError> {
    atom_of(value)?.store(doc, slot)
}

fn atom_stores_as(_: &ModelTable, value: &dyn Any, before: &dyn Any) -> bool {
    match (atom_of(value), atom_of(before)) {
        (Ok(value), Ok(before)) => value.stores_as(&before),
        _ => false,
    }
}

fn atom_store_changed(
    _: &ModelTable,
    value: &dyn Any,
    before: &dyn Any,
    doc: &mut Doc,
    slot: Slot<'_>,
    dirty: &Delta,
) -> Result<(), ModelError> {
    atom_of(value)?.store_changed(&atom_of(before)?, doc, slot, dirty)
}

fn atom_refresh(
    _: &ModelTable,
    target: &mut dyn Any,
    doc: &Doc,
    value: &Value<'_>,
    id: &ObjId,
    delta: &Delta,
) -> Result<(), ModelError> {
    let Some(target) = target.downcast_mut::<String>() else {
        return Err(mismatch());
    };
    let mut atom = crate::Atom(std::mem::take(target));
    let refreshed = atom.refresh(doc, value, id, delta);
    *target = atom.0;
    refreshed
}

#[allow(
    clippy::unnecessary_wraps,
    reason = "a table function: reading whole may fail for other types"
)]
fn atom_read_whole(_: &ModelTable, _: &mut dyn Any, _: &Doc) -> Result<(), ModelError> {
    Ok(())
}

fn atom_edit(
    _: &ModelTable,
    doc: &mut Doc,
    slot: Slot<'_>,
    path: &[Segment],
    op: &EditOp,
    cx: &mut ActionCx,
) -> Result<(), ModelError> {
    crate::Atom::edit(doc, slot, path, op, cx)
}

fn atom_diff(
    _: &ModelTable,
    before: &dyn Any,
    after: &dyn Any,
    path: &[Segment],
    out: &mut Vec<Edit<()>>,
) {
    if let (Ok(before), Ok(after)) = (atom_text(before), atom_text(after)) {
        before.diff(after, path, out);
    }
}

fn atom_collect_text(_: &ModelTable, value: &dyn Any, out: &mut Vec<String>) {
    if let Ok(text) = atom_text(value) {
        text.collect_text(out);
    }
}

fn atom_get_at<'a>(_: &ModelTable, value: &'a dyn Any, path: &[Segment]) -> Option<&'a dyn Any> {
    path.is_empty().then_some(value)
}

/// The functions of every record, over its [`ResourceDesc`].
pub static RESOURCE_OPS: ModelOps = ModelOps {
    without_absent: crate::shape::resource_without_absent,
    to_json: |table, value| match table.record() {
        Some(record) => to_json(record, value),
        None => serde_json::Value::Null,
    },
    from_json: |table, value, out| from_json(described(table)?, value, out),
    load: |table, doc, value, id, out| load(described(table)?, doc, value, id, out),
    missing: |table, out| missing(described(table)?, out),
    reload: |table, target, doc, slot| reload(described(table)?, target, doc, slot),
    store: |table, value, doc, slot| store(described(table)?, value, doc, slot),
    fresh: fresh::fields_made,
    stores_as: |table, value, before| {
        table
            .record()
            .is_some_and(|record| stores_as(record, value, before))
    },
    store_changed: |table, value, before, doc, slot, dirty| {
        store_changed(described(table)?, value, before, doc, slot, dirty)
    },
    refresh: |table, target, doc, value, id, delta| {
        refresh(described(table)?, target, doc, value, id, delta)
    },
    read_whole: |_, _, _| Ok(()),
    edit: |table, doc, slot, path, op, cx| edit(described(table)?, doc, slot, path, op, cx),
    diff: |table, before, after, path, out| {
        if let Some(record) = table.record() {
            diff(record, before, after, path, out);
        }
    },
    collect_text: |table, value, out| {
        if let Some(record) = table.record() {
            collect_text(record, value, out);
        }
    },
    check: |table, value| match table.record() {
        Some(record) => check(record, value),
        None => Ok(()),
    },
    get_at: |table, value, path| get_at(table.record()?, value, path),
    label: |table, value| label(table.record()?, value),
    nested_collections: |table, value| {
        table
            .record()
            .map_or_else(Vec::new, |record| item_collections(record, value))
    },
    op_coalesces: |table, path, previous, next| op_coalesces(table.record()?, path, previous, next),
    op_continuable: |table, path, op| op_continuable(table.record()?, path, op),
    op_describe: |table, path, op| op_describe(table.record()?, path, op),
    op_lands: |table, value, path, op| op_lands(table.record()?, value, path, op),
    op_schemas: |table, prefix, out| {
        if let Some(record) = table.record() {
            op_schemas(record, prefix, out);
        }
    },
};

impl ModelTable {
    /// The table of the record `record`.
    #[must_use]
    pub const fn of_resource(record: &'static ResourceDesc) -> Self {
        Self {
            ops: &RESOURCE_OPS,
            desc: Desc::Record(record),
            checks: record.checks,
            has_ops: record.has_ops,
            scalar: false,
        }
    }
}

pub(super) fn described(table: &ModelTable) -> Result<&'static ResourceDesc, ModelError> {
    table.record().ok_or_else(mismatch)
}

/// The value of the field at `index` of `record`.
pub(super) fn field_of<'a>(
    record: &ResourceDesc,
    value: &'a dyn Any,
    index: usize,
) -> Result<&'a dyn Any, ModelError> {
    (record.field)(value, index).ok_or_else(mismatch)
}

/// The same, mutably.
fn field_of_mut<'a>(
    record: &ResourceDesc,
    value: &'a mut dyn Any,
    index: usize,
) -> Result<&'a mut dyn Any, ModelError> {
    (record.field_mut)(value, index).ok_or_else(mismatch)
}

/// [`Model::to_json`] of a record.
#[must_use]
pub fn to_json(record: &ResourceDesc, value: &dyn Any) -> serde_json::Value {
    let mut fields = serde_json::Map::new();
    for (index, field) in record.fields.iter().enumerate() {
        if let Some(inner) = (record.field)(value, index) {
            fields.insert(
                field.key.to_owned(),
                (field.table.ops.to_json)(field.table, inner),
            );
        }
    }
    serde_json::Value::Object(fields)
}

/// Fields read from a record's JSON form.
struct JsonSource<'a> {
    record: &'a ResourceDesc,
    fields: &'a serde_json::Map<String, serde_json::Value>,
    index: usize,
}

impl FieldSource for JsonSource<'_> {
    fn next(&mut self, out: &mut dyn Any) -> Result<(), ModelError> {
        let field = self.record.fields.get(self.index).ok_or_else(mismatch)?;
        match self.fields.get(field.key) {
            Some(value) => (field.table.ops.from_json)(field.table, value, out),
            None => (field.table.ops.missing)(field.table, out),
        }
        .located(field.key)
    }

    fn read(&mut self, _: &mut dyn Any) -> Result<(), ModelError> {
        self.index = self.index.saturating_add(1);
        Ok(())
    }
}

/// The missing value of each field of a record.
struct MissingSource<'a> {
    record: &'a ResourceDesc,
    index: usize,
}

impl FieldSource for MissingSource<'_> {
    fn next(&mut self, out: &mut dyn Any) -> Result<(), ModelError> {
        let field = self.record.fields.get(self.index).ok_or_else(mismatch)?;
        (field.table.ops.missing)(field.table, out).located(field.key)
    }

    fn read(&mut self, _: &mut dyn Any) -> Result<(), ModelError> {
        self.index = self.index.saturating_add(1);
        Ok(())
    }
}

/// Fields read from what each key of a record's map holds.
struct DocSource<'a> {
    record: &'a ResourceDesc,
    doc: &'a Doc,
    slots: Vec<crate::model::MapSlot>,
    index: usize,
}

impl FieldSource for DocSource<'_> {
    fn next(&mut self, out: &mut dyn Any) -> Result<(), ModelError> {
        let field = self.record.fields.get(self.index).ok_or_else(mismatch)?;
        match crate::model::take_slot(&mut self.slots, self.index) {
            Some((value, id)) if !skipped(field) => {
                // What reading a demanded field costs is what a view asked for: counted, so a
                // test holds a list of thousands to reading none of them.
                let _phase = field
                    .demanded
                    .then(|| crate::profiling::Phase::start("resource.read_demanded"));
                (field.table.ops.load)(field.table, self.doc, &value, &id, out)
            }
            _ => (field.table.ops.missing)(field.table, out),
        }
        .located(field.key)
    }

    fn read(&mut self, value: &mut dyn Any) -> Result<(), ModelError> {
        let field = self.record.fields.get(self.index).ok_or_else(mismatch)?;
        self.index = self.index.saturating_add(1);
        if field.whole && !skipped(field) {
            (field.table.ops.read_whole)(field.table, value, self.doc).located(field.key)?;
        }
        Ok(())
    }
}

thread_local! {
    /// Whether what is read now is read for a view ([`for_view`]).
    static FOR_VIEW: std::cell::Cell<bool> = const { std::cell::Cell::new(false) };
}

/// Call `read` as a view's reader reads: every `#[model(demanded)]` field it
/// meets reads as its missing value, unread, until a view demands the item
/// holding it and the resource's [`load`](crate::Resource::load) reads that
/// item whole. A read outside it reads every field as stored.
pub fn for_view<T>(read: impl FnOnce() -> T) -> T {
    let before = FOR_VIEW.with(|flag| flag.replace(true));
    let read = read();
    FOR_VIEW.with(|flag| flag.set(before));
    read
}

/// Call `read` reading every field as stored, inside a read for a view too:
/// what a resource's `load` reads of the items a view demands.
pub fn whole<T>(read: impl FnOnce() -> T) -> T {
    let before = FOR_VIEW.with(|flag| flag.replace(false));
    let read = read();
    FOR_VIEW.with(|flag| flag.set(before));
    read
}

/// Whether `field` is left unread here: a demanded one, read for a view.
fn skipped(field: &FieldDesc) -> bool {
    field.demanded && FOR_VIEW.with(std::cell::Cell::get)
}

/// Whether a value of `table` holds a `#[model(demanded)]` field anywhere
/// (in its fields, their collections' items, and theirs): whether what a
/// view's reader holds of it may be less than the document holds.
#[must_use]
pub fn reads_on_demand(table: &ModelTable) -> bool {
    fn walk(table: &ModelTable, depth: usize) -> bool {
        if depth > 16 {
            return false;
        }
        if let Some(desc) = table.collection() {
            return walk(desc.item(), depth.saturating_add(1));
        }
        described(table).is_ok_and(|desc| {
            desc.fields
                .iter()
                .any(|field| field.demanded || walk(field.table, depth.saturating_add(1)))
        })
    }
    walk(table, 0)
}

/// [`Model::from_json`] of a record, put into `out`.
///
/// # Errors
/// Why `value` is not the record's JSON form.
pub fn from_json(
    record: &ResourceDesc,
    value: &serde_json::Value,
    out: &mut dyn Any,
) -> Result<(), ModelError> {
    match value {
        serde_json::Value::Object(fields) => (record.build)(
            &mut JsonSource {
                record,
                fields,
                index: 0,
            },
            out,
        ),
        serde_json::Value::Null => missing(record, out),
        _ => Err(ModelError::shape("an object")),
    }
}

/// [`Model::missing`] of a record, put into `out`.
pub fn missing(record: &ResourceDesc, out: &mut dyn Any) -> Result<(), ModelError> {
    (record.build)(&mut MissingSource { record, index: 0 }, out)
}

/// [`Model::load`] of a record, put into `out`.
pub fn load(
    record: &ResourceDesc,
    doc: &Doc,
    value: &Value<'_>,
    id: &ObjId,
    out: &mut dyn Any,
) -> Result<(), ModelError> {
    match value {
        Value::Object(ObjType::Map) => read_fields(record, doc, id, out),
        _ => Err(ModelError::shape("a map")),
    }
}

/// [`Fields::read_fields`](crate::Fields::read_fields), put into `out`:
/// every stored field read in one walk of the map.
pub fn read_fields(
    record: &ResourceDesc,
    doc: &Doc,
    obj: &ObjId,
    out: &mut dyn Any,
) -> Result<(), ModelError> {
    read_fields_over(record, doc, std::slice::from_ref(obj), out)
}

/// Read the record from the maps `objs`, field by field: each field from
/// the first map that holds it. Two replicas that made the same item
/// concurrently each made a map for it, and the document keeps both under
/// one key; this reads them as one item, so a field only the losing map
/// holds is not lost.
pub(crate) fn read_fields_merged(
    record: &ResourceDesc,
    doc: &Doc,
    objs: &[ObjId],
    out: &mut dyn Any,
) -> Result<(), ModelError> {
    read_fields_over(record, doc, objs, out)
}

/// Read the record from `objs`, each field from the first map holding it.
fn read_fields_over(
    record: &ResourceDesc,
    doc: &Doc,
    objs: &[ObjId],
    out: &mut dyn Any,
) -> Result<(), ModelError> {
    let mut keys: Vec<&str> = Vec::with_capacity(record.fields.len());
    for field in record.fields {
        keys.push(field.key);
    }
    let mut slots: Vec<crate::model::MapSlot> = vec![None; keys.len()];
    let mut objs = objs.iter();
    if let Some(first) = objs.next() {
        crate::model::fill_slots(doc, first, &keys, &mut slots);
    }
    for obj in objs {
        let mut found = vec![None; keys.len()];
        crate::model::fill_slots(doc, obj, &keys, &mut found);
        for (slot, found) in slots.iter_mut().zip(found) {
            if slot.is_none() {
                *slot = found;
            }
        }
    }
    (record.build)(
        &mut DocSource {
            record,
            doc,
            slots,
            index: 0,
        },
        out,
    )
}

fn reload(
    record: &ResourceDesc,
    target: &mut dyn Any,
    doc: &Doc,
    slot: Option<(&Value<'_>, &ObjId)>,
) -> Result<(), ModelError> {
    // A record is replaced by one read anew through its own table.
    let mut fresh = (record.empty)();
    if let Some((value, id)) = slot {
        load(record, doc, value, id, fresh.as_mut())?;
    } else {
        missing(record, fresh.as_mut())?;
    }
    (record.replace)(target, fresh.as_mut())
}

/// [`Fields::write_fields`](crate::Fields::write_fields) of a record.
pub fn write_fields(
    desc: &ResourceDesc,
    value: &dyn Any,
    doc: &mut Doc,
    obj: &ObjId,
) -> Result<(), ModelError> {
    write_fields_leaving(desc, value, doc, obj)
}

/// [`write_fields`], leaving out a scalar field that holds what its absent
/// key reads as ([`Model::missing`]) where the map does not hold its key: it
/// reads the same without a write.
fn write_fields_leaving(
    desc: &ResourceDesc,
    value: &dyn Any,
    doc: &mut Doc,
    obj: &ObjId,
) -> Result<(), ModelError> {
    let mut staged = (desc.empty)();
    let absent = missing(desc, staged.as_mut())
        .ok()
        .and_then(|()| (desc.unwrap)(staged.as_ref()));
    for (index, field) in desc.fields.iter().enumerate() {
        let inner = field_of(desc, value, index)?;
        if field.table.scalar
            && absent
                .and_then(|absent| (desc.field)(absent, index))
                .is_some_and(|empty| (field.table.ops.stores_as)(field.table, inner, empty))
            && Slot::Key(obj, field.key).current(doc)?.is_none()
        {
            continue;
        }
        (field.table.ops.store)(field.table, inner, doc, Slot::Key(obj, field.key))
            .located(field.key)?;
    }
    Ok(())
}

/// [`Model::store`] of a record. One whose map is made now is made with
/// every field that can be at once ([`fresh_fields`]): twenty fields are
/// one batch, not twenty writes each looking up its key first.
pub fn store(
    desc: &ResourceDesc,
    value: &dyn Any,
    doc: &mut Doc,
    at: Slot<'_>,
) -> Result<(), ModelError> {
    if let Some((Value::Object(ObjType::Map), obj)) = at.current(doc)? {
        return write_fields_leaving(desc, value, doc, &obj);
    }
    fresh::store_made(desc, value, doc, at)
}

/// [`Model::stores_as`] of a record.
#[must_use]
pub fn stores_as(desc: &ResourceDesc, value: &dyn Any, before: &dyn Any) -> bool {
    for (index, field) in desc.fields.iter().enumerate() {
        let (Some(now), Some(was)) = ((desc.field)(value, index), (desc.field)(before, index))
        else {
            return false;
        };
        if !(field.table.ops.stores_as)(field.table, now, was) {
            return false;
        }
    }
    true
}

/// [`Fields::write_changed_fields`](crate::Fields::write_changed_fields) of
/// a record: each field written as `write_key_changed` writes it.
pub fn write_changed_fields(
    desc: &ResourceDesc,
    value: &dyn Any,
    before: &dyn Any,
    doc: &mut Doc,
    obj: &ObjId,
    dirty: &Delta,
) -> Result<(), ModelError> {
    for (index, field) in desc.fields.iter().enumerate() {
        let now = field_of(desc, value, index)?;
        let was = field_of(desc, before, index)?;
        write_key_changed(field.table, (now, was), doc, obj, field.key, dirty)?;
    }
    Ok(())
}

/// Write `now` under `key` of the map `obj`, which holds `was`: what
/// [`crate::model::write_key_changed`] writes, through `table`.
///
/// # Errors
/// The document's write error, located at `key`.
pub(crate) fn write_key_changed(
    table: &ModelTable,
    (now, was): (&dyn Any, &dyn Any),
    doc: &mut Doc,
    obj: &ObjId,
    key: &str,
    dirty: &Delta,
) -> Result<(), ModelError> {
    let ops = table.ops;
    match dirty.key(obj, key) {
        Touch::Written => (ops.store)(table, now, doc, Slot::Key(obj, key)).located(key),
        Touch::Untouched if (ops.stores_as)(table, now, was) => Ok(()),
        Touch::Untouched | Touch::Below => {
            (ops.store_changed)(table, now, was, doc, Slot::Key(obj, key), dirty).located(key)
        }
    }
}

/// [`Model::store_changed`] of a record.
pub fn store_changed(
    desc: &ResourceDesc,
    value: &dyn Any,
    before: &dyn Any,
    doc: &mut Doc,
    at: Slot<'_>,
    dirty: &Delta,
) -> Result<(), ModelError> {
    // A value whose map is gone (deleted by a change this one raced) is
    // written whole, as a whole write would: writing only the fields that
    // changed into a map made now would leave the others missing, an item
    // no replica can read.
    if !matches!(at.current(doc)?, Some((Value::Object(ObjType::Map), _))) {
        return store(desc, value, doc, at);
    }
    let obj = at.object(doc, ObjType::Map)?;
    write_changed_fields(desc, value, before, doc, &obj, dirty)
}

/// [`Model::refresh`] of a record.
pub fn refresh(
    record: &ResourceDesc,
    target: &mut dyn Any,
    doc: &Doc,
    value: &Value<'_>,
    id: &ObjId,
    delta: &Delta,
) -> Result<(), ModelError> {
    match value {
        Value::Object(ObjType::Map) => refresh_fields(record, target, doc, id, delta),
        _ => Err(ModelError::shape("a map")),
    }
}

/// [`Fields::refresh_fields`](crate::Fields::refresh_fields) of a record:
/// a map changed all over is read anew, else each touched field.
pub fn refresh_fields(
    record: &ResourceDesc,
    target: &mut dyn Any,
    doc: &Doc,
    obj: &ObjId,
    delta: &Delta,
) -> Result<(), ModelError> {
    if delta.under(obj).is_all() {
        let mut fresh = (record.empty)();
        read_fields(record, doc, obj, fresh.as_mut())?;
        return (record.replace)(target, fresh.as_mut());
    }
    for (index, field) in record.fields.iter().enumerate() {
        let inner = field_of_mut(record, target, index)?;
        refresh_key(field, inner, doc, obj, delta)?;
    }
    Ok(())
}

/// Bring the field `field`, read earlier from the map `obj`, up to date
/// after `delta`: untouched keeps it, a written slot reads it again, a
/// change inside what it holds refreshes it in place.
fn refresh_key(
    field: &FieldDesc,
    target: &mut dyn Any,
    doc: &Doc,
    obj: &ObjId,
    delta: &Delta,
) -> Result<(), ModelError> {
    refresh_slot(field.table, target, doc, obj, field.key, delta)?;
    if field.whole {
        (field.table.ops.read_whole)(field.table, target, doc).located(field.key)?;
    }
    Ok(())
}

/// Make `target`, a value of `table`'s type just stored whole under `key` of
/// the map `obj`, what reading it back gives. A value reads back as it was
/// written but for what holds operations ([`ModelTable::has_ops`]): rich text
/// reads back as the structure the document made of it. So of a struct's
/// fields only those are read again, from where they were written; any other
/// value holding operations is read again whole.
///
/// # Errors
/// Why what was written does not read.
pub(crate) fn settle(
    table: &ModelTable,
    target: &mut dyn Any,
    doc: &Doc,
    (obj, key): (&ObjId, &str),
) -> Result<(), ModelError> {
    if !table.has_ops {
        return Ok(());
    }
    let stored = automerge::ReadDoc::get(doc, obj, key)?;
    let (Ok(desc), Some((Value::Object(ObjType::Map), map))) = (described(table), &stored) else {
        let stored = stored.as_ref().map(|(value, id)| (value, id));
        return (table.ops.reload)(table, target, doc, stored);
    };
    for (index, field) in desc.fields.iter().enumerate() {
        if !field.table.has_ops {
            continue;
        }
        let inner = field_of_mut(desc, target, index)?;
        let written = automerge::ReadDoc::get(doc, map, field.key)
            .map_err(ModelError::from)
            .located(field.key)?;
        (field.table.ops.reload)(
            field.table,
            inner,
            doc,
            written.as_ref().map(|(value, id)| (value, id)),
        )
        .located(field.key)?;
        if field.whole {
            (field.table.ops.read_whole)(field.table, inner, doc).located(field.key)?;
        }
    }
    Ok(())
}

/// Bring `target`, read earlier from `key` of the map `obj`, up to date
/// after `delta`, through `table`: what [`crate::model::refresh_key`] does.
///
/// # Errors
/// Why it does not read, located at `key`.
pub(crate) fn refresh_slot(
    table: &ModelTable,
    target: &mut dyn Any,
    doc: &Doc,
    obj: &ObjId,
    key: &str,
    delta: &Delta,
) -> Result<(), ModelError> {
    let ops = table.ops;
    match delta.key(obj, key) {
        Touch::Untouched => Ok(()),
        Touch::Written => {
            let slot = crate::model::get_slot(doc, obj, key).located(key)?;
            (ops.reload)(
                table,
                target,
                doc,
                slot.as_ref().map(|(value, id)| (value, id)),
            )
            .located(key)
        }
        Touch::Below => match crate::model::get_slot(doc, obj, key).located(key)? {
            Some((value, id)) => (ops.refresh)(table, target, doc, &value, &id, delta).located(key),
            None => (ops.reload)(table, target, doc, None).located(key),
        },
    }
}

/// Put what `slot` holds into `out`, an `Option` of `table`'s type: its
/// value, or its missing value when it holds nothing.
pub(crate) fn load_slot(
    table: &ModelTable,
    doc: &Doc,
    slot: Option<(&Value<'_>, &ObjId)>,
    out: &mut dyn Any,
) -> Result<(), ModelError> {
    match slot {
        Some((value, id)) => (table.ops.load)(table, doc, value, id, out),
        None => (table.ops.missing)(table, out),
    }
}

/// [`Model::edit`] of a record.
pub fn edit(
    record: &ResourceDesc,
    doc: &mut Doc,
    slot: Slot<'_>,
    path: &[Segment],
    op: &EditOp,
    cx: &mut ActionCx,
) -> Result<(), ModelError> {
    let obj = slot.object(doc, ObjType::Map)?;
    edit_fields(record, doc, &obj, path, op, cx)
}

/// [`Fields::edit_fields`](crate::Fields::edit_fields) of a record: a field
/// segment routes the edit to its field; a `set` of the record replaces it
/// whole; the record's own check runs after.
pub fn edit_fields(
    record: &ResourceDesc,
    doc: &mut Doc,
    obj: &ObjId,
    path: &[Segment],
    op: &EditOp,
    cx: &mut ActionCx,
) -> Result<(), ModelError> {
    // Builds with debug assertions (tests, dev runs) check the record
    // whole after an edit its declared reads say cannot break it, so a
    // declaration that leaves out a field the check reads is caught.
    #[cfg(debug_assertions)]
    let unchecked_was_valid = skips_check(record, path).then(|| valid_at(record, doc, obj));
    match path.split_first() {
        Some((Segment::Field(key), rest)) => {
            let Some(field) = record.fields.iter().find(|field| field.key == key) else {
                let editable: Vec<&str> = record
                    .fields
                    .iter()
                    .filter(|field| !field.readonly)
                    .map(|field| field.key)
                    .collect();
                return Err(ModelError::invalid(format!(
                    "no field `{key}`; the fields here are {}",
                    editable.join(", ")
                )));
            };
            // The outside settling an outbox entry, or forgetting a settled
            // one, is no edit of the field's content: a read-only outbox
            // takes them. A reaction is always the invoker's own (the
            // `Reactions` it reaches stores who invoked it), so it cannot
            // forge anything a read-only field protects: a read-only
            // message takes its reactions. Only a `Reactions` value accepts
            // them; anything else refuses them as unsupported.
            if field.readonly
                && !matches!(
                    op,
                    EditOp::Settle { .. }
                        | EditOp::Forget { .. }
                        | EditOp::React { .. }
                        | EditOp::Unreact { .. }
                )
            {
                return Err(ModelError::Refused(format!(
                    "`{}` is changed only by the record's actions",
                    field.name
                )));
            }
            (field.table.ops.edit)(field.table, doc, Slot::Key(obj, field.key), rest, op, cx)
                .located(field.key)?;
        }
        None => match op {
            EditOp::Set { value } => {
                if record.fields.iter().any(|field| field.readonly) {
                    return Err(ModelError::Refused(String::from(
                        "a record with read-only fields is not replaced whole",
                    )));
                }
                let mut whole = (record.empty)();
                from_json(record, value, whole.as_mut())?;
                let whole = (record.unwrap)(whole.as_ref()).ok_or_else(mismatch)?;
                check(record, whole).map_err(ModelError::refused)?;
                write_fields(record, whole, doc, obj)?;
            }
            other => return Err(ModelError::unsupported(other)),
        },
        Some((segment, _)) => {
            return Err(ModelError::invalid(format!(
                "nothing in this record is called `{segment}`"
            )));
        }
    }
    if let Some(own) = &record.own_check
        && own
            .reads
            .as_ref()
            .is_none_or(|reads| reads.touched_by(path))
    {
        let checked = obj.clone();
        let (read, own_check) = (own.read, own.check);
        crate::group::check_or_defer(format!("{}@{:?}", (record.name)(), obj), doc, move |doc| {
            match read(doc, &checked) {
                Ok(current) => own_check(current.as_ref()),
                Err(error) => Err(Refusal::new(error.to_string())),
            }
        })
        .map_err(ModelError::refused)?;
    }
    #[cfg(debug_assertions)]
    if unchecked_was_valid == Some(true) {
        guard_declared_reads(record, doc, obj, path)?;
    }
    Ok(())
}

/// Whether an edit at `path` skips `record`'s own check, by what the check
/// declares it reads.
#[cfg(debug_assertions)]
fn skips_check(record: &ResourceDesc, path: &[Segment]) -> bool {
    record
        .own_check
        .as_ref()
        .and_then(|own| own.reads.as_ref())
        .is_some_and(|reads| !reads.touched_by(path))
}

/// Whether the record at `obj` passes its own check.
#[cfg(debug_assertions)]
fn valid_at(record: &ResourceDesc, doc: &Doc, obj: &ObjId) -> bool {
    record.own_check.as_ref().is_none_or(|own| {
        (own.read)(doc, obj).is_ok_and(|current| (own.check)(current.as_ref()).is_ok())
    })
}

/// Check the record at `obj`, valid before an edit at `path` its declared
/// reads skip, once the edit (or its group) is done; a refusal means the
/// declaration leaves out a field the check reads.
#[cfg(debug_assertions)]
fn guard_declared_reads(
    record: &ResourceDesc,
    doc: &Doc,
    obj: &ObjId,
    path: &[Segment],
) -> Result<(), ModelError> {
    let Some(own) = &record.own_check else {
        return Ok(());
    };
    let (read, own_check, name) = (own.read, own.check, record.name);
    let at = path
        .iter()
        .map(ToString::to_string)
        .collect::<Vec<_>>()
        .join("/");
    let checked = obj.clone();
    crate::group::check_or_defer(format!("{}@{:?}#reads", name(), obj), doc, move |doc| {
        if let Ok(current) = read(doc, &checked)
            && let Err(refusal) = own_check(current.as_ref())
        {
            undeclared_read(name(), &at, &refusal);
        }
        Ok(())
    })
    .map_err(ModelError::refused)
}

#[cfg(debug_assertions)]
#[allow(
    clippy::panic,
    reason = "a check that reads what it does not declare is a bug in the record's declaration, \
              which only builds with debug assertions look for"
)]
fn undeclared_read(name: &str, at: &str, refusal: &Refusal) -> ! {
    panic!(
        "`{name}`'s check refuses an edit at `{at}` ({refusal}), but its `check_reads` / \
         `check_items` say that edit cannot change what it reads: add the field it reads"
    )
}

/// [`Model::check`] of a record: its own invariant, then its fields'.
pub fn check(record: &ResourceDesc, value: &dyn Any) -> Result<(), Refusal> {
    if !record.checks {
        return Ok(());
    }
    if let Some(own) = &record.own_check {
        (own.check)(value)?;
    }
    for (index, field) in record.fields.iter().enumerate() {
        if field.table.checks
            && let Some(inner) = (record.field)(value, index)
        {
            (field.table.ops.check)(field.table, inner)?;
        }
    }
    Ok(())
}

/// The first non-empty line of the text the field at `index` carries.
fn first_line(record: &ResourceDesc, value: &dyn Any, index: usize) -> Option<String> {
    let field = record.fields.get(index)?;
    let inner = (record.field)(value, index)?;
    let mut text = Vec::new();
    (field.table.ops.collect_text)(field.table, inner, &mut text);
    crate::__private::first_line_of(text)
}

/// [`Model::label`] of a record: what its `label = path` names it, else the
/// texts of its label fields joined by spaces, else its `#[model(label)]`
/// field.
#[must_use]
pub fn label(record: &ResourceDesc, value: &dyn Any) -> Option<String> {
    if let Some(name) = record.label_with {
        return name(value).filter(|label| !label.is_empty());
    }
    if !record.label_parts.is_empty() {
        let mut parts = Vec::new();
        for index in record.label_parts {
            if let Some(part) = first_line(record, value, *index) {
                parts.push(part);
            }
        }
        if !parts.is_empty() {
            return Some(parts.join(" "));
        }
    }
    first_line(record, value, record.label?)
}

/// The field `key` of `record`, with `rest`, when `path` starts at a field
/// whose type has a vocabulary of its own.
fn ops_field<'p>(
    record: &ResourceDesc,
    path: &'p [Segment],
) -> Option<(usize, &'static FieldDesc, &'p [Segment])> {
    let Some((Segment::Field(key), rest)) = path.split_first() else {
        return None;
    };
    let (index, field) = record
        .fields
        .iter()
        .enumerate()
        .find(|(_, field)| field.key == key)?;
    field.table.has_ops.then_some((index, field, rest))
}

/// [`Model::op_coalesces`] of a record.
#[must_use]
pub fn op_coalesces(
    record: &ResourceDesc,
    path: &[Segment],
    previous: &serde_json::Value,
    next: &serde_json::Value,
) -> Option<bool> {
    let (_, field, rest) = ops_field(record, path)?;
    (field.table.ops.op_coalesces)(field.table, rest, previous, next)
}

/// [`Model::op_continuable`] of a record.
#[must_use]
pub fn op_continuable(
    record: &ResourceDesc,
    path: &[Segment],
    op: &serde_json::Value,
) -> Option<bool> {
    let (_, field, rest) = ops_field(record, path)?;
    (field.table.ops.op_continuable)(field.table, rest, op)
}

/// [`Model::op_describe`] of a record.
#[must_use]
pub fn op_describe(
    record: &ResourceDesc,
    path: &[Segment],
    op: &serde_json::Value,
) -> Option<OpDescription> {
    let (_, field, rest) = ops_field(record, path)?;
    (field.table.ops.op_describe)(field.table, rest, op)
}

/// [`Model::op_lands`] of a record.
#[must_use]
pub fn op_lands(
    record: &ResourceDesc,
    value: &dyn Any,
    path: &[Segment],
    op: &serde_json::Value,
) -> Option<Place> {
    let (index, field, rest) = ops_field(record, path)?;
    let inner = (record.field)(value, index)?;
    (field.table.ops.op_lands)(field.table, inner, rest, op)
}

/// [`Model::op_schemas`] of a record: only a field whose type has a
/// vocabulary of its own is visited.
pub fn op_schemas(record: &ResourceDesc, prefix: &str, out: &mut Vec<(String, serde_json::Value)>) {
    // A type nested in itself has no vocabulary of its own deeper than
    // this.
    if prefix.matches('.').count() > 16 {
        return;
    }
    for field in record.fields {
        if field.table.has_ops {
            (field.table.ops.op_schemas)(field.table, &format!("{prefix}{}.", field.key), out);
        }
    }
}

/// [`Model::get_at`] of a record.
#[must_use]
pub fn get_at<'a>(
    record: &ResourceDesc,
    value: &'a dyn Any,
    path: &[Segment],
) -> Option<&'a dyn Any> {
    match path.split_first() {
        None => Some(value),
        Some((Segment::Field(key), rest)) => {
            let (index, field) = record
                .fields
                .iter()
                .enumerate()
                .find(|(_, field)| field.key == key)?;
            let inner = (record.field)(value, index)?;
            (field.table.ops.get_at)(field.table, inner, rest)
        }
        Some(_) => None,
    }
}

/// [`Model::collect_text`] of a record.
pub fn collect_text(record: &ResourceDesc, value: &dyn Any, out: &mut Vec<String>) {
    for (index, field) in record.fields.iter().enumerate() {
        if let Some(inner) = (record.field)(value, index) {
            (field.table.ops.collect_text)(field.table, inner, out);
        }
    }
}

/// [`Model::diff`] of a record: each field that is not read-only, at its
/// key. A field that would store as it is ([`Model::stores_as`]) has
/// nothing to submit and is passed over, compared in memory: no path made
/// for it, nothing turned into JSON. The path of a field compared further
/// is made once, in one buffer.
pub fn diff(
    record: &ResourceDesc,
    before: &dyn Any,
    after: &dyn Any,
    path: &[Segment],
    out: &mut Vec<Edit<()>>,
) {
    let mut at: Vec<Segment> = Vec::new();
    for (index, field) in record.fields.iter().enumerate() {
        if field.readonly {
            continue;
        }
        let (Some(was), Some(now)) = ((record.field)(before, index), (record.field)(after, index))
        else {
            continue;
        };
        if (field.table.ops.stores_as)(field.table, now, was) {
            continue;
        }
        if at.is_empty() {
            at.reserve_exact(path.len().saturating_add(1));
            at.extend_from_slice(path);
        } else {
            at.truncate(path.len());
        }
        at.push(Segment::Field(field.key.to_owned()));
        (field.table.ops.diff)(field.table, was, now, &at, out);
    }
}

/// [`Fields::item_collections`](crate::Fields::item_collections) of a
/// record: each collection field's first page, then the collections inside
/// their items.
#[must_use]
pub fn item_collections(record: &ResourceDesc, value: &dyn Any) -> Vec<ItemCollection> {
    let mut out = Vec::new();
    for (index, field) in record.fields.iter().enumerate() {
        if let (Some(items), Some(inner)) = (field.items, (record.field)(value, index))
            && let Some(collection) = (items.item_collection)(inner, field.name)
        {
            out.push(collection);
        }
    }
    for (index, field) in record.fields.iter().enumerate() {
        if let (Some(items), Some(inner)) = (field.items, (record.field)(value, index)) {
            (items.nested_items)(inner, field.name, &mut out);
        }
    }
    out
}

/// Every item the record `table` names holds, by the collection field holding
/// it: the id and the label each item is offered under, in the order the
/// collection keeps them. Nothing is left out: [`item_collections`] is the
/// page a publication carries, which a record with thousands of items is not.
#[must_use]
pub fn resource_items(
    table: &'static ModelTable,
    record: &dyn Any,
) -> Vec<(&'static str, Vec<(crate::Id, String)>)> {
    let Some(desc) = table.record() else {
        return Vec::new();
    };
    let mut out = Vec::new();
    for (index, field) in desc.fields.iter().enumerate() {
        let Some(items) = field.items else {
            continue;
        };
        let Some(inner) = (desc.field)(record, index) else {
            continue;
        };
        let Some(list) = (items.list)(inner) else {
            continue;
        };
        let mut found = Vec::with_capacity(list.count());
        for at in 0..list.count() {
            let Some((id, _)) = list.item(at) else {
                continue;
            };
            let label = (items.label_of_item)(inner, &id).unwrap_or_else(|| id.as_str().to_owned());
            found.push((id, label));
        }
        out.push((field.name, found));
    }
    out
}

/// The collection fields of published items a model of the table `table`
/// holds, by name: where an item's id (`<kind>/<field>/<item>`) may stand,
/// read from the table alone.
#[must_use]
pub fn item_fields(table: &'static ModelTable) -> Vec<&'static str> {
    table.record().map_or_else(Vec::new, |desc| {
        desc.fields
            .iter()
            .filter(|field| field.items.is_some())
            .map(|field| field.name)
            .collect()
    })
}

/// [`Fields::item_collection_sizes`](crate::Fields::item_collection_sizes)
/// of a record.
#[must_use]
pub fn item_collection_sizes(record: &ResourceDesc, value: &dyn Any) -> Vec<(&'static str, usize)> {
    let mut out = Vec::new();
    for (index, field) in record.fields.iter().enumerate() {
        if let Some(items) = field.items {
            let presence = (record.field)(value, index).map_or(0, items.item_presence);
            out.push((field.name, presence));
        }
    }
    out
}

/// [`Fields::item_label`](crate::Fields::item_label) of a record.
#[must_use]
pub fn item_label(
    record: &ResourceDesc,
    value: &dyn Any,
    name: &str,
    id: &crate::Id,
) -> Option<String> {
    let (index, field) = record
        .fields
        .iter()
        .enumerate()
        .find(|(_, field)| field.items.is_some() && field.name == name)?;
    let items = field.items?;
    (items.label_of_item)((record.field)(value, index)?, id)
}

/// Resolve `reference` to an item of the collection field `name`.
///
/// A reference is the item's id, an address its app publishes it under
/// (`<kind>/<field>/<id>`, `<kind>.<field>:<id>`, or either form of a
/// nested item's), or the label its collection publishes it under — which
/// is what a person or an agent knows it by, or its number counting from 1
/// as the collection lists it. A reference naming none of the
/// collection's items is refused with the items there are, so a name that
/// was mistyped or renamed is never reported as an item that went away.
pub fn item_named(
    record: &ResourceDesc,
    value: &dyn Any,
    name: &str,
    reference: &str,
) -> Result<crate::Id, crate::Refusal> {
    item_named_as(record, value, name, None, reference)
}

/// [`item_named`] in the words `what` names the items by — `("project or
/// area", "projects and areas")` where the field's own name is not what the
/// app calls them — the field's words when it is `None`.
pub fn item_named_as(
    record: &ResourceDesc,
    value: &dyn Any,
    name: &str,
    what: Option<(&str, &str)>,
    reference: &str,
) -> Result<crate::Id, crate::Refusal> {
    let many = tilo_actions::in_words(name);
    let one = tilo_actions::singular(&many);
    let (one, many) = what.unwrap_or((&one, &many));
    let Some((index, field)) = record
        .fields
        .iter()
        .enumerate()
        .find(|(_, field)| field.items.is_some() && field.name == name)
    else {
        return Err(crate::Refusal::new(format!("this record keeps no {name}")));
    };
    let asked = reference.trim();
    if asked.is_empty() {
        return Err(crate::Refusal::new(format!(
            "name the {one}, by its id or its name"
        )));
    }
    let Some(items) = field.items else {
        return Err(crate::Refusal::new(format!("this record keeps no {many}")));
    };
    let Some(inner) = (record.field)(value, index) else {
        return Err(crate::Refusal::new(format!("this record keeps no {many}")));
    };
    let Some(list) = (items.list)(inner) else {
        return Err(crate::Refusal::new(format!("this record keeps no {many}")));
    };
    // Its id first, then the item part of any address it is published under:
    // neither reads a label, so the common case — a caller that kept the id
    // — costs a scan of the ids alone.
    let by_id = |candidate: &str| {
        (0..list.count()).find_map(|at| {
            let (id, _) = list.item(at)?;
            (id.as_str() == candidate).then_some(id)
        })
    };
    if let Some(id) = by_id(asked) {
        return Ok(id);
    }
    for candidate in item_parts(asked) {
        if let Some(id) = by_id(&candidate) {
            return Ok(id);
        }
    }
    // Then the name the collection publishes it under, which is what a
    // person types.
    let named: Vec<(crate::Id, String)> = (0..list.count())
        .filter_map(|at| {
            let (id, item) = list.item(at)?;
            let label = crate::collection::label_of(items.item_table, &id, item);
            label.eq_ignore_ascii_case(asked).then_some((id, label))
        })
        .collect();
    match named.as_slice() {
        [(id, _)] => return Ok(id.clone()),
        [_, ..] => {
            let ids: Vec<&str> = named.iter().map(|(id, _)| id.as_str()).collect();
            return Err(crate::Refusal::new(format!(
                "more than one {one} is named {asked}; name it by its id: {}",
                ids.join(", ")
            )));
        }
        [] => {}
    }
    if let Ok(number) = asked.parse::<usize>() {
        return number
            .checked_sub(1)
            .and_then(|at| list.item(at))
            .map(|(id, _)| id)
            .ok_or_else(|| {
                crate::Refusal::new(format!(
                    "no {one} {number}: the {many} are numbered 1 to {}",
                    list.count()
                ))
            });
    }
    let listed: Vec<String> = (0..list.count())
        .filter_map(|at| {
            let (id, item) = list.item(at)?;
            Some(crate::collection::label_of(items.item_table, &id, item))
        })
        .collect();
    let shown: Vec<&str> = listed.iter().map(String::as_str).take(12).collect();
    let more = listed.len().saturating_sub(shown.len());
    let holds = if shown.is_empty() {
        "none yet".to_owned()
    } else if more > 0 {
        format!("{} and {more} more", shown.join(", "))
    } else {
        shown.join(", ")
    };
    Err(crate::Refusal::new(format!(
        "no {one} named {asked}; {many}: {holds}"
    )))
}

/// Whether the collection field `name` holds the item `id`, counting one it
/// keeps out because it no longer reads: the check an action makes before it
/// resolves a reference, so one that already names the id costs a scan of the
/// ids alone.
#[must_use]
pub fn item_holds(record: &ResourceDesc, value: &dyn Any, name: &str, id: &str) -> bool {
    let Some((index, field)) = record
        .fields
        .iter()
        .enumerate()
        .find(|(_, field)| field.items.is_some() && field.name == name)
    else {
        return false;
    };
    let Some(items) = field.items else {
        return false;
    };
    let Some(inner) = (record.field)(value, index) else {
        return false;
    };
    (items.list)(inner).is_some_and(|list| {
        list.quarantines(id)
            || (0..list.count())
                .any(|at| list.item(at).is_some_and(|(held, _)| held.as_str() == id))
    })
}

/// Whether `reference` is the id of an item of any of the record's
/// collections: an action that names one may hold it in a collection other
/// than the one its parameter is named after ([`item_named`]).
#[must_use]
pub fn item_id_any(record: &ResourceDesc, value: &dyn Any, reference: &str) -> bool {
    record
        .fields
        .iter()
        .enumerate()
        .filter_map(|(index, field)| Some((field.items?, (record.field)(value, index)?)))
        .any(|(items, inner)| {
            (items.list)(inner).is_some_and(|list| {
                (0..list.count()).any(|at| {
                    list.item(at)
                        .is_some_and(|(id, _)| id.as_str() == reference)
                })
            })
        })
}

/// The item an address names, as written: the last segment of an item
/// resource id (`<kind>/<field>/<id>`, and the nested forms), or of an
/// item's stable address (`<kind>.<field>:<id>`), or the id an outline
/// writes after an item (`{#<id>}`).
fn item_parts(reference: &str) -> Vec<String> {
    let mut parts = Vec::new();
    if let Some(id) = reference
        .strip_prefix("{#")
        .and_then(|rest| rest.strip_suffix('}'))
    {
        parts.push(id.to_owned());
    }
    if let Some(last) = reference.rsplit('/').next()
        && last != reference
    {
        parts.push(last.to_owned());
    }
    if let Some(form) = tilo_actions::item_form_of(reference)
        && let Some(last) = form.rsplit('/').next()
    {
        parts.push(last.to_owned());
    }
    parts
}

/// [`Fields::item_search`](crate::Fields::item_search) of a record.
#[must_use]
pub fn item_search(record: &ResourceDesc, value: &dyn Any) -> Vec<ItemText> {
    let mut found = Vec::new();
    for (index, field) in record.fields.iter().enumerate() {
        if let (Some(items), Some(inner)) = (field.items, (record.field)(value, index)) {
            (items.item_texts)(inner, field.name, &mut found);
        }
    }
    found
}

/// [`Model::diff`] of a record into edits of the record `E`.
pub fn diff_into<E>(
    record: &ResourceDesc,
    before: &dyn Any,
    after: &dyn Any,
    path: &[Segment],
    out: &mut Vec<Edit<E>>,
) {
    let mut found = Vec::new();
    diff(record, before, after, path, &mut found);
    out.reserve(found.len());
    for edit in found {
        out.push(edit.retyped());
    }
}

/// The value a record function put into `out`.
pub fn filled<T>(out: Option<T>) -> Result<T, ModelError> {
    match out {
        Some(value) => Ok(value),
        None => Err(mismatch()),
    }
}

/// The value in a filled `Option` of its type.
pub(crate) type Unstage = for<'a> fn(&'a dyn Any) -> Option<&'a dyn Any>;

/// [`Model::edit`] of a value edited only as a whole, through its table:
/// `set` at its own path, checked before it is written. `staged` is an empty
/// `Option` of the type, which `unstage` reads the value back out of.
pub(crate) fn edit_whole(
    table: &ModelTable,
    (staged, unstage): (Box<dyn Any>, Unstage),
    nullable: bool,
    doc: &mut Doc,
    slot: Slot<'_>,
    path: &[Segment],
    op: &EditOp,
) -> Result<(), ModelError> {
    if let Some(segment) = path.first() {
        return Err(ModelError::invalid(format!(
            "nothing inside this value is called `{segment}`"
        )));
    }
    match op {
        EditOp::Set { value } if value.is_null() && !nullable => Err(ModelError::invalid(
            "`null` is no value of this field: set a value of its type",
        )),
        EditOp::Set { value } => {
            let mut staged = staged;
            (table.ops.from_json)(table, value, staged.as_mut())?;
            let made = unstage(staged.as_ref()).ok_or_else(mismatch)?;
            (table.ops.check)(table, made).map_err(ModelError::refused)?;
            (table.ops.store)(table, made, doc, slot)
        }
        other => Err(ModelError::unsupported(other)),
    }
}

/// What `Option<T>`'s table reaches into one with.
#[allow(
    clippy::type_complexity,
    reason = "each field reaches into the option one way"
)]
pub struct OptionDesc {
    /// `T`'s table.
    pub inner: &'static ModelTable,
    /// The present value of an option.
    pub get: for<'a> fn(&'a dyn Any) -> Option<&'a dyn Any>,
    /// The same, mutably.
    pub get_mut: for<'a> fn(&'a mut dyn Any) -> Option<&'a mut dyn Any>,
    /// Put an absent option into `out` (an `Option` of the option) and hand
    /// back that option, for `T`'s table to put a value into.
    pub slot: for<'a> fn(&'a mut dyn Any) -> Option<&'a mut dyn Any>,
    /// Make an option absent.
    pub clear: fn(&mut dyn Any),
    /// An empty `Option` of the option, and the option in a filled one.
    pub staged: (
        fn() -> Box<dyn Any>,
        for<'a> fn(&'a dyn Any) -> Option<&'a dyn Any>,
    ),
}

/// The [`OptionDesc`] of `Option<T>`.
pub struct OptionOf<T>(PhantomData<T>);

impl<T: Model> OptionOf<T> {
    pub const DESC: OptionDesc = OptionDesc {
        inner: T::TABLE,
        get: option_get::<T>,
        get_mut: option_get_mut::<T>,
        slot: option_slot::<T>,
        clear: option_clear::<T>,
        staged: (empty_of::<Option<T>>, unwrap_of::<Option<T>>),
    };

    /// `Option<T>`'s table.
    pub const TABLE: ModelTable = ModelTable {
        ops: &OPTION_OPS,
        desc: Desc::Option(&Self::DESC),
        checks: T::CHECKS,
        has_ops: T::OPS,
        scalar: T::SCALAR,
    };
}

fn option_get<T: 'static>(value: &dyn Any) -> Option<&dyn Any> {
    match value.downcast_ref::<Option<T>>()? {
        Some(inner) => Some(inner),
        None => None,
    }
}

fn option_get_mut<T: 'static>(value: &mut dyn Any) -> Option<&mut dyn Any> {
    match value.downcast_mut::<Option<T>>()? {
        Some(inner) => Some(inner),
        None => None,
    }
}

fn option_slot<T: 'static>(out: &mut dyn Any) -> Option<&mut dyn Any> {
    let out = out.downcast_mut::<Option<Option<T>>>()?;
    Some(out.insert(None))
}

fn option_clear<T: 'static>(value: &mut dyn Any) {
    if let Some(value) = value.downcast_mut::<Option<T>>() {
        *value = None;
    }
}

fn optional(table: &ModelTable) -> Result<&'static OptionDesc, ModelError> {
    table.option().ok_or_else(mismatch)
}

fn is_null(value: &Value<'_>) -> bool {
    matches!(value, Value::Scalar(scalar) if matches!(scalar.as_ref(), automerge::ScalarValue::Null))
}

/// The functions of every `Option`: `None` is an absent key (or a null list
/// element).
pub static OPTION_OPS: ModelOps = ModelOps {
    without_absent: crate::shape::kept_whole,
    to_json: |table, value| match table.option() {
        Some(option) => match (option.get)(value) {
            Some(inner) => (option.inner.ops.to_json)(option.inner, inner),
            None => serde_json::Value::Null,
        },
        None => serde_json::Value::Null,
    },
    from_json: |table, value, out| {
        let option = optional(table)?;
        let slot = (option.slot)(out).ok_or_else(mismatch)?;
        if value.is_null() {
            return Ok(());
        }
        (option.inner.ops.from_json)(option.inner, value, slot)
    },
    load: |table, doc, value, id, out| {
        let option = optional(table)?;
        let slot = (option.slot)(out).ok_or_else(mismatch)?;
        if is_null(value) {
            return Ok(());
        }
        (option.inner.ops.load)(option.inner, doc, value, id, slot)
    },
    missing: |table, out| {
        let option = optional(table)?;
        (option.slot)(out).ok_or_else(mismatch)?;
        Ok(())
    },
    reload: |table, target, doc, slot| {
        let option = optional(table)?;
        match slot {
            Some((value, id)) if !is_null(value) => {
                // The option is itself where `T`'s table puts a value.
                (option.inner.ops.load)(option.inner, doc, value, id, target)
            }
            _ => {
                (option.clear)(target);
                Ok(())
            }
        }
    },
    store: |table, value, doc, slot| {
        let option = optional(table)?;
        match (option.get)(value) {
            Some(inner) => (option.inner.ops.store)(option.inner, inner, doc, slot),
            None => slot.remove(doc),
        }
    },
    fresh: |table, value, encoding| match table.option() {
        Some(option) => match (option.get)(value) {
            Some(inner) => (option.inner.ops.fresh)(option.inner, inner, encoding),
            None => Fresh::Nothing,
        },
        None => Fresh::Store,
    },
    stores_as: |table, value, before| {
        let Some(option) = table.option() else {
            return false;
        };
        match ((option.get)(value), (option.get)(before)) {
            (Some(value), Some(before)) => {
                (option.inner.ops.stores_as)(option.inner, value, before)
            }
            (None, None) => true,
            _ => false,
        }
    },
    store_changed: |table, value, before, doc, slot, dirty| {
        let option = optional(table)?;
        match ((option.get)(value), (option.get)(before)) {
            (Some(value), Some(before)) => {
                (option.inner.ops.store_changed)(option.inner, value, before, doc, slot, dirty)
            }
            _ => (OPTION_OPS.store)(table, value, doc, slot),
        }
    },
    refresh: |table, target, doc, value, id, delta| {
        let option = optional(table)?;
        if !is_null(value)
            && let Some(inner) = (option.get_mut)(target)
        {
            return (option.inner.ops.refresh)(option.inner, inner, doc, value, id, delta);
        }
        (OPTION_OPS.reload)(table, target, doc, Some((value, id)))
    },
    read_whole: |_, _, _| Ok(()),
    edit: |table, doc, slot, path, op, cx| {
        let option = optional(table)?;
        if path.is_empty() && matches!(op, EditOp::Set { .. }) {
            let staged = ((option.staged.0)(), option.staged.1);
            return edit_whole(table, staged, true, doc, slot, path, op);
        }
        match slot.current(doc)? {
            Some((value, _)) if !is_null(&value) => {
                (option.inner.ops.edit)(option.inner, doc, slot, path, op, cx)
            }
            _ => Err(ModelError::invalid("the value is absent")),
        }
    },
    diff: |table, before, after, path, out| {
        let Some(option) = table.option() else {
            return;
        };
        match ((option.get)(before), (option.get)(after)) {
            (Some(before), Some(after)) => {
                (option.inner.ops.diff)(option.inner, before, after, path, out);
            }
            (None, None) => {}
            _ => out.push(Edit::new(
                path.to_vec(),
                EditOp::Set {
                    value: (OPTION_OPS.to_json)(table, after),
                },
            )),
        }
    },
    collect_text: |table, value, out| {
        if let Some(option) = table.option()
            && let Some(inner) = (option.get)(value)
        {
            (option.inner.ops.collect_text)(option.inner, inner, out);
        }
    },
    check: |table, value| match table.option() {
        Some(option) => match (option.get)(value) {
            Some(inner) => (option.inner.ops.check)(option.inner, inner),
            None => Ok(()),
        },
        None => Ok(()),
    },
    get_at: |table, value, path| {
        if path.is_empty() {
            return Some(value);
        }
        let option = table.option()?;
        (option.inner.ops.get_at)(option.inner, (option.get)(value)?, path)
    },
    label: |table, value| {
        let option = table.option()?;
        (option.inner.ops.label)(option.inner, (option.get)(value)?)
    },
    nested_collections: no_nested,
    op_coalesces: |table, path, previous, next| {
        let option = table.option()?;
        (option.inner.ops.op_coalesces)(option.inner, path, previous, next)
    },
    op_continuable: |table, path, op| {
        let option = table.option()?;
        (option.inner.ops.op_continuable)(option.inner, path, op)
    },
    op_describe: |table, path, op| {
        let option = table.option()?;
        (option.inner.ops.op_describe)(option.inner, path, op)
    },
    op_lands: |table, value, path, op| {
        let option = table.option()?;
        (option.inner.ops.op_lands)(option.inner, (option.get)(value)?, path, op)
    },
    op_schemas: |table, prefix, out| {
        if let Some(option) = table.option() {
            (option.inner.ops.op_schemas)(option.inner, prefix, out);
        }
    },
};

/// A value of a type whose table does the work ([`Model::to_json`] of an
/// `Option`, a `Collection`): the type's functions as the table runs them.
pub struct Run<'t>(pub &'t ModelTable);

impl Run<'_> {
    #[must_use]
    pub fn to_json(&self, value: &dyn Any) -> serde_json::Value {
        (self.0.ops.to_json)(self.0, value)
    }

    /// # Errors
    /// Why `value` is no JSON form of the type.
    pub fn from_json<T: 'static>(&self, value: &serde_json::Value) -> Result<T, ModelError> {
        let mut out: Option<T> = None;
        (self.0.ops.from_json)(self.0, value, &mut out)?;
        filled(out)
    }

    pub fn load<T: 'static>(
        &self,
        doc: &Doc,
        value: &Value<'_>,
        id: &ObjId,
    ) -> Result<T, ModelError> {
        let mut out: Option<T> = None;
        (self.0.ops.load)(self.0, doc, value, id, &mut out)?;
        filled(out)
    }

    pub fn missing<T: 'static>(&self) -> Result<T, ModelError> {
        let mut out: Option<T> = None;
        (self.0.ops.missing)(self.0, &mut out)?;
        filled(out)
    }

    pub fn store(&self, value: &dyn Any, doc: &mut Doc, slot: Slot<'_>) -> Result<(), ModelError> {
        (self.0.ops.store)(self.0, value, doc, slot)
    }

    #[must_use]
    pub fn stores_as(&self, value: &dyn Any, before: &dyn Any) -> bool {
        (self.0.ops.stores_as)(self.0, value, before)
    }

    pub fn store_changed(
        &self,
        value: &dyn Any,
        before: &dyn Any,
        doc: &mut Doc,
        slot: Slot<'_>,
        dirty: &Delta,
    ) -> Result<(), ModelError> {
        (self.0.ops.store_changed)(self.0, value, before, doc, slot, dirty)
    }

    pub fn refresh(
        &self,
        target: &mut dyn Any,
        doc: &Doc,
        value: &Value<'_>,
        id: &ObjId,
        delta: &Delta,
    ) -> Result<(), ModelError> {
        (self.0.ops.refresh)(self.0, target, doc, value, id, delta)
    }

    pub fn edit(
        &self,
        doc: &mut Doc,
        slot: Slot<'_>,
        path: &[Segment],
        op: &EditOp,
        cx: &mut ActionCx,
    ) -> Result<(), ModelError> {
        (self.0.ops.edit)(self.0, doc, slot, path, op, cx)
    }

    pub fn diff<E>(
        &self,
        before: &dyn Any,
        after: &dyn Any,
        path: &[Segment],
        out: &mut Vec<Edit<E>>,
    ) {
        let mut found = Vec::new();
        (self.0.ops.diff)(self.0, before, after, path, &mut found);
        out.reserve(found.len());
        for edit in found {
            out.push(edit.retyped());
        }
    }

    pub fn collect_text(&self, value: &dyn Any, out: &mut Vec<String>) {
        (self.0.ops.collect_text)(self.0, value, out);
    }

    pub fn check(&self, value: &dyn Any) -> Result<(), Refusal> {
        (self.0.ops.check)(self.0, value)
    }

    #[must_use]
    pub fn get_at<'a>(&self, value: &'a dyn Any, path: &[Segment]) -> Option<&'a dyn Any> {
        (self.0.ops.get_at)(self.0, value, path)
    }

    #[must_use]
    pub fn op_coalesces(
        &self,
        path: &[Segment],
        previous: &serde_json::Value,
        next: &serde_json::Value,
    ) -> Option<bool> {
        (self.0.ops.op_coalesces)(self.0, path, previous, next)
    }

    #[must_use]
    pub fn op_continuable(&self, path: &[Segment], op: &serde_json::Value) -> Option<bool> {
        (self.0.ops.op_continuable)(self.0, path, op)
    }

    #[must_use]
    pub fn op_describe(&self, path: &[Segment], op: &serde_json::Value) -> Option<OpDescription> {
        (self.0.ops.op_describe)(self.0, path, op)
    }

    #[must_use]
    pub fn op_lands(
        &self,
        value: &dyn Any,
        path: &[Segment],
        op: &serde_json::Value,
    ) -> Option<Place> {
        (self.0.ops.op_lands)(self.0, value, path, op)
    }

    pub fn op_schemas(&self, prefix: &str, out: &mut Vec<(String, serde_json::Value)>) {
        (self.0.ops.op_schemas)(self.0, prefix, out);
    }
}

/// A `#[derive(Model)]` enum of unit variants, each stored as its name.
pub struct UnitDesc {
    /// The variants' stored names, in declaration order.
    pub names: &'static [&'static str],
    /// The names the variants have in a value's JSON form (serde's), in
    /// declaration order: a caller reads and writes these, while the
    /// document keeps the stored one.
    pub wire: &'static [&'static str],
    /// The `#[default]` variant's position.
    pub default: Option<usize>,
    /// The position of a value's variant.
    pub index: fn(&dyn Any) -> Option<usize>,
    /// Put the variant at a position into `out`, an `Option` of the enum.
    pub make: fn(usize, &mut dyn Any) -> Result<(), ModelError>,
    /// Set a value to the variant at a position.
    pub set: fn(usize, &mut dyn Any) -> Result<(), ModelError>,
    /// An empty `Option` of the enum and the enum in a filled one.
    pub staged: (fn() -> Box<dyn Any>, Unstage),
}

impl ModelTable {
    /// The table of an enum of unit variants.
    #[must_use]
    pub const fn of_unit(unit: &'static UnitDesc) -> Self {
        Self {
            ops: &UNIT_OPS,
            desc: Desc::Unit(unit),
            checks: false,
            has_ops: false,
            scalar: true,
        }
    }

    const fn unit(&self) -> Option<&'static UnitDesc> {
        match self.desc {
            Desc::Unit(unit) => Some(unit),
            _ => None,
        }
    }
}

fn units(table: &ModelTable) -> Result<&'static UnitDesc, ModelError> {
    table.unit().ok_or_else(mismatch)
}

/// The stored name of `value`'s variant.
fn unit_name(table: &ModelTable, value: &dyn Any) -> Option<&'static str> {
    let unit = table.unit()?;
    unit.names.get((unit.index)(value)?).copied()
}

/// The name `value`'s variant has in a value's JSON form.
fn unit_wire_name(table: &ModelTable, value: &dyn Any) -> Option<&'static str> {
    let unit = table.unit()?;
    unit.wire.get((unit.index)(value)?).copied()
}

/// The position of the variant stored as `text`.
fn unit_named(unit: &UnitDesc, text: &str) -> Result<usize, ModelError> {
    unit.names
        .iter()
        .position(|name| *name == text)
        .ok_or_else(|| ModelError::invalid(format!("unknown variant `{text}`")))
}

/// The position of the variant whose JSON form is `text`.
fn unit_wire_named(unit: &UnitDesc, text: &str) -> Result<usize, ModelError> {
    unit.wire
        .iter()
        .position(|name| *name == text)
        .ok_or_else(|| ModelError::invalid(format!("unknown variant `{text}`")))
}

/// [`Model::value_schema`] of an enum of the variants `names`.
#[must_use]
pub fn unit_schema(names: &[&str]) -> serde_json::Value {
    serde_json::json!({"type": "string", "enum": names})
}

/// The functions of every enum of unit variants.
pub static UNIT_OPS: ModelOps = ModelOps {
    without_absent: crate::shape::kept_whole,
    to_json: |table, value| {
        unit_wire_name(table, value).map_or(serde_json::Value::Null, |name| {
            serde_json::Value::String(name.to_owned())
        })
    },
    from_json: |table, value, out| {
        let unit = units(table)?;
        match value {
            serde_json::Value::String(text) => (unit.make)(unit_wire_named(unit, text)?, out),
            serde_json::Value::Null => (UNIT_OPS.missing)(table, out),
            _ => Err(ModelError::shape("a variant name")),
        }
    },
    load: |table, doc, value, id, out| {
        let unit = units(table)?;
        let crate::Atom(text) = crate::Atom::load(doc, value, id)?;
        (unit.make)(unit_named(unit, &text)?, out)
    },
    missing: |table, out| {
        let unit = units(table)?;
        match unit.default {
            Some(default) => (unit.make)(default, out),
            None => Err(ModelError::Missing {
                path: String::new(),
            }),
        }
    },
    reload: |table, target, doc, slot| {
        let unit = units(table)?;
        let index = match slot {
            Some((value, id)) => {
                let crate::Atom(text) = crate::Atom::load(doc, value, id)?;
                unit_named(unit, &text)?
            }
            None => unit.default.ok_or_else(|| ModelError::Missing {
                path: String::new(),
            })?,
        };
        (unit.set)(index, target)
    },
    store: |table, value, doc, slot| {
        let name = unit_name(table, value).ok_or_else(mismatch)?;
        slot.put_scalar(doc, automerge::ScalarValue::Str(name.into()))
    },
    fresh: |table, value, _| {
        unit_name(table, value).map_or(Fresh::Store, |name| {
            Fresh::scalar(automerge::ScalarValue::Str(name.into()))
        })
    },
    stores_as: |table, value, before| {
        table.unit().is_some_and(|unit| {
            (unit.index)(value).is_some() && (unit.index)(value) == (unit.index)(before)
        })
    },
    store_changed: |table, value, _, doc, slot, _| (UNIT_OPS.store)(table, value, doc, slot),
    refresh: |table, target, doc, value, id, _| {
        (UNIT_OPS.reload)(table, target, doc, Some((value, id)))
    },
    read_whole: |_, _, _| Ok(()),
    edit: |table, doc, slot, path, op, _| {
        let unit = units(table)?;
        edit_whole(
            table,
            ((unit.staged.0)(), unit.staged.1),
            false,
            doc,
            slot,
            path,
            op,
        )
    },
    diff: |table, before, after, path, out| {
        let value = (UNIT_OPS.to_json)(table, after);
        if (UNIT_OPS.to_json)(table, before) != value {
            out.push(Edit::new(path.to_vec(), EditOp::Set { value }));
        }
    },
    collect_text: |table, value, out| {
        // The case the surface shows, not the token a value's JSON form spells.
        if let Some(name) = unit_wire_name(table, value) {
            out.push(tilo_actions::field_type::label_of(name));
        }
    },
    check: |_, _| Ok(()),
    get_at: |_, value, path| path.is_empty().then_some(value),
    label: no_label,
    nested_collections: no_nested,
    op_coalesces: no_coalesces,
    op_continuable: no_continuable,
    op_describe: no_describe,
    op_lands: no_lands,
    op_schemas: no_schemas,
};

/// Put `variant` into `out`, an `Option` of its enum.
///
/// # Errors
/// When there is no such variant or `out` is of another type.
pub fn put_variant<T: 'static>(variant: Option<T>, out: &mut dyn Any) -> Result<(), ModelError> {
    put(out, variant.ok_or_else(mismatch)?)
}

/// Set `target` to `variant`.
///
/// # Errors
/// When there is no such variant or `target` is of another type.
pub fn set_variant<T: 'static>(variant: Option<T>, target: &mut dyn Any) -> Result<(), ModelError> {
    *target.downcast_mut::<T>().ok_or_else(mismatch)? = variant.ok_or_else(mismatch)?;
    Ok(())
}

/// A type stored whole through its serde form: as one JSON string, last
/// writer winning ([`json_model!`](crate::json_model)), or as that form's
/// maps, lists and scalars ([`value_model!`](crate::value_model)).
#[allow(
    clippy::type_complexity,
    reason = "each field converts the value one way"
)]
pub struct JsonDesc {
    /// The value's JSON form.
    pub to_value: fn(&dyn Any) -> serde_json::Value,
    /// The value's JSON form, or why it has none: what its stored text is
    /// written from (`json_text`).
    pub try_value: fn(&dyn Any) -> Result<serde_json::Value, ModelError>,
    /// The value serialised, as compact JSON text: equal texts are equal
    /// JSON forms, so two values compare without building either form.
    pub bytes: fn(&dyn Any) -> Option<Vec<u8>>,
    /// Whether two values are equal in memory, for a type whose equal values
    /// have equal JSON forms (a derived `PartialEq`): a diff passes over an
    /// equal pair without serialising either. `None` when the type has no
    /// such equality; unequal values are still compared by their forms.
    pub equal: Option<fn(&dyn Any, &dyn Any) -> bool>,
    /// Put the value of a JSON form into `out`, an `Option` of the type. The
    /// stored text is read through it too (`json_text`).
    pub from_value: fn(&serde_json::Value, &mut dyn Any) -> Result<(), ModelError>,
    /// Put the type's default into `out`.
    pub default: fn(&mut dyn Any) -> Result<(), ModelError>,
    /// `null` reads as the default rather than through serde.
    pub null_default: bool,
    /// Stored as its JSON form's maps, lists and scalars
    /// ([`value_model!`](crate::value_model)) rather than as JSON text.
    pub structural: bool,
    /// An empty `Option` of the type, the value in a filled one, and moving
    /// it out over another.
    pub staged: (fn() -> Box<dyn Any>, Unstage),
    pub replace: fn(&mut dyn Any, &mut dyn Any) -> Result<(), ModelError>,
}

impl ModelTable {
    /// The table of a type stored as JSON text.
    #[must_use]
    pub const fn of_json(json: &'static JsonDesc) -> Self {
        Self {
            ops: &JSON_OPS,
            desc: Desc::Json(json),
            checks: false,
            has_ops: false,
            scalar: false,
        }
    }

    const fn json(&self) -> Option<&'static JsonDesc> {
        match self.desc {
            Desc::Json(json) => Some(json),
            _ => None,
        }
    }
}

fn jsons(table: &ModelTable) -> Result<&'static JsonDesc, ModelError> {
    table.json().ok_or_else(mismatch)
}

/// An error of serde as a model error.
#[allow(
    clippy::needless_pass_by_value,
    reason = "`map_err` hands it the error by value"
)]
fn serde_invalid(error: serde_json::Error) -> ModelError {
    ModelError::invalid(error.to_string())
}

/// Put the value the stored JSON `text` holds into `out`: parsed once as
/// JSON, then read as the type through its one JSON reader.
fn json_from_text(json: &JsonDesc, text: &str, out: &mut dyn Any) -> Result<(), ModelError> {
    let value: serde_json::Value = serde_json::from_str(text).map_err(serde_invalid)?;
    (json.from_value)(&value, out)
}

/// The JSON text a value of a type stored as JSON text is stored as.
fn json_text(json: &JsonDesc, value: &dyn Any) -> Result<String, ModelError> {
    (json.try_value)(value).map(|value| value.to_string())
}

/// The serde functions of a type stored as JSON text.
pub struct JsonOf<T>(PhantomData<T>);

impl<T: serde::Serialize + serde::de::DeserializeOwned + Default + 'static> JsonOf<T> {
    /// A type stored as itself, compared only by its JSON form.
    pub const PLAIN: JsonDesc = JsonDesc {
        to_value: |value| {
            value
                .downcast_ref::<T>()
                .and_then(|value| crate::__private::json_via_bytes(value).ok())
                .unwrap_or(serde_json::Value::Null)
        },
        try_value: |value| {
            crate::__private::json_via_bytes(value.downcast_ref::<T>().ok_or_else(mismatch)?)
                .map_err(serde_invalid)
        },
        bytes: |value| serde_json::to_vec(value.downcast_ref::<T>()?).ok(),
        equal: None,
        from_value: |value, out| {
            put::<T>(
                out,
                serde_json::from_value(value.clone()).map_err(serde_invalid)?,
            )
        },
        default: |out| put(out, T::default()),
        null_default: true,
        structural: false,
        staged: (empty_of::<T>, unwrap_of::<T>),
        replace: replace_of::<T>,
    };
}

impl<T> JsonOf<T>
where
    T: serde::Serialize + serde::de::DeserializeOwned + Default + PartialEq + 'static,
{
    /// A [`json_model!`](crate::json_model) type, compared in memory first:
    /// its `PartialEq` holds only between values of equal JSON forms, as a
    /// derived one does, so an equal pair needs neither serialised.
    pub const COMPARED: JsonDesc = JsonDesc {
        equal: Some(|value, other| {
            matches!(
                (value.downcast_ref::<T>(), other.downcast_ref::<T>()),
                (Some(value), Some(other)) if value == other
            )
        }),
        ..Self::PLAIN
    };
}

/// The serde functions of a [`value_model!`](crate::value_model) type,
/// stored as its JSON form's maps, lists and scalars.
pub struct ValueOf<T>(PhantomData<T>);

impl<T> ValueOf<T>
where
    T: serde::Serialize + serde::de::DeserializeOwned + PartialEq + 'static,
{
    /// A type with no value of its own for an absent slot.
    pub const DESC: JsonDesc = JsonDesc {
        to_value: |value| {
            value
                .downcast_ref::<T>()
                .and_then(|value| crate::__private::json_via_bytes(value).ok())
                .unwrap_or(serde_json::Value::Null)
        },
        try_value: |value| {
            crate::__private::json_via_bytes(value.downcast_ref::<T>().ok_or_else(mismatch)?)
                .map_err(serde_invalid)
        },
        bytes: |value| serde_json::to_vec(value.downcast_ref::<T>()?).ok(),
        equal: Some(|value, other| {
            matches!(
                (value.downcast_ref::<T>(), other.downcast_ref::<T>()),
                (Some(value), Some(other)) if value == other
            )
        }),
        from_value: |value, out| {
            put::<T>(
                out,
                serde_json::from_value(value.clone()).map_err(serde_invalid)?,
            )
        },
        default: |_| {
            Err(ModelError::Missing {
                path: String::new(),
            })
        },
        null_default: false,
        structural: true,
        staged: (empty_of::<T>, unwrap_of::<T>),
        replace: replace_of::<T>,
    };
}

impl<T> ValueOf<T>
where
    T: serde::Serialize + serde::de::DeserializeOwned + PartialEq + Default + 'static,
{
    /// A type whose `Default` is the value of an absent slot.
    pub const DEFAULTED: JsonDesc = JsonDesc {
        default: |out| put(out, T::default()),
        null_default: true,
        ..Self::DESC
    };
}

/// The functions of every type stored as JSON text.
pub static JSON_OPS: ModelOps = ModelOps {
    without_absent: crate::shape::kept_whole,
    fresh: fresh::json_made,
    to_json: |table, value| match table.json() {
        Some(json) => (json.to_value)(value),
        None => serde_json::Value::Null,
    },
    from_json: |table, value, out| {
        let json = jsons(table)?;
        if json.null_default && value.is_null() {
            return (json.default)(out);
        }
        (json.from_value)(value, out)
    },
    load: |table, doc, value, id, out| {
        let json = jsons(table)?;
        if json.structural {
            let read = <serde_json::Value as Model>::load(doc, value, id)?;
            if read.is_null() && json.null_default {
                return (json.default)(out);
            }
            return (json.from_value)(&read, out);
        }
        match value {
            Value::Scalar(scalar) => match scalar.as_ref() {
                automerge::ScalarValue::Str(text) => json_from_text(json, text, out),
                automerge::ScalarValue::Null => (json.default)(out),
                _ => Err(ModelError::shape("a JSON string")),
            },
            Value::Object(_) => Err(ModelError::shape("a JSON string")),
        }
    },
    missing: |table, out| (jsons(table)?.default)(out),
    reload: |table, target, doc, slot| {
        let json = jsons(table)?;
        let mut staged = (json.staged.0)();
        match slot {
            Some((value, id)) => (JSON_OPS.load)(table, doc, value, id, staged.as_mut())?,
            None => (json.default)(staged.as_mut())?,
        }
        (json.replace)(target, staged.as_mut())
    },
    store: |table, value, doc, slot| {
        let json = jsons(table)?;
        if json.structural {
            return (json.try_value)(value)?.store(doc, slot);
        }
        let text = json_text(json, value)?;
        slot.put_scalar(doc, automerge::ScalarValue::Str(text.into()))
    },
    // Equal values of a structural type store the same maps, lists and
    // scalars; JSON text is written again, as it always was.
    stores_as: |table, value, before| {
        table.json().is_some_and(|json| {
            json.structural && json.equal.is_some_and(|equal| equal(value, before))
        })
    },
    store_changed: |table, value, _, doc, slot, _| (JSON_OPS.store)(table, value, doc, slot),
    refresh: |table, target, doc, value, id, _| {
        (JSON_OPS.reload)(table, target, doc, Some((value, id)))
    },
    read_whole: |_, _, _| Ok(()),
    edit: |table, doc, slot, path, op, _| {
        let json = jsons(table)?;
        edit_whole(
            table,
            ((json.staged.0)(), json.staged.1),
            true,
            doc,
            slot,
            path,
            op,
        )
    },
    diff: |table, before, after, path, out| {
        // Values equal in memory have equal forms; the same text is the same
        // form; a different text may still be (a map's keys serialised in
        // another order), so the forms decide.
        if let Some(json) = table.json() {
            if json.equal.is_some_and(|equal| equal(before, after)) {
                return;
            }
            if let Some(was) = (json.bytes)(before)
                && (json.bytes)(after).is_some_and(|now| now == was)
            {
                return;
            }
        }
        let value = (JSON_OPS.to_json)(table, after);
        if (JSON_OPS.to_json)(table, before) != value {
            out.push(Edit::new(path.to_vec(), EditOp::Set { value }));
        }
    },
    collect_text: |_, _, _| {},
    check: |_, _| Ok(()),
    get_at: |_, value, path| path.is_empty().then_some(value),
    label: no_label,
    nested_collections: no_nested,
    op_coalesces: no_coalesces,
    op_continuable: no_continuable,
    op_describe: no_describe,
    op_lands: no_lands,
    op_schemas: no_schemas,
};

/// A list's items, whatever their type.
pub trait ListItems {
    fn count(&self) -> usize;
    fn item_at(&self, at: usize) -> Option<&dyn Any>;
    /// Append an item, put by `fill` into an `Option` of the item type.
    ///
    /// # Errors
    /// What `fill` refused.
    fn push_filled(
        &mut self,
        fill: &mut dyn FnMut(&mut dyn Any) -> Result<(), ModelError>,
    ) -> Result<(), ModelError>;
}

impl<T: 'static> ListItems for Vec<T> {
    fn count(&self) -> usize {
        self.len()
    }

    fn item_at(&self, at: usize) -> Option<&dyn Any> {
        self.get(at).map(|item| item as &dyn Any)
    }

    fn push_filled(
        &mut self,
        fill: &mut dyn FnMut(&mut dyn Any) -> Result<(), ModelError>,
    ) -> Result<(), ModelError> {
        let mut slot: Option<T> = None;
        fill(&mut slot)?;
        self.push(filled(slot)?);
        Ok(())
    }
}

/// What `Vec<T>`'s table reaches into one with.
pub struct VecDesc {
    item: &'static ModelTable,
    items: for<'a> fn(&'a dyn Any) -> Option<&'a dyn ListItems>,
    /// Put an empty list into `out` (an `Option` of it), and hand it back.
    fresh: for<'a> fn(&'a mut dyn Any) -> Option<&'a mut dyn ListItems>,
    staged: (fn() -> Box<dyn Any>, Unstage),
    replace: fn(&mut dyn Any, &mut dyn Any) -> Result<(), ModelError>,
}

/// The [`VecDesc`] of `Vec<T>`.
pub struct VecOf<T>(PhantomData<T>);

impl<T: Model> VecOf<T> {
    pub const DESC: VecDesc = VecDesc {
        item: T::TABLE,
        items: |value| Some(value.downcast_ref::<Vec<T>>()? as &dyn ListItems),
        fresh: |out| {
            let out = out.downcast_mut::<Option<Vec<T>>>()?;
            Some(out.insert(Vec::new()) as &mut dyn ListItems)
        },
        staged: (empty_of::<Vec<T>>, unwrap_of::<Vec<T>>),
        replace: replace_of::<Vec<T>>,
    };

    pub const TABLE: ModelTable = ModelTable {
        ops: &VEC_OPS,
        desc: Desc::Vec(&Self::DESC),
        checks: T::CHECKS,
        has_ops: T::OPS,
        scalar: false,
    };
}

impl ModelTable {
    const fn list(&self) -> Option<&'static VecDesc> {
        match self.desc {
            Desc::Vec(list) => Some(list),
            _ => None,
        }
    }
}

fn lists(table: &ModelTable) -> Result<&'static VecDesc, ModelError> {
    table.list().ok_or_else(mismatch)
}

/// The functions of every `Vec`: a list of values.
pub static VEC_OPS: ModelOps = ModelOps {
    without_absent: crate::shape::kept_whole,
    fresh: fresh::list_made,
    to_json: |table, value| {
        let (Some(list), Some(items)) = (
            table.list(),
            table.list().and_then(|list| (list.items)(value)),
        ) else {
            return serde_json::Value::Null;
        };
        let mut out = Vec::with_capacity(items.count());
        for at in 0..items.count() {
            if let Some(item) = items.item_at(at) {
                out.push((list.item.ops.to_json)(list.item, item));
            }
        }
        serde_json::Value::Array(out)
    },
    from_json: |table, value, out| {
        let list = lists(table)?;
        let fresh = (list.fresh)(out).ok_or_else(mismatch)?;
        match value {
            serde_json::Value::Array(items) => {
                for (index, item) in items.iter().enumerate() {
                    fresh.push_filled(&mut |into| {
                        (list.item.ops.from_json)(list.item, item, into).located(&index.to_string())
                    })?;
                }
                Ok(())
            }
            serde_json::Value::Null => Ok(()),
            _ => Err(ModelError::shape("a list")),
        }
    },
    load: |table, doc, value, id, out| {
        let list = lists(table)?;
        if !matches!(value, Value::Object(ObjType::List)) {
            return Err(ModelError::shape("a list"));
        }
        let fresh = (list.fresh)(out).ok_or_else(mismatch)?;
        for index in 0..automerge::ReadDoc::length(doc, id) {
            let slot = crate::model::get_item(doc, id, index)?;
            fresh.push_filled(&mut |into| {
                load_slot(list.item, doc, slot.as_ref().map(|(v, i)| (v, i)), into)
                    .located(&index.to_string())
            })?;
        }
        Ok(())
    },
    missing: |table, out| {
        (lists(table)?.fresh)(out).ok_or_else(mismatch)?;
        Ok(())
    },
    reload: |table, target, doc, slot| {
        let list = lists(table)?;
        let mut staged = (list.staged.0)();
        match slot {
            Some((value, id)) => (VEC_OPS.load)(table, doc, value, id, staged.as_mut())?,
            None => (VEC_OPS.missing)(table, staged.as_mut())?,
        }
        (list.replace)(target, staged.as_mut())
    },
    store: |table, value, doc, slot| {
        let list = lists(table)?;
        let items = (list.items)(value).ok_or_else(mismatch)?;
        let obj = slot.object(doc, ObjType::List)?;
        let existing = automerge::ReadDoc::length(doc, &obj);
        for index in 0..items.count() {
            let Some(item) = items.item_at(index) else {
                continue;
            };
            let slot = if index < existing {
                Slot::Index(&obj, index)
            } else {
                Slot::Insert(&obj, index)
            };
            (list.item.ops.store)(list.item, item, doc, slot).located(&index.to_string())?;
        }
        for index in (items.count()..existing).rev() {
            automerge::transaction::Transactable::delete(doc, &obj, index)?;
        }
        Ok(())
    },
    stores_as: |table, value, before| {
        let Some(list) = table.list() else {
            return false;
        };
        let (Some(now), Some(was)) = ((list.items)(value), (list.items)(before)) else {
            return false;
        };
        now.count() == was.count()
            && (0..now.count()).all(|at| match (now.item_at(at), was.item_at(at)) {
                (Some(now), Some(was)) => (list.item.ops.stores_as)(list.item, now, was),
                _ => false,
            })
    },
    store_changed: |table, value, _, doc, slot, _| (VEC_OPS.store)(table, value, doc, slot),
    refresh: |table, target, doc, value, id, _| {
        (VEC_OPS.reload)(table, target, doc, Some((value, id)))
    },
    read_whole: |_, _, _| Ok(()),
    edit: |table, doc, slot, path, op, _| {
        let list = lists(table)?;
        edit_whole(
            table,
            ((list.staged.0)(), list.staged.1),
            false,
            doc,
            slot,
            path,
            op,
        )
    },
    diff: |table, before, after, path, out| {
        let value = (VEC_OPS.to_json)(table, after);
        if (VEC_OPS.to_json)(table, before) != value {
            out.push(Edit::new(path.to_vec(), EditOp::Set { value }));
        }
    },
    collect_text: |table, value, out| {
        if let Some(list) = table.list()
            && let Some(items) = (list.items)(value)
        {
            for at in 0..items.count() {
                if let Some(item) = items.item_at(at) {
                    (list.item.ops.collect_text)(list.item, item, out);
                }
            }
        }
    },
    check: |table, value| {
        let Some(list) = table.list() else {
            return Ok(());
        };
        if !list.item.checks {
            return Ok(());
        }
        if let Some(items) = (list.items)(value) {
            for at in 0..items.count() {
                if let Some(item) = items.item_at(at) {
                    (list.item.ops.check)(list.item, item)?;
                }
            }
        }
        Ok(())
    },
    get_at: |_, value, path| path.is_empty().then_some(value),
    label: no_label,
    nested_collections: no_nested,
    op_coalesces: no_coalesces,
    op_continuable: no_continuable,
    op_describe: no_describe,
    op_lands: no_lands,
    op_schemas: no_schemas,
};

/// A map's entries, whatever their value type.
pub trait MapEntries {
    fn count(&self) -> usize;
    /// Each entry in key order.
    fn each(&self, visit: &mut dyn FnMut(&str, &dyn Any));
    fn value(&self, key: &str) -> Option<&dyn Any>;
    fn value_mut(&mut self, key: &str) -> Option<&mut dyn Any>;
    fn remove_key(&mut self, key: &str);
    /// Insert (or replace) `key`, its value put by `fill` into an `Option`
    /// of the value type.
    ///
    /// # Errors
    /// What `fill` refused.
    fn insert_filled(
        &mut self,
        key: String,
        fill: &mut dyn FnMut(&mut dyn Any) -> Result<(), ModelError>,
    ) -> Result<(), ModelError>;
    /// Insert (or replace) `key` with the value moved out of `staged`, a
    /// filled `Option` of the value type.
    ///
    /// # Errors
    /// When `staged` is of another type or empty.
    fn insert_moved(&mut self, key: String, staged: &mut dyn Any) -> Result<(), ModelError>;
    /// The keys whose entries may differ from those of `before`, a map of
    /// this same type, in key order, once each: under any other key both
    /// hold the same entry. `None`, the default, when the map cannot tell,
    /// and every entry is compared.
    fn differing_keys<'a>(&'a self, before: &'a dyn Any) -> Option<Vec<&'a str>> {
        let _ = before;
        None
    }
}

impl<T: 'static> MapEntries for std::collections::BTreeMap<String, T> {
    fn count(&self) -> usize {
        self.len()
    }

    fn each(&self, visit: &mut dyn FnMut(&str, &dyn Any)) {
        for (key, value) in self {
            visit(key, value);
        }
    }

    fn value(&self, key: &str) -> Option<&dyn Any> {
        self.get(key).map(|value| value as &dyn Any)
    }

    fn value_mut(&mut self, key: &str) -> Option<&mut dyn Any> {
        self.get_mut(key).map(|value| value as &mut dyn Any)
    }

    fn remove_key(&mut self, key: &str) {
        self.remove(key);
    }

    fn insert_filled(
        &mut self,
        key: String,
        fill: &mut dyn FnMut(&mut dyn Any) -> Result<(), ModelError>,
    ) -> Result<(), ModelError> {
        let mut slot: Option<T> = None;
        fill(&mut slot)?;
        self.insert(key, filled(slot)?);
        Ok(())
    }

    fn insert_moved(&mut self, key: String, staged: &mut dyn Any) -> Result<(), ModelError> {
        let value = staged
            .downcast_mut::<Option<T>>()
            .and_then(Option::take)
            .ok_or_else(mismatch)?;
        self.insert(key, value);
        Ok(())
    }
}

/// What the table of a map of string keys reaches into one with.
pub struct MapDesc {
    item: &'static ModelTable,
    item_nullable: bool,
    entries: for<'a> fn(&'a dyn Any) -> Option<&'a dyn MapEntries>,
    entries_mut: for<'a> fn(&'a mut dyn Any) -> Option<&'a mut dyn MapEntries>,
    /// Put an empty map into `out` (an `Option` of it), and hand it back.
    fresh: for<'a> fn(&'a mut dyn Any) -> Option<&'a mut dyn MapEntries>,
    staged: (fn() -> Box<dyn Any>, Unstage),
    replace: fn(&mut dyn Any, &mut dyn Any) -> Result<(), ModelError>,
    item_staged: (fn() -> Box<dyn Any>, Unstage),
}

/// The [`MapDesc`] of the map `M` of string keys to `T`s: a
/// `BTreeMap<String, T>` ([`MapOf`]) or a [`Map`](crate::Map), stored
/// alike.
pub struct MapIn<T, M>(PhantomData<fn() -> (T, M)>);

/// The [`MapDesc`] of `BTreeMap<String, T>`.
pub type MapOf<T> = MapIn<T, std::collections::BTreeMap<String, T>>;

impl<T: Model, M: MapEntries + Default + 'static> MapIn<T, M> {
    pub const DESC: MapDesc = MapDesc {
        item: T::TABLE,
        item_nullable: T::NULLABLE,
        entries: |value| Some(value.downcast_ref::<M>()? as &dyn MapEntries),
        entries_mut: |value| Some(value.downcast_mut::<M>()? as &mut dyn MapEntries),
        fresh: |out| {
            let out = out.downcast_mut::<Option<M>>()?;
            Some(out.insert(M::default()) as &mut dyn MapEntries)
        },
        staged: (empty_of::<M>, unwrap_of::<M>),
        replace: replace_of::<M>,
        item_staged: (empty_of::<T>, unwrap_of::<T>),
    };

    pub const TABLE: ModelTable = ModelTable {
        ops: &MAP_OPS,
        desc: Desc::Map(&Self::DESC),
        checks: T::CHECKS,
        has_ops: T::OPS,
        scalar: false,
    };
}

impl ModelTable {
    const fn map(&self) -> Option<&'static MapDesc> {
        match self.desc {
            Desc::Map(map) => Some(map),
            _ => None,
        }
    }
}

fn maps(table: &ModelTable) -> Result<&'static MapDesc, ModelError> {
    table.map().ok_or_else(mismatch)
}

/// The value at the key `path` starts at, and the rest of the path, when
/// the map's values have a vocabulary of their own.
fn keyed<'p>(
    table: &ModelTable,
    path: &'p [Segment],
) -> Option<(&'static MapDesc, &'p str, &'p [Segment])> {
    match path.split_first() {
        Some((Segment::Key(key), rest)) if table.has_ops => Some((table.map()?, key, rest)),
        _ => None,
    }
}

/// The functions of every map of string keys: a map, one key per entry.
pub static MAP_OPS: ModelOps = ModelOps {
    without_absent: crate::shape::kept_whole,
    fresh: fresh::stored_after,
    to_json: |table, value| {
        let mut out = serde_json::Map::new();
        if let Some(map) = table.map()
            && let Some(entries) = (map.entries)(value)
        {
            entries.each(&mut |key, value| {
                out.insert(key.to_owned(), (map.item.ops.to_json)(map.item, value));
            });
        }
        serde_json::Value::Object(out)
    },
    from_json: |table, value, out| {
        let map = maps(table)?;
        match value {
            serde_json::Value::Object(entries) => {
                let fresh = (map.fresh)(out).ok_or_else(mismatch)?;
                for (key, value) in entries {
                    fresh.insert_filled(key.clone(), &mut |into| {
                        (map.item.ops.from_json)(map.item, value, into).located(key)
                    })?;
                }
                Ok(())
            }
            serde_json::Value::Null => {
                (map.fresh)(out).ok_or_else(mismatch)?;
                Ok(())
            }
            _ => Err(ModelError::shape("a map")),
        }
    },
    load: |table, doc, value, id, out| {
        let map = maps(table)?;
        if !matches!(value, Value::Object(ObjType::Map)) {
            return Err(ModelError::shape("a map"));
        }
        let fresh = (map.fresh)(out).ok_or_else(mismatch)?;
        // One walk of the map rather than a lookup per key.
        for (key, slot) in crate::model::map_slots(doc, id) {
            fresh.insert_filled(key.clone(), &mut |into| {
                load_slot(map.item, doc, slot.as_ref().map(|(v, i)| (v, i)), into).located(&key)
            })?;
        }
        Ok(())
    },
    missing: |table, out| {
        (maps(table)?.fresh)(out).ok_or_else(mismatch)?;
        Ok(())
    },
    reload: |table, target, doc, slot| {
        let map = maps(table)?;
        let mut staged = (map.staged.0)();
        match slot {
            Some((value, id)) => (MAP_OPS.load)(table, doc, value, id, staged.as_mut())?,
            None => (MAP_OPS.missing)(table, staged.as_mut())?,
        }
        (map.replace)(target, staged.as_mut())
    },
    store: |table, value, doc, slot| {
        let map = maps(table)?;
        let entries = (map.entries)(value).ok_or_else(mismatch)?;
        let obj = slot.object(doc, ObjType::Map)?;
        let stale: Vec<String> = automerge::ReadDoc::keys(doc, &obj)
            .filter(|key| entries.value(key).is_none())
            .collect();
        for key in stale {
            automerge::transaction::Transactable::delete(doc, &obj, key.as_str())?;
        }
        let mut written = Ok(());
        entries.each(&mut |key, value| {
            if written.is_ok() {
                written =
                    (map.item.ops.store)(map.item, value, doc, Slot::Key(&obj, key)).located(key);
            }
        });
        written
    },
    stores_as: |table, value, before| {
        let Some(map) = table.map() else {
            return false;
        };
        let (Some(now), Some(was)) = ((map.entries)(value), (map.entries)(before)) else {
            return false;
        };
        if now.count() != was.count() {
            return false;
        }
        let stores_as = |key: &str, value: &dyn Any| {
            was.value(key)
                .is_some_and(|before| (map.item.ops.stores_as)(map.item, value, before))
        };
        // Under any other key both hold the same entry.
        if let Some(keys) = now.differing_keys(before) {
            return keys
                .into_iter()
                .all(|key| now.value(key).is_some_and(|value| stores_as(key, value)));
        }
        let mut same = true;
        now.each(&mut |key, value| same = same && stores_as(key, value));
        same
    },
    store_changed: |table, value, before, doc, slot, dirty| {
        let map = maps(table)?;
        let now = (map.entries)(value).ok_or_else(mismatch)?;
        let was = (map.entries)(before).ok_or_else(mismatch)?;
        let Some(differing) = now.differing_keys(before) else {
            return (MAP_OPS.store)(table, value, doc, slot);
        };
        // A slot holding no map yet is written whole, as is a map someone
        // else changed otherwise than key by key.
        let Some((Value::Object(ObjType::Map), obj)) = slot.current(doc)? else {
            return (MAP_OPS.store)(table, value, doc, slot);
        };
        let touched = dirty.under(&obj);
        if touched.is_all() {
            return (MAP_OPS.store)(table, value, doc, slot);
        }
        // Under any other key the entry is the one `before` holds, and the
        // map holds it as a store left it: storing it writes nothing.
        let mut keys = differing;
        keys.extend(touched.keys());
        keys.compact_sort();
        keys.dedup();
        // What `store` writes: the stale keys deleted, then each entry
        // written, both in key order.
        for key in &keys {
            if now.value(key).is_none() && automerge::ReadDoc::get(doc, &obj, *key)?.is_some() {
                automerge::transaction::Transactable::delete(doc, &obj, *key)?;
            }
        }
        for key in &keys {
            let Some(next) = now.value(key) else {
                continue;
            };
            match was.value(key) {
                Some(held) => write_key_changed(map.item, (next, held), doc, &obj, key, dirty)?,
                None => {
                    (map.item.ops.store)(map.item, next, doc, Slot::Key(&obj, key)).located(key)?;
                }
            }
        }
        Ok(())
    },
    refresh: |table, target, doc, value, id, delta| {
        let map = maps(table)?;
        let touched = delta.under(id);
        if touched.is_all() {
            return (MAP_OPS.reload)(table, target, doc, Some((value, id)));
        }
        let entries = (map.entries_mut)(target).ok_or_else(mismatch)?;
        for key in touched.keys() {
            match crate::model::get_slot(doc, id, key)? {
                None => entries.remove_key(key),
                Some((value, slot)) => match entries.value_mut(key) {
                    Some(existing) => refresh_slot(map.item, existing, doc, id, key, delta)?,
                    None => entries.insert_filled(key.to_owned(), &mut |into| {
                        (map.item.ops.load)(map.item, doc, &value, &slot, into).located(key)
                    })?,
                },
            }
        }
        Ok(())
    },
    read_whole: |_, _, _| Ok(()),
    edit: |table, doc, slot, path, op, cx| {
        let map = maps(table)?;
        let item = map.item;
        match (path.split_first(), op) {
            (None, EditOp::RemoveKey { key }) => {
                let obj = slot.object(doc, ObjType::Map)?;
                Slot::Key(&obj, key).remove(doc)
            }
            (Some((Segment::Key(key), rest)), op) => {
                let obj = slot.object(doc, ObjType::Map)?;
                if rest.is_empty() && matches!(op, EditOp::Set { .. }) {
                    let staged = ((map.item_staged.0)(), map.item_staged.1);
                    return edit_whole(
                        item,
                        staged,
                        map.item_nullable,
                        doc,
                        Slot::Key(&obj, key),
                        rest,
                        op,
                    )
                    .located(key);
                }
                // An edit inside an entry that is not there yet starts it
                // from its value's empty value (a rule for an app that had
                // none).
                if automerge::ReadDoc::get(doc, &obj, key.as_str())?.is_none() {
                    let mut empty = (map.item_staged.0)();
                    (item.ops.missing)(item, empty.as_mut())
                        .map_err(|_| ModelError::invalid(format!("no entry `{key}`")))?;
                    let empty = (map.item_staged.1)(empty.as_ref()).ok_or_else(mismatch)?;
                    (item.ops.store)(item, empty, doc, Slot::Key(&obj, key)).located(key)?;
                }
                (item.ops.edit)(item, doc, Slot::Key(&obj, key), rest, op, cx).located(key)
            }
            _ => {
                let staged = ((map.staged.0)(), map.staged.1);
                edit_whole(table, staged, false, doc, slot, path, op)
            }
        }
    },
    diff: |table, before, after, path, out| {
        let Some(map) = table.map() else {
            return;
        };
        let (Some(was), Some(now)) = ((map.entries)(before), (map.entries)(after)) else {
            return;
        };
        let at = |key: &str| {
            let mut at = path.to_vec();
            at.push(Segment::Key(key.to_owned()));
            at
        };
        // An entry `before` holds: changed, or removed.
        let kept = |key: &str, before: &dyn Any, out: &mut Vec<Edit<()>>| match now.value(key) {
            Some(next) => (map.item.ops.diff)(map.item, before, next, &at(key), out),
            None => out.push(Edit::new(
                path.to_vec(),
                EditOp::RemoveKey {
                    key: key.to_owned(),
                },
            )),
        };
        // An entry `after` holds: added, when `before` had none.
        let added = |key: &str, next: &dyn Any, out: &mut Vec<Edit<()>>| {
            if was.value(key).is_none() {
                out.push(Edit::new(
                    at(key),
                    EditOp::Set {
                        value: (map.item.ops.to_json)(map.item, next),
                    },
                ));
            }
        };
        // Under any other key both hold the same entry: no edit.
        if let Some(keys) = now.differing_keys(before) {
            for key in &keys {
                if let Some(before) = was.value(key) {
                    kept(key, before, out);
                }
            }
            for key in &keys {
                if let Some(next) = now.value(key) {
                    added(key, next, out);
                }
            }
        } else {
            was.each(&mut |key, before| kept(key, before, out));
            now.each(&mut |key, next| added(key, next, out));
        }
    },
    collect_text: |table, value, out| {
        if let Some(map) = table.map()
            && let Some(entries) = (map.entries)(value)
        {
            entries.each(&mut |_, value| (map.item.ops.collect_text)(map.item, value, out));
        }
    },
    check: |table, value| {
        let Some(map) = table.map() else {
            return Ok(());
        };
        if !map.item.checks {
            return Ok(());
        }
        let Some(entries) = (map.entries)(value) else {
            return Ok(());
        };
        let mut checked = Ok(());
        entries.each(&mut |_, value| {
            if checked.is_ok() {
                checked = (map.item.ops.check)(map.item, value);
            }
        });
        checked
    },
    get_at: |table, value, path| match path.split_first() {
        None => Some(value),
        Some((Segment::Key(key), rest)) => {
            let map = table.map()?;
            (map.item.ops.get_at)(map.item, (map.entries)(value)?.value(key)?, rest)
        }
        Some(_) => None,
    },
    label: no_label,
    nested_collections: no_nested,
    op_coalesces: |table, path, previous, next| {
        let (map, _, rest) = keyed(table, path)?;
        (map.item.ops.op_coalesces)(map.item, rest, previous, next)
    },
    op_continuable: |table, path, op| {
        let (map, _, rest) = keyed(table, path)?;
        (map.item.ops.op_continuable)(map.item, rest, op)
    },
    op_describe: |table, path, op| {
        let (map, _, rest) = keyed(table, path)?;
        (map.item.ops.op_describe)(map.item, rest, op)
    },
    op_lands: |table, value, path, op| {
        let (map, key, rest) = keyed(table, path)?;
        (map.item.ops.op_lands)(map.item, (map.entries)(value)?.value(key)?, rest, op)
    },
    op_schemas: |table, prefix, out| {
        if table.has_ops
            && let Some(map) = table.map()
        {
            (map.item.ops.op_schemas)(map.item, &format!("{prefix}*."), out);
        }
    },
};