zirium 0.5.0

Lossless textual MLIR syntax parsing and semantic processing
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
//! Typed, immutable query expressions. Construction never reads a document.

use super::{
    model::{self, Expression, Stage, StructuredStage},
    *,
};
use crate::source::TextRange;
use std::{
    marker::PhantomData,
    ops::{BitAnd, BitOr, Not},
};

fn range() -> TextRange {
    TextRange::at(0)
}
fn expression(stages: Vec<Stage>) -> Expression {
    Expression {
        first: stages,
        rest: Vec::new(),
        range: range(),
    }
}

/// A reusable query returning `T`. Use [`ops`] or [`input`] to start one.
///
/// Query construction is immutable. Execution happens only at [`Document::query`].
/// Nested expressions are limited to 64 levels, including boolean predicates.
///
/// ```
/// use zirium::query::{ops, op};
/// let consumers = ops().filter(op("arith.addi")).users().unique();
/// let histogram = consumers.names().tally();
/// ```
///
/// Methods follow the result type:
///
/// ```compile_fail
/// use zirium::query::ops;
/// let invalid = ops().names().users(); // Strings have no SSA users.
/// ```
#[derive(Clone, Debug)]
pub struct QueryExpr<T> {
    functions: Vec<FunctionDefinition>,
    function_limits: FunctionLimits,
    parameters: Vec<ParameterDeclaration>,
    expression: Expression,
    depth: usize,
    nodes: usize,
    invalid: Option<&'static str>,
    result: PhantomData<fn() -> T>,
}

pub type OpQuery = QueryExpr<Vec<OperationId>>;
pub type StringQuery = QueryExpr<Vec<String>>;
pub type CountQuery = QueryExpr<usize>;
pub type MapQuery<T> = QueryExpr<Vec<(String, T)>>;
pub type TypeQuery = QueryExpr<Vec<TypeId>>;
pub type AttributeQuery = QueryExpr<Vec<AttributeId>>;

fn merge_parameters(
    left: &[ParameterDeclaration],
    right: &[ParameterDeclaration],
) -> Vec<ParameterDeclaration> {
    let mut parameters = left.to_vec();
    parameters.extend(
        right
            .iter()
            .filter(|declaration| !left.contains(declaration))
            .cloned(),
    );
    parameters
}

impl<T> QueryExpr<T> {
    /// Attach function declarations to this request, retaining conflicts for preflight.
    pub fn with_functions(mut self, functions: Vec<FunctionDefinition>) -> Self {
        self.functions = functions::merge(&self.functions, &functions);
        self
    }
    /// Bound active non-tail calls independently of expression nesting.
    pub fn with_function_limits(mut self, limits: FunctionLimits) -> Self {
        self.function_limits = limits;
        self
    }
    /// Attach immutable required declarations to this root request.
    /// Composition shares identical declarations and retains conflicting declarations
    /// for admission to refuse; existing evaluation methods supply no caller inputs.
    pub fn with_parameters(&self, declarations: Vec<ParameterDeclaration>) -> Self {
        Self {
            functions: self.functions.clone(),
            function_limits: self.function_limits,
            parameters: merge_parameters(&self.parameters, &declarations),
            expression: self.expression.clone(),
            depth: self.depth,
            nodes: self.nodes,
            invalid: self.invalid,
            result: PhantomData,
        }
    }
    pub fn parameters(&self) -> &[ParameterDeclaration] {
        &self.parameters
    }

    /// Evaluate exact typed scalar caller inputs to the query's native result type.
    pub fn evaluate_with_parameters(
        &self,
        document: &Document,
        registry: &DialectRegistry,
        parameters: &[(String, ConstructedValue)],
        limits: EvaluationLimits,
    ) -> Result<T, EvaluationError>
    where
        T: QueryResult,
    {
        let mut budget = self.new_budget(limits);
        T::from_query_output(self.evaluate_output_with_parameters_and_budget(
            document,
            registry,
            EvaluationOptions::default(),
            ParameterInputs::Typed(parameters),
            &mut budget,
        )?)
    }

    /// Erase the static result type for language bindings. The expression stays read-only.
    pub fn erased(&self) -> QueryExpr<QueryOutput> {
        QueryExpr {
            functions: self.functions.clone(),
            function_limits: self.function_limits,
            parameters: self.parameters.clone(),
            expression: self.expression.clone(),
            depth: self.depth,
            nodes: self.nodes,
            invalid: self.invalid,
            result: PhantomData,
        }
    }
    fn start(stages: Vec<Stage>) -> Self {
        Self {
            functions: Vec::new(),
            function_limits: functions::DEFAULT_LIMITS,
            parameters: Vec::new(),
            nodes: stages.len(),
            expression: expression(stages),
            depth: 1,
            invalid: None,
            result: PhantomData,
        }
    }
    fn append<U>(
        &self,
        stage: Stage,
        depth: usize,
        nodes: usize,
        invalid: Option<&'static str>,
    ) -> QueryExpr<U> {
        let depth = self.depth.max(depth);
        let invalid = self
            .invalid
            .or(invalid)
            .or((depth > parser::DEFAULT_NESTING_LIMIT).then_some("query nesting limit exceeded"));
        // Do not retain an excessively nested tree: even dropping it can overflow the stack.
        let mut expression = if invalid.is_some() {
            expression(Vec::new())
        } else {
            self.expression.clone()
        };
        if invalid.is_none() {
            expression.first.push(stage);
        }
        QueryExpr {
            functions: self.functions.clone(),
            function_limits: self.function_limits,
            parameters: self.parameters.clone(),
            expression,
            depth,
            nodes: self.nodes.saturating_add(nodes),
            invalid,
            result: PhantomData,
        }
    }
    fn stage<U>(&self, stage: Stage) -> QueryExpr<U> {
        self.append(stage, 1, 1, None)
    }
    fn structured<U>(&self, step: StructuredStage) -> QueryExpr<U> {
        self.stage(Stage::Structured {
            step,
            range: range(),
        })
    }
    fn nested<U, V>(&self, other: &QueryExpr<V>, stage: Stage) -> QueryExpr<U> {
        self.append(
            stage,
            other.depth.saturating_add(1),
            other.nodes.saturating_add(1),
            other.invalid,
        )
        .with_parameters(other.parameters.clone())
        .with_functions(other.functions.clone())
    }
    /// Execute with a specific registry and evaluation budget, returning native data.
    ///
    /// The result owns its collection storage; operation, type, and attribute IDs
    /// remain scoped to `document`. Evaluation is read-only and deterministic.
    /// Work and result materialization are bounded by `limits`; exceeding either
    /// bound returns [`EvaluationError`]. Cost follows visited stages and produced
    /// items rather than expression-construction time.
    pub fn evaluate(
        &self,
        document: &Document,
        registry: &DialectRegistry,
        limits: EvaluationLimits,
    ) -> Result<T, EvaluationError>
    where
        T: QueryResult,
    {
        T::from_query_output(self.evaluate_output(document, registry, limits)?)
    }
    /// Execute with explicit semantic options and limits.
    ///
    /// This has the same ownership, error, and cost contract as [`Self::evaluate`].
    pub fn evaluate_with_options(
        &self,
        document: &Document,
        registry: &DialectRegistry,
        options: EvaluationOptions,
        limits: EvaluationLimits,
    ) -> Result<T, EvaluationError>
    where
        T: QueryResult,
    {
        T::from_query_output(
            self.evaluate_output_with_options(document, registry, options, limits)?,
        )
    }
    /// Execute to the shared result representation, primarily for language bindings.
    pub fn evaluate_output(
        &self,
        document: &Document,
        registry: &DialectRegistry,
        limits: EvaluationLimits,
    ) -> Result<QueryOutput, EvaluationError> {
        self.evaluate_output_with_options(document, registry, EvaluationOptions::default(), limits)
    }
    pub fn evaluate_output_with_options(
        &self,
        document: &Document,
        registry: &DialectRegistry,
        options: EvaluationOptions,
        limits: EvaluationLimits,
    ) -> Result<QueryOutput, EvaluationError> {
        let mut budget = self.new_budget(limits);
        self.evaluate_output_with_budget(document, registry, options, &mut budget)
    }
    /// Create this request's allowance, retaining legacy policy for ordinary queries.
    pub fn new_budget(&self, limits: EvaluationLimits) -> zirql::Budget {
        if !self.functions.is_empty()
            || !self.parameters.is_empty()
            || report::has_constructed(&self.expression)
        {
            zirql::Budget::for_program(ProgramLimits {
                work: limits.max_work,
                stream_items: limits.max_items,
                ..comprehension::default_limits()
            })
        } else {
            evaluation_budget(limits)
        }
    }
    /// Evaluate and retain the caller's remaining allowance for native conversion.
    pub fn evaluate_output_with_budget(
        &self,
        document: &Document,
        registry: &DialectRegistry,
        options: EvaluationOptions,
        budget: &mut zirql::Budget,
    ) -> Result<QueryOutput, EvaluationError> {
        self.evaluate_output_with_parameters_and_budget(
            document,
            registry,
            options,
            ParameterInputs::Typed(&[]),
            budget,
        )
    }

    /// Admit, preflight and execute with the caller's allowance, retaining it for conversion.
    pub fn evaluate_output_with_parameters_and_budget(
        &self,
        document: &Document,
        registry: &DialectRegistry,
        options: EvaluationOptions,
        parameters: ParameterInputs<'_>,
        budget: &mut Budget,
    ) -> Result<QueryOutput, EvaluationError> {
        if let Some(message) = self.invalid {
            return Err(EvaluationError::new(message));
        }
        if (!self.functions.is_empty()
            || !self.parameters.is_empty()
            || report::has_constructed(&self.expression))
            && budget.remaining_results().is_none()
        {
            return Err(EvaluationError::new(
                "constructed reports require an aggregate result allowance",
            ));
        }
        let admitted =
            program::admit_parameters(&self.parameters, parameters, &["document"], 0..0, budget)?;
        let bindings = zirql::Bindings::new(admitted).map_err(core_error)?;
        let names = program::parameter_names(&self.parameters, budget)?;
        charge(budget, self.nodes)?;
        let function_host = report::ReportHost {
            functions: &self.functions,
        };
        let mut functions =
            if self.functions.is_empty() && !report::requires_session(&self.expression) {
                None
            } else {
                Some(functions::Session::new(
                    &self.functions,
                    &function_host,
                    self.function_limits,
                    budget,
                )?)
            };
        if let Some(session) = &mut functions {
            session.prepare_expression(
                &self.expression,
                program::Kind::Operations,
                &names,
                &function_host,
                budget,
            )?;
        } else {
            program::validate_expression(
                &self.expression,
                program::Kind::Operations,
                &names,
                budget,
            )?;
        }

        let selected = QueryOutput::Operations(collect(budget, document.operations())?);
        let mut access = DocumentAccess::Shared(document);
        let mut emit = |_: &Document, _: QueryOutput, _: &mut zirql::Budget| {
            Err(EvaluationError::new("cannot emit in a read-only query"))
        };
        let function_roots = functions::expression_roots(&self.functions);
        let expressions =
            program::expressions(std::iter::once(&self.expression).chain(function_roots));
        let mut context = EvaluationContext {
            functions: functions.as_ref(),
            current_stage: 0,
            document: &mut access,
            registry,
            expressions: &expressions,
            parameters: Vec::new(),
            options,
            output: OutputMode::Native,
            emit: &mut emit,
        };
        let value =
            evaluate_expression(&self.expression, &mut context, selected, &bindings, budget)?;
        functions::owned(value, budget, &(0..0))
    }
    /// Execute a constructed request with explicit aggregate and stream bounds.
    pub fn evaluate_with_program_limits(
        &self,
        document: &Document,
        registry: &DialectRegistry,
        limits: ProgramLimits,
    ) -> Result<T, EvaluationError>
    where
        T: QueryResult,
    {
        T::from_query_output(self.evaluate_output_with_budget(
            document,
            registry,
            EvaluationOptions::default(),
            &mut zirql::Budget::for_program(limits),
        )?)
    }
}

/// Start with all operations in the document, including inside nested queries.
pub fn ops() -> OpQuery {
    QueryExpr::start(vec![Stage::Input { range: range() }])
}
/// Start with the operations supplied by the caller of a nested query.
/// At top level this is all operations in the document.
pub fn input() -> OpQuery {
    QueryExpr::start(Vec::new())
}

/// Direct native edges supported by bounded operation paths.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum PathEdge {
    Users,
}

fn path_target(predicate: model::Predicate) -> zirql::Predicate<model::Predicate> {
    use model::Predicate as P;
    let location = program::range(predicate.range());
    let value = match predicate {
        P::Not { predicate, .. } => zirql::PredicateKind::Not(Box::new(path_target(*predicate))),
        P::Group { predicate, .. } => {
            zirql::PredicateKind::Group(Box::new(path_target(*predicate)))
        }
        P::And { predicates, .. } => {
            zirql::PredicateKind::And(predicates.into_iter().map(path_target).collect())
        }
        P::Or { predicates, .. } => {
            zirql::PredicateKind::Or(predicates.into_iter().map(path_target).collect())
        }
        predicate => zirql::PredicateKind::Leaf(predicate),
    };
    zirql::Located::new(value, location)
}

impl Document {
    /// Evaluate a structured query with the baseline dialect registry and default limits.
    /// See the [registry contract](https://github.com/zayenz/zirium/blob/main/docs/custom-formats.md#registry-contract-for-each-rust-stage).
    /// The document is not mutated. Returned IDs remain document-owned and may
    /// become stale after later edits; owned strings and collections are snapshots.
    /// Errors include invalid expression structure and exhausted budgets.
    pub fn query<T: QueryResult>(&self, query: &QueryExpr<T>) -> Result<T, EvaluationError> {
        query.evaluate(
            self,
            DialectRegistry::baseline(),
            EvaluationLimits::default(),
        )
    }
    /// Evaluate with the registry describing this document's dialect semantics.
    ///
    /// Ownership, mutation visibility, conversion, and error behavior match
    /// [`Self::query`]. Default evaluation limits apply.
    pub fn query_with_registry<T: QueryResult>(
        &self,
        query: &QueryExpr<T>,
        registry: &DialectRegistry,
    ) -> Result<T, EvaluationError> {
        query.evaluate(self, registry, EvaluationLimits::default())
    }
}

impl OpQuery {
    pub fn filter(&self, predicate: Predicate) -> Self {
        let functions = predicate.functions.clone();
        let parameters = predicate.parameters.clone();
        self.append(
            Stage::Filter {
                constructed: None,
                predicate: predicate.inner,
                range: range(),
            },
            predicate.depth + 1,
            predicate.nodes + 1,
            predicate.invalid,
        )
        .with_parameters(parameters)
        .with_functions(functions)
    }
    pub fn root(&self, predicate: Predicate) -> Self {
        let functions = predicate.functions.clone();
        let parameters = predicate.parameters.clone();
        self.append(
            Stage::Root {
                predicate: predicate.inner,
                range: range(),
            },
            predicate.depth + 1,
            predicate.nodes + 1,
            predicate.invalid,
        )
        .with_parameters(parameters)
        .with_functions(functions)
    }
    pub fn defs(&self) -> Self {
        self.stage(Stage::Defs {
            index: None,
            range: range(),
        })
    }
    pub fn defs_at(&self, index: usize) -> Self {
        self.stage(Stage::Defs {
            index: Some(index),
            range: range(),
        })
    }
    /// Retain one shortest native witness for each source/sink pair within the edge bound.
    pub fn paths(&self, edge: PathEdge, to: Predicate, max_depth: usize) -> CaptureQuery {
        let functions = functions::merge(&self.functions, &to.functions);
        let parameters = merge_parameters(&self.parameters, &to.parameters);
        let edge = match edge {
            PathEdge::Users => Stage::Users {
                index: None,
                range: range(),
            },
        };
        self.append(
            Stage::Paths {
                value: capture::ParsedPaths::new(zirql::NativePaths {
                    edge: zirql::Located::new(edge, 0..0),
                    target: path_target(to.inner),
                    max_depth: zirql::Located::new(max_depth, 0..0),
                    range: 0..0,
                }),
                range: range(),
            },
            to.depth + 1,
            to.nodes + 1,
            to.invalid,
        )
        .with_parameters(parameters)
        .with_functions(functions)
    }
    pub fn users(&self) -> Self {
        self.stage(Stage::Users {
            index: None,
            range: range(),
        })
    }
    pub fn users_at(&self, index: usize) -> Self {
        self.stage(Stage::Users {
            index: Some(index),
            range: range(),
        })
    }
    /// Keep each input operation for which the relative subquery is nonempty.
    pub fn where_exists(&self, query: &OpQuery) -> Self {
        self.nested(
            query,
            Stage::Structured {
                step: StructuredStage::WhereExists(Box::new(query.expression.clone())),
                range: range(),
            },
        )
    }
    /// Build a map. Each key query must return one string; duplicate keys are errors.
    pub fn map_by<T: QueryResult>(
        &self,
        key: &QueryExpr<String>,
        value: &QueryExpr<T>,
    ) -> MapQuery<T> {
        self.append(
            Stage::Structured {
                step: StructuredStage::MapBy {
                    key: Box::new(key.expression.clone()),
                    value: Box::new(value.expression.clone()),
                },
                range: range(),
            },
            key.depth.max(value.depth) + 1,
            key.nodes.saturating_add(value.nodes).saturating_add(1),
            key.invalid.or(value.invalid),
        )
        .with_parameters(merge_parameters(&key.parameters, &value.parameters))
        .with_functions(functions::merge(&key.functions, &value.functions))
    }
    pub fn string_attr(&self, name: impl Into<String>) -> StringQuery {
        self.structured(StructuredStage::StringAttr(name.into()))
    }
    /// Project attribute spellings using the textual `attr` stage's rules.
    pub fn attr_expr(&self, name: ReportExpr) -> StringQuery {
        self.stage(Stage::Computed {
            value: model::ComputedStage::Attr(name.value),
            range: range(),
        })
        .with_parameters(name.parameters)
        .with_functions(name.functions)
    }
    pub fn defs_at_expr(&self, index: ReportExpr) -> Self {
        self.stage(Stage::Computed {
            value: model::ComputedStage::Defs(index.value),
            range: range(),
        })
        .with_parameters(index.parameters)
        .with_functions(index.functions)
    }
    pub fn users_at_expr(&self, index: ReportExpr) -> Self {
        self.stage(Stage::Computed {
            value: model::ComputedStage::Users(index.value),
            range: range(),
        })
        .with_parameters(index.parameters)
        .with_functions(index.functions)
    }
    pub fn attr(&self, name: impl Into<String>) -> StringQuery {
        self.stage(Stage::Attr {
            name: name.into(),
            range: range(),
        })
    }
    pub fn attributes(&self, name: impl Into<String>) -> AttributeQuery {
        self.structured(StructuredStage::Attributes(name.into()))
    }
    pub fn result_types(&self) -> TypeQuery {
        self.structured(StructuredStage::Types { operands: false })
    }
    pub fn operand_types(&self) -> TypeQuery {
        self.structured(StructuredStage::Types { operands: true })
    }
    /// Replace the selection repeatedly until it is unchanged. Duplicates matter.
    pub fn fixpoint(&self, body: &OpQuery) -> Self {
        self.nested(
            body,
            Stage::Fixpoint {
                expression: super::model::FixedPointBody::Selection(Box::new(
                    body.expression.clone(),
                )),
                range: range(),
            },
        )
    }
}

macro_rules! stages {
    ($ty:ty; $($method:ident => $stage:ident : $out:ty),* $(,)?) => {
        impl $ty { $(pub fn $method(&self) -> $out { self.stage(Stage::$stage { range: range() }) })* }
    };
}
stages!(OpQuery; parent => Parent: OpQuery, children => Children: OpQuery, subtree => Subtree: OpQuery,
    closure => Closure: OpQuery, reachable => Reachable: OpQuery, names => Names: StringQuery);
impl OpQuery {
    /// Follow transitive SSA definitions from the current selection.
    ///
    /// Construction clones the existing expression but does not inspect a document.
    /// Evaluation terminates on cycles, preserves deterministic order, and charges
    /// traversal against [`EvaluationLimits::max_work`]. Returned IDs belong to the
    /// evaluated document and later edits can make them stale. Use
    /// [`Self::reachable`] to include control-flow reachability.
    pub fn slice(&self) -> OpQuery {
        self.stage(Stage::Slice { range: range() })
    }

    /// Explicit alias for [`Self::slice`].
    pub fn backward_slice(&self) -> OpQuery {
        self.slice()
    }

    /// Follow transitive SSA users from the current selection.
    pub fn forward_slice(&self) -> OpQuery {
        self.stage(Stage::ForwardSlice { range: range() })
    }
}
stages!(StringQuery; sort => Sort: StringQuery, min => Min: StringQuery, max => Max: StringQuery,
    min_all => MinAll: StringQuery, max_all => MaxAll: StringQuery, tally => Tally: MapQuery<usize>);

macro_rules! stream {
    ($ty:ty) => {
        stages!($ty; unique => Unique: Self, reverse => Reverse: Self, count => Count: CountQuery);
        impl $ty {
            pub fn head(&self, count: usize) -> Self { self.stage(Stage::Head { count, range: range() }) }
            pub fn tail(&self, count: usize) -> Self { self.stage(Stage::Tail { count, range: range() }) }
            pub fn head_expr(&self, count: ReportExpr) -> Self { self.stage(Stage::Computed {value:model::ComputedStage::Head(count.value),range:range()}).with_parameters(count.parameters).with_functions(count.functions) }
            pub fn tail_expr(&self, count: ReportExpr) -> Self { self.stage(Stage::Computed {value:model::ComputedStage::Tail(count.value),range:range()}).with_parameters(count.parameters).with_functions(count.functions) }
        }
    };
}
stream!(OpQuery);
stream!(StringQuery);
stream!(TypeQuery);
stream!(AttributeQuery);
impl<T> MapQuery<T> {
    /// Erase map value types for language bindings.
    #[doc(hidden)]
    pub fn map_values_erased(&self) -> MapQuery<QueryOutput> {
        QueryExpr {
            functions: self.functions.clone(),
            function_limits: self.function_limits,
            parameters: self.parameters.clone(),
            expression: self.expression.clone(),
            depth: self.depth,
            nodes: self.nodes,
            invalid: self.invalid,
            result: PhantomData,
        }
    }
    pub fn sort(&self) -> Self {
        self.stage(Stage::Sort { range: range() })
    }
    pub fn sort_by_value(&self) -> Self {
        self.stage(Stage::SortBy {
            selector: report::OrderingSelector::MapValue(range()),
            range: range(),
        })
    }
    pub fn reverse(&self) -> Self {
        self.stage(Stage::Reverse { range: range() })
    }
    pub fn head(&self, count: usize) -> Self {
        self.stage(Stage::Head {
            count,
            range: range(),
        })
    }
    pub fn tail(&self, count: usize) -> Self {
        self.stage(Stage::Tail {
            count,
            range: range(),
        })
    }
    pub fn head_expr(&self, count: ReportExpr) -> Self {
        self.stage(Stage::Computed {
            value: model::ComputedStage::Head(count.value),
            range: range(),
        })
        .with_parameters(count.parameters)
        .with_functions(count.functions)
    }
    pub fn tail_expr(&self, count: ReportExpr) -> Self {
        self.stage(Stage::Computed {
            value: model::ComputedStage::Tail(count.value),
            range: range(),
        })
        .with_parameters(count.parameters)
        .with_functions(count.functions)
    }
    pub fn count(&self) -> CountQuery {
        self.stage(Stage::Count { range: range() })
    }
}
impl StringQuery {
    /// Require exactly one string and return it as a scalar.
    pub fn one(&self) -> QueryExpr<String> {
        self.structured(StructuredStage::One)
    }
}
impl TypeQuery {
    pub fn spellings(&self) -> StringQuery {
        self.structured(StructuredStage::Spellings)
    }
}
impl AttributeQuery {
    pub fn spellings(&self) -> StringQuery {
        self.structured(StructuredStage::Spellings)
    }
}

macro_rules! sets {
    ($ty:ty) => {
        impl $ty {
            fn set(&self, right: &Self, operator: model::SetOperator) -> Self {
                // A chain of set operators stays flat, just like the textual language.
                let (mut left, left_depth) = match self.expression.first.as_slice() {
                    [Stage::Group { expression, .. }] if !expression.rest.is_empty() => {
                        ((**expression).clone(), self.depth)
                    }
                    _ => (
                        expression(vec![Stage::Group {
                            expression: Box::new(self.expression.clone()),
                            range: range(),
                        }]),
                        self.depth + 2,
                    ),
                };
                left.rest.push((
                    operator,
                    vec![Stage::Group {
                        expression: Box::new(right.expression.clone()),
                        range: range(),
                    }],
                ));
                QueryExpr::<()>::start(Vec::new())
                    .append(
                        Stage::Group {
                            expression: Box::new(left),
                            range: range(),
                        },
                        left_depth.max(right.depth + 2),
                        self.nodes.saturating_add(right.nodes).saturating_add(3),
                        self.invalid.or(right.invalid),
                    )
                    .with_parameters(merge_parameters(&self.parameters, &right.parameters))
                    .with_functions(functions::merge(&self.functions, &right.functions))
                    .with_function_limits(self.function_limits)
            }
            pub fn union(&self, right: &Self) -> Self {
                self.set(right, model::SetOperator::Union)
            }
            pub fn intersect(&self, right: &Self) -> Self {
                self.set(right, model::SetOperator::Intersect)
            }
            pub fn difference(&self, right: &Self) -> Self {
                self.set(right, model::SetOperator::Except)
            }
        }
    };
}
sets!(OpQuery);
sets!(StringQuery);

/// A scalar string or count usable as an ordering key.
pub trait OrderKey: QueryResult + private::OrderKey {}
impl OrderKey for String {}
impl OrderKey for usize {}
macro_rules! ordering {
    ($($method:ident => $stage:ident),*) => { impl OpQuery { $(
        pub fn $method<T: OrderKey>(&self, selector: &QueryExpr<T>) -> Self {
            self.nested(selector, Stage::$stage { selector: super::report::OrderingSelector::new(&selector.expression), range: range() })
        }
    )* }};
}
ordering!(sort_by => SortBy, min_by => MinBy, max_by => MaxBy, min_all_by => MinAllBy, max_all_by => MaxAllBy);

/// An operation predicate. Combine with `&`, `|`, and `!`.
#[derive(Clone, Debug)]
pub struct Predicate {
    functions: Vec<FunctionDefinition>,
    parameters: Vec<ParameterDeclaration>,
    inner: model::Predicate,
    depth: usize,
    nodes: usize,
    invalid: Option<&'static str>,
}
impl Predicate {
    pub(crate) fn model(&self) -> model::Predicate {
        self.inner.clone()
    }

    pub(super) fn checked_model(&self) -> Result<model::Predicate, EvaluationError> {
        if let Some(error) = self.invalid {
            return Err(EvaluationError::new(error));
        }
        if !self.parameters.is_empty() {
            return Err(EvaluationError::new(
                "parameterized predicate needs a program scope",
            ));
        }
        Ok(self.model())
    }

    fn new(inner: model::Predicate) -> Self {
        Self {
            functions: Vec::new(),
            parameters: Vec::new(),
            inner,
            depth: 1,
            nodes: 1,
            invalid: None,
        }
    }
    fn combine(self, right: Self, and: bool) -> Self {
        let functions = functions::merge(&self.functions, &right.functions);
        let parameters = merge_parameters(&self.parameters, &right.parameters);
        let flatten = |predicate: &model::Predicate| {
            matches!(
                (and, predicate),
                (true, model::Predicate::And { .. }) | (false, model::Predicate::Or { .. })
            )
        };
        let left_depth = self.depth - usize::from(flatten(&self.inner));
        let right_depth = right.depth - usize::from(flatten(&right.inner));
        let depth = left_depth.max(right_depth) + 1;
        let invalid = self
            .invalid
            .or(right.invalid)
            .or((depth >= parser::DEFAULT_NESTING_LIMIT)
                .then_some("predicate nesting limit exceeded"));
        let nodes = self.nodes.saturating_add(right.nodes).saturating_add(1);
        if invalid.is_some() {
            return Self {
                functions,
                parameters,
                inner: model::Predicate::Bool {
                    value: false,
                    range: range(),
                },
                depth,
                nodes,
                invalid,
            };
        }
        let mut predicates = Vec::new();
        for predicate in [self.inner, right.inner] {
            match predicate {
                model::Predicate::And {
                    predicates: children,
                    ..
                } if and => predicates.extend(children),
                model::Predicate::Or {
                    predicates: children,
                    ..
                } if !and => predicates.extend(children),
                predicate => predicates.push(predicate),
            }
        }
        Self {
            functions,
            parameters,
            inner: if and {
                model::Predicate::And {
                    predicates,
                    range: range(),
                }
            } else {
                model::Predicate::Or {
                    predicates,
                    range: range(),
                }
            },
            depth,
            nodes,
            invalid,
        }
    }
}
impl BitAnd for Predicate {
    type Output = Self;
    fn bitand(self, right: Self) -> Self {
        self.combine(right, true)
    }
}
impl BitOr for Predicate {
    type Output = Self;
    fn bitor(self, right: Self) -> Self {
        self.combine(right, false)
    }
}
impl Not for Predicate {
    type Output = Self;
    fn not(self) -> Self {
        let invalid = self
            .invalid
            .or((self.depth + 1 >= parser::DEFAULT_NESTING_LIMIT)
                .then_some("predicate nesting limit exceeded"));
        let inner = if invalid.is_some() {
            model::Predicate::Bool {
                value: false,
                range: range(),
            }
        } else {
            model::Predicate::Not {
                predicate: Box::new(self.inner),
                range: range(),
            }
        };
        Self {
            functions: self.functions,
            parameters: self.parameters,
            inner,
            depth: self.depth.saturating_add(1),
            nodes: self.nodes.saturating_add(1),
            invalid,
        }
    }
}
pub fn op(name: impl Into<String>) -> Predicate {
    Predicate::new(model::Predicate::Op {
        name: name.into(),
        range: range(),
    })
}
pub fn dialect(name: impl Into<String>) -> Predicate {
    Predicate::new(model::Predicate::Dialect {
        name: name.into(),
        range: range(),
    })
}
pub fn has_attr(name: impl Into<String>) -> Predicate {
    Predicate::new(model::Predicate::HasAttr {
        name: name.into(),
        range: range(),
    })
}
pub fn result_type(spelling: impl Into<String>) -> Predicate {
    Predicate::new(model::Predicate::ResultType {
        spelling: spelling.into(),
        range: range(),
    })
}
pub fn string_attr_eq(name: impl Into<String>, value: impl Into<String>) -> Predicate {
    Predicate::new(model::Predicate::Attr {
        name: name.into(),
        value: value.into(),
        range: range(),
    })
}
pub fn always(value: bool) -> Predicate {
    Predicate::new(model::Predicate::Bool {
        value,
        range: range(),
    })
}

mod private {
    pub trait Sealed {}
    pub trait OrderKey {}
    impl OrderKey for String {}
    impl OrderKey for usize {}
}
/// Native return types supported by structured queries.
pub trait QueryResult: private::Sealed + Sized {
    #[doc(hidden)]
    fn from_query_output(output: QueryOutput) -> Result<Self, EvaluationError>;
}
fn wrong_result() -> EvaluationError {
    EvaluationError::new("unexpected structured query result type")
}
macro_rules! result {
    ($ty:ty, $pat:pat => $value:expr) => {
        impl private::Sealed for $ty {}
        impl QueryResult for $ty {
            fn from_query_output(output: QueryOutput) -> Result<Self, EvaluationError> {
                match output {
                    $pat => Ok($value),
                    _ => Err(wrong_result()),
                }
            }
        }
    };
}
result!(Vec<OperationId>, QueryOutput::Operations(value) | QueryOutput::Native(NativeValue::OperationSequence(value)) => value);
result!(Vec<String>, QueryOutput::Values(value) => value);
result!(usize, QueryOutput::Count(value) => value);
result!(String, QueryOutput::Native(NativeValue::String(value)) => value);
result!(Vec<TypeId>, QueryOutput::Native(NativeValue::Types(value)) => value);
result!(Vec<AttributeId>, QueryOutput::Native(NativeValue::Attributes(value)) => value.into_iter().map(|(_, id)| id).collect());
impl<T: QueryResult> private::Sealed for Vec<(String, T)> {}
impl<T: QueryResult> QueryResult for Vec<(String, T)> {
    fn from_query_output(output: QueryOutput) -> Result<Self, EvaluationError> {
        let entries = match output {
            QueryOutput::Native(NativeValue::Map(entries)) => entries,
            // The shared tally stage also serves the textual frontend.
            QueryOutput::Map(entries) => entries
                .into_iter()
                .map(|(key, value)| {
                    let count = value
                        .as_u64()
                        .and_then(|n| usize::try_from(n).ok())
                        .ok_or_else(wrong_result)?;
                    Ok((key, QueryOutput::Count(count)))
                })
                .collect::<Result<_, EvaluationError>>()?,
            _ => return Err(wrong_result()),
        };
        entries
            .into_iter()
            .map(|(key, value)| Ok((key, T::from_query_output(value)?)))
            .collect()
    }
}

pub(super) fn evaluate_structured(
    step: &StructuredStage,
    context: &mut EvaluationContext<'_, '_, '_>,
    current: QueryOutput,
    bindings: &zirql::Bindings<QueryOutput>,
    budget: &mut zirql::Budget,
) -> Result<QueryOutput, EvaluationError> {
    Ok(match step {
        StructuredStage::One => {
            let QueryOutput::Values(values) = current else {
                return Err(wrong_result());
            };
            let count = values.len();
            let value = zirql::take_one(values, 0..0).map_err(|_| {
                EvaluationError::new(format!("one requires exactly one string, got {count}"))
            })?;
            QueryOutput::Native(NativeValue::String(value))
        }
        StructuredStage::WhereExists(query) => QueryOutput::Operations(
            zirql::filter_native_exists(
                take_operations(current, "where_exists")?,
                budget,
                zirql::Location::Query(0..0),
                |operation, budget| {
                    program::charge_results(budget, 1, &(0..0))
                        .map_err(zirql::EvaluationError::Host)?;
                    let result = evaluate_expression(
                        query,
                        context,
                        QueryOutput::Operations(vec![*operation]),
                        bindings,
                        budget,
                    )
                    .map_err(zirql::EvaluationError::Host)?;
                    take_operations(result, "where_exists").map_err(zirql::EvaluationError::Host)
                },
            )
            .map_err(program::evaluation_error)?,
        ),
        StructuredStage::MapBy { key, value } => {
            let selected = take_operations(current, "map_by")?;
            let mapping = zirql::NativeMap {
                key: &**key,
                value: &**value,
            };
            let mut items = 0usize;
            let entries = zirql::map_native_by(
                selected,
                context,
                budget,
                zirql::Location::Query(0..0),
                |operation, context, budget| {
                    program::charge_results(budget, 1, &(0..0))
                        .map_err(zirql::EvaluationError::Host)?;
                    let seed = QueryOutput::Operations(vec![*operation]);
                    let input = program::copy_value(&seed, budget, &(0..0))
                        .map_err(zirql::EvaluationError::Host)?;
                    let key = String::from_query_output(
                        evaluate_expression(mapping.key, context, input, bindings, budget)
                            .map_err(zirql::EvaluationError::Host)?,
                    )
                    .map_err(zirql::EvaluationError::Host)?;
                    program::charge_results(budget, 1, &(0..0))
                        .map_err(zirql::EvaluationError::Host)?;
                    Ok(Some(vec![key]))
                },
                |operation, context, budget| {
                    program::charge_results(budget, 1, &(0..0))
                        .map_err(zirql::EvaluationError::Host)?;
                    let value = evaluate_expression(
                        mapping.value,
                        context,
                        QueryOutput::Operations(vec![operation]),
                        bindings,
                        budget,
                    )
                    .map_err(zirql::EvaluationError::Host)?;
                    items = items.saturating_add(output_size(&value).saturating_add(1));
                    check_items(budget, items).map_err(zirql::EvaluationError::Host)?;
                    charge(budget, output_size(&value)).map_err(zirql::EvaluationError::Host)?;
                    Ok(value)
                },
            )
            .map_err(program::evaluation_error)?;
            QueryOutput::Native(NativeValue::Map(entries))
        }
        StructuredStage::StringAttr(name) => {
            let mut values = Vec::new();
            for operation in take_operations(current, "string_attr")? {
                let Some(id) = context.document.attribute_id(operation, name) else {
                    continue;
                };
                let Some(AttributeValue::String(spelling)) = context.document.attribute_value(id)
                else {
                    return Err(EvaluationError::new(format!(
                        "attribute `{name}` is not a string"
                    )));
                };
                program::charge_results(budget, 1, &(0..0))?;
                program::charge_bytes(budget, spelling.len(), &(0..0))?;
                values.push(decode_mlir_string(spelling).ok_or_else(|| {
                    EvaluationError::new(format!("attribute `{name}` cannot be decoded as UTF-8"))
                })?);
            }
            QueryOutput::Values(values)
        }
        StructuredStage::Attributes(name) => {
            let mut values = Vec::new();
            for operation in take_operations(current, "attributes")? {
                if let Some(id) = context.document.attribute_id(operation, name) {
                    program::charge_results(budget, 1, &(0..0))?;
                    program::charge_bytes(budget, name.len(), &(0..0))?;
                    values.push((name.clone(), id));
                }
            }
            QueryOutput::Native(NativeValue::Attributes(values))
        }
        StructuredStage::Types { operands } => {
            let mut values = Vec::new();
            for operation in take_operations(current, "types")? {
                if *operands {
                    for &value in context.document.operands(operation).unwrap_or(&[]) {
                        charge(budget, 1)?;
                        if let Some(id) = context.document.value_type_id(value) {
                            program::charge_results(budget, 1, &(0..0))?;
                            values.push(id);
                            check_items(budget, values.len())?;
                        }
                    }
                } else {
                    let types = context.document.result_types(operation).unwrap_or(&[]);
                    charge(budget, types.len())?;
                    check_items(budget, values.len().saturating_add(types.len()))?;
                    program::charge_results(budget, types.len(), &(0..0))?;
                    values.extend_from_slice(types);
                }
            }
            QueryOutput::Native(NativeValue::Types(values))
        }
        StructuredStage::Spellings => QueryOutput::Values(match current {
            QueryOutput::Native(NativeValue::Types(values)) => values
                .into_iter()
                .map(|id| {
                    context
                        .document
                        .type_spelling(id)
                        .ok_or_else(wrong_result)
                        .and_then(|value| {
                            program::charge_results(budget, 1, &(0..0))?;
                            program::charge_bytes(budget, value.len(), &(0..0))?;
                            Ok(value.to_owned())
                        })
                })
                .collect::<Result<_, _>>()?,
            QueryOutput::Native(NativeValue::Attributes(values)) => values
                .into_iter()
                .map(|(_, id)| {
                    context
                        .document
                        .attribute_spelling_value(id)
                        .ok_or_else(wrong_result)
                        .and_then(|value| {
                            program::charge_results(budget, 1, &(0..0))?;
                            program::charge_bytes(budget, value.len(), &(0..0))?;
                            Ok(value.to_owned())
                        })
                })
                .collect::<Result<_, _>>()?,
            _ => return Err(wrong_result()),
        }),
    })
}

impl private::Sealed for QueryOutput {}
impl QueryResult for QueryOutput {
    fn from_query_output(output: QueryOutput) -> Result<Self, EvaluationError> {
        Ok(output)
    }
}

/// Constructed report data, before JSON or Python rendering.
pub type ReportQuery = QueryExpr<ConstructedReport>;
/// The shared native operand representation used by report expressions.
pub type ReportOperand = zirql::Expression<parser::Stage, parser::SetOperator, ()>;

/// Immutable shared value expression. Native leaves retain typed query trees.
#[derive(Clone, Debug)]
pub struct ReportExpr {
    functions: Vec<FunctionDefinition>,
    parameters: Vec<ParameterDeclaration>,
    value: ParsedComprehension,
}
/// One ordered value-match arm. Its pattern binds only in its guard and value.
#[derive(Debug)]
pub struct ReportMatchArm {
    pub pattern: Pattern,
    pub guard: Option<ReportExpr>,
    pub value: ReportExpr,
}

impl ReportExpr {
    fn with_metadata(
        mut self,
        parameters: Vec<ParameterDeclaration>,
        functions: Vec<FunctionDefinition>,
    ) -> Self {
        self.parameters = parameters;
        self.functions = functions;
        self
    }

    fn node(value: zirql::ValueExpressionKind<ReportOperand>) -> Self {
        Self {
            functions: Vec::new(),
            parameters: Vec::new(),
            value: ParsedComprehension::new(zirql::Located::new(value, 0..0)),
        }
    }
    pub(super) fn into_expression(mut self) -> zirql::ValueExpression<ReportOperand> {
        if let Some(expression) = std::sync::Arc::get_mut(&mut self.value.expression) {
            return std::mem::replace(
                expression,
                zirql::Located::new(
                    zirql::ValueExpressionKind::Literal(zirql::ConstructedValue::Integer(0)),
                    0..0,
                ),
            );
        }
        zirql::Located::new(
            zirql::ValueExpressionKind::NativeQuery(Box::new(report::operand(
                &super::builder::expression(vec![Stage::FunctionValue {
                    value: self.value,
                    range: range(),
                }]),
            ))),
            0..0,
        )
    }
    /// Explicit absence in a read-only report.
    pub fn null() -> Self {
        Self::node(zirql::ValueExpressionKind::Literal(
            zirql::ConstructedValue::Absent,
        ))
    }
    pub fn occurs(self) -> Self {
        let functions = self.functions.clone();
        let parameters = self.parameters.clone();
        Self::node(zirql::ValueExpressionKind::Occurs(Box::new(
            self.into_expression(),
        )))
        .with_metadata(parameters, functions)
    }
    pub fn absent(self) -> Self {
        let functions = self.functions.clone();
        let parameters = self.parameters.clone();
        Self::node(zirql::ValueExpressionKind::Absent(Box::new(
            self.into_expression(),
        )))
        .with_metadata(parameters, functions)
    }
    pub fn lookup(self, key: Self) -> Self {
        let functions = functions::merge(&self.functions, &key.functions);
        let parameters = merge_parameters(&self.parameters, &key.parameters);
        Self::node(zirql::ValueExpressionKind::Lookup {
            value: Box::new(self.into_expression()),
            key: Box::new(key.into_expression()),
        })
        .with_metadata(parameters, functions)
    }
    pub fn has_key(self, key: Self) -> Self {
        let functions = functions::merge(&self.functions, &key.functions);
        let parameters = merge_parameters(&self.parameters, &key.parameters);
        Self::node(zirql::ValueExpressionKind::HasKey {
            value: Box::new(self.into_expression()),
            key: Box::new(key.into_expression()),
        })
        .with_metadata(parameters, functions)
    }
    pub fn default(self, fallback: Self) -> Self {
        let functions = functions::merge(&self.functions, &fallback.functions);
        let parameters = merge_parameters(&self.parameters, &fallback.parameters);
        Self::node(zirql::ValueExpressionKind::Default {
            value: Box::new(self.into_expression()),
            fallback: Box::new(fallback.into_expression()),
        })
        .with_metadata(parameters, functions)
    }
    pub fn integer(value: i64) -> Self {
        Self::node(zirql::ValueExpressionKind::Literal(
            zirql::ConstructedValue::Integer(value),
        ))
    }
    pub fn boolean(value: bool) -> Self {
        Self::node(zirql::ValueExpressionKind::Literal(
            zirql::ConstructedValue::Boolean(value),
        ))
    }
    pub fn string(value: impl Into<String>) -> Self {
        Self::node(zirql::ValueExpressionKind::Literal(
            zirql::ConstructedValue::String(value.into()),
        ))
    }
    /// Finite floating literal construction; invalid decimals are rejected before storage.
    pub fn float(value: f64) -> Result<Self, EvaluationError> {
        if !value.is_finite() {
            return Err(EvaluationError::new("nonfinite float literal"));
        }
        Ok(Self::node(zirql::ValueExpressionKind::Literal(
            zirql::ConstructedValue::Float(value),
        )))
    }
    pub fn name(name: impl Into<String>) -> Self {
        Self::node(zirql::ValueExpressionKind::Name(name.into()))
    }
    pub fn array(values: impl IntoIterator<Item = Self>) -> Self {
        let mut functions = Vec::new();
        let mut parameters = Vec::new();
        let values = values
            .into_iter()
            .map(|value| {
                functions = functions::merge(&functions, &value.functions);
                parameters = merge_parameters(&parameters, &value.parameters);
                value.into_expression()
            })
            .collect();
        Self::node(zirql::ValueExpressionKind::Array(values)).with_metadata(parameters, functions)
    }
    /// Construct a positional tuple, distinct from a report array.
    pub fn tuple(values: impl IntoIterator<Item = Self>) -> Self {
        let mut functions = Vec::new();
        let mut parameters = Vec::new();
        let values = values
            .into_iter()
            .map(|value| {
                functions = functions::merge(&functions, &value.functions);
                parameters = merge_parameters(&parameters, &value.parameters);
                functions::normalize(value.into_expression())
            })
            .collect();
        Self::node(zirql::ValueExpressionKind::Tuple(values)).with_metadata(parameters, functions)
    }
    /// Evaluate immutable pattern bindings in order, then return the final value.
    pub fn block(bindings: Vec<(Pattern, Self)>, value: Self) -> Result<Self, EvaluationError> {
        if bindings.is_empty() {
            return Ok(value);
        }
        let mut functions = Vec::new();
        let mut parameters = Vec::new();
        let mut budget = Budget::for_program(comprehension::default_limits());
        if let Err(error) = bindings
            .iter()
            .try_for_each(|(pattern, _)| functions::validate_pattern(pattern, &mut budget))
        {
            for (pattern, _) in bindings {
                zirql::dispose_pattern(pattern);
            }
            return Err(error);
        }
        let bindings = bindings
            .into_iter()
            .map(|(pattern, value)| {
                functions = functions::merge(&functions, &value.functions);
                parameters = merge_parameters(&parameters, &value.parameters);
                (pattern, functions::normalize(value.into_expression()))
            })
            .collect();
        functions = functions::merge(&functions, &value.functions);
        parameters = merge_parameters(&parameters, &value.parameters);
        Ok(Self::node(zirql::ValueExpressionKind::Block {
            bindings,
            value: Box::new(functions::normalize(value.into_expression())),
        })
        .with_metadata(parameters, functions))
    }
    /// Select the first matching arm with a true known-Boolean guard.
    pub fn value_match(subject: Self, arms: Vec<ReportMatchArm>) -> Result<Self, EvaluationError> {
        let mut functions = subject.functions.clone();
        let mut parameters = subject.parameters.clone();
        let mut budget = Budget::for_program(comprehension::default_limits());
        if let Err(error) = arms
            .iter()
            .try_for_each(|arm| functions::validate_pattern(&arm.pattern, &mut budget))
        {
            for arm in arms {
                zirql::dispose_pattern(arm.pattern);
            }
            return Err(error);
        }
        let arms = arms
            .into_iter()
            .map(|arm| {
                if let Some(guard) = &arm.guard {
                    functions = functions::merge(&functions, &guard.functions);
                    parameters = merge_parameters(&parameters, &guard.parameters);
                }
                functions = functions::merge(&functions, &arm.value.functions);
                parameters = merge_parameters(&parameters, &arm.value.parameters);
                zirql::ValueMatchArm {
                    pattern: arm.pattern,
                    guard: arm
                        .guard
                        .map(|guard| functions::normalize(guard.into_expression())),
                    value: functions::normalize(arm.value.into_expression()),
                }
            })
            .collect();
        Ok(Self::node(zirql::ValueExpressionKind::ValueMatch {
            subject: Box::new(functions::normalize(subject.into_expression())),
            arms,
        })
        .with_metadata(parameters, functions))
    }
    pub fn record<S: Into<String>>(fields: impl IntoIterator<Item = (S, Self)>) -> Self {
        let mut functions = Vec::new();
        let mut parameters = Vec::new();
        let fields = fields
            .into_iter()
            .map(|(name, value)| {
                functions = functions::merge(&functions, &value.functions);
                parameters = merge_parameters(&parameters, &value.parameters);
                (
                    zirql::Located::new(name.into(), 0..0),
                    value.into_expression(),
                )
            })
            .collect();
        Self::node(zirql::ValueExpressionKind::Record(fields)).with_metadata(parameters, functions)
    }
    pub fn field(self, name: impl Into<String>) -> Self {
        let functions = self.functions.clone();
        let parameters = self.parameters.clone();
        Self::node(zirql::ValueExpressionKind::Field {
            value: Box::new(self.into_expression()),
            field: zirql::Located::new(name.into(), 0..0),
        })
        .with_metadata(parameters, functions)
    }
    pub fn at(self, index: Self) -> Self {
        let functions = functions::merge(&self.functions, &index.functions);
        let parameters = merge_parameters(&self.parameters, &index.parameters);
        Self::node(zirql::ValueExpressionKind::ArrayAccess {
            array: Box::new(self.into_expression()),
            index: Box::new(index.into_expression()),
        })
        .with_metadata(parameters, functions)
    }
    pub fn unary(self, operator: zirql::ValueUnaryOperator) -> Self {
        let functions = self.functions.clone();
        let parameters = self.parameters.clone();
        Self::node(zirql::ValueExpressionKind::Unary {
            operator,
            operand: Box::new(self.into_expression()),
        })
        .with_metadata(parameters, functions)
    }
    pub fn binary(self, operator: zirql::ValueBinaryOperator, right: Self) -> Self {
        let functions = functions::merge(&self.functions, &right.functions);
        let parameters = merge_parameters(&self.parameters, &right.parameters);
        Self::node(zirql::ValueExpressionKind::Binary {
            operator,
            left: Box::new(self.into_expression()),
            right: Box::new(right.into_expression()),
        })
        .with_metadata(parameters, functions)
    }
    /// Match an exact case-sensitive substring. An empty fragment matches.
    pub fn contains(self, fragment: Self) -> Self {
        self.binary(zirql::ValueBinaryOperator::Contains, fragment)
    }
    /// Match an exact case-sensitive prefix. An empty prefix matches.
    pub fn starts_with(self, prefix: Self) -> Self {
        self.binary(zirql::ValueBinaryOperator::StartsWith, prefix)
    }
    /// Match an exact case-sensitive suffix. An empty suffix matches.
    pub fn ends_with(self, suffix: Self) -> Self {
        self.binary(zirql::ValueBinaryOperator::EndsWith, suffix)
    }
    pub fn one(self) -> Self {
        let functions = self.functions.clone();
        let parameters = self.parameters.clone();
        Self::node(zirql::ValueExpressionKind::One(Box::new(
            self.into_expression(),
        )))
        .with_metadata(parameters, functions)
    }
    pub fn reduce(self, operator: zirql::ValueReducer) -> Self {
        let functions = self.functions.clone();
        let parameters = self.parameters.clone();
        Self::node(zirql::ValueExpressionKind::Reduce {
            operator,
            array: Box::new(self.into_expression()),
        })
        .with_metadata(parameters, functions)
    }
    pub fn length(self) -> Self {
        self.reduce(zirql::ValueReducer::Length)
    }
    pub fn sum(self) -> Self {
        self.reduce(zirql::ValueReducer::Sum)
    }
    pub fn forall(self) -> Self {
        self.reduce(zirql::ValueReducer::Forall)
    }
    pub fn exists(self) -> Self {
        self.reduce(zirql::ValueReducer::Exists)
    }
    /// Stably sort scalar values. Descending order keeps input order for ties.
    pub fn sort(self, descending: bool) -> Self {
        self.sort_selector(None, descending)
    }
    /// Stably sort records by a static field, retaining original rows and ties.
    pub fn sort_by(self, field: impl Into<String>, descending: bool) -> Self {
        self.sort_selector(Some(zirql::SortSelector::Field(field.into())), descending)
    }
    /// Stably sort dictionary entries by their scalar values.
    pub fn sort_by_value(self, descending: bool) -> Self {
        self.sort_selector(Some(zirql::SortSelector::Value), descending)
    }
    fn sort_selector(self, selector: Option<zirql::SortSelector>, descending: bool) -> Self {
        let functions = self.functions.clone();
        let parameters = self.parameters.clone();
        Self::node(zirql::ValueExpressionKind::Sort {
            array: Box::new(self.into_expression()),
            selector: selector.map(|selector| zirql::Located::new(selector, 0..0)),
            descending,
        })
        .with_metadata(parameters, functions)
    }
    /// Smallest scalar, or absence for empty input; first input wins ties.
    pub fn min(self) -> Self {
        self.extremum(zirql::ValueExtremum::Min, None)
    }
    /// Largest scalar, or absence for empty input; first input wins ties.
    pub fn max(self) -> Self {
        self.extremum(zirql::ValueExtremum::Max, None)
    }
    /// Original record with the smallest field; empty is absent and ties keep first.
    pub fn min_by(self, field: impl Into<String>) -> Self {
        self.extremum(zirql::ValueExtremum::Min, Some(field.into()))
    }
    /// Original record with the largest field; empty is absent and ties keep first.
    pub fn max_by(self, field: impl Into<String>) -> Self {
        self.extremum(zirql::ValueExtremum::Max, Some(field.into()))
    }
    fn extremum(self, operator: zirql::ValueExtremum, field: Option<String>) -> Self {
        let functions = self.functions.clone();
        let parameters = self.parameters.clone();
        Self::node(zirql::ValueExpressionKind::Extremum {
            operator,
            array: Box::new(self.into_expression()),
            field: field.map(|field| zirql::Located::new(field, 0..0)),
        })
        .with_metadata(parameters, functions)
    }
    /// Group positional records by a static field, preserving first-seen keys
    /// and every row's order. Evaluation requires homogeneous supported keys.
    pub fn group_by(self, field: impl Into<String>) -> Self {
        let functions = self.functions.clone();
        let parameters = self.parameters.clone();
        Self::node(zirql::ValueExpressionKind::GroupBy {
            rows: Box::new(self.into_expression()),
            field: zirql::Located::new(field.into(), 0..0),
        })
        .with_metadata(parameters, functions)
    }
    pub fn require(condition: Self, value: Self, message: impl Into<String>) -> Self {
        let functions = functions::merge(&condition.functions, &value.functions);
        let parameters = merge_parameters(&condition.parameters, &value.parameters);
        Self::node(zirql::ValueExpressionKind::Require {
            condition: Box::new(condition.into_expression()),
            value: Box::new(value.into_expression()),
            message: zirql::Located::new(message.into(), 0..0),
        })
        .with_metadata(parameters, functions)
    }
    pub fn comprehension(head: Self, clauses: impl IntoIterator<Item = ReportGenerator>) -> Self {
        let mut functions = head.functions.clone();
        let mut parameters = head.parameters.clone();
        let clauses = clauses
            .into_iter()
            .map(|clause| {
                functions = functions::merge(&functions, &clause.functions);
                parameters = merge_parameters(&parameters, &clause.parameters);
                clause.clause
            })
            .collect();
        Self::node(zirql::ValueExpressionKind::Comprehension {
            constructor: zirql::ValueConstructor::Array,
            clauses,
            head: Box::new(head.into_expression()),
        })
        .with_metadata(parameters, functions)
    }
    /// Evaluate immutable local bindings in order, then return one constructed value.
    pub fn scope<S: Into<String>>(
        bindings: impl IntoIterator<Item = (S, Self)>,
        value: Self,
    ) -> Self {
        Self::comprehension(
            value,
            bindings
                .into_iter()
                .map(|(name, value)| ReportGenerator::bind(name, value)),
        )
        .one()
    }
}
/// A shared generator clause, with immutable binding and optional known-Boolean filter.
pub struct ReportGenerator {
    functions: Vec<FunctionDefinition>,
    parameters: Vec<ParameterDeclaration>,
    clause: zirql::Located<zirql::ValueGenerator<ReportOperand>>,
}
impl ReportGenerator {
    pub fn in_values(
        name: impl Into<String>,
        source: ReportExpr,
        filter: Option<ReportExpr>,
    ) -> Self {
        let functions = functions::merge(
            &source.functions,
            &filter
                .as_ref()
                .map(|value| value.functions.clone())
                .unwrap_or_default(),
        );
        let parameters = merge_parameters(
            &source.parameters,
            &filter
                .as_ref()
                .map(|value| value.parameters.clone())
                .unwrap_or_default(),
        );
        Self {
            functions,
            parameters,
            clause: zirql::Located::new(
                zirql::ValueGenerator::In {
                    binders: vec![zirql::Located::new(
                        zirql::PatternKind::Name(zirql::Located::new(name.into(), 0..0)),
                        0..0,
                    )],
                    source: source.into_expression(),
                    filter: filter.map(ReportExpr::into_expression),
                },
                0..0,
            ),
        }
    }
    pub fn bind(name: impl Into<String>, value: ReportExpr) -> Self {
        Self {
            functions: value.functions.clone(),
            parameters: value.parameters.clone(),
            clause: zirql::Located::new(
                zirql::ValueGenerator::Bind {
                    binder: zirql::Located::new(
                        zirql::PatternKind::Name(zirql::Located::new(name.into(), 0..0)),
                        0..0,
                    ),
                    value: value.into_expression(),
                    filter: None,
                },
                0..0,
            ),
        }
    }
}
/// Refer to a saved native operation selection or the local projection subject.
pub fn bound_ops(name: impl Into<String>) -> OpQuery {
    QueryExpr::start(vec![Stage::Binding {
        name: name.into(),
        range: range(),
    }])
}
fn project_rows<T, S: Into<String>>(
    query: &QueryExpr<T>,
    subject: impl Into<String>,
    fields: impl IntoIterator<Item = (S, ReportExpr)>,
) -> ReportQuery {
    let mut functions = Vec::new();
    let mut parameters = Vec::new();
    let fields = fields
        .into_iter()
        .map(|(name, value)| {
            functions = functions::merge(&functions, &value.functions);
            parameters = merge_parameters(&parameters, &value.parameters);
            (
                zirql::Located::new(name.into(), 0..0),
                value.into_expression(),
            )
        })
        .collect();
    query
        .stage(Stage::Projection {
            value: report::ParsedProjection::new(zirql::Projection {
                subject: zirql::Located::new(subject.into(), 0..0),
                fields,
            }),
            range: range(),
        })
        .with_parameters(parameters)
        .with_functions(functions)
}
impl OpQuery {
    pub fn project<S: Into<String>>(
        &self,
        subject: impl Into<String>,
        fields: impl IntoIterator<Item = (S, ReportExpr)>,
    ) -> ReportQuery {
        project_rows(self, subject, fields)
    }
}
/// Construct a typed read-only report without requesting an emitter.
pub fn report(value: ReportExpr) -> ReportQuery {
    let stage = if report::value_requires_session(&value.value.expression) {
        Stage::FunctionValue {
            value: value.value,
            range: range(),
        }
    } else {
        Stage::Comprehension {
            value: value.value,
            range: range(),
        }
    };
    QueryExpr::start(vec![stage])
        .with_parameters(value.parameters)
        .with_functions(value.functions)
}
macro_rules! report_query_conversion {
    ($result:ty) => {
        impl From<QueryExpr<$result>> for ReportExpr {
            fn from(query: QueryExpr<$result>) -> Self {
                Self::node(zirql::ValueExpressionKind::NativeQuery(Box::new(
                    report::operand(&query.expression),
                )))
                .with_metadata(query.parameters, query.functions)
            }
        }
    };
}
report_query_conversion!(Vec<String>);
report_query_conversion!(String);
report_query_conversion!(usize);
report_query_conversion!(ConstructedReport);
impl From<i64> for ReportExpr {
    fn from(value: i64) -> Self {
        Self::integer(value)
    }
}
impl From<bool> for ReportExpr {
    fn from(value: bool) -> Self {
        Self::boolean(value)
    }
}
impl From<String> for ReportExpr {
    fn from(value: String) -> Self {
        Self::string(value)
    }
}
impl From<&str> for ReportExpr {
    fn from(value: &str) -> Self {
        Self::string(value)
    }
}
result!(ConstructedReport, QueryOutput::Native(NativeValue::Constructed(value))=>value);

/// Compare an operation name with a checked shared string expression.
pub fn op_expr(name: ReportExpr) -> Predicate {
    let functions = name.functions;
    let parameters = name.parameters;
    let mut predicate = Predicate::new(model::Predicate::OpValue {
        name: name.value,
        range: range(),
    });
    predicate.parameters = parameters;
    predicate.functions = functions;
    predicate
}
/// A query returning one exact document-owned SSA value.
pub type SsaQuery = QueryExpr<ValueId>;
/// A query returning ordered native capture records, with an empty-result schema.
pub type CaptureQuery = QueryExpr<CaptureMatches>;
result!(ValueId, QueryOutput::Native(NativeValue::Ssa(value)) => value);
result!(CaptureMatches, QueryOutput::Native(NativeValue::Captures(value)) => value);

impl OpQuery {
    /// Read a required zero-based operand from exactly one selected operation.
    pub fn operand(&self, index: usize) -> SsaQuery {
        let mut query = QueryExpr::start(vec![Stage::Operand {
            operation: capture::ParsedOperand::new(report::operand(&self.expression)),
            index,
            range: range(),
        }])
        .with_parameters(self.parameters.clone())
        .with_functions(self.functions.clone());
        query.depth = self.depth.saturating_add(1);
        query.nodes = self.nodes.saturating_add(1);
        query.invalid = self
            .invalid
            .or((query.depth > parser::DEFAULT_NESTING_LIMIT)
                .then_some("query nesting limit exceeded"));
        query
    }
}
/// Read a previously captured SSA value in a later clause.
pub fn bound_ssa(name: impl Into<String>) -> SsaQuery {
    QueryExpr::start(vec![Stage::Binding {
        name: name.into(),
        range: range(),
    }])
}
/// Select a native operation field from one named capture record.
pub fn capture_ops(subject: impl Into<String>, field: impl Into<String>) -> OpQuery {
    QueryExpr::start(vec![Stage::Native {
        value: capture::ParsedOperand::field(
            subject.into(),
            field.into(),
            capture::NativeKind::Operations,
        ),
        range: range(),
    }])
}
/// Select an exact SSA field from one named capture record.
pub fn capture_ssa(subject: impl Into<String>, field: impl Into<String>) -> SsaQuery {
    QueryExpr::start(vec![Stage::Native {
        value: capture::ParsedOperand::field(
            subject.into(),
            field.into(),
            capture::NativeKind::Ssa,
        ),
        range: range(),
    }])
}

/// Immutable Boolean guard over native SSA queries. Use `&`, `|` and `!` to compose.
#[derive(Clone, Debug)]
pub struct MatchPredicate {
    inner: zirql::Predicate<model::Predicate>,
    functions: Vec<FunctionDefinition>,
    parameters: Vec<ParameterDeclaration>,
    depth: usize,
    nodes: usize,
    invalid: Option<&'static str>,
}
/// Compare full checked ValueId identities, including result/argument position.
pub fn same_value(left: &SsaQuery, right: &SsaQuery) -> MatchPredicate {
    MatchPredicate {
        functions: functions::merge(&left.functions, &right.functions),
        inner: zirql::Located::new(
            zirql::PredicateKind::Leaf(model::Predicate::SameValue {
                left: capture::ParsedOperand::new(report::operand(&left.expression)),
                right: capture::ParsedOperand::new(report::operand(&right.expression)),
                range: range(),
            }),
            0..0,
        ),
        parameters: merge_parameters(&left.parameters, &right.parameters),
        depth: left.depth.max(right.depth).saturating_add(1),
        nodes: left.nodes.saturating_add(right.nodes).saturating_add(1),
        invalid: left.invalid.or(right.invalid),
    }
}
impl MatchPredicate {
    fn combine(self, other: Self, conjunction: bool) -> Self {
        let depth = self.depth.max(other.depth).saturating_add(1);
        let invalid = self
            .invalid
            .or(other.invalid)
            .or((depth > parser::DEFAULT_NESTING_LIMIT).then_some("query nesting limit exceeded"));
        let parameters = merge_parameters(&self.parameters, &other.parameters);
        let functions = functions::merge(&self.functions, &other.functions);
        let nodes = self.nodes.saturating_add(other.nodes).saturating_add(1);
        let inner = if invalid.is_some() {
            zirql::PredicateKind::Leaf(model::Predicate::Bool {
                value: false,
                range: range(),
            })
        } else if conjunction {
            zirql::PredicateKind::And(vec![self.inner, other.inner])
        } else {
            zirql::PredicateKind::Or(vec![self.inner, other.inner])
        };
        Self {
            inner: zirql::Located::new(inner, 0..0),
            functions,
            parameters,
            depth,
            nodes,
            invalid,
        }
    }
}
impl BitAnd for MatchPredicate {
    type Output = Self;
    fn bitand(self, other: Self) -> Self {
        self.combine(other, true)
    }
}
impl BitOr for MatchPredicate {
    type Output = Self;
    fn bitor(self, other: Self) -> Self {
        self.combine(other, false)
    }
}
impl Not for MatchPredicate {
    type Output = Self;
    fn not(self) -> Self {
        let depth = self.depth.saturating_add(1);
        let invalid = self
            .invalid
            .or((depth > parser::DEFAULT_NESTING_LIMIT).then_some("query nesting limit exceeded"));
        let inner = if invalid.is_some() {
            zirql::PredicateKind::Leaf(model::Predicate::Bool {
                value: false,
                range: range(),
            })
        } else {
            zirql::PredicateKind::Not(Box::new(self.inner))
        };
        Self {
            inner: zirql::Located::new(inner, 0..0),
            functions: self.functions,
            parameters: self.parameters,
            depth,
            nodes: self.nodes.saturating_add(1),
            invalid,
        }
    }
}

/// Build required native captures in written clause order. Construction reads no document.
#[derive(Debug)]
pub struct MatchBuilder {
    clauses: Vec<zirql::Located<zirql::MatchClause<capture::ParsedOperand, model::Predicate>>>,
    functions: Vec<FunctionDefinition>,
    parameters: Vec<ParameterDeclaration>,
    depth: usize,
    nodes: usize,
    invalid: Option<&'static str>,
}
impl Clone for MatchBuilder {
    fn clone(&self) -> Self {
        let clauses = self
            .clauses
            .iter()
            .map(|clause| {
                zirql::Located::new(
                    match &clause.value {
                        zirql::MatchClause::From { name, source } => zirql::MatchClause::From {
                            name: name.clone(),
                            source: source.clone(),
                        },
                        zirql::MatchClause::Bind { name, value } => zirql::MatchClause::Bind {
                            name: name.clone(),
                            value: value.clone(),
                        },
                        zirql::MatchClause::Where { predicate } => zirql::MatchClause::Where {
                            predicate: predicate.clone(),
                        },
                    },
                    clause.range.clone(),
                )
            })
            .collect();
        Self {
            clauses,
            functions: self.functions.clone(),
            parameters: self.parameters.clone(),
            depth: self.depth,
            nodes: self.nodes,
            invalid: self.invalid,
        }
    }
}
/// Start an empty finite native match chain.
pub fn matches() -> MatchBuilder {
    MatchBuilder {
        clauses: vec![],
        functions: vec![],
        parameters: vec![],
        depth: 1,
        nodes: 1,
        invalid: None,
    }
}
impl MatchBuilder {
    fn operand<T>(mut self, name: String, query: &QueryExpr<T>, binding: bool) -> Self {
        self.functions = functions::merge(&self.functions, &query.functions);
        self.parameters = merge_parameters(&self.parameters, &query.parameters);
        self.depth = self.depth.max(query.depth.saturating_add(1));
        self.nodes = self.nodes.saturating_add(query.nodes).saturating_add(1);
        self.invalid = self.invalid.or(query.invalid);
        let source = capture::ParsedOperand::new(report::operand(&query.expression));
        let name = zirql::Located::new(name, 0..0);
        let clause = if binding {
            zirql::MatchClause::Bind {
                name,
                value: source,
            }
        } else {
            zirql::MatchClause::From { name, source }
        };
        self.clauses.push(zirql::Located::new(clause, 0..0));
        self
    }
    pub fn from(self, name: impl Into<String>, source: &OpQuery) -> Self {
        self.operand(name.into(), source, false)
    }
    pub fn bind(self, name: impl Into<String>, value: &SsaQuery) -> Self {
        self.operand(name.into(), value, true)
    }
    pub fn where_(mut self, guard: &MatchPredicate) -> Self {
        self.functions = functions::merge(&self.functions, &guard.functions);
        self.parameters = merge_parameters(&self.parameters, &guard.parameters);
        self.depth = self.depth.max(guard.depth.saturating_add(1));
        self.nodes = self.nodes.saturating_add(guard.nodes).saturating_add(1);
        self.invalid = self.invalid.or(guard.invalid);
        self.clauses.push(zirql::Located::new(
            zirql::MatchClause::Where {
                predicate: guard.inner.clone(),
            },
            0..0,
        ));
        self
    }
    pub fn build(self) -> CaptureQuery {
        let native = |value: capture::ParsedOperand| capture::native_source(value, 0..0);
        let count = self.clauses.len();
        let clauses = self
            .clauses
            .into_iter()
            .map(|clause| {
                zirql::Located::new(
                    match clause.value {
                        zirql::MatchClause::From { name, source } => zirql::MatchClause::From {
                            name,
                            source: native(source),
                        },
                        zirql::MatchClause::Bind { name, value } => zirql::MatchClause::Bind {
                            name,
                            value: native(value),
                        },
                        zirql::MatchClause::Where { predicate } => {
                            zirql::MatchClause::Where { predicate }
                        }
                    },
                    clause.range,
                )
            })
            .collect();
        let mut query = QueryExpr::start(vec![Stage::Match {
            value: capture::ParsedMatch::new(zirql::NativeMatch {
                clauses,
                range: 0..0,
            }),
            range: range(),
        }])
        .with_parameters(self.parameters)
        .with_functions(self.functions);
        query.depth = self.depth.max(count.saturating_add(1));
        query.nodes = self.nodes;
        query.invalid = self
            .invalid
            .or((query.depth > parser::DEFAULT_NESTING_LIMIT)
                .then_some("query nesting limit exceeded"));
        query
    }
}
impl CaptureQuery {
    /// Explicitly project native capture fields into ordered scalar report rows.
    pub fn project<S: Into<String>>(
        &self,
        subject: impl Into<String>,
        fields: impl IntoIterator<Item = (S, ReportExpr)>,
    ) -> ReportQuery {
        project_rows(self, subject, fields)
    }
}

impl ReportExpr {
    /// Call a declared pure function with explicit inputs.
    pub fn call(name: impl Into<String>, arguments: impl IntoIterator<Item = Self>) -> Self {
        let mut parameters = Vec::new();
        let mut functions = Vec::new();
        let arguments = arguments
            .into_iter()
            .map(|argument| {
                parameters = merge_parameters(&parameters, &argument.parameters);
                functions = functions::merge(&functions, &argument.functions);
                functions::normalize(argument.into_expression())
            })
            .collect();
        Self::node(zirql::ValueExpressionKind::Call {
            function: Located::new(name.into(), 0..0),
            arguments,
        })
        .with_metadata(parameters, functions)
    }
    /// Retain a native query result as an explicit function operand.
    pub fn native<T>(query: &QueryExpr<T>) -> Self {
        Self::node(zirql::ValueExpressionKind::NativeValue(Box::new(
            report::operand(&query.expression),
        )))
        .with_metadata(query.parameters.clone(), query.functions.clone())
    }
    pub fn user_info(operation: Self) -> Self {
        Self::primitive(functions::Primitive::UserInfo, operation)
    }
    pub fn same_operation(left: Self, right: Self) -> Self {
        Self::primitive(
            functions::Primitive::SameOperation,
            Self::tuple([left, right]),
        )
    }
    pub fn direct_children(operation: Self) -> Self {
        Self::primitive(functions::Primitive::DirectChildren, operation)
    }
    pub fn cost_annotation(operation: Self) -> Self {
        Self::primitive(functions::Primitive::CostAnnotation, operation)
    }
    fn primitive(primitive: functions::Primitive, argument: Self) -> Self {
        let parameters = argument.parameters.clone();
        let functions = argument.functions.clone();
        Self::node(zirql::ValueExpressionKind::NativeValue(Box::new(
            report::operand(&expression(vec![Stage::FunctionPrimitive {
                primitive,
                argument: ParsedComprehension::new(functions::normalize(
                    argument.into_expression(),
                )),
                range: range(),
            }])),
        )))
        .with_metadata(parameters, functions)
    }
    /// Evaluate only the selected branch; prepare both written branches.
    pub fn conditional(condition: Self, selected: Self, otherwise: Self) -> Self {
        let parameters = merge_parameters(
            &merge_parameters(&condition.parameters, &selected.parameters),
            &otherwise.parameters,
        );
        let functions = functions::merge(
            &functions::merge(&condition.functions, &selected.functions),
            &otherwise.functions,
        );
        Self::node(zirql::ValueExpressionKind::Conditional {
            branches: vec![(condition.into_expression(), selected.into_expression())],
            otherwise: Box::new(otherwise.into_expression()),
        })
        .with_metadata(parameters, functions)
    }
}
/// Start a native or scalar query with a declared function call.
pub fn function_call<T: QueryResult>(
    name: impl Into<String>,
    arguments: impl IntoIterator<Item = ReportExpr>,
) -> QueryExpr<T> {
    let call = ReportExpr::call(name, arguments);
    QueryExpr::start(vec![Stage::FunctionValue {
        value: call.value,
        range: range(),
    }])
    .with_parameters(call.parameters)
    .with_functions(call.functions)
}

impl ReportExpr {
    /// Supply an explicit document-owned operation to a checked function argument.
    pub fn operation(operation: OperationId) -> Self {
        Self::native_input(QueryOutput::Operations(vec![operation]))
    }
    /// Supply an exact SSA identity; admission checks its current document owner.
    pub fn ssa_value(value: ValueId) -> Self {
        Self::native_input(QueryOutput::Native(NativeValue::Ssa(value)))
    }
    /// Supply an explicit native record view. Pattern admission checks retained
    /// handles against the current document before exposing selected fields.
    pub fn capture(fields: Vec<(String, QueryOutput)>) -> Self {
        Self::native_input(QueryOutput::Native(NativeValue::Capture(
            zirql::NativeCapture { fields },
        )))
    }
    /// Supply a sequence whose cardinality remains explicit, including zero or one.
    pub fn operation_sequence(operations: Vec<OperationId>) -> Self {
        Self::native_input(QueryOutput::Native(NativeValue::OperationSequence(
            operations,
        )))
    }
    pub fn native_input(value: QueryOutput) -> Self {
        Self::node(zirql::ValueExpressionKind::NativeValue(Box::new(
            report::operand(&expression(vec![Stage::FunctionInput {
                value: std::sync::Arc::new(value),
                range: range(),
            }])),
        )))
    }
}

impl ReportExpr {
    /// Repeatedly replace all immutable state slots until a selected break.
    pub fn loop_(states: impl IntoIterator<Item = (String, Self)>, body: Self) -> Self {
        let mut parameters = body.parameters.clone();
        let mut functions = body.functions.clone();
        let states = states
            .into_iter()
            .map(|(name, value)| {
                parameters = merge_parameters(&parameters, &value.parameters);
                functions = functions::merge(&functions, &value.functions);
                (
                    Located::new(name, 0..0),
                    functions::normalize(value.into_expression()),
                )
            })
            .collect();
        Self::node(zirql::ValueExpressionKind::Loop {
            states,
            body: Box::new(functions::normalize(body.into_expression())),
        })
        .with_metadata(parameters, functions)
    }
    /// Exit the innermost loop with this value.
    pub fn break_(value: Self) -> Self {
        let parameters = value.parameters.clone();
        let functions = value.functions.clone();
        Self::node(zirql::ValueExpressionKind::Break(Box::new(
            functions::normalize(value.into_expression()),
        )))
        .with_metadata(parameters, functions)
    }
    /// Compute every successor against the old state, in written order.
    pub fn continue_(values: impl IntoIterator<Item = Self>) -> Self {
        let mut parameters = Vec::new();
        let mut functions = Vec::new();
        let values = values
            .into_iter()
            .map(|value| {
                parameters = merge_parameters(&parameters, &value.parameters);
                functions = functions::merge(&functions, &value.functions);
                functions::normalize(value.into_expression())
            })
            .collect();
        Self::node(zirql::ValueExpressionKind::Continue(values))
            .with_metadata(parameters, functions)
    }
    /// Reduce an eager sequence using a resolved named pure step.
    pub fn fold(items: Self, initial: Self, step: impl Into<String>) -> Self {
        Self::named_reducer(items, initial, step.into(), false)
    }
    /// Retain every post-step state, excluding the initial state.
    pub fn scan(items: Self, initial: Self, step: impl Into<String>) -> Self {
        Self::named_reducer(items, initial, step.into(), true)
    }
    fn named_reducer(items: Self, initial: Self, step: String, scan: bool) -> Self {
        let parameters = merge_parameters(&items.parameters, &initial.parameters);
        let functions = functions::merge(&items.functions, &initial.functions);
        let items = Box::new(functions::normalize(items.into_expression()));
        let initial = Box::new(functions::normalize(initial.into_expression()));
        let step = Located::new(step, 0..0);
        Self::node(if scan {
            zirql::ValueExpressionKind::Scan {
                items,
                initial,
                step,
            }
        } else {
            zirql::ValueExpressionKind::Fold {
                items,
                initial,
                step,
            }
        })
        .with_metadata(parameters, functions)
    }
    pub fn queue(items: Self) -> Self {
        Self::queue_with_type(items, None)
    }
    /// Establish an element declaration even when the input is empty.
    pub fn typed_queue(items: Self, element: zirql::SignatureType) -> Self {
        Self::queue_with_type(items, Some(element))
    }
    fn queue_with_type(items: Self, element: Option<zirql::SignatureType>) -> Self {
        let parameters = items.parameters.clone();
        let functions = items.functions.clone();
        Self::node(zirql::ValueExpressionKind::Queue {
            items: Box::new(functions::normalize(items.into_expression())),
            element: element.map(|value| Located::new(value, 0..0)),
        })
        .with_metadata(parameters, functions)
    }
    pub fn pop_front(queue: Self) -> Self {
        let parameters = queue.parameters.clone();
        let functions = queue.functions.clone();
        Self::node(zirql::ValueExpressionKind::PopFront(Box::new(
            functions::normalize(queue.into_expression()),
        )))
        .with_metadata(parameters, functions)
    }
    pub fn push_back_all(queue: Self, items: Self) -> Self {
        let parameters = merge_parameters(&queue.parameters, &items.parameters);
        let functions = functions::merge(&queue.functions, &items.functions);
        Self::node(zirql::ValueExpressionKind::PushBackAll {
            queue: Box::new(functions::normalize(queue.into_expression())),
            items: Box::new(functions::normalize(items.into_expression())),
        })
        .with_metadata(parameters, functions)
    }
    pub fn identity_set(element: FunctionNativeType) -> Self {
        let name = match element {
            FunctionNativeType::Operation => "Operation",
            FunctionNativeType::SSAValue => "SSAValue",
        };
        Self::node(zirql::ValueExpressionKind::IdentitySet {
            element: Located::new(
                zirql::SignatureType::Named(Located::new(name.to_owned(), 0..0)),
                0..0,
            ),
        })
    }
    pub fn is_in(self, set: Self) -> Self {
        self.binary(zirql::ValueBinaryOperator::In, set)
    }
    pub fn insert(set: Self, item: Self) -> Self {
        let parameters = merge_parameters(&set.parameters, &item.parameters);
        let functions = functions::merge(&set.functions, &item.functions);
        Self::node(zirql::ValueExpressionKind::Insert {
            set: Box::new(functions::normalize(set.into_expression())),
            item: Box::new(functions::normalize(item.into_expression())),
        })
        .with_metadata(parameters, functions)
    }
}