surrealdb-expr 4.0.0

A scalable, distributed, collaborative, document-graph database, for the realtime web
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
4835
4836
4837
4838
4839
4840
4841
4842
4843
4844
4845
4846
4847
4848
4849
4850
4851
4852
4853
4854
4855
4856
4857
4858
4859
4860
4861
4862
4863
4864
4865
4866
4867
4868
4869
4870
4871
4872
4873
4874
4875
4876
4877
4878
4879
4880
4881
4882
4883
4884
4885
4886
4887
4888
4889
4890
4891
4892
4893
4894
4895
4896
4897
4898
4899
4900
4901
4902
4903
4904
4905
4906
4907
4908
4909
4910
4911
4912
4913
4914
4915
4916
4917
4918
4919
4920
4921
4922
4923
4924
4925
4926
4927
4928
4929
4930
4931
4932
4933
4934
4935
4936
4937
4938
4939
4940
4941
4942
4943
4944
4945
4946
4947
4948
4949
4950
4951
4952
4953
4954
4955
4956
4957
4958
4959
4960
4961
4962
4963
4964
4965
4966
4967
4968
4969
4970
4971
4972
4973
4974
4975
4976
4977
4978
4979
4980
4981
4982
4983
4984
4985
4986
4987
4988
4989
4990
4991
4992
4993
4994
4995
4996
4997
4998
4999
5000
5001
5002
5003
5004
5005
5006
5007
5008
5009
5010
5011
5012
5013
5014
5015
5016
5017
5018
5019
5020
5021
5022
5023
5024
5025
5026
5027
5028
5029
5030
5031
5032
5033
5034
5035
5036
5037
5038
5039
5040
5041
5042
5043
//! The scalar type of the logical plan.
//!
//! [`LogicalExpr`] is what an operator evaluates per row: a literal, a field
//! read, a step of a path, an operator application, a call, a closure, an `IF …
//! THEN … ELSE … END`, or a statement in scalar position. It holds scalars
//! only. Every statement kind is a [`LogicalOp`], and the one way a statement
//! appears inside a scalar is [`LogicalExpr::Subquery`]: a `SELECT` in a
//! predicate, a block in a projection, a `RETURN` as a value. Nothing
//! statement-shaped is re-encoded as a scalar variant, so there is exactly one
//! form for each construct and a pass that understands operators understands
//! every nested statement too.
//!
//! # Paths are expressions
//!
//! A surface idiom — `a.b[0].c`, `arr[WHERE x > 1]`, `a.len()`, `v.{ x, y }`,
//! `->likes->post` — is a composition of ordinary forms rather than a sequence
//! of parts walked by a dedicated evaluator. [`LogicalExpr::Field`] reads a
//! field of the row; every other step ([`LogicalExpr::Access`],
//! [`LogicalExpr::Index`], [`LogicalExpr::Filter`], [`LogicalExpr::Lookup`],
//! …) applies to the value of its `base`. The one rule a path carries that a
//! plain expression tree does not — a field read, `.*` or destructure applied
//! to an array applies the whole rest of the path to each element — is made
//! explicit by [`LogicalExpr::Broadcast`], whose `body` is applied to
//! [`LogicalExpr::Current`], the element. The rules that place a `Broadcast`
//! are static functions of the sequence of steps and live in lowering
//! (`lower.rs`); this module defines the forms, their traversal, their naming
//! and their rendering.
//!
//! The leaf types that carry no expression — [`Param`], [`TableName`],
//! [`Constant`], [`Kind`], the operator enums, [`Function`], [`LookupKind`],
//! [`Recurse`], [`RecordIdKeyGen`] and the `val` value types — are shared with
//! the expression layer. Everything that holds an expression in that layer has
//! a mirror here holding a `LogicalExpr`: lookups, record-id literals, field
//! lists, orderings, closures and calls.
//!
//! # Rendering
//!
//! A scalar renders as SurrealQL through the same helpers the expression layer
//! uses, so a predicate prints identically whichever type holds it, and a
//! lowered path renders as the idiom it came from: a body's `Current` renders
//! as nothing and the step above it renders with its normal prefix. A
//! [`LogicalExpr::Subquery`] renders as the plan it holds, in parentheses over
//! several lines; the enclosing operator re-indents those lines beneath itself.
//! A rendered plan is deterministic text for golden tests and caches; it is not
//! reparseable SurrealQL, and nothing needs it to be.
//!
//! # Traversal
//!
//! [`LogicalExpr::children`] lists every `LogicalExpr` nested directly in a
//! scalar — the base and the operands of a step, lookup clauses, calls,
//! closures, branches, array and object elements and record-id keys — and
//! [`LogicalExpr::visit`], [`LogicalExpr::visit_mut`] and
//! [`LogicalExpr::transform`] are built on it. A `Subquery` is a leaf to these:
//! the plan inside it is walked by [`LogicalOp`]'s own traversal, and a pass
//! that wants both descends explicitly when it meets the variant.

use std::fmt::{self, Display, Formatter};
use std::hash::{Hash, Hasher};
use std::ops::{Bound, ControlFlow};

use common::fmt::{EscapeIdent, EscapeKwFreeIdent, EscapeObjectKey, EscapeRidKey, Fmt, QuoteStr};
use rust_decimal::Decimal;
use surrealdb_strand::{Strand, TableName};
use surrealdb_types::{BigDecimal, SqlFormat, ToSql, write_sql};

use super::{EvalFrame, LogicalOp};
use crate::expr::binding_power::BindingPower;
use crate::expr::lookup::LookupKind;
use crate::expr::method::is_builtin_method;
use crate::expr::part::Recurse;
use crate::expr::record_id::RecordIdKeyGen;
use crate::expr::{BinaryOperator, Constant, Function, Kind, Literal, Mock, Param, PrefixOperator};
use crate::val::{
	Bytes, Date, Datetime, Duration, File, Geometry, Interval, Regex, Time, Timestamp, Uuid,
};

/// A leaf literal: a value that needs no evaluation and holds no expression.
///
/// Equality and hashing are by representation, as for the expression layer's
/// literal: two floats are equal when their bits are, so `NaN` equals itself
/// and `-0f` does not equal `0f`.
#[derive(Clone, Debug)]
pub enum LogicalLiteral {
	None,
	Null,
	/// `..` with neither bound.
	UnboundedRange,
	Bool(bool),
	Float(f64),
	Integer(i64),
	Decimal(Decimal),
	BigDecimal(Box<BigDecimal>),
	String(Strand),
	Bytes(Bytes),
	Regex(Regex),
	Duration(Duration),
	Datetime(Datetime),
	Uuid(Uuid),
	Geometry(Geometry),
	File(File),
	I8(i8),
	U8(u8),
	I16(i16),
	U16(u16),
	I32(i32),
	U32(u32),
	U64(u64),
	F16(half::f16),
	F32(f32),
	Date(Date),
	Time(Time),
	Timestamp(Timestamp),
	Interval(Interval),
}

impl LogicalLiteral {
	/// The expression-layer literal with the same value, for rendering through
	/// the shared formatter.
	pub fn to_expr_literal(&self) -> Literal {
		match self {
			LogicalLiteral::None => Literal::None,
			LogicalLiteral::Null => Literal::Null,
			LogicalLiteral::UnboundedRange => Literal::UnboundedRange,
			LogicalLiteral::Bool(x) => Literal::Bool(*x),
			LogicalLiteral::Float(x) => Literal::Float(*x),
			LogicalLiteral::Integer(x) => Literal::Integer(*x),
			LogicalLiteral::Decimal(x) => Literal::Decimal(*x),
			LogicalLiteral::BigDecimal(x) => Literal::BigDecimal(x.clone()),
			LogicalLiteral::String(x) => Literal::String(x.clone()),
			LogicalLiteral::Bytes(x) => Literal::Bytes(x.clone()),
			LogicalLiteral::Regex(x) => Literal::Regex(x.clone()),
			LogicalLiteral::Duration(x) => Literal::Duration(*x),
			LogicalLiteral::Datetime(x) => Literal::Datetime(*x),
			LogicalLiteral::Date(x) => Literal::Date(*x),
			LogicalLiteral::Time(x) => Literal::Time(*x),
			LogicalLiteral::Timestamp(x) => Literal::Timestamp(*x),
			LogicalLiteral::Interval(x) => Literal::Interval(*x),
			LogicalLiteral::Uuid(x) => Literal::Uuid(*x),
			LogicalLiteral::Geometry(x) => Literal::Geometry(x.clone()),
			LogicalLiteral::File(x) => Literal::File(x.clone()),
			LogicalLiteral::I8(x) => Literal::I8(*x),
			LogicalLiteral::U8(x) => Literal::U8(*x),
			LogicalLiteral::I16(x) => Literal::I16(*x),
			LogicalLiteral::U16(x) => Literal::U16(*x),
			LogicalLiteral::I32(x) => Literal::I32(*x),
			LogicalLiteral::U32(x) => Literal::U32(*x),
			LogicalLiteral::U64(x) => Literal::U64(*x),
			LogicalLiteral::F16(x) => Literal::F16(*x),
			LogicalLiteral::F32(x) => Literal::F32(*x),
		}
	}
}

impl PartialEq for LogicalLiteral {
	fn eq(&self, other: &Self) -> bool {
		match (self, other) {
			(LogicalLiteral::None, LogicalLiteral::None) => true,
			(LogicalLiteral::Null, LogicalLiteral::Null) => true,
			(LogicalLiteral::UnboundedRange, LogicalLiteral::UnboundedRange) => true,
			(LogicalLiteral::Bool(a), LogicalLiteral::Bool(b)) => a == b,
			(LogicalLiteral::Float(a), LogicalLiteral::Float(b)) => a.to_bits() == b.to_bits(),
			(LogicalLiteral::Integer(a), LogicalLiteral::Integer(b)) => a == b,
			(LogicalLiteral::Decimal(a), LogicalLiteral::Decimal(b)) => a == b,
			(LogicalLiteral::BigDecimal(a), LogicalLiteral::BigDecimal(b)) => a == b,
			(LogicalLiteral::String(a), LogicalLiteral::String(b)) => a == b,
			(LogicalLiteral::Bytes(a), LogicalLiteral::Bytes(b)) => a == b,
			(LogicalLiteral::Regex(a), LogicalLiteral::Regex(b)) => a == b,
			(LogicalLiteral::Duration(a), LogicalLiteral::Duration(b)) => a == b,
			(LogicalLiteral::Datetime(a), LogicalLiteral::Datetime(b)) => a == b,
			(LogicalLiteral::Date(a), LogicalLiteral::Date(b)) => a == b,
			(LogicalLiteral::Time(a), LogicalLiteral::Time(b)) => a == b,
			(LogicalLiteral::Timestamp(a), LogicalLiteral::Timestamp(b)) => a == b,
			(LogicalLiteral::Interval(a), LogicalLiteral::Interval(b)) => a.identical(b),
			(LogicalLiteral::Uuid(a), LogicalLiteral::Uuid(b)) => a == b,
			(LogicalLiteral::Geometry(a), LogicalLiteral::Geometry(b)) => a == b,
			(LogicalLiteral::File(a), LogicalLiteral::File(b)) => a == b,
			(LogicalLiteral::I8(a), LogicalLiteral::I8(b)) => a == b,
			(LogicalLiteral::U8(a), LogicalLiteral::U8(b)) => a == b,
			(LogicalLiteral::I16(a), LogicalLiteral::I16(b)) => a == b,
			(LogicalLiteral::U16(a), LogicalLiteral::U16(b)) => a == b,
			(LogicalLiteral::I32(a), LogicalLiteral::I32(b)) => a == b,
			(LogicalLiteral::U32(a), LogicalLiteral::U32(b)) => a == b,
			(LogicalLiteral::U64(a), LogicalLiteral::U64(b)) => a == b,
			(LogicalLiteral::F16(a), LogicalLiteral::F16(b)) => a.to_bits() == b.to_bits(),
			(LogicalLiteral::F32(a), LogicalLiteral::F32(b)) => a.to_bits() == b.to_bits(),
			// Mismatched variants only. Every variant has an arm above; the
			// `every_literal_variant_equals_itself` test is what keeps that
			// true, since a variant that fell through here would compare
			// unequal to itself and silently break structural comparison.
			_ => false,
		}
	}
}

impl Eq for LogicalLiteral {}

impl Hash for LogicalLiteral {
	fn hash<H: Hasher>(&self, state: &mut H) {
		std::mem::discriminant(self).hash(state);
		match self {
			LogicalLiteral::None | LogicalLiteral::Null | LogicalLiteral::UnboundedRange => {}
			LogicalLiteral::Bool(x) => x.hash(state),
			LogicalLiteral::Float(x) => x.to_bits().hash(state),
			LogicalLiteral::Integer(x) => x.hash(state),
			LogicalLiteral::Decimal(x) => x.hash(state),
			LogicalLiteral::BigDecimal(x) => x.hash(state),
			LogicalLiteral::String(x) => x.hash(state),
			LogicalLiteral::Bytes(x) => x.hash(state),
			LogicalLiteral::Regex(x) => x.hash(state),
			LogicalLiteral::Duration(x) => x.hash(state),
			LogicalLiteral::Datetime(x) => x.hash(state),
			LogicalLiteral::Date(x) => x.hash(state),
			LogicalLiteral::Time(x) => x.hash(state),
			LogicalLiteral::Timestamp(x) => x.hash(state),
			LogicalLiteral::Interval(x) => x.hash(state),
			LogicalLiteral::Uuid(x) => x.hash(state),
			LogicalLiteral::Geometry(x) => x.hash(state),
			LogicalLiteral::File(x) => x.hash(state),
			LogicalLiteral::I8(x) => x.hash(state),
			LogicalLiteral::U8(x) => x.hash(state),
			LogicalLiteral::I16(x) => x.hash(state),
			LogicalLiteral::U16(x) => x.hash(state),
			LogicalLiteral::I32(x) => x.hash(state),
			LogicalLiteral::U32(x) => x.hash(state),
			LogicalLiteral::U64(x) => x.hash(state),
			LogicalLiteral::F16(x) => x.to_bits().hash(state),
			LogicalLiteral::F32(x) => x.to_bits().hash(state),
		}
	}
}

impl ToSql for LogicalLiteral {
	fn fmt_sql(&self, f: &mut String, fmt: SqlFormat) {
		self.to_expr_literal().fmt_sql(f, fmt);
	}
}

/// A scalar expression of the logical plan. See the [module docs](self).
///
/// # Path forms
///
/// The forms from [`Self::Field`] to [`Self::Current`] compose a path. Every
/// *step* form holds the expression it applies to as `base`; a step whose base
/// is [`Self::Current`] is the innermost step of a body. Three forms hold a
/// body over `Current`: [`Self::Broadcast`], [`Self::Optional`] and
/// [`Self::Recurse`]; a destructure alias
/// ([`LogicalDestructureField::Aliased`]) is one as well.
///
/// The evaluation of each step is that of the corresponding physical part; the
/// contract each one upholds is stated on the variant. A path renders as the
/// idiom it was lowered from ([`ToSql`]), names its output through
/// [`Self::output_path`], and declares the position it reads through
/// [`Self::field_path`](super::schema).
#[derive(Debug, PartialEq, Eq, surrealdb_stored_derive::DynHash)]
pub enum LogicalExpr {
	Literal(LogicalLiteral),
	/// `[a, b]`. Flattened out of the literal because its elements are
	/// expressions.
	Array(Vec<LogicalExpr>),
	/// `{a, b}`, a set literal.
	Set(Vec<LogicalExpr>),
	/// `{ k: v }`, in source order.
	Object(Vec<(String, LogicalExpr)>),
	/// `table:key`, whose key may hold expressions.
	RecordId(Box<LogicalRecordIdLit>),
	Param(Param),
	Table(TableName),
	/// `|t:10|`, `|t:1..10|`: a generated record set. A leaf that denotes the
	/// record ids themselves, not records read from storage — the table need
	/// not exist and nothing is fetched. Carries no sub-expressions: the count
	/// and the bounds are integers fixed at parse time.
	Mock(Mock),
	Constant(Constant),
	/// `a`: a read of the row's field. The root of a path into the row, and
	/// the only form index analysis and schema typing need at the root.
	Field(Strand),
	/// `@`: the record id of the current row, as the leading part of an
	/// idiom. Evaluates as `Field("id")` does; kept distinct so that the path
	/// renders as written.
	Doc,
	/// The value a body is applied to: the element a [`Self::Broadcast`] maps
	/// over, the value an [`Self::Optional`] guards, the value at each depth
	/// of a [`Self::Recurse`], the value a destructure alias reads from. Also
	/// the row itself at the root of a path that starts with a lookup
	/// (`->likes->person`). Renders as nothing.
	Current,
	/// `v.f`: the field `f` of `base`. On an object, the field; on a record
	/// id, the field of the fetched record; on an array or a set, the access
	/// mapped over the elements into the same kind of collection; on a
	/// geometry, its GeoJSON field. A mapping step.
	Access {
		base: Box<LogicalExpr>,
		field: Strand,
	},
	/// `v[e]`: `base` indexed by the value of `index`, which is evaluated
	/// against the row, not against `base`.
	Index {
		base: Box<LogicalExpr>,
		index: Box<LogicalExpr>,
	},
	/// `v[0]`: the first element of an array or set; any other value passes
	/// through.
	First(Box<LogicalExpr>),
	/// `v[$]`: the last element of an array or set; any other value passes
	/// through.
	Last(Box<LogicalExpr>),
	/// `v.*`: every element. A record id is fetched; an array or a set has
	/// each record-id element fetched and every other element kept; an object
	/// passes through; anything else is `NONE`. A mapping step.
	Each(Box<LogicalExpr>),
	/// `v…`: one level of nesting removed from an array; any other value
	/// passes through. `explicit` is `false` for the flatten lowering places
	/// between a lookup and a following [`Self::Filter`], which renders as
	/// nothing; the written `…` renders as itself.
	Flatten {
		base: Box<LogicalExpr>,
		explicit: bool,
	},
	/// `v[WHERE p]`: the elements of an array or set for which `predicate` is
	/// truthy, evaluated with the element as the current value and the row as
	/// `$parent`. Anything that is not a collection yields `NONE`.
	Filter {
		base: Box<LogicalExpr>,
		predicate: Box<LogicalExpr>,
	},
	/// `v.name(args)`: a method on `base`. A registered name dispatches on
	/// the receiver's type; an unregistered one calls a closure stored under
	/// that name on the receiver. The arguments are evaluated against the row.
	Method {
		base: Box<LogicalExpr>,
		name: Strand,
		args: Vec<LogicalExpr>,
	},
	/// `v.{ … }`: an object of the listed fields of `base`. A record id is
	/// fetched first; an array or a set has the destructure mapped over its
	/// elements into the same kind of collection. A mapping step.
	Destructure {
		base: Box<LogicalExpr>,
		fields: Vec<LogicalDestructureField>,
	},
	/// `v.?…`: `NONE` or `NULL` as `base` is the result; otherwise `then` is
	/// evaluated with `base` as [`Self::Current`]. `then` is the rest of the
	/// path, and is `Current` itself for a trailing `.?`.
	Optional {
		base: Box<LogicalExpr>,
		then: Box<LogicalExpr>,
	},
	/// `v->e`, `v<-e`, `v<~e`: one hop of a graph or reference lookup from the
	/// record ids in `base`. Consecutive hops nest, and the physical planner
	/// fuses a nested chain into one operator pipeline.
	Lookup {
		base: Box<LogicalExpr>,
		lookup: Box<LogicalLookup>,
	},
	/// `v.{n}(body)` or `v.{n}.body`: a fixpoint over a body. See
	/// [`LogicalRecurse`].
	Recurse(Box<LogicalRecurse>),
	/// `v.@`: the marker inside a recursion body at which the recursion
	/// re-enters. A step on the value the body has produced so far.
	RepeatRecurse(Box<LogicalExpr>),
	/// The array-continuation rule made explicit. When `base` is an array or
	/// a set, `body` is evaluated once per element with the element as
	/// [`Self::Current`], and the results form an array or a set as `base`
	/// is; when `base` is anything else, `body` is evaluated once with `base`
	/// as `Current`. `flatten` asks for the per-element results to be
	/// flattened one level, and applies only when `base` is an array.
	///
	/// A `Broadcast` nested inside the body of a `Broadcast` that is mapping
	/// does not map again: it evaluates its base, then its body against that
	/// value. The rest of a path applied to one element runs as a plain
	/// sequence of steps, as the idiom evaluator's per-element loop did.
	/// Likewise an [`Self::Each`] directly on `Current` at the start of a
	/// mapped body fetches a record-id element and passes any other element
	/// through unchanged. No syntax renders: a `Broadcast` renders as its base
	/// followed by its body.
	Broadcast {
		base: Box<LogicalExpr>,
		body: Box<LogicalExpr>,
		flatten: bool,
	},
	/// The object `base` with `field` set to `value`. A `NONE` value removes
	/// the key; a `base` that is not an object is returned unchanged. Other
	/// keys and, in a value the form is applied to per element, array indices
	/// are untouched: the form replaces one key and never shifts anything.
	///
	/// Not a path form: it is a rebuilt value, not a read of one, so it has
	/// no [`Self::step_base`] and no declared position. It has no surface
	/// syntax; a plan renders it as `set_field(base, "field", value)`.
	SetField {
		base: Box<LogicalExpr>,
		field: Strand,
		value: Box<LogicalExpr>,
	},
	Prefix {
		op: PrefixOperator,
		expr: Box<LogicalExpr>,
	},
	/// `v..` or `v>..`: an open-ended range from `expr`. The one postfix
	/// operator form: a call written after an expression is [`Self::Invoke`],
	/// and a method written after one is [`Self::Method`].
	Postfix {
		expr: Box<LogicalExpr>,
		op: LogicalPostfixOperator,
	},
	/// `v(args)`: `target`, evaluated to a closure value, applied to `args`.
	/// The body is whatever the closure holds and is not in the expression
	/// unless `target` is a [`Self::Closure`] literal. Renders with the target
	/// parenthesised, `(v)(args)`.
	Invoke {
		target: Box<LogicalExpr>,
		args: Vec<LogicalExpr>,
	},
	Binary {
		left: Box<LogicalExpr>,
		op: BinaryOperator,
		right: Box<LogicalExpr>,
	},
	Call(Box<LogicalCall>),
	Closure(Box<LogicalClosure>),
	/// `IF … THEN … ELSE … END` in value position. An `IF` in statement
	/// position is [`LogicalOp::If`].
	If(Box<LogicalIf>),
	/// `THROW` in value position; in statement position it is
	/// [`LogicalOp::Throw`].
	Throw(Box<LogicalExpr>),
	/// `BREAK` in value position; in statement position it is
	/// [`LogicalOp::Break`].
	Break,
	/// `CONTINUE` in value position; in statement position it is
	/// [`LogicalOp::Continue`].
	Continue,
	/// Any statement in scalar position.
	Subquery(Box<LogicalOp>),
}

/// One body for every clone of an expression, whichever crate clones it: a
/// derived `clone` is `#[inline]`, so each crate that clones an expression, or
/// a `Box` of one, would carry its own copy of the whole match.
impl Clone for LogicalExpr {
	#[inline]
	fn clone(&self) -> Self {
		clone_expr(self)
	}
}

#[inline(never)]
fn clone_expr(expr: &LogicalExpr) -> LogicalExpr {
	use LogicalExpr as E;
	match expr {
		E::Literal(v) => E::Literal(v.clone()),
		E::Array(v) => E::Array(v.clone()),
		E::Set(v) => E::Set(v.clone()),
		E::Object(v) => E::Object(v.clone()),
		E::RecordId(v) => E::RecordId(v.clone()),
		E::Param(v) => E::Param(v.clone()),
		E::Table(v) => E::Table(v.clone()),
		E::Mock(v) => E::Mock(v.clone()),
		E::Constant(v) => E::Constant(v.clone()),
		E::Field(v) => E::Field(v.clone()),
		E::Doc => E::Doc,
		E::Current => E::Current,
		E::Access {
			base,
			field,
		} => E::Access {
			base: base.clone(),
			field: field.clone(),
		},
		E::Index {
			base,
			index,
		} => E::Index {
			base: base.clone(),
			index: index.clone(),
		},
		E::First(v) => E::First(v.clone()),
		E::Last(v) => E::Last(v.clone()),
		E::Each(v) => E::Each(v.clone()),
		E::Flatten {
			base,
			explicit,
		} => E::Flatten {
			base: base.clone(),
			explicit: *explicit,
		},
		E::Filter {
			base,
			predicate,
		} => E::Filter {
			base: base.clone(),
			predicate: predicate.clone(),
		},
		E::Method {
			base,
			name,
			args,
		} => E::Method {
			base: base.clone(),
			name: name.clone(),
			args: args.clone(),
		},
		E::Destructure {
			base,
			fields,
		} => E::Destructure {
			base: base.clone(),
			fields: fields.clone(),
		},
		E::Optional {
			base,
			then,
		} => E::Optional {
			base: base.clone(),
			then: then.clone(),
		},
		E::Lookup {
			base,
			lookup,
		} => E::Lookup {
			base: base.clone(),
			lookup: lookup.clone(),
		},
		E::Recurse(v) => E::Recurse(v.clone()),
		E::RepeatRecurse(v) => E::RepeatRecurse(v.clone()),
		E::Broadcast {
			base,
			body,
			flatten,
		} => E::Broadcast {
			base: base.clone(),
			body: body.clone(),
			flatten: *flatten,
		},
		E::SetField {
			base,
			field,
			value,
		} => E::SetField {
			base: base.clone(),
			field: field.clone(),
			value: value.clone(),
		},
		E::Prefix {
			op,
			expr,
		} => E::Prefix {
			op: op.clone(),
			expr: expr.clone(),
		},
		E::Postfix {
			expr,
			op,
		} => E::Postfix {
			expr: expr.clone(),
			op: op.clone(),
		},
		E::Invoke {
			target,
			args,
		} => E::Invoke {
			target: target.clone(),
			args: args.clone(),
		},
		E::Binary {
			left,
			op,
			right,
		} => E::Binary {
			left: left.clone(),
			op: op.clone(),
			right: right.clone(),
		},
		E::Call(v) => E::Call(v.clone()),
		E::Closure(v) => E::Closure(v.clone()),
		E::If(v) => E::If(v.clone()),
		E::Throw(v) => E::Throw(v.clone()),
		E::Break => E::Break,
		E::Continue => E::Continue,
		E::Subquery(v) => E::Subquery(v.clone()),
	}
}

/// A record-id literal. The key may hold expressions.
#[derive(Clone, Debug, PartialEq, Eq, Hash)]
pub struct LogicalRecordIdLit {
	pub table: TableName,
	pub key: LogicalRecordIdKey,
}

/// The key of a [`LogicalRecordIdLit`].
#[derive(Clone, Debug, PartialEq, Eq, Hash)]
pub enum LogicalRecordIdKey {
	Number(i64),
	String(Strand),
	Uuid(Uuid),
	Array(Vec<LogicalExpr>),
	Object(Vec<(String, LogicalExpr)>),
	Generate(RecordIdKeyGen),
	Range(Box<LogicalRecordIdKeyRange>),
}

/// A record-id key range, `table:start..end`.
#[derive(Clone, Debug, PartialEq, Eq, Hash)]
pub struct LogicalRecordIdKeyRange {
	pub start: Bound<LogicalRecordIdKey>,
	pub end: Bound<LogicalRecordIdKey>,
}

/// `v.{n}(body)`, `v.{n+instruction}.body`: a recursion.
///
/// The body is evaluated repeatedly from `base`, with the value of each depth
/// as [`LogicalExpr::Current`] for the next, between the depth bounds of
/// `recurse`; `instruction` chooses what is collected. The body itself is a
/// plain sequence of steps: no [`LogicalExpr::Broadcast`] appears inside it.
#[derive(Clone, Debug, PartialEq, Eq, Hash)]
pub struct LogicalRecurse {
	pub base: LogicalExpr,
	pub recurse: Recurse,
	/// `None` for `v.{n}` with nothing after it: each depth is the value
	/// itself.
	pub path: Option<LogicalRecursePath>,
	pub instruction: Option<LogicalRecurseInstruction>,
}

/// The body of a [`LogicalRecurse`], and how it was written. Both evaluate
/// the same way; they render differently.
#[derive(Clone, Debug, PartialEq, Eq, Hash)]
pub enum LogicalRecursePath {
	/// `v.{n}(body)`: the body in parentheses. The steps after `)` apply once
	/// to the recursion's result, so they wrap the [`LogicalExpr::Recurse`].
	Nested(LogicalExpr),
	/// `v.{n}.body`: the rest of the path is the body, up to and including a
	/// [`LogicalExpr::RepeatRecurse`] (`.@`) at the body's top level. The
	/// steps after `.@` wrap the [`LogicalExpr::Recurse`].
	Trailing(LogicalExpr),
}

impl LogicalRecursePath {
	/// The body, however it was written.
	pub fn body(&self) -> &LogicalExpr {
		match self {
			LogicalRecursePath::Nested(body) | LogicalRecursePath::Trailing(body) => body,
		}
	}

	/// [`Self::body`], mutably.
	pub fn body_mut(&mut self) -> &mut LogicalExpr {
		match self {
			LogicalRecursePath::Nested(body) | LogicalRecursePath::Trailing(body) => body,
		}
	}
}

/// One entry of a `.{ … }` destructure.
#[derive(Clone, Debug, PartialEq, Eq, Hash)]
pub enum LogicalDestructureField {
	/// `f.*`: the field, with a record id fetched.
	All(Strand),
	/// `f`: the field.
	Field(Strand),
	/// `name: body`: `body` evaluated with the destructured value as
	/// [`LogicalExpr::Current`], under `name`. The body is a plain sequence of
	/// steps, or any expression when it was not written as a path.
	Aliased(Strand, LogicalExpr),
	/// `f.{ … }`: a nested destructure of the field.
	Destructure(Strand, Vec<LogicalDestructureField>),
	/// `...`: every field of the destructured object not named by another
	/// entry in the same pattern, kept as-is. Only valid as the pattern's
	/// last entry.
	Rest,
}

/// The `+instruction` of a `.{n+instruction}` recursion.
#[derive(Clone, Debug, PartialEq, Eq, Hash)]
pub enum LogicalRecurseInstruction {
	Path {
		inclusive: bool,
	},
	Collect {
		inclusive: bool,
	},
	Shortest {
		expects: LogicalExpr,
		inclusive: bool,
	},
}

/// A graph or reference lookup, `->edge`, `<-edge`, `<~ref`, with its clauses.
#[derive(Clone, Debug, PartialEq, Eq, Hash)]
pub struct LogicalLookup {
	pub kind: LookupKind,
	pub expr: Option<LogicalFields>,
	pub only: bool,
	pub what: Vec<LogicalLookupSubject>,
	pub cond: Option<LogicalExpr>,
	pub split: Option<Vec<LogicalExpr>>,
	pub group: Option<Vec<LogicalExpr>>,
	pub order: Option<LogicalOrdering>,
	pub limit: Option<LogicalExpr>,
	pub start: Option<LogicalExpr>,
	/// `AS name`: where the lookup's value lands in the output, which is also
	/// the name of any path containing this lookup.
	pub alias: Option<OutputPath>,
	/// What a query trace does with the lookup ([`super::trace`]). Set only for
	/// a request that asks for a trace; [`LookupTrace::None`] otherwise.
	pub trace: super::LookupTrace,
}

/// What a [`LogicalLookup`] scans: a whole table or a key range on it.
#[derive(Clone, Debug, PartialEq, Eq, Hash)]
pub enum LogicalLookupSubject {
	Table {
		table: TableName,
		referencing_field: Option<String>,
	},
	Range {
		table: TableName,
		range: LogicalRecordIdKeyRange,
		referencing_field: Option<String>,
	},
}

impl LogicalLookupSubject {
	fn referencing_field(&self) -> Option<&String> {
		match self {
			LogicalLookupSubject::Table {
				referencing_field,
				..
			}
			| LogicalLookupSubject::Range {
				referencing_field,
				..
			} => referencing_field.as_ref(),
		}
	}
}

/// A postfix operator: the two open-ended range forms. A method or closure
/// call written after an expression lowers to [`LogicalExpr::Method`] or
/// [`LogicalExpr::Invoke`] rather than to an operator, so every pass meets
/// one node per construct whichever way it was spelled.
#[derive(Clone, Debug, PartialEq, Eq, Hash)]
pub enum LogicalPostfixOperator {
	/// `a..`
	Range,
	/// `a>..`
	RangeSkip,
}

/// A function call. The receiver names a builtin, a user function, a script,
/// a model, a module or a silo package; none of those holds an expression.
#[derive(Clone, Debug, PartialEq, Eq, Hash)]
pub struct LogicalCall {
	pub receiver: Function,
	pub args: Vec<LogicalExpr>,
}

/// A closure literal, `|$a: int| -> int $a + 1`.
#[derive(Clone, Debug, PartialEq, Eq, Hash)]
pub struct LogicalClosure {
	pub args: Vec<(Param, Kind)>,
	pub returns: Option<Kind>,
	pub body: LogicalExpr,
	/// The body as written, in canonical SurrealQL: the text a closure's
	/// content digest is taken over, which a stored or shipped reference can
	/// carry where the tree cannot. Two bodies print alike where the printer
	/// does not tell them apart (a negated literal and the negative literal),
	/// so a reader that must know the body is the same compares `body`.
	pub body_sql: std::sync::Arc<str>,
}

/// `IF c1 THEN v1 ELSE IF c2 THEN v2 ELSE v3 END`.
#[derive(Clone, Debug, PartialEq, Eq, Hash)]
pub struct LogicalIf {
	/// `(condition, value)` pairs, in order.
	pub branches: Vec<(LogicalExpr, LogicalExpr)>,
	pub otherwise: Option<LogicalExpr>,
}

/// A projection list: `SELECT VALUE e` or `SELECT a, b AS c, *`.
#[derive(Clone, Debug, PartialEq, Eq, Hash)]
pub enum LogicalFields {
	/// `VALUE e`: each row is the bare value. The alias names the value for
	/// `GROUP BY` and is not projected.
	Value {
		expr: LogicalExpr,
		alias: Option<OutputPath>,
	},
	/// An object per row with one entry per field.
	Select(Vec<LogicalField>),
}

impl LogicalFields {
	/// The `*` projection.
	pub fn all() -> Self {
		LogicalFields::Select(vec![LogicalField::All])
	}

	/// Whether the projection includes `*`.
	pub fn has_all_selection(&self) -> bool {
		match self {
			LogicalFields::Value {
				..
			} => false,
			LogicalFields::Select(fields) => fields.iter().any(|f| matches!(f, LogicalField::All)),
		}
	}
}

/// One entry of a [`LogicalFields::Select`].
///
/// `Single` is left unboxed: `*` is a marker a projection list holds at most a
/// few times among its fields, so the padding it costs is per `*`, while
/// boxing the payload would put an indirection on every read of every
/// projected field. The variant exceeds the lint's size threshold only with
/// 64-bit pointers, so the expectation is scoped to them.
#[cfg_attr(target_pointer_width = "64", expect(clippy::large_enum_variant))]
#[derive(Clone, Debug, PartialEq, Eq, Hash)]
pub enum LogicalField {
	/// `*`
	All,
	/// `expr` or `expr AS alias`.
	///
	/// The alias is where the value lands. Written by the user as `AS`, or
	/// set at lowering to the SurrealQL text of `expr` as written when the
	/// name [`LogicalExpr::output_path`] would derive is spelled from a
	/// nested plan ([`LogicalExpr::output_name_renders_a_statement`]). A
	/// consumer treats the two alike: an alias and a derived name are one
	/// thing to a projection.
	///
	/// `kind` and `frame` say how the value is produced. A field the user
	/// wrote has no kind and the caller's frame ([`LogicalField::user`]). A
	/// *column* of a projection layer (see [`LogicalOp::is_layer`]) carries
	/// a frame that is not the caller's: a `COMPUTED` field body evaluates in
	/// [`EvalMode::Computed`](super::EvalMode::Computed) under the definer's
	/// limit and carries the field's declared kind, to which the value is
	/// coerced wherever it is derived; a field `PERMISSIONS FOR select` guard
	/// evaluates in [`EvalMode::Permission`](super::EvalMode::Permission)
	/// and carries no kind, since the value it yields is a stored field as
	/// stored, or `NONE`, and a read never coerces a stored value.
	Single {
		expr: LogicalExpr,
		alias: Option<OutputPath>,
		/// The declared kind the value is coerced to; `None` leaves the value
		/// as `expr` produced it.
		kind: Option<Kind>,
		/// Who evaluates `expr`.
		frame: EvalFrame,
	},
}

impl LogicalField {
	/// A field the user wrote: `expr` or `expr AS alias`, evaluated as the
	/// caller with no coercion.
	pub fn user(expr: LogicalExpr, alias: Option<OutputPath>) -> Self {
		LogicalField::Single {
			expr,
			alias,
			kind: None,
			frame: EvalFrame::caller(),
		}
	}

	/// A column of a projection layer: `expr` landing on the row under
	/// `name`, coerced to `kind` when one is given, evaluated in `frame`.
	pub fn column(
		name: impl Into<String>,
		expr: LogicalExpr,
		kind: Option<Kind>,
		frame: EvalFrame,
	) -> Self {
		LogicalField::Single {
			expr,
			alias: Some(OutputPath::field(name)),
			kind,
			frame,
		}
	}

	/// The name a projected field lands under: its alias, or the name
	/// [`LogicalExpr::output_path`] derives. `None` for `*`.
	pub fn output_path(&self) -> Option<OutputPath> {
		match self {
			LogicalField::All => None,
			LogicalField::Single {
				expr,
				alias,
				..
			} => Some(alias.clone().unwrap_or_else(|| expr.output_path())),
		}
	}
}

/// `ORDER BY`.
#[derive(Clone, Debug, PartialEq, Eq, Hash)]
pub enum LogicalOrdering {
	Random,
	Order(Vec<LogicalOrder>),
}

/// One `ORDER BY` key.
#[derive(Clone, Debug, PartialEq, Eq, Hash)]
pub struct LogicalOrder {
	pub value: LogicalExpr,
	pub collate: bool,
	pub numeric: bool,
	/// `true` for ascending.
	pub direction: bool,
}

/// What a [`LogicalOp::Source`] reads.
///
/// A source is not a scalar: choosing an access path for it is the physical
/// planner's job, and the syntactic classification here is what it chooses
/// from. [`SourceRef::classify`] is the one place that classification lives.
#[derive(Clone, Debug, PartialEq, Eq, Hash)]
pub enum SourceRef {
	/// A whole table.
	Table(TableName),
	/// One record, or a key range on a table.
	RecordId(Box<LogicalRecordIdLit>),
	/// A generated record set, `|t:10|`.
	Mock(Mock),
	/// A parameter resolved to a source when the statement runs.
	Param(Param),
	/// Any other expression, resolved to a source when the statement runs.
	Dynamic(LogicalExpr),
}

impl SourceRef {
	/// Classifies a `FROM` expression by its syntax. A pass that rewrites a
	/// source's expression re-applies this so the physical planner sees the
	/// rewritten form's access path rather than the original's.
	pub fn classify(expr: LogicalExpr) -> Self {
		match expr {
			LogicalExpr::Table(table) => SourceRef::Table(table),
			LogicalExpr::Mock(mock) => SourceRef::Mock(mock),
			LogicalExpr::RecordId(rid) => SourceRef::RecordId(rid),
			LogicalExpr::Param(param) => SourceRef::Param(param),
			LogicalExpr::Literal(_)
			| LogicalExpr::Array(_)
			| LogicalExpr::Set(_)
			| LogicalExpr::Object(_)
			| LogicalExpr::Constant(_)
			| LogicalExpr::Field(_)
			| LogicalExpr::Doc
			| LogicalExpr::Current
			| LogicalExpr::Access {
				..
			}
			| LogicalExpr::Index {
				..
			}
			| LogicalExpr::First(_)
			| LogicalExpr::Last(_)
			| LogicalExpr::Each(_)
			| LogicalExpr::Flatten {
				..
			}
			| LogicalExpr::Filter {
				..
			}
			| LogicalExpr::Method {
				..
			}
			| LogicalExpr::Destructure {
				..
			}
			| LogicalExpr::Optional {
				..
			}
			| LogicalExpr::Lookup {
				..
			}
			| LogicalExpr::Recurse(_)
			| LogicalExpr::RepeatRecurse(_)
			| LogicalExpr::Broadcast {
				..
			}
			| LogicalExpr::Prefix {
				..
			}
			| LogicalExpr::Postfix {
				..
			}
			| LogicalExpr::Invoke {
				..
			}
			| LogicalExpr::Binary {
				..
			}
			| LogicalExpr::Call(_)
			| LogicalExpr::Closure(_)
			| LogicalExpr::If(_)
			| LogicalExpr::Throw(_)
			| LogicalExpr::Break
			| LogicalExpr::Continue
			| LogicalExpr::SetField {
				..
			}
			| LogicalExpr::Subquery(_) => SourceRef::Dynamic(expr),
		}
	}

	/// Every expression the source holds. A table, mock or parameter holds
	/// none; a record id holds those in its key; a dynamic source is one.
	pub fn for_each_expr<'a>(&'a self, out: &mut dyn FnMut(&'a LogicalExpr)) {
		match self {
			SourceRef::Table(_) | SourceRef::Mock(_) | SourceRef::Param(_) => {}
			SourceRef::RecordId(rid) => rid.key.for_each_expr(out),
			SourceRef::Dynamic(expr) => out(expr),
		}
	}

	/// [`Self::for_each_expr`], collected.
	pub fn exprs<'a>(&'a self, out: &mut Vec<&'a LogicalExpr>) {
		self.for_each_expr(&mut |expr| out.push(expr));
	}

	/// [`Self::exprs`], mutably.
	pub fn exprs_mut<'a>(&'a mut self, out: &mut Vec<&'a mut LogicalExpr>) {
		match self {
			SourceRef::Table(_) | SourceRef::Mock(_) | SourceRef::Param(_) => {}
			SourceRef::RecordId(rid) => rid.key.exprs_mut(out),
			SourceRef::Dynamic(expr) => out.push(expr),
		}
	}

	/// Whether resolving the source only reads.
	pub fn read_only(&self) -> bool {
		match self {
			SourceRef::Table(_) | SourceRef::Mock(_) | SourceRef::Param(_) => true,
			SourceRef::RecordId(rid) => rid.read_only(),
			SourceRef::Dynamic(expr) => expr.read_only(),
		}
	}
}

// ---------------------------------------------------------------------------
// Path structure
// ---------------------------------------------------------------------------

impl LogicalExpr {
	/// Whether this is a path form: a root ([`Self::Field`], [`Self::Doc`],
	/// [`Self::Current`]), a step, or a [`Self::Broadcast`].
	pub fn is_path(&self) -> bool {
		matches!(
			self,
			LogicalExpr::Field(_)
				| LogicalExpr::Doc
				| LogicalExpr::Current
				| LogicalExpr::Access { .. }
				| LogicalExpr::Index { .. }
				| LogicalExpr::First(_)
				| LogicalExpr::Last(_)
				| LogicalExpr::Each(_)
				| LogicalExpr::Flatten { .. }
				| LogicalExpr::Filter { .. }
				| LogicalExpr::Method { .. }
				| LogicalExpr::Destructure { .. }
				| LogicalExpr::Optional { .. }
				| LogicalExpr::Lookup { .. }
				| LogicalExpr::Recurse(_)
				| LogicalExpr::RepeatRecurse(_)
				| LogicalExpr::Broadcast { .. }
		)
	}

	/// The expression a step applies to: the `base` of every step form and of
	/// a [`Self::Broadcast`]. `None` for a path root and for anything that is
	/// not a path.
	pub fn step_base(&self) -> Option<&LogicalExpr> {
		match self {
			LogicalExpr::Access {
				base,
				..
			}
			| LogicalExpr::Index {
				base,
				..
			}
			| LogicalExpr::Flatten {
				base,
				..
			}
			| LogicalExpr::Filter {
				base,
				..
			}
			| LogicalExpr::Method {
				base,
				..
			}
			| LogicalExpr::Destructure {
				base,
				..
			}
			| LogicalExpr::Optional {
				base,
				..
			}
			| LogicalExpr::Lookup {
				base,
				..
			}
			| LogicalExpr::Broadcast {
				base,
				..
			} => Some(base),
			LogicalExpr::First(base)
			| LogicalExpr::Last(base)
			| LogicalExpr::Each(base)
			| LogicalExpr::RepeatRecurse(base) => Some(base),
			LogicalExpr::Recurse(recurse) => Some(&recurse.base),
			LogicalExpr::Field(_)
			| LogicalExpr::Doc
			| LogicalExpr::Current
			| LogicalExpr::Literal(_)
			| LogicalExpr::Array(_)
			| LogicalExpr::Set(_)
			| LogicalExpr::Object(_)
			| LogicalExpr::RecordId(_)
			| LogicalExpr::Param(_)
			| LogicalExpr::Table(_)
			| LogicalExpr::Mock(_)
			| LogicalExpr::Constant(_)
			| LogicalExpr::Prefix {
				..
			}
			| LogicalExpr::Postfix {
				..
			}
			| LogicalExpr::Invoke {
				..
			}
			| LogicalExpr::Binary {
				..
			}
			| LogicalExpr::Call(_)
			| LogicalExpr::Closure(_)
			| LogicalExpr::If(_)
			| LogicalExpr::Throw(_)
			| LogicalExpr::Break
			| LogicalExpr::Continue
			| LogicalExpr::SetField {
				..
			}
			| LogicalExpr::Subquery(_) => None,
		}
	}

	/// The expression a path starts from, following `base` through every step
	/// and [`Self::Broadcast`]: a [`Self::Field`], [`Self::Doc`] or
	/// [`Self::Current`] root, or the expression a `(e).rest` path began with
	/// (`$param.x` starts from the parameter). An expression that is not a
	/// step is its own root.
	pub fn path_root(&self) -> &LogicalExpr {
		let mut current = self;
		while let Some(base) = current.step_base() {
			current = base;
		}
		current
	}
}

// ---------------------------------------------------------------------------
// Traversal
// ---------------------------------------------------------------------------

impl LogicalExpr {
	/// Every `LogicalExpr` nested directly in this one, in source order,
	/// including the base and operands of a step, bodies, lookups, record-id
	/// keys, calls, closures, branches and collection elements. A
	/// [`Self::Subquery`] has no children here: its plan is walked by
	/// [`LogicalOp`].
	pub fn for_each_child<'a>(&'a self, out: &mut dyn FnMut(&'a LogicalExpr)) {
		match self {
			LogicalExpr::Literal(_)
			| LogicalExpr::Param(_)
			| LogicalExpr::Table(_)
			| LogicalExpr::Mock(_)
			| LogicalExpr::Constant(_)
			| LogicalExpr::Field(_)
			| LogicalExpr::Doc
			| LogicalExpr::Current
			| LogicalExpr::Break
			| LogicalExpr::Continue
			| LogicalExpr::Subquery(_) => {}
			LogicalExpr::Array(items) | LogicalExpr::Set(items) => {
				for e in items {
					out(e);
				}
			}
			LogicalExpr::Object(entries) => {
				for e in entries.iter().map(|(_, v)| v) {
					out(e);
				}
			}
			LogicalExpr::RecordId(rid) => rid.key.for_each_expr(out),
			LogicalExpr::Access {
				base,
				..
			}
			| LogicalExpr::Flatten {
				base,
				..
			} => out(base),
			LogicalExpr::First(base)
			| LogicalExpr::Last(base)
			| LogicalExpr::Each(base)
			| LogicalExpr::RepeatRecurse(base) => out(base),
			LogicalExpr::Index {
				base,
				index,
			} => {
				out(base);
				out(index);
			}
			LogicalExpr::Filter {
				base,
				predicate,
			} => {
				out(base);
				out(predicate);
			}
			LogicalExpr::Method {
				base,
				args,
				..
			} => {
				out(base);
				for e in args {
					out(e);
				}
			}
			LogicalExpr::Destructure {
				base,
				fields,
			} => {
				out(base);
				for field in fields {
					field.for_each_expr(out);
				}
			}
			LogicalExpr::Optional {
				base,
				then,
			} => {
				out(base);
				out(then);
			}
			LogicalExpr::Lookup {
				base,
				lookup,
			} => {
				out(base);
				lookup.for_each_expr(out);
			}
			LogicalExpr::Recurse(recurse) => {
				out(&recurse.base);
				if let Some(path) = &recurse.path {
					out(path.body());
				}
				if let Some(LogicalRecurseInstruction::Shortest {
					expects,
					..
				}) = &recurse.instruction
				{
					out(expects);
				}
			}
			LogicalExpr::Broadcast {
				base,
				body,
				..
			} => {
				out(base);
				out(body);
			}
			LogicalExpr::SetField {
				base,
				value,
				..
			} => {
				out(base);
				out(value);
			}
			LogicalExpr::Prefix {
				expr,
				..
			} => out(expr),
			LogicalExpr::Postfix {
				expr,
				..
			} => out(expr),
			LogicalExpr::Invoke {
				target,
				args,
			} => {
				out(target);
				for e in args {
					out(e);
				}
			}
			LogicalExpr::Binary {
				left,
				right,
				..
			} => {
				out(left);
				out(right);
			}
			LogicalExpr::Call(call) => {
				for e in &call.args {
					out(e);
				}
			}
			LogicalExpr::Closure(closure) => out(&closure.body),
			LogicalExpr::If(branches) => {
				for (cond, then) in &branches.branches {
					out(cond);
					out(then);
				}
				if let Some(e) = &branches.otherwise {
					out(e);
				};
			}
			LogicalExpr::Throw(expr) => out(expr),
		}
	}

	/// [`Self::for_each_child`], collected. Allocates once per node, so a walk
	/// of a whole tree takes the callback form.
	pub fn children(&self) -> Vec<&LogicalExpr> {
		let mut out = Vec::new();
		self.for_each_child(&mut |child| out.push(child));
		out
	}

	/// [`Self::children`], mutably.
	pub fn children_mut(&mut self) -> Vec<&mut LogicalExpr> {
		let mut out = Vec::new();
		match self {
			LogicalExpr::Literal(_)
			| LogicalExpr::Param(_)
			| LogicalExpr::Table(_)
			| LogicalExpr::Mock(_)
			| LogicalExpr::Constant(_)
			| LogicalExpr::Field(_)
			| LogicalExpr::Doc
			| LogicalExpr::Current
			| LogicalExpr::Break
			| LogicalExpr::Continue
			| LogicalExpr::Subquery(_) => {}
			LogicalExpr::Array(items) | LogicalExpr::Set(items) => out.extend(items),
			LogicalExpr::Object(entries) => out.extend(entries.iter_mut().map(|(_, v)| v)),
			LogicalExpr::RecordId(rid) => rid.key.exprs_mut(&mut out),
			LogicalExpr::Access {
				base,
				..
			}
			| LogicalExpr::Flatten {
				base,
				..
			} => out.push(base),
			LogicalExpr::First(base)
			| LogicalExpr::Last(base)
			| LogicalExpr::Each(base)
			| LogicalExpr::RepeatRecurse(base) => out.push(base),
			LogicalExpr::Index {
				base,
				index,
			} => {
				out.push(base);
				out.push(index);
			}
			LogicalExpr::Filter {
				base,
				predicate,
			} => {
				out.push(base);
				out.push(predicate);
			}
			LogicalExpr::Method {
				base,
				args,
				..
			} => {
				out.push(base);
				out.extend(args);
			}
			LogicalExpr::Destructure {
				base,
				fields,
			} => {
				out.push(base);
				fields.iter_mut().for_each(|field| field.exprs_mut(&mut out));
			}
			LogicalExpr::Optional {
				base,
				then,
			} => {
				out.push(base);
				out.push(then);
			}
			LogicalExpr::Lookup {
				base,
				lookup,
			} => {
				out.push(base);
				lookup.exprs_mut(&mut out);
			}
			LogicalExpr::Recurse(recurse) => {
				let LogicalRecurse {
					base,
					path,
					instruction,
					..
				} = &mut **recurse;
				out.push(base);
				if let Some(path) = path {
					out.push(path.body_mut());
				}
				if let Some(LogicalRecurseInstruction::Shortest {
					expects,
					..
				}) = instruction
				{
					out.push(expects);
				}
			}
			LogicalExpr::Broadcast {
				base,
				body,
				..
			} => {
				out.push(base);
				out.push(body);
			}
			LogicalExpr::SetField {
				base,
				value,
				..
			} => {
				out.push(base);
				out.push(value);
			}
			LogicalExpr::Prefix {
				expr,
				..
			} => out.push(expr),
			LogicalExpr::Postfix {
				expr,
				..
			} => out.push(expr),
			LogicalExpr::Invoke {
				target,
				args,
			} => {
				out.push(target);
				out.extend(args);
			}
			LogicalExpr::Binary {
				left,
				right,
				..
			} => {
				out.push(left);
				out.push(right);
			}
			LogicalExpr::Call(call) => out.extend(&mut call.args),
			LogicalExpr::Closure(closure) => out.push(&mut closure.body),
			LogicalExpr::If(branches) => {
				for (cond, then) in &mut branches.branches {
					out.push(cond);
					out.push(then);
				}
				out.extend(&mut branches.otherwise);
			}
			LogicalExpr::Throw(expr) => out.push(expr),
		}
		out
	}

	/// Walks the expression in pre-order, stopping at the first `Break`. Does
	/// not enter a [`Self::Subquery`].
	pub fn visit<B>(&self, f: &mut impl FnMut(&LogicalExpr) -> ControlFlow<B>) -> ControlFlow<B> {
		// The recursion is over `dyn FnMut` rather than the caller's closure
		// type: a generic function that handed itself a fresh closure at every
		// level would have no monomorphic form.
		fn walk<B>(
			expr: &LogicalExpr,
			f: &mut dyn FnMut(&LogicalExpr) -> ControlFlow<B>,
		) -> ControlFlow<B> {
			f(expr)?;
			let mut flow = ControlFlow::Continue(());
			expr.for_each_child(&mut |child| {
				if flow.is_continue() {
					flow = walk(child, &mut *f);
				}
			});
			flow
		}
		walk(self, f)
	}

	/// [`Self::visit`], entering every [`Self::Subquery`]: the scalars of a
	/// nested plan are walked in turn, so the walk reaches every expression
	/// evaluated within this one.
	pub fn visit_deep<B>(
		&self,
		f: &mut impl FnMut(&LogicalExpr) -> ControlFlow<B>,
	) -> ControlFlow<B> {
		fn walk<B>(
			expr: &LogicalExpr,
			f: &mut dyn FnMut(&LogicalExpr) -> ControlFlow<B>,
		) -> ControlFlow<B> {
			f(expr)?;
			if let LogicalExpr::Subquery(op) = expr {
				return match op.visit_scalars_deep(&mut |scalar| match walk(scalar, &mut *f) {
					ControlFlow::Continue(()) => Ok(()),
					ControlFlow::Break(b) => Err(b),
				}) {
					Ok(()) => ControlFlow::Continue(()),
					Err(b) => ControlFlow::Break(b),
				};
			}
			let mut flow = ControlFlow::Continue(());
			expr.for_each_child(&mut |child| {
				if flow.is_continue() {
					flow = walk(child, &mut *f);
				}
			});
			flow
		}
		walk(self, f)
	}

	/// Rewrites in place, bottom-up: every nested expression is rewritten
	/// before `f` sees the expression holding it. Does not enter a
	/// [`Self::Subquery`].
	pub fn visit_mut<E>(
		&mut self,
		f: &mut impl FnMut(&mut LogicalExpr) -> Result<(), E>,
	) -> Result<(), E> {
		self.visit_mut_dyn(f)
	}

	/// [`Self::visit_mut`] recursing behind `dyn`: one body per error type rather than one per
	/// closure.
	fn visit_mut_dyn<E>(
		&mut self,
		f: &mut dyn FnMut(&mut LogicalExpr) -> Result<(), E>,
	) -> Result<(), E> {
		for child in self.children_mut() {
			child.visit_mut_dyn(&mut *f)?;
		}
		f(self)
	}

	/// Rebuilds the expression bottom-up, replacing every node with `f(node)`.
	/// Does not enter a [`Self::Subquery`].
	pub fn transform<E>(
		mut self,
		f: &mut impl FnMut(LogicalExpr) -> Result<LogicalExpr, E>,
	) -> Result<LogicalExpr, E> {
		self.visit_mut(&mut |node| {
			let taken = std::mem::replace(node, LogicalExpr::Break);
			*node = f(taken)?;
			Ok(())
		})?;
		Ok(self)
	}

	/// Whether any nested expression, this one included, satisfies `pred`.
	pub fn any(&self, mut pred: impl FnMut(&LogicalExpr) -> bool) -> bool {
		self.visit(&mut |node| {
			if pred(node) {
				ControlFlow::Break(())
			} else {
				ControlFlow::Continue(())
			}
		})
		.is_break()
	}
}

impl LogicalDestructureField {
	fn for_each_expr<'a>(&'a self, out: &mut dyn FnMut(&'a LogicalExpr)) {
		match self {
			LogicalDestructureField::All(_)
			| LogicalDestructureField::Field(_)
			| LogicalDestructureField::Rest => {}
			LogicalDestructureField::Aliased(_, body) => out(body),
			LogicalDestructureField::Destructure(_, fields) => {
				for field in fields {
					field.for_each_expr(out);
				}
			}
		}
	}

	fn exprs_mut<'a>(&'a mut self, out: &mut Vec<&'a mut LogicalExpr>) {
		match self {
			LogicalDestructureField::All(_)
			| LogicalDestructureField::Field(_)
			| LogicalDestructureField::Rest => {}
			LogicalDestructureField::Aliased(_, body) => out.push(body),
			LogicalDestructureField::Destructure(_, fields) => {
				fields.iter_mut().for_each(|field| field.exprs_mut(out))
			}
		}
	}
}

impl LogicalLookup {
	fn for_each_expr<'a>(&'a self, out: &mut dyn FnMut(&'a LogicalExpr)) {
		if let Some(fields) = &self.expr {
			fields.for_each_expr(out);
		}
		for subject in &self.what {
			subject.for_each_expr(out);
		}
		if let Some(e) = &self.cond {
			out(e);
		};
		for e in self.split.iter().flatten() {
			out(e);
		}
		for e in self.group.iter().flatten() {
			out(e);
		}
		if let Some(order) = &self.order {
			order.for_each_expr(out);
		}
		if let Some(e) = &self.limit {
			out(e);
		};
		if let Some(e) = &self.start {
			out(e);
		};
	}

	fn exprs_mut<'a>(&'a mut self, out: &mut Vec<&'a mut LogicalExpr>) {
		if let Some(fields) = &mut self.expr {
			fields.exprs_mut(out);
		}
		for subject in &mut self.what {
			subject.exprs_mut(out);
		}
		out.extend(&mut self.cond);
		out.extend(self.split.iter_mut().flatten());
		out.extend(self.group.iter_mut().flatten());
		if let Some(order) = &mut self.order {
			order.exprs_mut(out);
		}
		out.extend(&mut self.limit);
		out.extend(&mut self.start);
	}
}

impl LogicalLookupSubject {
	fn for_each_expr<'a>(&'a self, out: &mut dyn FnMut(&'a LogicalExpr)) {
		match self {
			LogicalLookupSubject::Table {
				..
			} => {}
			LogicalLookupSubject::Range {
				range,
				..
			} => range.for_each_expr(out),
		}
	}

	fn exprs_mut<'a>(&'a mut self, out: &mut Vec<&'a mut LogicalExpr>) {
		match self {
			LogicalLookupSubject::Table {
				..
			} => {}
			LogicalLookupSubject::Range {
				range,
				..
			} => range.exprs_mut(out),
		}
	}
}

impl LogicalRecordIdKey {
	fn for_each_expr<'a>(&'a self, out: &mut dyn FnMut(&'a LogicalExpr)) {
		match self {
			LogicalRecordIdKey::Number(_)
			| LogicalRecordIdKey::String(_)
			| LogicalRecordIdKey::Uuid(_)
			| LogicalRecordIdKey::Generate(_) => {}
			LogicalRecordIdKey::Array(items) => {
				for e in items {
					out(e);
				}
			}
			LogicalRecordIdKey::Object(entries) => {
				for e in entries.iter().map(|(_, v)| v) {
					out(e);
				}
			}
			LogicalRecordIdKey::Range(range) => range.for_each_expr(out),
		}
	}

	fn exprs_mut<'a>(&'a mut self, out: &mut Vec<&'a mut LogicalExpr>) {
		match self {
			LogicalRecordIdKey::Number(_)
			| LogicalRecordIdKey::String(_)
			| LogicalRecordIdKey::Uuid(_)
			| LogicalRecordIdKey::Generate(_) => {}
			LogicalRecordIdKey::Array(items) => out.extend(items),
			LogicalRecordIdKey::Object(entries) => out.extend(entries.iter_mut().map(|(_, v)| v)),
			LogicalRecordIdKey::Range(range) => range.exprs_mut(out),
		}
	}
}

impl LogicalRecordIdKeyRange {
	fn for_each_expr<'a>(&'a self, out: &mut dyn FnMut(&'a LogicalExpr)) {
		for bound in [&self.start, &self.end] {
			if let Bound::Included(key) | Bound::Excluded(key) = bound {
				key.for_each_expr(out);
			}
		}
	}

	fn exprs_mut<'a>(&'a mut self, out: &mut Vec<&'a mut LogicalExpr>) {
		for bound in [&mut self.start, &mut self.end] {
			if let Bound::Included(key) | Bound::Excluded(key) = bound {
				key.exprs_mut(out);
			}
		}
	}
}

impl LogicalFields {
	/// Every expression the projection holds: each selector. An alias is a
	/// name, not an expression.
	pub fn for_each_expr<'a>(&'a self, out: &mut dyn FnMut(&'a LogicalExpr)) {
		match self {
			LogicalFields::Value {
				expr,
				..
			} => out(expr),
			LogicalFields::Select(fields) => {
				for field in fields {
					if let LogicalField::Single {
						expr,
						..
					} = field
					{
						out(expr);
					}
				}
			}
		}
	}

	/// [`Self::for_each_expr`], collected.
	pub fn exprs<'a>(&'a self, out: &mut Vec<&'a LogicalExpr>) {
		self.for_each_expr(&mut |expr| out.push(expr));
	}

	/// [`Self::exprs`], mutably.
	pub fn exprs_mut<'a>(&'a mut self, out: &mut Vec<&'a mut LogicalExpr>) {
		match self {
			LogicalFields::Value {
				expr,
				..
			} => out.push(expr),
			LogicalFields::Select(fields) => {
				for field in fields {
					if let LogicalField::Single {
						expr,
						..
					} = field
					{
						out.push(expr);
					}
				}
			}
		}
	}
}

impl LogicalOrdering {
	/// Every ordering key.
	pub fn for_each_expr<'a>(&'a self, out: &mut dyn FnMut(&'a LogicalExpr)) {
		match self {
			LogicalOrdering::Random => {}
			LogicalOrdering::Order(orders) => {
				for e in orders.iter().map(|o| &o.value) {
					out(e);
				}
			}
		}
	}

	/// [`Self::for_each_expr`], collected.
	pub fn exprs<'a>(&'a self, out: &mut Vec<&'a LogicalExpr>) {
		self.for_each_expr(&mut |expr| out.push(expr));
	}

	/// [`Self::exprs`], mutably.
	pub fn exprs_mut<'a>(&'a mut self, out: &mut Vec<&'a mut LogicalExpr>) {
		match self {
			LogicalOrdering::Random => {}
			LogicalOrdering::Order(orders) => out.extend(orders.iter_mut().map(|o| &mut o.value)),
		}
	}
}

// ---------------------------------------------------------------------------
// Shallow identity
// ---------------------------------------------------------------------------

impl LogicalExpr {
	/// Whether `self` and `other` agree on everything that
	/// [`Self::for_each_child`] does not yield: the variant, the operator, the
	/// name, the kind, the literal, the flags and the shape of the clauses a
	/// node holds around its children. The children themselves are not
	/// compared. A caller that interns bottom-up compares the child nodes it
	/// already holds in their place, so a whole tree is compared in time linear
	/// in its size.
	///
	/// For two expressions whose children are pairwise equal, `shallow_eq` is
	/// `self == other`, with one exception: a [`Self::Subquery`] is equal only
	/// to itself, by address, since the plan it holds is not a child and is
	/// never compared. Every payload of a node is either yielded by
	/// [`Self::for_each_child`] or compared here, so no expression is compared
	/// deeply.
	pub fn shallow_eq(&self, other: &LogicalExpr) -> bool {
		match self {
			LogicalExpr::Literal(x) => matches!(other, LogicalExpr::Literal(y) if x == y),
			LogicalExpr::Array(_) => matches!(other, LogicalExpr::Array(_)),
			LogicalExpr::Set(_) => matches!(other, LogicalExpr::Set(_)),
			LogicalExpr::Object(entries) => matches!(
				other,
				LogicalExpr::Object(others) if entries.len() == others.len()
					&& entries.iter().zip(others).all(|((a, _), (b, _))| a == b)
			),
			LogicalExpr::RecordId(rid) => matches!(
				other,
				LogicalExpr::RecordId(o) if rid.table == o.table && key_shape_eq(&rid.key, &o.key)
			),
			LogicalExpr::Param(x) => matches!(other, LogicalExpr::Param(y) if x == y),
			LogicalExpr::Table(x) => matches!(other, LogicalExpr::Table(y) if x == y),
			LogicalExpr::Mock(x) => matches!(other, LogicalExpr::Mock(y) if x == y),
			LogicalExpr::Constant(x) => matches!(other, LogicalExpr::Constant(y) if x == y),
			LogicalExpr::Field(x) => matches!(other, LogicalExpr::Field(y) if x == y),
			LogicalExpr::Doc => matches!(other, LogicalExpr::Doc),
			LogicalExpr::Current => matches!(other, LogicalExpr::Current),
			LogicalExpr::Access {
				field,
				..
			} => matches!(
				other,
				LogicalExpr::Access { field: o, .. } if field == o
			),
			LogicalExpr::Index {
				..
			} => matches!(other, LogicalExpr::Index { .. }),
			LogicalExpr::First(_) => matches!(other, LogicalExpr::First(_)),
			LogicalExpr::Last(_) => matches!(other, LogicalExpr::Last(_)),
			LogicalExpr::Each(_) => matches!(other, LogicalExpr::Each(_)),
			LogicalExpr::Flatten {
				explicit,
				..
			} => matches!(
				other,
				LogicalExpr::Flatten { explicit: o, .. } if explicit == o
			),
			LogicalExpr::Filter {
				..
			} => matches!(other, LogicalExpr::Filter { .. }),
			LogicalExpr::Method {
				name,
				..
			} => matches!(
				other,
				LogicalExpr::Method { name: o, .. } if name == o
			),
			LogicalExpr::Destructure {
				fields,
				..
			} => matches!(
				other,
				LogicalExpr::Destructure { fields: o, .. } if destructure_shape_eq(fields, o)
			),
			LogicalExpr::Optional {
				..
			} => matches!(other, LogicalExpr::Optional { .. }),
			LogicalExpr::Lookup {
				lookup,
				..
			} => matches!(
				other,
				LogicalExpr::Lookup { lookup: o, .. } if lookup_shape_eq(lookup, o)
			),
			LogicalExpr::Recurse(recurse) => matches!(
				other,
				LogicalExpr::Recurse(o) if recurse.recurse == o.recurse
					&& recurse_path_tag(&recurse.path) == recurse_path_tag(&o.path)
					&& recurse_instruction_tag(&recurse.instruction)
						== recurse_instruction_tag(&o.instruction)
			),
			LogicalExpr::RepeatRecurse(_) => matches!(other, LogicalExpr::RepeatRecurse(_)),
			LogicalExpr::Broadcast {
				flatten,
				..
			} => matches!(
				other,
				LogicalExpr::Broadcast { flatten: o, .. } if flatten == o
			),
			LogicalExpr::SetField {
				field,
				..
			} => matches!(
				other,
				LogicalExpr::SetField { field: o, .. } if field == o
			),
			LogicalExpr::Prefix {
				op,
				..
			} => matches!(other, LogicalExpr::Prefix { op: o, .. } if op == o),
			LogicalExpr::Postfix {
				op,
				..
			} => matches!(other, LogicalExpr::Postfix { op: o, .. } if op == o),
			LogicalExpr::Invoke {
				..
			} => matches!(other, LogicalExpr::Invoke { .. }),
			LogicalExpr::Binary {
				op,
				..
			} => matches!(other, LogicalExpr::Binary { op: o, .. } if op == o),
			LogicalExpr::Call(call) => {
				matches!(other, LogicalExpr::Call(o) if call.receiver == o.receiver)
			}
			LogicalExpr::Closure(closure) => matches!(
				other,
				LogicalExpr::Closure(o) if closure.args == o.args
					&& closure.returns == o.returns
					&& closure.body_sql == o.body_sql
			),
			LogicalExpr::If(branches) => matches!(
				other,
				LogicalExpr::If(o) if branches.branches.len() == o.branches.len()
					&& branches.otherwise.is_some() == o.otherwise.is_some()
			),
			LogicalExpr::Throw(_) => matches!(other, LogicalExpr::Throw(_)),
			LogicalExpr::Break => matches!(other, LogicalExpr::Break),
			LogicalExpr::Continue => matches!(other, LogicalExpr::Continue),
			LogicalExpr::Subquery(_) => std::ptr::eq(self, other),
		}
	}

	/// Hashes what [`Self::shallow_eq`] compares: two expressions that are
	/// `shallow_eq` hash alike.
	pub fn shallow_hash<H: Hasher>(&self, state: &mut H) {
		std::mem::discriminant(self).hash(state);
		match self {
			LogicalExpr::Literal(x) => x.hash(state),
			LogicalExpr::Array(_)
			| LogicalExpr::Set(_)
			| LogicalExpr::Doc
			| LogicalExpr::Current
			| LogicalExpr::Index {
				..
			}
			| LogicalExpr::First(_)
			| LogicalExpr::Last(_)
			| LogicalExpr::Each(_)
			| LogicalExpr::Filter {
				..
			}
			| LogicalExpr::Optional {
				..
			}
			| LogicalExpr::RepeatRecurse(_)
			| LogicalExpr::Invoke {
				..
			}
			| LogicalExpr::Throw(_)
			| LogicalExpr::Break
			| LogicalExpr::Continue => {}
			LogicalExpr::Object(entries) => {
				entries.len().hash(state);
				entries.iter().for_each(|(key, _)| key.hash(state));
			}
			LogicalExpr::RecordId(rid) => {
				rid.table.hash(state);
				key_shape_hash(&rid.key, state);
			}
			LogicalExpr::Param(x) => x.hash(state),
			LogicalExpr::Table(x) => x.hash(state),
			LogicalExpr::Mock(x) => x.hash(state),
			LogicalExpr::Constant(x) => x.hash(state),
			LogicalExpr::Field(x) => x.hash(state),
			LogicalExpr::Access {
				field,
				..
			}
			| LogicalExpr::SetField {
				field,
				..
			} => field.hash(state),
			LogicalExpr::Flatten {
				explicit: flag,
				..
			}
			| LogicalExpr::Broadcast {
				flatten: flag,
				..
			} => flag.hash(state),
			LogicalExpr::Method {
				name,
				..
			} => name.hash(state),
			LogicalExpr::Destructure {
				fields,
				..
			} => destructure_shape_hash(fields, state),
			LogicalExpr::Lookup {
				lookup,
				..
			} => lookup_shape_hash(lookup, state),
			LogicalExpr::Recurse(recurse) => {
				recurse.recurse.hash(state);
				recurse_path_tag(&recurse.path).hash(state);
				recurse_instruction_tag(&recurse.instruction).hash(state);
			}
			LogicalExpr::Prefix {
				op,
				..
			} => op.hash(state),
			LogicalExpr::Postfix {
				op,
				..
			} => op.hash(state),
			LogicalExpr::Binary {
				op,
				..
			} => op.hash(state),
			LogicalExpr::Call(call) => call.receiver.hash(state),
			LogicalExpr::Closure(closure) => {
				closure.args.hash(state);
				closure.returns.hash(state);
				closure.body_sql.hash(state);
			}
			LogicalExpr::If(branches) => {
				branches.branches.len().hash(state);
				branches.otherwise.is_some().hash(state);
			}
			LogicalExpr::Subquery(_) => std::ptr::from_ref(self).hash(state),
		}
	}
}

/// `Some(inclusive)` of an instruction that carries one, and the variant
/// otherwise: the part of a recursion's instruction that its children do not
/// hold.
fn recurse_instruction_tag(instruction: &Option<LogicalRecurseInstruction>) -> Option<(u8, bool)> {
	match instruction {
		None => None,
		Some(LogicalRecurseInstruction::Path {
			inclusive,
		}) => Some((0, *inclusive)),
		Some(LogicalRecurseInstruction::Collect {
			inclusive,
		}) => Some((1, *inclusive)),
		Some(LogicalRecurseInstruction::Shortest {
			inclusive,
			..
		}) => Some((2, *inclusive)),
	}
}

/// How a recursion's body was written; the body is a child.
fn recurse_path_tag(path: &Option<LogicalRecursePath>) -> Option<u8> {
	match path {
		None => None,
		Some(LogicalRecursePath::Nested(_)) => Some(0),
		Some(LogicalRecursePath::Trailing(_)) => Some(1),
	}
}

/// [`LogicalRecordIdKey`] equality with every expression it holds skipped.
fn key_shape_eq(a: &LogicalRecordIdKey, b: &LogicalRecordIdKey) -> bool {
	match a {
		LogicalRecordIdKey::Number(x) => matches!(b, LogicalRecordIdKey::Number(y) if x == y),
		LogicalRecordIdKey::String(x) => matches!(b, LogicalRecordIdKey::String(y) if x == y),
		LogicalRecordIdKey::Uuid(x) => matches!(b, LogicalRecordIdKey::Uuid(y) if x == y),
		LogicalRecordIdKey::Generate(x) => matches!(b, LogicalRecordIdKey::Generate(y) if x == y),
		LogicalRecordIdKey::Array(items) => {
			matches!(b, LogicalRecordIdKey::Array(others) if items.len() == others.len())
		}
		LogicalRecordIdKey::Object(entries) => matches!(
			b,
			LogicalRecordIdKey::Object(others) if entries.len() == others.len()
				&& entries.iter().zip(others).all(|((a, _), (b, _))| a == b)
		),
		LogicalRecordIdKey::Range(range) => {
			matches!(b, LogicalRecordIdKey::Range(other) if range_shape_eq(range, other))
		}
	}
}

fn key_shape_hash<H: Hasher>(key: &LogicalRecordIdKey, state: &mut H) {
	std::mem::discriminant(key).hash(state);
	match key {
		LogicalRecordIdKey::Number(x) => x.hash(state),
		LogicalRecordIdKey::String(x) => x.hash(state),
		LogicalRecordIdKey::Uuid(x) => x.hash(state),
		LogicalRecordIdKey::Generate(x) => x.hash(state),
		LogicalRecordIdKey::Array(items) => items.len().hash(state),
		LogicalRecordIdKey::Object(entries) => {
			entries.len().hash(state);
			entries.iter().for_each(|(key, _)| key.hash(state));
		}
		LogicalRecordIdKey::Range(range) => range_shape_hash(range, state),
	}
}

fn range_shape_eq(a: &LogicalRecordIdKeyRange, b: &LogicalRecordIdKeyRange) -> bool {
	bound_shape_eq(&a.start, &b.start) && bound_shape_eq(&a.end, &b.end)
}

fn range_shape_hash<H: Hasher>(range: &LogicalRecordIdKeyRange, state: &mut H) {
	bound_shape_hash(&range.start, state);
	bound_shape_hash(&range.end, state);
}

fn bound_shape_eq(a: &Bound<LogicalRecordIdKey>, b: &Bound<LogicalRecordIdKey>) -> bool {
	match (a, b) {
		(Bound::Included(a), Bound::Included(b)) | (Bound::Excluded(a), Bound::Excluded(b)) => {
			key_shape_eq(a, b)
		}
		(Bound::Unbounded, Bound::Unbounded) => true,
		(Bound::Included(_) | Bound::Excluded(_) | Bound::Unbounded, _) => false,
	}
}

fn bound_shape_hash<H: Hasher>(bound: &Bound<LogicalRecordIdKey>, state: &mut H) {
	match bound {
		Bound::Included(key) => {
			0u8.hash(state);
			key_shape_hash(key, state);
		}
		Bound::Excluded(key) => {
			1u8.hash(state);
			key_shape_hash(key, state);
		}
		Bound::Unbounded => 2u8.hash(state),
	}
}

/// Equality of destructure patterns with every aliased body skipped.
fn destructure_shape_eq(a: &[LogicalDestructureField], b: &[LogicalDestructureField]) -> bool {
	a.len() == b.len()
		&& a.iter().zip(b).all(|(a, b)| match a {
			LogicalDestructureField::All(x) => {
				matches!(b, LogicalDestructureField::All(y) if x == y)
			}
			LogicalDestructureField::Field(x) => {
				matches!(b, LogicalDestructureField::Field(y) if x == y)
			}
			LogicalDestructureField::Aliased(x, _) => {
				matches!(b, LogicalDestructureField::Aliased(y, _) if x == y)
			}
			LogicalDestructureField::Destructure(x, fields) => matches!(
				b,
				LogicalDestructureField::Destructure(y, others)
					if x == y && destructure_shape_eq(fields, others)
			),
			LogicalDestructureField::Rest => matches!(b, LogicalDestructureField::Rest),
		})
}

fn destructure_shape_hash<H: Hasher>(fields: &[LogicalDestructureField], state: &mut H) {
	fields.len().hash(state);
	for field in fields {
		std::mem::discriminant(field).hash(state);
		match field {
			LogicalDestructureField::All(name)
			| LogicalDestructureField::Field(name)
			| LogicalDestructureField::Aliased(name, _) => name.hash(state),
			LogicalDestructureField::Destructure(name, fields) => {
				name.hash(state);
				destructure_shape_hash(fields, state);
			}
			LogicalDestructureField::Rest => {}
		}
	}
}

/// [`LogicalLookup`] equality with every expression it holds skipped: which
/// clauses are present, how many entries each holds, and the clauses that are
/// not expressions.
fn lookup_shape_eq(a: &LogicalLookup, b: &LogicalLookup) -> bool {
	a.kind == b.kind
		&& a.only == b.only
		&& a.alias == b.alias
		&& match (&a.expr, &b.expr) {
			(None, None) => true,
			(Some(a), Some(b)) => fields_shape_eq(a, b),
			(None, Some(_)) | (Some(_), None) => false,
		} && a.what.len() == b.what.len()
		&& a.what.iter().zip(&b.what).all(|(a, b)| subject_shape_eq(a, b))
		&& a.cond.is_some() == b.cond.is_some()
		&& a.split.as_ref().map(Vec::len) == b.split.as_ref().map(Vec::len)
		&& a.group.as_ref().map(Vec::len) == b.group.as_ref().map(Vec::len)
		&& match (&a.order, &b.order) {
			(None, None) => true,
			(Some(a), Some(b)) => ordering_shape_eq(a, b),
			(None, Some(_)) | (Some(_), None) => false,
		} && a.limit.is_some() == b.limit.is_some()
		&& a.start.is_some() == b.start.is_some()
}

fn lookup_shape_hash<H: Hasher>(lookup: &LogicalLookup, state: &mut H) {
	lookup.kind.hash(state);
	lookup.only.hash(state);
	lookup.alias.hash(state);
	match &lookup.expr {
		None => 0u8.hash(state),
		Some(fields) => {
			1u8.hash(state);
			fields_shape_hash(fields, state);
		}
	}
	lookup.what.len().hash(state);
	lookup.what.iter().for_each(|subject| subject_shape_hash(subject, state));
	lookup.cond.is_some().hash(state);
	lookup.split.as_ref().map(Vec::len).hash(state);
	lookup.group.as_ref().map(Vec::len).hash(state);
	match &lookup.order {
		None => 0u8.hash(state),
		Some(order) => {
			1u8.hash(state);
			ordering_shape_hash(order, state);
		}
	}
	lookup.limit.is_some().hash(state);
	lookup.start.is_some().hash(state);
}

fn subject_shape_eq(a: &LogicalLookupSubject, b: &LogicalLookupSubject) -> bool {
	match a {
		LogicalLookupSubject::Table {
			table,
			referencing_field,
		} => matches!(
			b,
			LogicalLookupSubject::Table { table: t, referencing_field: r }
				if table == t && referencing_field == r
		),
		LogicalLookupSubject::Range {
			table,
			range,
			referencing_field,
		} => matches!(
			b,
			LogicalLookupSubject::Range { table: t, range: g, referencing_field: r }
				if table == t && referencing_field == r && range_shape_eq(range, g)
		),
	}
}

fn subject_shape_hash<H: Hasher>(subject: &LogicalLookupSubject, state: &mut H) {
	std::mem::discriminant(subject).hash(state);
	match subject {
		LogicalLookupSubject::Table {
			table,
			referencing_field,
		} => {
			table.hash(state);
			referencing_field.hash(state);
		}
		LogicalLookupSubject::Range {
			table,
			range,
			referencing_field,
		} => {
			table.hash(state);
			referencing_field.hash(state);
			range_shape_hash(range, state);
		}
	}
}

fn fields_shape_eq(a: &LogicalFields, b: &LogicalFields) -> bool {
	match a {
		LogicalFields::Value {
			alias,
			..
		} => matches!(b, LogicalFields::Value { alias: o, .. } if alias == o),
		LogicalFields::Select(fields) => matches!(
			b,
			LogicalFields::Select(others) if fields.len() == others.len()
				&& fields.iter().zip(others).all(|(a, b)| match a {
					LogicalField::All => matches!(b, LogicalField::All),
					LogicalField::Single { alias, kind, frame, .. } => matches!(
						b,
						LogicalField::Single { alias: a2, kind: k2, frame: f2, .. }
							if alias == a2 && kind == k2 && frame == f2
					),
				})
		),
	}
}

fn fields_shape_hash<H: Hasher>(fields: &LogicalFields, state: &mut H) {
	std::mem::discriminant(fields).hash(state);
	match fields {
		LogicalFields::Value {
			alias,
			..
		} => alias.hash(state),
		LogicalFields::Select(fields) => {
			fields.len().hash(state);
			for field in fields {
				std::mem::discriminant(field).hash(state);
				if let LogicalField::Single {
					alias,
					kind,
					frame,
					..
				} = field
				{
					alias.hash(state);
					kind.hash(state);
					frame.hash(state);
				}
			}
		}
	}
}

fn ordering_shape_eq(a: &LogicalOrdering, b: &LogicalOrdering) -> bool {
	match a {
		LogicalOrdering::Random => matches!(b, LogicalOrdering::Random),
		LogicalOrdering::Order(orders) => matches!(
			b,
			LogicalOrdering::Order(others) if orders.len() == others.len()
				&& orders.iter().zip(others).all(|(a, b)| {
					a.collate == b.collate && a.numeric == b.numeric && a.direction == b.direction
				})
		),
	}
}

fn ordering_shape_hash<H: Hasher>(ordering: &LogicalOrdering, state: &mut H) {
	std::mem::discriminant(ordering).hash(state);
	if let LogicalOrdering::Order(orders) = ordering {
		orders.len().hash(state);
		for order in orders {
			order.collate.hash(state);
			order.numeric.hash(state);
			order.direction.hash(state);
		}
	}
}

// ---------------------------------------------------------------------------
// Read-only classification
// ---------------------------------------------------------------------------

impl LogicalExpr {
	/// Whether evaluating this expression only reads.
	///
	/// One-sided, as for the expression layer: it may call a reading
	/// expression writable, and never the reverse. Every construct whose
	/// effect is invisible from the syntax — a closure invoked through a value,
	/// an unregistered method, a custom or scripted function — answers `false`.
	pub fn read_only(&self) -> bool {
		match self {
			LogicalExpr::Literal(_)
			| LogicalExpr::Param(_)
			| LogicalExpr::Table(_)
			| LogicalExpr::Mock(_)
			| LogicalExpr::Constant(_)
			| LogicalExpr::Field(_)
			| LogicalExpr::Doc
			| LogicalExpr::Current
			| LogicalExpr::Break
			| LogicalExpr::Continue => true,
			LogicalExpr::Array(items) | LogicalExpr::Set(items) => {
				items.iter().all(LogicalExpr::read_only)
			}
			LogicalExpr::Object(entries) => entries.iter().all(|(_, v)| v.read_only()),
			LogicalExpr::RecordId(rid) => rid.read_only(),
			// A builtin method writes nothing beyond what its receiver and
			// arguments carry; an unregistered name invokes a closure stored
			// on the receiver, whose body is invisible here.
			LogicalExpr::Method {
				base,
				name,
				args,
			} => {
				is_builtin_method(name)
					&& base.read_only()
					&& args.iter().all(LogicalExpr::read_only)
			}
			LogicalExpr::Lookup {
				base,
				lookup,
			} => base.read_only() && lookup.read_only(),
			LogicalExpr::SetField {
				base,
				value,
				..
			} => base.read_only() && value.read_only(),
			// Every other step reads whatever its base and operands read.
			LogicalExpr::Access {
				..
			}
			| LogicalExpr::Index {
				..
			}
			| LogicalExpr::First(_)
			| LogicalExpr::Last(_)
			| LogicalExpr::Each(_)
			| LogicalExpr::Flatten {
				..
			}
			| LogicalExpr::Filter {
				..
			}
			| LogicalExpr::Destructure {
				..
			}
			| LogicalExpr::Optional {
				..
			}
			| LogicalExpr::Recurse(_)
			| LogicalExpr::RepeatRecurse(_)
			| LogicalExpr::Broadcast {
				..
			} => {
				let mut reads = true;
				self.for_each_child(&mut |child| reads = reads && child.read_only());
				reads
			}
			LogicalExpr::Prefix {
				expr,
				..
			} => expr.read_only(),
			LogicalExpr::Postfix {
				expr,
				..
			} => expr.read_only(),
			// Applying a value runs a body this expression can only see when
			// the target is a closure literal; anything else must
			// over-approximate to writable.
			LogicalExpr::Invoke {
				target,
				args,
			} => {
				matches!(&**target, LogicalExpr::Closure(_))
					&& target.read_only()
					&& args.iter().all(LogicalExpr::read_only)
			}
			LogicalExpr::Binary {
				left,
				right,
				..
			} => left.read_only() && right.read_only(),
			LogicalExpr::Call(call) => {
				call.receiver.read_only() && call.args.iter().all(LogicalExpr::read_only)
			}
			// A closure literal is inert as a value, but wherever it can flow
			// it can also be invoked, so a writing body makes it writable.
			LogicalExpr::Closure(closure) => closure.body.read_only(),
			LogicalExpr::If(branches) => {
				branches.branches.iter().all(|(c, t)| c.read_only() && t.read_only())
					&& branches.otherwise.as_ref().is_none_or(LogicalExpr::read_only)
			}
			LogicalExpr::Throw(expr) => expr.read_only(),
			LogicalExpr::Subquery(op) => op.read_only(),
		}
	}
}

impl LogicalRecordIdLit {
	/// Whether evaluating the key only reads.
	pub fn read_only(&self) -> bool {
		self.key.read_only()
	}
}

impl LogicalRecordIdKey {
	fn read_only(&self) -> bool {
		match self {
			LogicalRecordIdKey::Number(_)
			| LogicalRecordIdKey::String(_)
			| LogicalRecordIdKey::Uuid(_)
			| LogicalRecordIdKey::Generate(_) => true,
			LogicalRecordIdKey::Array(items) => items.iter().all(LogicalExpr::read_only),
			LogicalRecordIdKey::Object(entries) => entries.iter().all(|(_, v)| v.read_only()),
			LogicalRecordIdKey::Range(range) => range.read_only(),
		}
	}
}

impl LogicalRecordIdKeyRange {
	fn read_only(&self) -> bool {
		[&self.start, &self.end].into_iter().all(|bound| match bound {
			Bound::Included(key) | Bound::Excluded(key) => key.read_only(),
			Bound::Unbounded => true,
		})
	}
}

impl LogicalLookup {
	fn read_only(&self) -> bool {
		self.what.iter().all(LogicalLookupSubject::read_only)
			&& self.expr.as_ref().is_none_or(LogicalFields::read_only)
			&& self.cond.as_ref().is_none_or(LogicalExpr::read_only)
			&& self.split.iter().flatten().all(LogicalExpr::read_only)
			&& self.group.iter().flatten().all(LogicalExpr::read_only)
			&& self.order.as_ref().is_none_or(LogicalOrdering::read_only)
			&& self.limit.as_ref().is_none_or(LogicalExpr::read_only)
			&& self.start.as_ref().is_none_or(LogicalExpr::read_only)
	}
}

impl LogicalLookupSubject {
	fn read_only(&self) -> bool {
		match self {
			LogicalLookupSubject::Table {
				..
			} => true,
			LogicalLookupSubject::Range {
				range,
				..
			} => range.read_only(),
		}
	}
}

impl LogicalFields {
	/// Whether evaluating every selector only reads.
	pub fn read_only(&self) -> bool {
		match self {
			LogicalFields::Value {
				expr,
				..
			} => expr.read_only(),
			LogicalFields::Select(fields) => fields.iter().all(|field| match field {
				LogicalField::All => true,
				LogicalField::Single {
					expr,
					..
				} => expr.read_only(),
			}),
		}
	}
}

impl LogicalOrdering {
	/// Whether evaluating every ordering key only reads.
	pub fn read_only(&self) -> bool {
		match self {
			LogicalOrdering::Random => true,
			LogicalOrdering::Order(orders) => orders.iter().all(|o| o.value.read_only()),
		}
	}
}

// ---------------------------------------------------------------------------
// Naming
// ---------------------------------------------------------------------------

/// Where a projected value lands in the result object.
///
/// A sequence of keys, each written into the object at the previous key:
/// `a.b` puts the value at `{ a: { b: … } }`, while the single key `a.b`
/// (an escaped identifier containing a dot) puts it at `{ "a.b": … }`. A
/// [`OutputPathPart::Lookup`] is a key spelled as a lookup renders,
/// `->likes`, which is how a graph traversal names itself in the output.
///
/// The keys are all a writer can address, but the path they were derived
/// from may have said more: `arr[0]`, `arr[$]`, `tags[WHERE …].value` and
/// `a.*` each contain a step that names no key. [`Self::exact`] records
/// whether the written path was exactly its keys, so that two paths landing
/// at the same keys still compare unequal when only one of them was written
/// as those keys, and so that a writer which can only address one bare key
/// can decline a path that asked for a position inside it.
#[derive(Clone, Debug, PartialEq, Eq, Hash)]
pub struct OutputPath {
	/// The keys, outermost first.
	pub parts: Vec<OutputPathPart>,
	/// Whether every step of the written path is one of `parts`.
	pub exact: bool,
}

/// One key of an [`OutputPath`].
#[derive(Clone, Debug, PartialEq, Eq, Hash)]
pub enum OutputPathPart {
	/// A field name, unescaped.
	Field(String),
	/// A lookup, as it renders: `->likes`, `<-(knows WHERE x)`.
	Lookup(String),
}

impl OutputPath {
	/// The path of one key.
	pub fn field(name: impl Into<String>) -> Self {
		OutputPath::keys(vec![OutputPathPart::Field(name.into())])
	}

	/// A path written as exactly these keys.
	pub fn keys(parts: Vec<OutputPathPart>) -> Self {
		OutputPath {
			parts,
			exact: true,
		}
	}

	/// The keys, outermost first.
	pub fn parts(&self) -> &[OutputPathPart] {
		&self.parts
	}

	/// The one key, when the path lands at a single field.
	pub fn as_field(&self) -> Option<&str> {
		match self.parts.as_slice() {
			[OutputPathPart::Field(name)] => Some(name),
			_ => None,
		}
	}

	/// Whether the path lands at the single field `name`.
	pub fn is_field(&self, name: &str) -> bool {
		self.as_field() == Some(name)
	}

	/// The flat name of the path: a single field's name as written, and
	/// otherwise the path rendered as an idiom.
	pub fn name(&self) -> String {
		match self.as_field() {
			Some(name) => name.to_owned(),
			None => self.to_sql(),
		}
	}
}

impl ToSql for OutputPath {
	fn fmt_sql(&self, f: &mut String, fmt: SqlFormat) {
		for (i, part) in self.parts.iter().enumerate() {
			match part {
				OutputPathPart::Field(name) if i == 0 => EscapeIdent(name).fmt_sql(f, fmt),
				OutputPathPart::Field(name) => write_sql!(f, fmt, ".{}", EscapeKwFreeIdent(name)),
				OutputPathPart::Lookup(lookup) => f.push_str(lookup),
			}
		}
	}
}

/// One naming-relevant piece of a linearised path.
enum Segment<'a> {
	/// A field read: the root `Field` or an `Access`.
	Field(&'a Strand),
	/// The expression a `(e).rest` path starts from.
	Start(&'a LogicalExpr),
	Lookup(&'a LogicalLookup),
	/// Any other step: contributes nothing to a name.
	Other,
}

impl LogicalExpr {
	/// The path in the order its steps apply, following a [`Self::Broadcast`]
	/// and an [`Self::Optional`] into their bodies and a
	/// [`LogicalRecursePath::Trailing`] body into its steps, since all of
	/// those are the continuation of the same written path. A
	/// [`LogicalRecursePath::Nested`] body and destructure alias bodies are
	/// not part of the path they sit in.
	fn segments<'a>(&'a self, out: &mut Vec<Segment<'a>>) {
		match self {
			LogicalExpr::Current => {}
			LogicalExpr::Field(name) => out.push(Segment::Field(name)),
			LogicalExpr::Doc => out.push(Segment::Other),
			LogicalExpr::Access {
				base,
				field,
			} => {
				base.segments(out);
				out.push(Segment::Field(field));
			}
			LogicalExpr::Lookup {
				base,
				lookup,
			} => {
				base.segments(out);
				out.push(Segment::Lookup(lookup));
			}
			LogicalExpr::Optional {
				base,
				then,
			} => {
				base.segments(out);
				out.push(Segment::Other);
				then.segments(out);
			}
			LogicalExpr::Recurse(recurse) => {
				recurse.base.segments(out);
				out.push(Segment::Other);
				if let Some(LogicalRecursePath::Trailing(body)) = &recurse.path {
					body.segments(out);
				}
			}
			LogicalExpr::Broadcast {
				base,
				body,
				..
			} => {
				base.segments(out);
				body.segments(out);
			}
			LogicalExpr::Index {
				base,
				..
			}
			| LogicalExpr::Flatten {
				base,
				..
			}
			| LogicalExpr::Filter {
				base,
				..
			}
			| LogicalExpr::Method {
				base,
				..
			}
			| LogicalExpr::Destructure {
				base,
				..
			} => {
				base.segments(out);
				out.push(Segment::Other);
			}
			LogicalExpr::First(base)
			| LogicalExpr::Last(base)
			| LogicalExpr::Each(base)
			| LogicalExpr::RepeatRecurse(base) => {
				base.segments(out);
				out.push(Segment::Other);
			}
			LogicalExpr::Literal(_)
			| LogicalExpr::Array(_)
			| LogicalExpr::Set(_)
			| LogicalExpr::Object(_)
			| LogicalExpr::RecordId(_)
			| LogicalExpr::Param(_)
			| LogicalExpr::Table(_)
			| LogicalExpr::Mock(_)
			| LogicalExpr::Constant(_)
			| LogicalExpr::Prefix {
				..
			}
			| LogicalExpr::Postfix {
				..
			}
			| LogicalExpr::Invoke {
				..
			}
			| LogicalExpr::Binary {
				..
			}
			| LogicalExpr::Call(_)
			| LogicalExpr::Closure(_)
			| LogicalExpr::If(_)
			| LogicalExpr::Throw(_)
			| LogicalExpr::Break
			| LogicalExpr::Continue
			| LogicalExpr::SetField {
				..
			}
			| LogicalExpr::Subquery(_) => out.push(Segment::Start(self)),
		}
	}

	/// The expression an unaliased field is named after: the expression with each `AND` or `OR`
	/// whose left operand is a boolean literal replaced by what it evaluates to. `false AND x` and
	/// `true OR x` are their left literal, and `true AND x` and `false OR x` are `x`, so the name
	/// is the one the folded expression gets, whichever of these the fold pass applies to the
	/// value. An expression with no such gate is its own name.
	pub fn named_after_gates(&self) -> std::borrow::Cow<'_, LogicalExpr> {
		fn is_literal_gate(expr: &LogicalExpr) -> bool {
			matches!(
				expr,
				LogicalExpr::Binary {
					left,
					op: BinaryOperator::And | BinaryOperator::Or,
					..
				} if matches!(left.as_ref(), LogicalExpr::Literal(LogicalLiteral::Bool(_)))
			)
		}
		if !self.any(is_literal_gate) {
			return std::borrow::Cow::Borrowed(self);
		}
		let folded = self.clone().transform::<std::convert::Infallible>(&mut |node| {
			let LogicalExpr::Binary {
				left,
				op,
				right,
			} = node
			else {
				return Ok(node);
			};
			Ok(match (*left, op) {
				(LogicalExpr::Literal(LogicalLiteral::Bool(true)), BinaryOperator::And)
				| (LogicalExpr::Literal(LogicalLiteral::Bool(false)), BinaryOperator::Or) => *right,
				(
					literal @ LogicalExpr::Literal(LogicalLiteral::Bool(false)),
					BinaryOperator::And,
				)
				| (
					literal @ LogicalExpr::Literal(LogicalLiteral::Bool(true)),
					BinaryOperator::Or,
				) => literal,
				(left, op) => LogicalExpr::Binary {
					left: Box::new(left),
					op,
					right,
				},
			})
		});
		match folded {
			Ok(folded) => std::borrow::Cow::Owned(folded),
			Err(never) => match never {},
		}
	}

	/// Where a projected expression lands in the result when it has no alias.
	///
	/// A path names itself by its field reads, lookups and starting
	/// expression, in order; every other step (`[0]`, `[WHERE …]`, `.*`, a
	/// method, a destructure, `.?`, a recursion) contributes nothing, so
	/// `tags[WHERE type = 'x'][0].value` lands at `tags.value`. A lookup with
	/// an alias names the whole path by that alias, as a single key. A path
	/// starting from an expression (`$p.a`, `(SELECT …).x`) is a single key
	/// spelled as it renders, as is a path with nothing left to name it. A
	/// parameter is named by its name, a call by its function's name, a
	/// string literal by its contents, a datetime by its text, and anything
	/// else by its rendering. The result is [`OutputPath::exact`] when every
	/// step of the path became one of its keys; a non-path is always exact.
	///
	/// A rendering that spells a statement in scalar position is not a usable
	/// name — a [`Self::Subquery`] renders as the plan it holds — so a
	/// projection whose name would be one carries its SurrealQL text as its
	/// alias instead; see [`Self::output_name_renders_a_statement`].
	pub fn output_path(&self) -> OutputPath {
		if self.is_path() {
			let mut segments = Vec::new();
			self.segments(&mut segments);
			return path_output(&segments);
		}
		match self {
			LogicalExpr::Param(param) => OutputPath::field(param.as_str()),
			LogicalExpr::Call(call) => OutputPath::field(function_name(&call.receiver).as_str()),
			LogicalExpr::Literal(LogicalLiteral::String(s)) => OutputPath::field(s.as_str()),
			LogicalExpr::Literal(LogicalLiteral::Datetime(d)) => OutputPath::field(d.to_string()),
			// The path forms are named above; `is_path` covers all of them.
			LogicalExpr::Literal(_)
			| LogicalExpr::Array(_)
			| LogicalExpr::Set(_)
			| LogicalExpr::Object(_)
			| LogicalExpr::RecordId(_)
			| LogicalExpr::Table(_)
			| LogicalExpr::Mock(_)
			| LogicalExpr::Constant(_)
			| LogicalExpr::Prefix {
				..
			}
			| LogicalExpr::Postfix {
				..
			}
			| LogicalExpr::Invoke {
				..
			}
			| LogicalExpr::Binary {
				..
			}
			| LogicalExpr::Closure(_)
			| LogicalExpr::If(_)
			| LogicalExpr::Throw(_)
			| LogicalExpr::Break
			| LogicalExpr::Continue
			| LogicalExpr::Subquery(_)
			| LogicalExpr::Field(_)
			| LogicalExpr::Doc
			| LogicalExpr::Current
			| LogicalExpr::Access {
				..
			}
			| LogicalExpr::Index {
				..
			}
			| LogicalExpr::First(_)
			| LogicalExpr::Last(_)
			| LogicalExpr::Each(_)
			| LogicalExpr::Flatten {
				..
			}
			| LogicalExpr::Filter {
				..
			}
			| LogicalExpr::Method {
				..
			}
			| LogicalExpr::Destructure {
				..
			}
			| LogicalExpr::Optional {
				..
			}
			| LogicalExpr::Lookup {
				..
			}
			| LogicalExpr::Recurse(_)
			| LogicalExpr::RepeatRecurse(_)
			| LogicalExpr::Broadcast {
				..
			}
			| LogicalExpr::SetField {
				..
			} => OutputPath::field(self.to_sql()),
		}
	}

	/// Whether the name [`Self::output_path`] derives is spelled from the
	/// rendering of a statement in scalar position.
	///
	/// True for a [`Self::Subquery`] or [`Self::If`], for an expression named
	/// by its rendering that holds one anywhere, and for a path whose
	/// starting expression or whose lookups hold one, since those render into
	/// the path's name. False for the shapes whose name never renders a
	/// nested expression, whatever they hold: a parameter, a call, a string
	/// or datetime literal, a path named by its field reads alone, and a path
	/// named by a lookup alias.
	pub fn output_name_renders_a_statement(&self) -> bool {
		let is_statement =
			|expr: &LogicalExpr| matches!(expr, LogicalExpr::Subquery(_) | LogicalExpr::If(_));
		if self.is_path() {
			let mut segments = Vec::new();
			self.segments(&mut segments);
			if segments
				.iter()
				.any(|segment| matches!(segment, Segment::Lookup(lookup) if lookup.alias.is_some()))
			{
				return false;
			}
			return segments.iter().any(|segment| match segment {
				Segment::Start(start) => start.any(is_statement),
				Segment::Lookup(lookup) => {
					let mut found = false;
					lookup.for_each_expr(&mut |expr| found = found || expr.any(is_statement));
					found
				}
				Segment::Field(_) | Segment::Other => false,
			});
		}
		match self {
			LogicalExpr::Param(_)
			| LogicalExpr::Call(_)
			| LogicalExpr::Literal(
				LogicalLiteral::String(_)
				| LogicalLiteral::Datetime(_)
				| LogicalLiteral::Date(_)
				| LogicalLiteral::Time(_)
				| LogicalLiteral::Timestamp(_)
				| LogicalLiteral::Interval(_),
			) => false,
			LogicalExpr::Subquery(_) | LogicalExpr::If(_) => true,
			// The path forms were handled above; every other form is named by
			// its rendering.
			LogicalExpr::Literal(_)
			| LogicalExpr::Array(_)
			| LogicalExpr::Set(_)
			| LogicalExpr::Object(_)
			| LogicalExpr::RecordId(_)
			| LogicalExpr::Table(_)
			| LogicalExpr::Mock(_)
			| LogicalExpr::Constant(_)
			| LogicalExpr::Prefix {
				..
			}
			| LogicalExpr::Postfix {
				..
			}
			| LogicalExpr::Invoke {
				..
			}
			| LogicalExpr::Binary {
				..
			}
			| LogicalExpr::Closure(_)
			| LogicalExpr::Throw(_)
			| LogicalExpr::Break
			| LogicalExpr::Continue
			| LogicalExpr::Field(_)
			| LogicalExpr::Doc
			| LogicalExpr::Current
			| LogicalExpr::Access {
				..
			}
			| LogicalExpr::Index {
				..
			}
			| LogicalExpr::First(_)
			| LogicalExpr::Last(_)
			| LogicalExpr::Each(_)
			| LogicalExpr::Flatten {
				..
			}
			| LogicalExpr::Filter {
				..
			}
			| LogicalExpr::Method {
				..
			}
			| LogicalExpr::Destructure {
				..
			}
			| LogicalExpr::Optional {
				..
			}
			| LogicalExpr::Lookup {
				..
			}
			| LogicalExpr::Recurse(_)
			| LogicalExpr::RepeatRecurse(_)
			| LogicalExpr::Broadcast {
				..
			}
			| LogicalExpr::SetField {
				..
			} => self.any(is_statement),
		}
	}
}

/// [`LogicalExpr::output_path`] for a linearised path.
fn path_output(segments: &[Segment<'_>]) -> OutputPath {
	// The path is exact when every step became one of the keys.
	let exact_when = |parts: Vec<OutputPathPart>| OutputPath {
		exact: parts.len() == segments.len(),
		parts,
	};
	// A lookup with an alias names the whole path.
	for segment in segments {
		if let Segment::Lookup(lookup) = segment
			&& let Some(alias) = &lookup.alias
		{
			return exact_when(vec![OutputPathPart::Field(alias.name())]);
		}
	}
	let naming: Vec<&Segment<'_>> =
		segments.iter().filter(|s| !matches!(s, Segment::Other)).collect();
	let name = match naming.as_slice() {
		[Segment::Field(name)] => name.as_str().to_owned(),
		_ => {
			let mut out = String::new();
			for (i, segment) in naming.iter().enumerate() {
				match segment {
					Segment::Field(name) if i == 0 => {
						EscapeIdent(name.as_str()).fmt_sql(&mut out, SqlFormat::SingleLine)
					}
					Segment::Field(name) => {
						out.push('.');
						EscapeKwFreeIdent(name.as_str()).fmt_sql(&mut out, SqlFormat::SingleLine);
					}
					Segment::Start(start) => fmt_start(start, &mut out, SqlFormat::SingleLine),
					Segment::Lookup(lookup) => lookup.fmt_sql(&mut out, SqlFormat::SingleLine),
					Segment::Other => {}
				}
			}
			out
		}
	};
	if naming.is_empty() || naming.iter().any(|s| matches!(s, Segment::Start(_))) {
		return exact_when(vec![OutputPathPart::Field(name)]);
	}
	exact_when(
		naming
			.iter()
			.filter_map(|segment| match segment {
				Segment::Field(name) => Some(OutputPathPart::Field(name.as_str().to_owned())),
				Segment::Lookup(lookup) => Some(OutputPathPart::Lookup(lookup.to_sql())),
				Segment::Start(_) | Segment::Other => None,
			})
			.collect(),
	)
}

/// The name a function call projects as, `fn::name` for a user function and
/// the bare name for a builtin.
fn function_name(function: &Function) -> Strand {
	let mut parts = function.to_idiom().0.into_iter();
	if let Some(crate::expr::Part::Field(name)) = parts.next() {
		name
	} else {
		Strand::new("function")
	}
}

// ---------------------------------------------------------------------------
// Rendering
// ---------------------------------------------------------------------------

/// Renders a scalar in a position where a statement-shaped one would be
/// ambiguous, parenthesising it. An `IF` is the one such shape; a
/// [`LogicalExpr::Subquery`] renders with its own parentheses.
struct Cover<'a>(&'a LogicalExpr);

impl ToSql for Cover<'_> {
	fn fmt_sql(&self, f: &mut String, fmt: SqlFormat) {
		if let LogicalExpr::If(_) = self.0 {
			f.push('(');
			self.0.fmt_sql(f, fmt);
			f.push(')');
		} else {
			self.0.fmt_sql(f, fmt);
		}
	}
}

impl LogicalExpr {
	/// Whether the expression must be parenthesised when it is an operand.
	fn needs_parentheses(&self) -> bool {
		match self {
			LogicalExpr::Literal(LogicalLiteral::UnboundedRange)
			| LogicalExpr::RecordId(_)
			| LogicalExpr::Closure(_)
			| LogicalExpr::Break
			| LogicalExpr::Continue
			| LogicalExpr::Throw(_)
			| LogicalExpr::If(_)
			| LogicalExpr::Postfix {
				..
			}
			| LogicalExpr::Invoke {
				..
			} => true,
			LogicalExpr::Literal(_)
			| LogicalExpr::Array(_)
			| LogicalExpr::Set(_)
			| LogicalExpr::Object(_)
			| LogicalExpr::Param(_)
			| LogicalExpr::Table(_)
			| LogicalExpr::Mock(_)
			| LogicalExpr::Constant(_)
			| LogicalExpr::Field(_)
			| LogicalExpr::Doc
			| LogicalExpr::Current
			| LogicalExpr::Access {
				..
			}
			| LogicalExpr::Index {
				..
			}
			| LogicalExpr::First(_)
			| LogicalExpr::Last(_)
			| LogicalExpr::Each(_)
			| LogicalExpr::Flatten {
				..
			}
			| LogicalExpr::Filter {
				..
			}
			| LogicalExpr::Method {
				..
			}
			| LogicalExpr::Destructure {
				..
			}
			| LogicalExpr::Optional {
				..
			}
			| LogicalExpr::Lookup {
				..
			}
			| LogicalExpr::Recurse(_)
			| LogicalExpr::RepeatRecurse(_)
			| LogicalExpr::Broadcast {
				..
			}
			| LogicalExpr::Prefix {
				..
			}
			| LogicalExpr::Binary {
				..
			}
			| LogicalExpr::SetField {
				..
			}
			| LogicalExpr::Call(_)
			| LogicalExpr::Subquery(_) => false,
		}
	}

	/// The step that renders first in a path: the innermost step whose base
	/// is [`Self::Current`], looking through a [`Self::Broadcast`] over the
	/// row into its body. `None` for a path rooted in a field, `@` or a
	/// starting expression, since those render first themselves.
	fn leading_step(&self) -> Option<&LogicalExpr> {
		let mut current = self;
		loop {
			if let LogicalExpr::Broadcast {
				base,
				body,
				..
			} = current && matches!(**base, LogicalExpr::Current)
			{
				current = body;
				continue;
			}
			match current.step_base() {
				Some(LogicalExpr::Current) => return Some(current),
				Some(base) => current = base,
				None => return None,
			}
		}
	}

	/// Whether the leftmost token of the rendering is a minus sign, so that a
	/// negation in front of it must be parenthesised to avoid `--`.
	fn has_left_minus(&self) -> bool {
		match self {
			LogicalExpr::Prefix {
				op: PrefixOperator::Negate,
				..
			} => true,
			LogicalExpr::Postfix {
				expr,
				..
			}
			| LogicalExpr::Binary {
				left: expr,
				..
			}
			| LogicalExpr::Invoke {
				target: expr,
				..
			} => expr.has_left_minus(),
			LogicalExpr::Literal(LogicalLiteral::Integer(x)) => x.is_negative(),
			LogicalExpr::Literal(LogicalLiteral::Float(x)) => x.is_sign_negative(),
			LogicalExpr::Literal(LogicalLiteral::Decimal(x)) => x.is_sign_negative(),
			LogicalExpr::Literal(LogicalLiteral::I8(x)) => x.is_negative(),
			LogicalExpr::Literal(LogicalLiteral::I16(x)) => x.is_negative(),
			LogicalExpr::Literal(LogicalLiteral::I32(x)) => x.is_negative(),
			LogicalExpr::Literal(LogicalLiteral::F16(x)) => x.is_finite() && x.is_sign_negative(),
			LogicalExpr::Literal(LogicalLiteral::F32(x)) => x.is_finite() && x.is_sign_negative(),
			// A path starting with an outgoing lookup renders `->` first.
			LogicalExpr::Field(_)
			| LogicalExpr::Doc
			| LogicalExpr::Current
			| LogicalExpr::Access {
				..
			}
			| LogicalExpr::Index {
				..
			}
			| LogicalExpr::First(_)
			| LogicalExpr::Last(_)
			| LogicalExpr::Each(_)
			| LogicalExpr::Flatten {
				..
			}
			| LogicalExpr::Filter {
				..
			}
			| LogicalExpr::Method {
				..
			}
			| LogicalExpr::Destructure {
				..
			}
			| LogicalExpr::Optional {
				..
			}
			| LogicalExpr::Lookup {
				..
			}
			| LogicalExpr::Recurse(_)
			| LogicalExpr::RepeatRecurse(_)
			| LogicalExpr::Broadcast {
				..
			} => matches!(
				self.leading_step(),
				Some(LogicalExpr::Lookup { lookup, .. })
					if lookup.kind == LookupKind::Graph(crate::expr::Dir::Out)
			),
			LogicalExpr::Literal(_)
			| LogicalExpr::Array(_)
			| LogicalExpr::Set(_)
			| LogicalExpr::Object(_)
			| LogicalExpr::RecordId(_)
			| LogicalExpr::Param(_)
			| LogicalExpr::Table(_)
			| LogicalExpr::Mock(_)
			| LogicalExpr::Constant(_)
			| LogicalExpr::SetField {
				..
			}
			| LogicalExpr::Prefix {
				..
			}
			| LogicalExpr::Call(_)
			| LogicalExpr::Closure(_)
			| LogicalExpr::If(_)
			| LogicalExpr::Throw(_)
			| LogicalExpr::Break
			| LogicalExpr::Continue
			| LogicalExpr::Subquery(_) => false,
		}
	}

	/// Whether the rendering starts with a path, which a closure body must
	/// parenthesise so `->` is not read as a return-kind arrow.
	fn has_left_idiom(&self) -> bool {
		match self {
			LogicalExpr::Postfix {
				expr,
				..
			}
			| LogicalExpr::Binary {
				left: expr,
				..
			}
			| LogicalExpr::Invoke {
				target: expr,
				..
			} => expr.has_left_idiom(),
			LogicalExpr::Literal(_)
			| LogicalExpr::Array(_)
			| LogicalExpr::Set(_)
			| LogicalExpr::Object(_)
			| LogicalExpr::RecordId(_)
			| LogicalExpr::Param(_)
			| LogicalExpr::Table(_)
			| LogicalExpr::Mock(_)
			| LogicalExpr::Constant(_)
			| LogicalExpr::SetField {
				..
			}
			| LogicalExpr::Prefix {
				..
			}
			| LogicalExpr::Call(_)
			| LogicalExpr::Closure(_)
			| LogicalExpr::If(_)
			| LogicalExpr::Throw(_)
			| LogicalExpr::Break
			| LogicalExpr::Continue
			| LogicalExpr::Subquery(_) => false,
			LogicalExpr::Field(_)
			| LogicalExpr::Doc
			| LogicalExpr::Current
			| LogicalExpr::Access {
				..
			}
			| LogicalExpr::Index {
				..
			}
			| LogicalExpr::First(_)
			| LogicalExpr::Last(_)
			| LogicalExpr::Each(_)
			| LogicalExpr::Flatten {
				..
			}
			| LogicalExpr::Filter {
				..
			}
			| LogicalExpr::Method {
				..
			}
			| LogicalExpr::Destructure {
				..
			}
			| LogicalExpr::Optional {
				..
			}
			| LogicalExpr::Lookup {
				..
			}
			| LogicalExpr::Recurse(_)
			| LogicalExpr::RepeatRecurse(_)
			| LogicalExpr::Broadcast {
				..
			} => true,
		}
	}

	/// How tightly this expression binds as an operand; `Prime` for anything
	/// that is not itself an operator application.
	fn binding_power(&self) -> BindingPower {
		match self {
			LogicalExpr::Prefix {
				op,
				..
			} => {
				if let PrefixOperator::Range | PrefixOperator::RangeInclusive = op {
					BindingPower::Range
				} else {
					BindingPower::Prefix
				}
			}
			LogicalExpr::Postfix {
				op,
				..
			} => op.binding_power(),
			LogicalExpr::Invoke {
				..
			} => BindingPower::Call,
			LogicalExpr::Binary {
				op,
				..
			} => BindingPower::for_binary_operator(op),
			LogicalExpr::Literal(_)
			| LogicalExpr::Array(_)
			| LogicalExpr::Set(_)
			| LogicalExpr::Object(_)
			| LogicalExpr::RecordId(_)
			| LogicalExpr::Param(_)
			| LogicalExpr::Table(_)
			| LogicalExpr::Mock(_)
			| LogicalExpr::Constant(_)
			| LogicalExpr::Field(_)
			| LogicalExpr::Doc
			| LogicalExpr::Current
			| LogicalExpr::Access {
				..
			}
			| LogicalExpr::Index {
				..
			}
			| LogicalExpr::First(_)
			| LogicalExpr::Last(_)
			| LogicalExpr::Each(_)
			| LogicalExpr::Flatten {
				..
			}
			| LogicalExpr::Filter {
				..
			}
			| LogicalExpr::Method {
				..
			}
			| LogicalExpr::Destructure {
				..
			}
			| LogicalExpr::Optional {
				..
			}
			| LogicalExpr::Lookup {
				..
			}
			| LogicalExpr::Recurse(_)
			| LogicalExpr::RepeatRecurse(_)
			| LogicalExpr::Broadcast {
				..
			}
			| LogicalExpr::Call(_)
			| LogicalExpr::Closure(_)
			| LogicalExpr::If(_)
			| LogicalExpr::Throw(_)
			| LogicalExpr::Break
			| LogicalExpr::Continue
			| LogicalExpr::SetField {
				..
			}
			| LogicalExpr::Subquery(_) => BindingPower::Prime,
		}
	}
}

impl LogicalPostfixOperator {
	fn binding_power(&self) -> BindingPower {
		match self {
			LogicalPostfixOperator::Range | LogicalPostfixOperator::RangeSkip => {
				BindingPower::Range
			}
		}
	}
}

/// Writes the indentation of the line closing a pretty-printed bracket: one
/// level less than the contents.
fn write_closing_indent(f: &mut String, fmt: SqlFormat) {
	if let SqlFormat::Indented(level) = fmt
		&& level > 0
	{
		for _ in 0..(level - 1) {
			f.push('\t');
		}
	}
}

fn fmt_object_entries(entries: &[(String, LogicalExpr)], f: &mut String, fmt: SqlFormat) {
	if fmt.is_pretty() {
		f.push('{');
	} else {
		f.push_str("{ ");
	}
	if !entries.is_empty() {
		let fmt = fmt.increment();
		if fmt.is_pretty() {
			f.push('\n');
			fmt.write_indent(f);
		}
		for (i, (key, value)) in entries.iter().enumerate() {
			if i > 0 {
				fmt.write_separator(f);
			}
			write_sql!(f, fmt, "{}: {}", EscapeObjectKey(key), Cover(value));
		}
		if fmt.is_pretty() {
			f.push('\n');
			write_closing_indent(f, fmt);
		}
	}
	if fmt.is_pretty() {
		f.push('}');
	} else {
		f.push_str(" }");
	}
}

/// How the innermost step of a body renders when its base is
/// [`LogicalExpr::Current`].
#[derive(Clone, Copy, PartialEq, Eq)]
enum BodyRoot {
	/// With its normal prefix: `.f`, `[e]`, `->e`. The body of a
	/// `Broadcast`, an `Optional` or a `Recurse`.
	Step,
	/// A leading field renders bare, as the first part of an idiom does. A
	/// destructure alias body, which is written as an idiom.
	Bare,
}

/// Renders the expression a path starts from, parenthesised whenever the
/// steps that follow could otherwise bind into it: an operator application,
/// a negative number, or anything that is parenthesised as an operand.
fn fmt_start(start: &LogicalExpr, f: &mut String, fmt: SqlFormat) {
	let negative_number = matches!(start, LogicalExpr::Literal(LogicalLiteral::Decimal(d)) if d.is_sign_negative())
		|| matches!(start, LogicalExpr::Literal(LogicalLiteral::Integer(i)) if i.is_negative())
		|| matches!(start, LogicalExpr::Literal(LogicalLiteral::Float(x)) if x.is_sign_negative())
		|| matches!(start, LogicalExpr::Literal(LogicalLiteral::I8(i)) if i.is_negative())
		|| matches!(start, LogicalExpr::Literal(LogicalLiteral::I16(i)) if i.is_negative())
		|| matches!(start, LogicalExpr::Literal(LogicalLiteral::I32(i)) if i.is_negative())
		|| matches!(start, LogicalExpr::Literal(LogicalLiteral::F16(x)) if x.is_finite() && x.is_sign_negative())
		|| matches!(start, LogicalExpr::Literal(LogicalLiteral::F32(x)) if x.is_finite() && x.is_sign_negative());
	if start.needs_parentheses()
		|| matches!(
			start,
			LogicalExpr::Binary { .. }
				| LogicalExpr::Prefix { .. }
				| LogicalExpr::Postfix { .. }
				| LogicalExpr::Invoke { .. }
		) || negative_number
	{
		write_sql!(f, fmt, "({start})");
	} else {
		start.fmt_sql(f, fmt);
	}
}

/// Renders a path: its root, then each step with its prefix, then the bodies
/// it holds. The steps of a chain are rendered iteratively so that a long
/// idiom does not recurse once per step.
/// Whether parsing this step directly onto a field access would attach it to
/// the access's elements rather than to the access's own value.
///
/// [`LogicalExpr::Access`] itself does not: `a.b.c` and `(a.b).c` are one
/// expression, and so is `.*`, which takes the access's value whole. Every
/// other step reads as the body of a broadcast over the access, which is a
/// different expression from the same step applied to the access's result.
fn binds_onto_a_broadcast(step: &LogicalExpr) -> bool {
	// Stated as the exceptions, so a step form added later is grouped rather
	// than run together with what precedes it. That is the safe default: a
	// grouping that was not needed still reads back as the same expression,
	// where a missing one does not.
	!matches!(step, LogicalExpr::Access { .. } | LogicalExpr::Each(_) | LogicalExpr::Flatten { .. })
}

fn fmt_path(expr: &LogicalExpr, f: &mut String, fmt: SqlFormat, root: BodyRoot) {
	// Where this path's text begins, so a step that must not extend the chain
	// to its left can parenthesise everything emitted so far.
	let start = f.len();
	// Collect the chain from the outermost step down to its root.
	let mut steps = Vec::new();
	let mut current = expr;
	// A fold whose base is itself a path folds over what that whole path
	// produces, so the base is a group whose parentheses have to survive:
	// rendered flat, `(a.b).c[0]` reads back as `a.b.c[0]`, which folds over
	// `a` and maps `.b` inside it instead — a different plan over the same
	// steps.
	//
	// Only a base ending in a step that a following fold would take for its
	// own needs them. A mapping step is one, and so is a fold already placed;
	// every other step stays attached to the root it was written on when the
	// path is read back, and reads the same flat. Neither does a base rooted
	// at the element need them: it continues the path its body is already
	// inside rather than standing on its own.
	let mut grouped = false;
	let root_expr = loop {
		if let LogicalExpr::Broadcast {
			base,
			..
		} = current
			// A mapping step, which a following fold would take for its own,
			// or a fold already placed over a path. A fold whose body is not a
			// path renders as a plan form with no surface spelling, which no
			// parentheses make readable back.
			&& (matches!(
				base.as_ref(),
				LogicalExpr::Access { .. } | LogicalExpr::Destructure { .. }
			) || matches!(
				base.as_ref(),
				LogicalExpr::Broadcast { body, .. } if body.step_base().is_some()
			)) && !matches!(base.path_root(), LogicalExpr::Current)
		{
			steps.push(current);
			grouped = true;
			break base.as_ref();
		}
		match current.step_base() {
			Some(base) => {
				steps.push(current);
				current = base;
			}
			None => break current,
		}
	};
	// The root.
	if grouped {
		write_sql!(f, fmt, "({root_expr})");
	} else if let LogicalExpr::Field(name) = root_expr {
		EscapeIdent(name.as_str()).fmt_sql(f, fmt);
	} else if matches!(root_expr, LogicalExpr::Doc) {
		f.push('@');
	} else if !matches!(root_expr, LogicalExpr::Current) {
		fmt_start(root_expr, f, fmt);
	}
	// A bare leading field applies to the step directly on `Current`, which
	// is the innermost one; a broadcast over `Current` passes the mode on to
	// its body.
	let mut root = root;
	let on_current = matches!(root_expr, LogicalExpr::Current);
	// Whether the step just emitted was a field access. Parsing a step onto a
	// bare field access broadcasts — `a.b[0]` indexes each element of `a.b`,
	// not the array it is — so a chain that does *not* broadcast has to group
	// what came before it or its own text would read back as the broadcasting
	// form. A body over `Current` is the inside of a broadcast already, so the
	// question does not arise there.
	//
	// Every group a chain needs opens at the same place — each wraps all the
	// text emitted before it, so the groups nest and their opening
	// parentheses sit together at the start. Count them first and write that
	// run once, rather than shifting the whole path along for each one: a
	// chain of n steps would otherwise cost O(n^2) to render.
	let groups = if on_current {
		0
	} else {
		let mut after_access = false;
		let mut groups = 0usize;
		for step in steps.iter().rev() {
			if after_access && binds_onto_a_broadcast(step) {
				groups += 1;
			}
			after_access = matches!(step, LogicalExpr::Access { .. });
		}
		groups
	};
	if groups > 0 {
		f.insert_str(start, &"(".repeat(groups));
	}
	let mut after_access = false;
	for (i, step) in steps.iter().rev().enumerate() {
		let innermost = i == 0 && on_current;
		if after_access && !on_current && binds_onto_a_broadcast(step) {
			f.push(')');
		}
		after_access = matches!(step, LogicalExpr::Access { .. });
		match step {
			LogicalExpr::Access {
				field,
				..
			} => {
				if innermost && root == BodyRoot::Bare {
					EscapeIdent(field.as_str()).fmt_sql(f, fmt);
				} else {
					write_sql!(f, fmt, ".{}", EscapeKwFreeIdent(field.as_str()));
				}
				root = BodyRoot::Step;
			}
			LogicalExpr::Index {
				index,
				..
			} => {
				write_sql!(f, fmt, "[{index}]");
				root = BodyRoot::Step;
			}
			LogicalExpr::First(_) => {
				f.push_str("[0]");
				root = BodyRoot::Step;
			}
			LogicalExpr::Last(_) => {
				f.push_str("[$]");
				root = BodyRoot::Step;
			}
			LogicalExpr::Each(_) => {
				f.push_str(".*");
				root = BodyRoot::Step;
			}
			LogicalExpr::Flatten {
				explicit,
				..
			} => {
				if *explicit {
					f.push('…');
				}
				root = BodyRoot::Step;
			}
			LogicalExpr::Filter {
				predicate,
				..
			} => {
				write_sql!(f, fmt, "[WHERE {predicate}]");
				root = BodyRoot::Step;
			}
			LogicalExpr::Method {
				name,
				args,
				..
			} => {
				write_sql!(
					f,
					fmt,
					".{}({})",
					EscapeKwFreeIdent(name.as_str()),
					Fmt::comma_separated(args.iter().map(Cover))
				);
				root = BodyRoot::Step;
			}
			LogicalExpr::Destructure {
				fields,
				..
			} => {
				fmt_destructure(fields, f, fmt);
				root = BodyRoot::Step;
			}
			LogicalExpr::Lookup {
				lookup,
				..
			} => {
				lookup.fmt_sql(f, fmt);
				root = BodyRoot::Step;
			}
			LogicalExpr::RepeatRecurse(_) => {
				f.push_str(".@");
				root = BodyRoot::Step;
			}
			LogicalExpr::Optional {
				then,
				..
			} => {
				f.push_str(".?");
				fmt_path(then, f, fmt, BodyRoot::Step);
				root = BodyRoot::Step;
			}
			LogicalExpr::Recurse(recurse) => {
				write_sql!(f, fmt, ".{{{}", recurse.recurse);
				if let Some(instruction) = &recurse.instruction {
					write_sql!(f, fmt, "+{instruction}");
				}
				f.push('}');
				match &recurse.path {
					Some(LogicalRecursePath::Nested(body)) => {
						f.push('(');
						fmt_path(body, f, fmt, BodyRoot::Step);
						f.push(')');
					}
					Some(LogicalRecursePath::Trailing(body)) => {
						fmt_path(body, f, fmt, BodyRoot::Step)
					}
					None => {}
				}
				root = BodyRoot::Step;
			}
			LogicalExpr::Broadcast {
				body,
				..
			} => {
				// Over the row, the body's leading step is the path's
				// leading step and keeps the mode; over anything else the
				// body continues a path already begun.
				let body_root = if innermost {
					root
				} else {
					BodyRoot::Step
				};
				fmt_path(body, f, fmt, body_root);
				root = BodyRoot::Step;
			}
			// `step_base` answers `None` for every other form, so none is
			// collected as a step.
			LogicalExpr::Field(_)
			| LogicalExpr::Doc
			| LogicalExpr::Current
			| LogicalExpr::Literal(_)
			| LogicalExpr::Array(_)
			| LogicalExpr::Set(_)
			| LogicalExpr::Object(_)
			| LogicalExpr::RecordId(_)
			| LogicalExpr::Param(_)
			| LogicalExpr::Table(_)
			| LogicalExpr::Mock(_)
			| LogicalExpr::Constant(_)
			| LogicalExpr::Prefix {
				..
			}
			| LogicalExpr::Postfix {
				..
			}
			| LogicalExpr::Invoke {
				..
			}
			| LogicalExpr::Binary {
				..
			}
			| LogicalExpr::Call(_)
			| LogicalExpr::Closure(_)
			| LogicalExpr::If(_)
			| LogicalExpr::Throw(_)
			| LogicalExpr::Break
			| LogicalExpr::Continue
			| LogicalExpr::SetField {
				..
			}
			| LogicalExpr::Subquery(_) => {}
		}
	}
}

/// Renders `.{ … }`.
fn fmt_destructure(fields: &[LogicalDestructureField], f: &mut String, fmt: SqlFormat) {
	f.push_str(".{");
	if !fmt.is_pretty() {
		f.push(' ');
	}
	if !fields.is_empty() {
		let fmt = fmt.increment();
		write_sql!(f, fmt, "{}", Fmt::pretty_comma_separated(fields));
	}
	if fmt.is_pretty() {
		f.push('}');
	} else {
		f.push_str(" }");
	}
}

impl ToSql for LogicalExpr {
	fn fmt_sql(&self, f: &mut String, fmt: SqlFormat) {
		match self {
			LogicalExpr::Literal(literal) => literal.fmt_sql(f, fmt),
			LogicalExpr::Array(items) => {
				f.push('[');
				if !items.is_empty() {
					let fmt = fmt.increment();
					if fmt.is_pretty() {
						f.push('\n');
						fmt.write_indent(f);
					}
					for (i, item) in items.iter().enumerate() {
						if i > 0 {
							fmt.write_separator(f);
						}
						Cover(item).fmt_sql(f, fmt);
					}
					if fmt.is_pretty() {
						f.push('\n');
						write_closing_indent(f, fmt);
					}
				}
				f.push(']');
			}
			LogicalExpr::Set(items) => {
				f.push('{');
				if !items.is_empty() {
					let fmt = fmt.increment();
					if fmt.is_pretty() {
						f.push('\n');
						fmt.write_indent(f);
					}
					for (i, item) in items.iter().enumerate() {
						if i > 0 {
							fmt.write_separator(f);
						} else if let LogicalExpr::RecordId(_) = item {
							// A leading record id would otherwise read as an
							// object key.
							f.push('(');
							item.fmt_sql(f, fmt);
							f.push(')');
							continue;
						}
						Cover(item).fmt_sql(f, fmt);
					}
					if items.len() == 1 {
						f.push(',');
					}
					if fmt.is_pretty() {
						f.push('\n');
						write_closing_indent(f, fmt);
					}
				} else {
					f.push(',');
				}
				f.push('}');
			}
			LogicalExpr::Object(entries) => fmt_object_entries(entries, f, fmt),
			LogicalExpr::RecordId(rid) => rid.fmt_sql(f, fmt),
			LogicalExpr::Param(param) => param.fmt_sql(f, fmt),
			LogicalExpr::Table(table) => EscapeIdent(table.as_str()).fmt_sql(f, fmt),
			LogicalExpr::Mock(mock) => mock.fmt_sql(f, fmt),
			LogicalExpr::Constant(constant) => constant.fmt_sql(f, fmt),
			LogicalExpr::Field(_)
			| LogicalExpr::Doc
			| LogicalExpr::Current
			| LogicalExpr::Access {
				..
			}
			| LogicalExpr::Index {
				..
			}
			| LogicalExpr::First(_)
			| LogicalExpr::Last(_)
			| LogicalExpr::Each(_)
			| LogicalExpr::Flatten {
				..
			}
			| LogicalExpr::Filter {
				..
			}
			| LogicalExpr::Method {
				..
			}
			| LogicalExpr::Destructure {
				..
			}
			| LogicalExpr::Optional {
				..
			}
			| LogicalExpr::Lookup {
				..
			}
			| LogicalExpr::Recurse(_)
			| LogicalExpr::RepeatRecurse(_)
			| LogicalExpr::Broadcast {
				..
			} => fmt_path(self, f, fmt, BodyRoot::Step),
			// No surface syntax; the rendering is plan text.
			LogicalExpr::SetField {
				base,
				field,
				value,
			} => write_sql!(
				f,
				fmt,
				"set_field({}, {}, {})",
				Cover(base),
				QuoteStr(field.as_str()),
				Cover(value)
			),
			LogicalExpr::Prefix {
				op,
				expr,
			} => {
				let expr: &LogicalExpr = expr;
				let expr_bp = expr.binding_power();
				let op_bp = if let PrefixOperator::Range | PrefixOperator::RangeInclusive = op {
					BindingPower::Range
				} else {
					BindingPower::Prefix
				};
				if expr.needs_parentheses()
					|| expr_bp < op_bp
					|| expr_bp == op_bp && matches!(expr_bp, BindingPower::Range)
					|| *op == PrefixOperator::Negate && expr.has_left_minus()
					// `-1u8` lexes as one (negative, out of range) literal, so a negated
					// unsigned literal keeps its parentheses
					|| *op == PrefixOperator::Negate
						&& matches!(
							expr,
							LogicalExpr::Literal(
								LogicalLiteral::U8(_)
									| LogicalLiteral::U16(_) | LogicalLiteral::U32(_)
									| LogicalLiteral::U64(_)
							)
						) {
					write_sql!(f, fmt, "{op}({expr})");
				} else {
					write_sql!(f, fmt, "{op}{expr}");
				}
			}
			LogicalExpr::Postfix {
				expr,
				op,
			} => {
				let expr: &LogicalExpr = expr;
				let expr_bp = expr.binding_power();
				let op_bp = op.binding_power();
				if expr.needs_parentheses()
					|| expr_bp < op_bp
					|| expr_bp == op_bp && matches!(expr_bp, BindingPower::Range)
				{
					write_sql!(f, fmt, "({expr}){op}");
				} else {
					write_sql!(f, fmt, "{expr}{op}");
				}
			}
			// The target is always parenthesised, so `$f(1)` and `(a.b)(1)`
			// both read back as an application of the whole target.
			LogicalExpr::Invoke {
				target,
				args,
			} => {
				let target: &LogicalExpr = target;
				write_sql!(f, fmt, "({target})");
				write_sql!(f, fmt, "({})", Fmt::comma_separated(args.iter().map(Cover)));
			}
			LogicalExpr::Binary {
				left,
				op,
				right,
			} => {
				let left: &LogicalExpr = left;
				let right: &LogicalExpr = right;
				let op_bp = self.binding_power();
				let left_bp = left.binding_power();
				let right_bp = right.binding_power();

				// A same-power left child under a left-associative operator
				// is the default nesting and needs no parentheses; under a
				// right-associative one (`**`), or a non-associative one, it
				// only exists because it was written parenthesised.
				if left.needs_parentheses()
					|| left_bp < op_bp
					|| left_bp == op_bp
						&& matches!(
							left_bp,
							BindingPower::Range
								| BindingPower::Relation | BindingPower::Equality
								| BindingPower::Power
						) || matches!(op, BinaryOperator::Matches(_))
					&& left_bp == BindingPower::Relation
				{
					write_sql!(f, fmt, "({left})");
				} else {
					write_sql!(f, fmt, "{left}");
				}

				if matches!(
					op,
					BinaryOperator::Range
						| BinaryOperator::RangeSkip
						| BinaryOperator::RangeInclusive
						| BinaryOperator::RangeSkipInclusive
				) {
					op.fmt_sql(f, fmt);
				} else {
					f.push(' ');
					op.fmt_sql(f, fmt);
					f.push(' ');
				}

				// The mirror image: a same-power right child under a
				// left-associative operator was written parenthesised.
				if right.needs_parentheses()
					|| right_bp < op_bp
					|| right_bp == op_bp
						&& matches!(
							right_bp,
							BindingPower::Nullish
								| BindingPower::Range | BindingPower::Relation
								| BindingPower::Equality | BindingPower::AddSub
								| BindingPower::MulDiv
						) || matches!(op, BinaryOperator::Matches(_))
					&& right_bp == BindingPower::Relation
				{
					write_sql!(f, fmt, "({right})");
				} else {
					write_sql!(f, fmt, "{right}");
				}
			}
			LogicalExpr::Call(call) => call.fmt_sql(f, fmt),
			LogicalExpr::Closure(closure) => closure.fmt_sql(f, fmt),
			LogicalExpr::If(branches) => branches.fmt_sql(f, fmt),
			LogicalExpr::Throw(expr) => write_sql!(f, fmt, "THROW {}", Cover(expr)),
			LogicalExpr::Break => f.push_str("BREAK"),
			LogicalExpr::Continue => f.push_str("CONTINUE"),
			// The plan, parenthesised, one operator per line. The enclosing
			// operator's renderer re-indents the continuation lines beneath
			// itself, so the plan reads as a nested source does.
			LogicalExpr::Subquery(op) => {
				f.push_str("(\n");
				op.render(f, 1);
				f.push(')');
			}
		}
	}
}

impl Display for LogicalExpr {
	fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
		f.write_str(&self.to_sql())
	}
}

impl ToSql for LogicalPostfixOperator {
	fn fmt_sql(&self, f: &mut String, _fmt: SqlFormat) {
		match self {
			LogicalPostfixOperator::Range => f.push_str(".."),
			LogicalPostfixOperator::RangeSkip => f.push_str(">.."),
		}
	}
}

impl ToSql for LogicalRecordIdLit {
	fn fmt_sql(&self, f: &mut String, fmt: SqlFormat) {
		write_sql!(f, fmt, "{}:{}", EscapeIdent(self.table.as_str()), self.key);
	}
}

impl ToSql for LogicalRecordIdKey {
	fn fmt_sql(&self, f: &mut String, fmt: SqlFormat) {
		match self {
			LogicalRecordIdKey::Number(v) => write_sql!(f, fmt, "{v}"),
			LogicalRecordIdKey::String(v) => EscapeRidKey(v).fmt_sql(f, fmt),
			LogicalRecordIdKey::Uuid(v) => write_sql!(f, fmt, "u{}", QuoteStr(&v.to_string())),
			LogicalRecordIdKey::Array(items) => {
				f.push('[');
				if !items.is_empty() {
					let fmt = fmt.increment();
					write_sql!(f, fmt, "{}", Fmt::pretty_comma_separated(items.iter().map(Cover)));
				}
				f.push(']');
			}
			LogicalRecordIdKey::Object(entries) => {
				if fmt.is_pretty() {
					f.push('{');
				} else {
					f.push_str("{ ");
				}
				if !entries.is_empty() {
					let fmt = fmt.increment();
					write_sql!(
						f,
						fmt,
						"{}",
						Fmt::pretty_comma_separated(entries.iter().map(|(key, value)| Fmt::new(
							(key, value),
							|(key, value), f, fmt| write_sql!(
								f,
								fmt,
								"{}: {}",
								EscapeObjectKey(key),
								Cover(value)
							)
						)))
					);
				}
				if fmt.is_pretty() {
					f.push('}');
				} else {
					f.push_str(" }");
				}
			}
			LogicalRecordIdKey::Generate(generator) => match generator {
				RecordIdKeyGen::Rand => f.push_str("rand()"),
				RecordIdKeyGen::Ulid => f.push_str("ulid()"),
				RecordIdKeyGen::Uuid => f.push_str("uuid()"),
			},
			LogicalRecordIdKey::Range(range) => range.fmt_sql(f, fmt),
		}
	}
}

impl ToSql for LogicalRecordIdKeyRange {
	fn fmt_sql(&self, f: &mut String, fmt: SqlFormat) {
		match &self.start {
			Bound::Unbounded => {}
			Bound::Included(v) => v.fmt_sql(f, fmt),
			Bound::Excluded(v) => {
				v.fmt_sql(f, fmt);
				f.push('>');
			}
		}
		match &self.end {
			Bound::Unbounded => f.push_str(".."),
			Bound::Excluded(v) => {
				f.push_str("..");
				v.fmt_sql(f, fmt);
			}
			Bound::Included(v) => {
				f.push_str("..=");
				v.fmt_sql(f, fmt);
			}
		}
	}
}

impl ToSql for LogicalDestructureField {
	fn fmt_sql(&self, f: &mut String, fmt: SqlFormat) {
		match self {
			LogicalDestructureField::All(name) => {
				write_sql!(f, fmt, "{}.*", EscapeKwFreeIdent(name.as_str()))
			}
			LogicalDestructureField::Field(name) => {
				write_sql!(f, fmt, "{}", EscapeKwFreeIdent(name.as_str()))
			}
			// The body is written as an idiom, so its leading field is bare.
			LogicalDestructureField::Aliased(name, body) => {
				write_sql!(f, fmt, "{}: ", EscapeKwFreeIdent(name.as_str()));
				fmt_path(body, f, fmt, BodyRoot::Bare);
			}
			LogicalDestructureField::Destructure(name, fields) => {
				write_sql!(f, fmt, "{}", EscapeKwFreeIdent(name.as_str()));
				fmt_destructure(fields, f, fmt);
			}
			LogicalDestructureField::Rest => f.push_str("..."),
		}
	}
}

impl ToSql for LogicalRecurseInstruction {
	fn fmt_sql(&self, f: &mut String, fmt: SqlFormat) {
		match self {
			LogicalRecurseInstruction::Path {
				inclusive,
			} => {
				f.push_str("path");
				if *inclusive {
					f.push_str("+inclusive");
				}
			}
			LogicalRecurseInstruction::Collect {
				inclusive,
			} => {
				f.push_str("collect");
				if *inclusive {
					f.push_str("+inclusive");
				}
			}
			LogicalRecurseInstruction::Shortest {
				expects,
				inclusive,
			} => {
				write_sql!(f, fmt, "shortest={expects}");
				if *inclusive {
					f.push_str("+inclusive");
				}
			}
		}
	}
}

impl ToSql for LogicalLookup {
	fn fmt_sql(&self, f: &mut String, fmt: SqlFormat) {
		// The short form `->edge` is only unambiguous for a single subject
		// with no clauses, no referencing field and no open-ended range.
		let short = self.what.len() <= 1
			&& self.what.iter().all(|subject| {
				subject.referencing_field().is_none()
					&& !matches!(
						subject,
						LogicalLookupSubject::Range {
							range: LogicalRecordIdKeyRange {
								end: Bound::Unbounded,
								..
							},
							..
						}
					)
			}) && self.cond.is_none()
			&& self.alias.is_none()
			&& self.expr.is_none();
		if short {
			self.kind.fmt_sql(f, fmt);
			if self.what.is_empty() {
				f.push('?');
			} else {
				write_sql!(f, fmt, "{}", Fmt::comma_separated(self.what.iter()));
			}
			return;
		}
		write_sql!(f, fmt, "{}(", self.kind);
		if let Some(fields) = &self.expr {
			write_sql!(f, fmt, "SELECT {} FROM ", fields);
			if self.only {
				f.push_str("ONLY ");
			}
		}
		if self.what.is_empty() {
			f.push('?');
		} else {
			write_sql!(f, fmt, "{}", Fmt::comma_separated(&self.what));
		}
		if let Some(cond) = &self.cond {
			write_sql!(f, fmt, " WHERE {}", Cover(cond));
		}
		if let Some(split) = &self.split {
			write_sql!(f, fmt, " SPLIT ON {}", Fmt::comma_separated(split));
		}
		if let Some(group) = &self.group {
			if group.is_empty() {
				f.push_str(" GROUP ALL");
			} else {
				write_sql!(f, fmt, " GROUP BY {}", Fmt::comma_separated(group));
			}
		}
		if let Some(order) = &self.order {
			write_sql!(f, fmt, " {order}");
		}
		if let Some(limit) = &self.limit {
			write_sql!(f, fmt, " LIMIT {}", Cover(limit));
		}
		if let Some(start) = &self.start {
			write_sql!(f, fmt, " START {}", Cover(start));
		}
		if let Some(alias) = &self.alias {
			write_sql!(f, fmt, " AS {alias}");
		}
		f.push(')');
	}
}

impl ToSql for LogicalLookupSubject {
	fn fmt_sql(&self, f: &mut String, fmt: SqlFormat) {
		match self {
			LogicalLookupSubject::Table {
				table,
				referencing_field,
			} => {
				write_sql!(f, fmt, "{}", EscapeKwFreeIdent(table.as_str()));
				if let Some(field) = referencing_field {
					write_sql!(f, fmt, " FIELD {}", EscapeKwFreeIdent(field));
				}
			}
			LogicalLookupSubject::Range {
				table,
				range,
				referencing_field,
			} => {
				write_sql!(f, fmt, "{}:{range}", EscapeKwFreeIdent(table.as_str()));
				if let Some(field) = referencing_field {
					write_sql!(f, fmt, " FIELD {}", EscapeKwFreeIdent(field));
				}
			}
		}
	}
}

impl ToSql for LogicalCall {
	fn fmt_sql(&self, f: &mut String, fmt: SqlFormat) {
		let args = || Fmt::comma_separated(self.args.iter().map(Cover));
		match &self.receiver {
			Function::Normal(name) => {
				for (i, segment) in name.split("::").enumerate() {
					if i == 0 {
						write_sql!(f, fmt, "{}", EscapeIdent(segment));
					} else {
						f.push_str("::");
						f.push_str(segment);
					}
				}
			}
			Function::Custom(name) => {
				f.push_str("fn");
				for segment in name.split("::") {
					write_sql!(f, fmt, "::{}", EscapeKwFreeIdent(segment));
				}
			}
			Function::Script(script) => {
				write_sql!(f, fmt, "function({}) {{{}}}", args(), script);
				return;
			}
			Function::Model(model) => write_sql!(f, fmt, "{model}"),
			Function::Module(module, sub, prefix) => {
				write_sql!(f, fmt, "{}::{}", prefix.as_str(), EscapeKwFreeIdent(module));
				if let Some(sub) = sub {
					for segment in sub.split("::") {
						write_sql!(f, fmt, "::{}", EscapeKwFreeIdent(segment));
					}
				}
			}
			Function::Silo {
				org,
				pkg,
				major,
				minor,
				patch,
				sub,
			} => {
				write_sql!(
					f,
					fmt,
					"silo::{}::{}<{major}.{minor}.{patch}>",
					EscapeKwFreeIdent(org),
					EscapeKwFreeIdent(pkg),
				);
				if let Some(sub) = sub {
					for segment in sub.split("::") {
						write_sql!(f, fmt, "::{}", EscapeKwFreeIdent(segment));
					}
				}
			}
		}
		write_sql!(f, fmt, "({})", args());
	}
}

impl ToSql for LogicalClosure {
	fn fmt_sql(&self, f: &mut String, fmt: SqlFormat) {
		f.push('|');
		for (i, (name, kind)) in self.args.iter().enumerate() {
			if i > 0 {
				f.push_str(", ");
			}
			write_sql!(f, fmt, "{name}: ");
			if let Kind::Either(_) = kind {
				write_sql!(f, fmt, "<{kind}>");
			} else {
				write_sql!(f, fmt, "{kind}");
			}
		}
		f.push('|');
		if let Some(returns) = &self.returns {
			write_sql!(f, fmt, " -> {returns}");
		}
		// A body starting with a path is parenthesised so a leading `->` is
		// not read as a return-kind arrow.
		if self.body.has_left_idiom() {
			write_sql!(f, fmt, " ({})", self.body);
		} else {
			write_sql!(f, fmt, " {}", Cover(&self.body));
		}
	}
}

impl ToSql for LogicalIf {
	/// Always the `IF … THEN … ELSE … END` form on one line: a plan has no
	/// bracketed-block form, since a block is a nested plan.
	fn fmt_sql(&self, f: &mut String, fmt: SqlFormat) {
		for (i, (cond, then)) in self.branches.iter().enumerate() {
			if i > 0 {
				f.push_str(" ELSE ");
			}
			write_sql!(f, fmt, "IF {} THEN {then}", Cover(cond));
		}
		if let Some(otherwise) = &self.otherwise {
			write_sql!(f, fmt, " ELSE {}", Cover(otherwise));
		}
		f.push_str(" END");
	}
}

impl ToSql for LogicalFields {
	fn fmt_sql(&self, f: &mut String, fmt: SqlFormat) {
		match self {
			LogicalFields::Value {
				expr,
				alias,
			} => {
				write_sql!(f, fmt, "VALUE {}", Cover(expr));
				if let Some(alias) = alias {
					write_sql!(f, fmt, " AS {alias}");
				}
			}
			LogicalFields::Select(fields) => {
				write_sql!(f, fmt, "{}", Fmt::comma_separated(fields))
			}
		}
	}
}

impl ToSql for LogicalField {
	fn fmt_sql(&self, f: &mut String, fmt: SqlFormat) {
		match self {
			LogicalField::All => f.push('*'),
			// A column's kind and frame are plan text, so a rendered layer
			// shows which values are coerced and which bodies run narrowed.
			LogicalField::Single {
				expr,
				alias,
				kind,
				frame,
			} => {
				write_sql!(f, fmt, "{}", Cover(expr));
				if let Some(alias) = alias {
					write_sql!(f, fmt, " AS {alias}");
				}
				if let Some(kind) = kind {
					write_sql!(f, fmt, " : {kind}");
				}
				if let Some(rendered) = super::render_frame(frame) {
					f.push(' ');
					f.push_str(&rendered);
				}
			}
		}
	}
}

impl ToSql for LogicalOrdering {
	fn fmt_sql(&self, f: &mut String, fmt: SqlFormat) {
		match self {
			LogicalOrdering::Random => f.push_str("ORDER BY RAND()"),
			LogicalOrdering::Order(orders) => {
				write_sql!(f, fmt, "ORDER BY {}", Fmt::comma_separated(orders))
			}
		}
	}
}

impl ToSql for LogicalOrder {
	fn fmt_sql(&self, f: &mut String, fmt: SqlFormat) {
		self.value.fmt_sql(f, fmt);
		if self.collate {
			f.push_str(" COLLATE");
		}
		if self.numeric {
			f.push_str(" NUMERIC");
		}
		if !self.direction {
			f.push_str(" DESC");
		}
	}
}

impl ToSql for SourceRef {
	fn fmt_sql(&self, f: &mut String, fmt: SqlFormat) {
		match self {
			SourceRef::Table(table) => EscapeIdent(table.as_str()).fmt_sql(f, fmt),
			SourceRef::RecordId(rid) => rid.fmt_sql(f, fmt),
			SourceRef::Mock(mock) => mock.fmt_sql(f, fmt),
			SourceRef::Param(param) => param.fmt_sql(f, fmt),
			SourceRef::Dynamic(expr) => expr.fmt_sql(f, fmt),
		}
	}
}

#[cfg(test)]
mod tests {
	use std::convert::Infallible;

	use super::*;

	fn expr(sql: &str) -> LogicalExpr {
		let ast = crate::parser::parse(&format!("RETURN {sql}")).expect("expression should parse");
		let crate::parser::TopLevelExpr::Expr(crate::expr::Expr::Return(out)) =
			ast.expressions.into_iter().next().expect("one statement")
		else {
			panic!("expected a RETURN");
		};
		crate::expr::logical::lower_expr(out.what).expect("expression should lower")
	}

	/// Occurrences of `$p` the walk reaches.
	fn count_p(e: &LogicalExpr) -> usize {
		let mut n = 0;
		let _ = e.visit(&mut |x| {
			if matches!(x, LogicalExpr::Param(p) if p.as_str() == "p") {
				n += 1;
			}
			ControlFlow::<()>::Continue(())
		});
		n
	}

	/// `$p` in every position a scalar nests an expression, with the number of
	/// occurrences the walk must reach. A position the walk skips shows up as
	/// an uncounted parameter.
	fn nested_positions() -> Vec<(&'static str, LogicalExpr, usize)> {
		vec![
			("array elements", expr("[$p, $p]"), 2),
			("set elements", LogicalExpr::Set(vec![expr("$p"), expr("$p")]), 2),
			("object values", expr("{ a: $p, b: $p }"), 2),
			("record-id array key", expr("t:[$p, $p]"), 2),
			("record-id object key", expr("t:{ a: $p }"), 1),
			("record-id range key", expr("t:[$p]..=[$p]"), 2),
			("filter predicate", expr("a[WHERE b = $p]"), 1),
			("index", expr("a[$p]"), 1),
			("path start", expr("$p.a"), 1),
			("method arguments", expr("a.slice($p, $p)"), 2),
			("broadcast body", expr("a.b[$p]"), 1),
			("optional body", expr("a.?.b[$p]"), 1),
			("destructure alias", expr("a.{ b: c[$p] }"), 1),
			("nested destructure", expr("a.{ b.{ c: d[$p] } }"), 1),
			("lookup condition", expr("->(likes WHERE x = $p)"), 1),
			(
				"lookup projection and clauses",
				expr("->(SELECT a[$p] FROM likes WHERE x = $p LIMIT $p START $p)"),
				4,
			),
			("recurse nest", expr("a.{2..}(.b[$p])"), 1),
			("recurse trailing body", expr("a.{2..}.b[$p]"), 1),
			("recurse shortest", expr("a.{1..3+shortest=$p}"), 1),
			("prefix operand", expr("-$p"), 1),
			("cast operand", expr("<int> $p"), 1),
			("postfix operand", expr("$p.."), 1),
			("postfix call arguments", expr("$f($p, $p)"), 2),
			("binary operands", expr("$p + $p"), 2),
			("call arguments", expr("count($p, $p)"), 2),
			("closure body", expr("|$x: int| $x + $p"), 1),
			("if branches", expr("IF $p THEN $p ELSE IF $p THEN $p ELSE $p END"), 5),
			("throw", expr("THROW $p"), 1),
			("set_field base and value", set_field(expr("$p"), "f", expr("$p")), 2),
			("subquery, not entered", expr("[(SELECT * FROM t WHERE a = $p)]"), 0),
		]
	}

	fn set_field(base: LogicalExpr, field: &str, value: LogicalExpr) -> LogicalExpr {
		LogicalExpr::SetField {
			base: Box::new(base),
			field: Strand::new(field),
			value: Box::new(value),
		}
	}

	#[test]
	fn set_field_is_a_value_not_a_path() {
		let guard = set_field(expr("a"), "b", expr("IF p THEN a.b ELSE NONE END"));
		// Not a read of a position: no step base, no root but itself.
		assert!(!guard.is_path());
		assert_eq!(guard.step_base(), None);
		assert_eq!(guard.path_root(), &guard);
		assert!(guard.read_only());
		assert!(!set_field(expr("a"), "b", expr("fn::write()")).read_only());
		// Plan text, since the form has no surface syntax: the key is quoted
		// as a string literal is, so a name containing a quote or a space
		// reads back unambiguously, and the arguments render as a call's do.
		assert_eq!(guard.to_sql(), "set_field(a, 'b', (IF p THEN a.b ELSE NONE END))");
		assert_eq!(set_field(expr("a"), "b", expr("x + 1")).to_sql(), "set_field(a, 'b', x + 1)");
		assert_eq!(set_field(expr("a"), "it's", expr("1")).to_sql(), r#"set_field(a, "it's", 1)"#);
		// A projection names it by its rendering, as any non-path, so a
		// statement inside it renders into the name.
		assert_eq!(guard.output_path(), OutputPath::field(guard.to_sql()));
		assert!(guard.output_name_renders_a_statement());
		assert!(!set_field(expr("a"), "b", expr("x + 1")).output_name_renders_a_statement());
		// The base and the value are its children; the key is a name.
		assert_eq!(guard.children().len(), 2);
	}

	#[test]
	fn the_walk_reaches_every_nested_position_and_stops_at_a_subquery() {
		for (position, e, want) in nested_positions() {
			assert_eq!(count_p(&e), want, "{position}: {e}");
		}
	}

	#[test]
	fn visit_mut_rewrites_the_same_positions() {
		for (position, mut e, want) in nested_positions() {
			let mut rewritten = 0;
			let Ok(()) = e.visit_mut(&mut |x| {
				if matches!(x, LogicalExpr::Param(p) if p.as_str() == "p") {
					*x = LogicalExpr::Literal(LogicalLiteral::Integer(1));
					rewritten += 1;
				}
				Ok::<(), Infallible>(())
			});
			assert_eq!(rewritten, want, "{position}");
			assert_eq!(count_p(&e), 0, "{position}: {e}");
		}
	}

	#[test]
	fn an_identity_transform_rebuilds_the_same_expression() {
		for (position, e, _) in nested_positions() {
			let Ok(rebuilt) = e.clone().transform(&mut Ok::<LogicalExpr, Infallible>);
			assert_eq!(rebuilt, e, "{position}");
		}
	}

	#[test]
	fn a_path_names_its_output_by_its_naming_steps() {
		let field = |name: &str| OutputPathPart::Field(name.into());
		let lookup = |name: &str| OutputPathPart::Lookup(name.into());
		// (path, the keys it lands at, whether it was written as those keys)
		let cases: Vec<(&str, Vec<OutputPathPart>, bool)> = vec![
			("a", vec![field("a")], true),
			("a.b", vec![field("a"), field("b")], true),
			// Steps that select or transform do not name, and make the path
			// inexact.
			("tags[WHERE type = 'x'][0].value", vec![field("tags"), field("value")], false),
			("a[0]", vec![field("a")], false),
			("a[$]", vec![field("a")], false),
			("a.*", vec![field("a")], false),
			("a.?.b", vec![field("a"), field("b")], false),
			("a.len()", vec![field("a")], false),
			("a.{ b, c }", vec![field("a")], false),
			// A trailing recursion body is part of the path; a nested one is
			// not.
			("a.{..}.b", vec![field("a"), field("b")], false),
			("a.{..}(.b)", vec![field("a")], false),
			// Lookups name themselves as they render.
			("->likes->person", vec![lookup("->likes"), lookup("->person")], true),
			(
				"->likes->person.name",
				vec![lookup("->likes"), lookup("->person"), field("name")],
				true,
			),
			// A lookup alias names the whole path.
			("->(likes AS l)->person.name", vec![field("l")], false),
			("->(likes AS l)", vec![field("l")], true),
			// A path from an expression is one key spelled as it renders.
			("$p.a", vec![field("$p.a")], false),
			("(1 + 2).b", vec![field("(1 + 2).b")], false),
			// Non-paths.
			("$p", vec![field("p")], true),
			("count()", vec![field("count")], true),
			("fn::f()", vec![field("fn::f")], true),
			("'x'", vec![field("x")], true),
			("1 + 2", vec![field("1 + 2")], true),
		];
		for (sql, parts, exact) in cases {
			let got = expr(sql).output_path();
			assert_eq!(got.parts(), parts.as_slice(), "output path of `{sql}`");
			assert_eq!(got.exact, exact, "exactness of `{sql}`");
		}
		// The same keys written with and without a non-naming step are
		// distinct paths.
		assert_ne!(expr("a[0]").output_path(), expr("a").output_path());
		assert_eq!(expr("a.b").output_path().name(), "a.b");
		assert_eq!(expr("a").output_path().name(), "a");
		assert_eq!(expr("->likes->person").output_path().name(), "->likes->person");
		assert_eq!(expr("`a.b`").output_path().name(), "a.b");
		assert_eq!(expr("`a.b`").output_path(), OutputPath::field("a.b"));
		assert!(expr("id").output_path().is_field("id"));
	}

	/// A step that would otherwise read as a broadcast over the access before
	/// it groups everything to its left, so a chain of them nests: every
	/// opening parenthesis sits at the path's start, and each closes just
	/// before the step that asked for it.
	///
	/// Asserted over a chain long enough that the text before a group is much
	/// larger than the group itself. The run of openers is written once for
	/// that reason — prepending them one at a time shifts the whole path
	/// already rendered, which costs O(n^2) in the number of steps.
	#[test]
	fn a_chain_of_grouped_steps_opens_all_its_parentheses_at_the_start() {
		// `a`, then a `.<name>[0]` pair per name: each `[0]` sits directly on
		// a field access, so each one groups what precedes it.
		let mut plan = LogicalExpr::Field(Strand::new("a"));
		let mut expected = String::from("a");
		for name in ["b", "c", "d", "e", "g", "h", "i", "j"] {
			plan = LogicalExpr::Access {
				base: Box::new(plan),
				field: Strand::new(name),
			};
			plan = LogicalExpr::Index {
				base: Box::new(plan),
				index: Box::new(LogicalExpr::Literal(LogicalLiteral::Integer(0))),
			};
			expected = format!("({expected}.{name})[0]");
		}
		assert_eq!(plan.to_sql(), expected);
		assert_eq!(expr(&expected), plan, "`{expected}` reads back as a different plan");
	}

	#[test]
	fn a_path_root_is_the_expression_it_starts_from() {
		assert_eq!(expr("a.b[0].c").path_root(), &LogicalExpr::Field(Strand::new("a")));
		assert_eq!(expr("$p.a[0]").path_root(), &expr("$p"));
		assert_eq!(expr("->likes->person").path_root(), &LogicalExpr::Current);
		assert_eq!(expr("1 + 2").path_root(), &expr("1 + 2"));
		assert!(expr("a[0]").is_path());
		assert!(!expr("$p").is_path());
	}

	/// `Eq` is asserted for the literal, so every variant must equal itself.
	/// The hand-written `PartialEq` falls through to `false` for a variant it
	/// does not list, which would break structural comparison silently.
	#[test]
	fn every_literal_variant_equals_itself() {
		// Exhaustive so a new variant fails to compile until it is sampled.
		fn _forces_this_list_to_be_updated(l: &LogicalLiteral) {
			match l {
				LogicalLiteral::None
				| LogicalLiteral::Null
				| LogicalLiteral::UnboundedRange
				| LogicalLiteral::Bool(_)
				| LogicalLiteral::Float(_)
				| LogicalLiteral::Integer(_)
				| LogicalLiteral::Decimal(_)
				| LogicalLiteral::BigDecimal(_)
				| LogicalLiteral::String(_)
				| LogicalLiteral::Bytes(_)
				| LogicalLiteral::Regex(_)
				| LogicalLiteral::Duration(_)
				| LogicalLiteral::Datetime(_)
				| LogicalLiteral::Date(_)
				| LogicalLiteral::Time(_)
				| LogicalLiteral::Timestamp(_)
				| LogicalLiteral::Interval(_)
				| LogicalLiteral::Uuid(_)
				| LogicalLiteral::Geometry(_)
				| LogicalLiteral::File(_)
				| LogicalLiteral::I8(_)
				| LogicalLiteral::U8(_)
				| LogicalLiteral::I16(_)
				| LogicalLiteral::U16(_)
				| LogicalLiteral::I32(_)
				| LogicalLiteral::U32(_)
				| LogicalLiteral::U64(_)
				| LogicalLiteral::F16(_)
				| LogicalLiteral::F32(_) => {}
			}
		}
		let samples = [
			LogicalLiteral::None,
			LogicalLiteral::Null,
			LogicalLiteral::UnboundedRange,
			LogicalLiteral::Bool(true),
			LogicalLiteral::Float(1.5),
			LogicalLiteral::Float(f64::NAN),
			LogicalLiteral::Integer(7),
			LogicalLiteral::Decimal(Decimal::new(150, 2)),
			LogicalLiteral::BigDecimal(Box::new(BigDecimal::from(7i64))),
			LogicalLiteral::String(Strand::new("s")),
			LogicalLiteral::Bytes(Bytes::from(vec![1u8])),
			LogicalLiteral::Regex("a".parse::<Regex>().expect("regex")),
			LogicalLiteral::Duration(Duration::from_secs(1)),
			LogicalLiteral::Datetime(Datetime::MIN_UTC),
			LogicalLiteral::Uuid(Uuid::nil()),
			LogicalLiteral::Geometry(Geometry::Point(geo_types::Point::new(1.0, 2.0))),
			LogicalLiteral::File(File::new("b".to_owned(), "p".to_owned())),
			LogicalLiteral::I8(-5),
			LogicalLiteral::U8(5),
			LogicalLiteral::I16(-500),
			LogicalLiteral::U16(500),
			LogicalLiteral::I32(-50000),
			LogicalLiteral::U32(50000),
			LogicalLiteral::U64(500000),
			LogicalLiteral::F16(half::f16::from_f32(1.5)),
			LogicalLiteral::F16(half::f16::NAN),
			LogicalLiteral::F32(1.5),
			LogicalLiteral::F32(f32::NAN),
		];
		for sample in samples {
			assert_eq!(sample, sample.clone(), "{sample:?} must equal itself");
		}
		assert_ne!(LogicalLiteral::Float(-0.0), LogicalLiteral::Float(0.0));
	}

	/// Every subexpression of a corpus covering each variant, and each lookup,
	/// recursion, destructure and record-id key shape the identity compares.
	fn shallow_corpus() -> Vec<LogicalExpr> {
		let mut corpus = Vec::new();
		let texts = [
			"1",
			"2",
			"'s'",
			"[a, 1]",
			"[a]",
			"{ a: 1, b: c }",
			"{ a: 1, d: c }",
			"{ a: 1 }",
			"t:1",
			"t:2",
			"u:1",
			"t:[a, 1]",
			"t:[a]",
			"t:{ k: a }",
			"t:{ j: a }",
			"t:[1]..=[a]",
			"t:[1]..[a]",
			"t:rand()",
			"t:ulid()",
			"$p",
			"$q",
			"|t:3|",
			"|t:4|",
			"math::pi",
			"math::e",
			"a.b",
			"a.c",
			"a.b.c",
			"a[0]",
			"a[$]",
			"a[a + 1]",
			"a[WHERE x > 1]",
			"a.*",
			"a…",
			"a.b.*",
			"a.slice(1, 2)",
			"a.slice(1)",
			"a.other(1, 2)",
			"a.{ x, y }",
			"a.{ x, y: z }",
			"a.{ x, w: z }",
			"a.{ x.*, y }",
			"a.{ x.{ y }, ... }",
			"a.?.b",
			"->likes->person",
			"->likes",
			"<-likes",
			"->(likes WHERE x = 1)",
			"->(SELECT * FROM likes WHERE x = 1 LIMIT 3)",
			"->(SELECT * FROM likes LIMIT 3 START 1)",
			"->(SELECT * FROM likes SPLIT a)",
			"->(SELECT * FROM likes GROUP BY a)",
			"->(SELECT * FROM likes ORDER BY a)",
			"->(SELECT * FROM likes ORDER BY a DESC)",
			"->(SELECT * FROM likes ORDER BY a NUMERIC)",
			"->(SELECT * FROM likes ORDER BY RAND())",
			"->(likes AS x)",
			"->(likes:1..3)",
			"->(likes:1..=3)",
			"->(likes, knows)",
			"->(SELECT a, b AS c FROM likes)",
			"->(SELECT VALUE a FROM likes)",
			"<~person",
			"a.{2}",
			"a.{2}(.b)",
			"a.{2}.b.@",
			"a.{3}.b.@",
			"a.{1..3+collect}(.b)",
			"a.{1..3+path}(.b)",
			"a.{1..3+path+inclusive}(.b)",
			"a.{1..3+shortest=t:1}(.b)",
			"a.b[0].c",
			"<int> a",
			"<string> a",
			"-a",
			"!a",
			"+a",
			"a..",
			"a>..",
			"..a",
			"a + 1",
			"a - 1",
			"a AND b",
			"a ?? b",
			"a ?: b",
			"a = b",
			"math::abs(1)",
			"math::abs(a)",
			"math::sqrt(a)",
			"fn::f(1)",
			"$f(1)",
			"|$x: int| $x + 1",
			"|$x: int| $x + 2",
			"|$x: int| -> int { $x + 1 }",
			"|$x: string| $x + 1",
			"IF a THEN 1 ELSE 2 END",
			"IF a THEN 1 END",
			"IF a THEN 1 ELSE IF b THEN 2 ELSE 3 END",
			"(SELECT * FROM t)",
			"(SELECT a FROM t)",
		];
		for text in texts {
			corpus.push(expr(text));
		}
		corpus.extend([
			LogicalExpr::Set(vec![expr("1"), expr("2")]),
			LogicalExpr::Set(vec![expr("1")]),
			LogicalExpr::Table(TableName::from("t")),
			LogicalExpr::Table(TableName::from("u")),
			LogicalExpr::Doc,
			LogicalExpr::Current,
			LogicalExpr::First(Box::new(expr("a"))),
			LogicalExpr::Break,
			LogicalExpr::Continue,
			LogicalExpr::Throw(Box::new(expr("1"))),
			LogicalExpr::RepeatRecurse(Box::new(LogicalExpr::Current)),
			LogicalExpr::SetField {
				base: Box::new(expr("o")),
				field: Strand::new("k"),
				value: Box::new(expr("1")),
			},
			LogicalExpr::SetField {
				base: Box::new(expr("o")),
				field: Strand::new("j"),
				value: Box::new(expr("1")),
			},
			LogicalExpr::Flatten {
				base: Box::new(expr("a")),
				explicit: false,
			},
		]);
		let mut all = Vec::new();
		for root in &corpus {
			let _ = root.visit(&mut |node| {
				all.push(node.clone());
				ControlFlow::<()>::Continue(())
			});
		}
		all
	}

	#[test]
	fn shallow_identity_is_equality_modulo_children() {
		use std::collections::hash_map::DefaultHasher;
		let corpus = shallow_corpus();
		let variants =
			corpus.iter().map(std::mem::discriminant).collect::<std::collections::HashSet<_>>();
		// One per variant of `LogicalExpr`.
		assert_eq!(variants.len(), 38, "the corpus must cover every variant");
		let hash = |expr: &LogicalExpr| {
			let mut state = DefaultHasher::new();
			expr.shallow_hash(&mut state);
			state.finish()
		};
		for a in &corpus {
			for b in &corpus {
				let children_equal = a.children() == b.children();
				if matches!(a, LogicalExpr::Subquery(_)) {
					assert_eq!(a.shallow_eq(b), std::ptr::eq(a, b));
				} else {
					assert_eq!(
						a.shallow_eq(b) && children_equal,
						a == b,
						"shallow identity of {a:?} and {b:?}"
					);
				}
				if a.shallow_eq(b) {
					assert_eq!(hash(a), hash(b), "{a:?} and {b:?} are shallow-equal");
				}
			}
		}
	}
}