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
//! Typed pure functions retain shared trees and document-owned native handles.
use super::*;
use std::{ops::Range, sync::Arc};
use zirql::{DeclaredType as D, FunctionHost, ProjectionHost, RuntimeTypeHost, ValueType};

pub use zirql::{FunctionLimits, FunctionParameter, Pattern, PatternKind, PatternParameter};
/// Native signature identities; `SSAValue` is Zirium's checked `ValueId`.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum FunctionNativeType {
    Operation,
    SSAValue,
}
pub type FunctionType = D<FunctionNativeType>;
pub(super) type Declaration = zirql::PatternFunctionDeclaration<report::Operand, program::Kind>;
pub(super) const DEFAULT_LIMITS: FunctionLimits = FunctionLimits { active_depth: 64 };

/// A located function definition shared through typed query composition.
#[derive(Debug)]
pub struct FunctionDefinition {
    pub(super) declaration: Arc<Declaration>,
}
impl Clone for FunctionDefinition {
    fn clone(&self) -> Self {
        Self {
            declaration: Arc::clone(&self.declaration),
        }
    }
}
impl PartialEq for FunctionDefinition {
    fn eq(&self, other: &Self) -> bool {
        self.declaration == other.declaration
    }
}
impl Eq for FunctionDefinition {}
impl Drop for FunctionDefinition {
    fn drop(&mut self) {
        if let Some(d) = Arc::get_mut(&mut self.declaration) {
            for parameter in std::mem::take(&mut d.parameters) {
                zirql::dispose_pattern(parameter.value.pattern);
            }
            let value = std::mem::replace(
                &mut d.value.value,
                zirql::ValueExpressionKind::Literal(ConstructedValue::Absent),
            );
            report::dispose_value(value);
        }
    }
}
impl FunctionDefinition {
    pub(super) fn parsed(declaration: Declaration) -> Self {
        Self {
            declaration: Arc::new(declaration),
        }
    }
}
pub(super) fn merge(
    left: &[FunctionDefinition],
    right: &[FunctionDefinition],
) -> Vec<FunctionDefinition> {
    let mut result = left.to_vec();
    for function in right {
        if !result
            .iter()
            .any(|f| Arc::ptr_eq(&f.declaration, &function.declaration))
        {
            result.push(function.clone());
        }
    }
    result
}
pub(super) fn resolve_type(
    name: Located<&str>,
    _: &mut Budget,
) -> Result<D<program::Kind>, zirql::QueryError> {
    Ok(D::Native(match name.value {
        "Operation" => program::Kind::Operations,
        "SSAValue" => program::Kind::Ssa,
        _ => {
            return Err(zirql::QueryError::query(
                name.range,
                "unknown function signature type",
            ));
        }
    }))
}

pub(super) fn scalar_facts(
    ty: &D<program::Kind>,
    budget: &mut Budget,
    range: &Range<usize>,
) -> Result<Vec<ValueType>, zirql::QueryError> {
    {
        budget.charge(1, ValueLocation::Query(range.clone()))?;
        budget.charge_results(1, ValueLocation::Query(range.clone()))?;
        Ok(match ty {
            D::Boolean => vec![ValueType::Boolean],
            D::Integer => vec![ValueType::Integer],
            D::Float => vec![ValueType::Float],
            D::String => vec![ValueType::String],
            D::Optional(value) => {
                let mut facts = scalar_facts(value, budget, range)?;
                facts.push(ValueType::Absent);
                facts
            }
            D::Sequence(value) | D::Array(value) => vec![ValueType::Array(
                zirql::ArrayType::Elements(scalar_facts(value, budget, range)?),
            )],
            D::Tuple(values) => vec![ValueType::Tuple(
                values
                    .iter()
                    .map(|v| scalar_facts(v, budget, range).map(|mut t| t.remove(0)))
                    .collect::<Result<_, _>>()?,
            )],
            D::Record(fields) => vec![ValueType::Record(
                fields
                    .iter()
                    .map(|(n, v)| {
                        budget.charge(n.len() + 1, ValueLocation::Query(range.clone()))?;
                        Ok((n.clone(), scalar_facts(v, budget, range)?.remove(0)))
                    })
                    .collect::<Result<_, zirql::QueryError>>()?,
            )],
            D::Set(element) => vec![ValueType::Set(Some(*element))],
            D::Member(id) => vec![ValueType::Member(*id)],
            D::Keyed(value) => vec![ValueType::KeyedArray(zirql::KeyedArrayType {
                axes: None,
                elements: scalar_facts(value, budget, range)?,
            })],
            D::Native(_) => vec![ValueType::Unestablished],
            D::Queue(_) | D::IdentitySet(_) => vec![ValueType::Unestablished],
        })
    }
}
impl<'q> FunctionHost<EvaluationContext<'_, '_, 'q>> for report::ReportHost<'_> {
    fn retains_native_admission(&self) -> bool {
        true
    }
    fn resolve_type_name(
        &self,
        name: Located<&str>,
        budget: &mut Budget,
    ) -> Result<D<program::Kind>, zirql::QueryError> {
        budget.charge(
            name.value.len() + 1,
            ValueLocation::Query(name.range.clone()),
        )?;
        resolve_type(name, budget)
    }
    fn prepare_computational(
        &self,
        declaration: Option<&D<program::Kind>>,
        budget: &mut Budget,
        range: &Range<usize>,
    ) -> Result<(), zirql::QueryError> {
        budget.charge(1, ValueLocation::Query(range.clone()))?;
        if let Some(declaration) = declaration {
            if matches!(declaration, D::IdentitySet(kind) if !matches!(kind, program::Kind::Operations | program::Kind::Ssa))
            {
                return Err(zirql::QueryError::query(
                    range.clone(),
                    "identity_set requires Operation or SSAValue",
                ));
            }
            self.declaration_kind(declaration, budget, range)?;
        }
        Ok(())
    }
    fn computational_value<'v>(
        &self,
        value: &'v QueryOutput,
    ) -> Option<&'v zirql::ComputationalValue<QueryOutput, program::Kind>> {
        match unretained(value) {
            QueryOutput::Native(NativeValue::Computational(value)) => Some(&value.value),
            _ => None,
        }
    }
    fn lift_computational(
        &self,
        value: zirql::ComputationalValue<QueryOutput, program::Kind>,
        _: &mut EvaluationContext<'_, '_, 'q>,
        budget: &mut Budget,
        range: &Range<usize>,
    ) -> Result<QueryOutput, zirql::EvaluationError<EvaluationError>> {
        budget.charge_results(1, ValueLocation::Query(range.clone()))?;
        Ok(QueryOutput::Native(NativeValue::Computational(
            worklists::Computational {
                value: Arc::new(value),
                range: range.clone(),
            },
        )))
    }
    fn construct_tuple(
        &self,
        values: Vec<QueryOutput>,
        _: &mut EvaluationContext<'_, '_, 'q>,
        budget: &mut Budget,
        range: &Range<usize>,
    ) -> Result<QueryOutput, zirql::EvaluationError<EvaluationError>> {
        budget.charge_results(values.len() + 1, ValueLocation::Query(range.clone()))?;
        Ok(QueryOutput::Native(NativeValue::Tuple(worklists::Tuple {
            values: Arc::new(values),
            range: range.clone(),
        })))
    }
    fn sequence_items(
        &self,
        value: &QueryOutput,
        element: &D<program::Kind>,
        context: &mut EvaluationContext<'_, '_, 'q>,
        budget: &mut Budget,
        range: &Range<usize>,
    ) -> Result<Vec<QueryOutput>, zirql::EvaluationError<EvaluationError>> {
        worklists::sequence_items(self, value, element, context, budget, range)
    }
    fn construct_sequence(
        &self,
        values: Vec<QueryOutput>,
        element: &D<program::Kind>,
        _: &mut EvaluationContext<'_, '_, 'q>,
        budget: &mut Budget,
        range: &Range<usize>,
    ) -> Result<QueryOutput, zirql::EvaluationError<EvaluationError>> {
        budget.charge_results(values.len() + 1, ValueLocation::Query(range.clone()))?;
        Ok(QueryOutput::Native(NativeValue::Sequence(
            worklists::Sequence {
                values: Arc::new(values),
                element: worklists::declaration(element, budget, range)?,
                range: range.clone(),
            },
        )))
    }
    fn worklist_context(
        &self,
        context: &mut EvaluationContext<'_, '_, 'q>,
        budget: &mut Budget,
        range: &Range<usize>,
    ) -> Result<zirql::NativeContextId, zirql::EvaluationError<EvaluationError>> {
        budget.charge(1, ValueLocation::Query(range.clone()))?;
        let owner = context.document.owner_identity();
        Ok(zirql::NativeContextId([
            owner as u64,
            (owner >> 64) as u64,
            context.document.revision(),
        ]))
    }
    fn native_identity(
        &self,
        value: &QueryOutput,
        expected: &program::Kind,
        context: &mut EvaluationContext<'_, '_, 'q>,
        budget: &mut Budget,
        range: &Range<usize>,
    ) -> Result<zirql::NativeIdentity, zirql::EvaluationError<EvaluationError>> {
        worklists::identity(value, expected, context, budget, range)
    }

    fn declaration_kind(
        &self,
        ty: &D<program::Kind>,
        budget: &mut Budget,
        range: &Range<usize>,
    ) -> Result<program::Kind, zirql::QueryError> {
        {
            budget.charge(1, ValueLocation::Query(range.clone()))?;
            Ok(match ty {
                D::Native(kind) => kind.clone(),
                D::Queue(_) | D::IdentitySet(_) => {
                    program::Kind::Computational(worklists::declaration(ty, budget, range)?)
                }
                D::Tuple(values) if contains_native(ty, budget, range)? => {
                    capture::slots::<program::Kind>(values.len(), budget, range)
                        .map_err(report::query_error)?;
                    program::Kind::Tuple(Arc::new(
                        values
                            .iter()
                            .map(|v| self.declaration_kind(v, budget, range))
                            .collect::<Result<_, _>>()?,
                    ))
                }
                D::Sequence(value) | D::Array(value)
                    if matches!(value.as_ref(), D::Native(program::Kind::Operations)) =>
                {
                    program::Kind::Operations
                }
                D::Sequence(value) | D::Array(value)
                    if matches!(value.as_ref(), D::Record(_))
                        && contains_native(value, budget, range)? =>
                {
                    let program::Kind::Capture(schema) =
                        self.declaration_kind(value, budget, range)?
                    else {
                        unreachable!("native record kind")
                    };
                    program::Kind::Captures(schema)
                }
                D::Sequence(value) | D::Array(value) if contains_native(value, budget, range)? => {
                    program::Kind::Sequence(worklists::declaration(value, budget, range)?)
                }
                D::Optional(value) if contains_native(value, budget, range)? => {
                    self.declaration_kind(value, budget, range)?
                }
                D::Record(fields) if contains_native(ty, budget, range)? => {
                    capture::slots::<(String, program::Kind)>(fields.len(), budget, range)
                        .map_err(report::query_error)?;
                    budget.charge_results(fields.len() + 1, ValueLocation::Query(range.clone()))?;
                    let mut kinds = Vec::with_capacity(fields.len());
                    for (name, value) in fields {
                        budget.charge(name.len() + 1, ValueLocation::Query(range.clone()))?;
                        kinds.push((name.clone(), self.declaration_kind(value, budget, range)?));
                    }
                    program::Kind::Capture(Arc::new(zirql::NativeCapture { fields: kinds }))
                }
                _ => self.constructed_kind(scalar_facts(ty, budget, range)?),
            })
        }
    }
    fn is_operation_name(&self, name: &str) -> bool {
        parser::is_reserved(name)
            || matches!(
                name,
                "direct_children"
                    | "cost_annotation"
                    | "same_operation"
                    | "user_info"
                    | "operand"
                    | "project"
                    | "paths"
                    | "match"
            )
    }
}
impl<'q> RuntimeTypeHost<EvaluationContext<'_, '_, 'q>> for report::ReportHost<'_> {
    type Kind = program::Kind;
    fn constructed_value<'v>(&self, value: &'v QueryOutput) -> Option<&'v ConstructedValue> {
        match unretained(value) {
            QueryOutput::Native(NativeValue::Constructed(v)) => Some(v.value()),
            _ => None,
        }
    }
    fn admit_native(
        &self,
        value: &QueryOutput,
        expected: &D<program::Kind>,
        context: &mut EvaluationContext<'_, '_, 'q>,
        budget: &mut Budget,
        location: ValueLocation,
    ) -> Result<(), zirql::EvaluationError<EvaluationError>> {
        if zirql::admit_computational(value, expected, self, context, budget, location.clone())? {
            return Ok(());
        }
        let range = match &location {
            ValueLocation::Query(r) | ValueLocation::Source(r) => r,
        };
        {
            budget.charge(1, location.clone())?;
            match (expected, unretained(value)) {
                (D::Optional(inner), value) => {
                    return zirql::admit_value(
                        value,
                        inner,
                        self,
                        context,
                        budget,
                        location.clone(),
                    );
                }
                (D::Native(program::Kind::Operations), QueryOutput::Operations(ops))
                    if ops.len() == 1 =>
                {
                    check_operations(context.document, ops, budget, range)?
                }
                (D::Native(program::Kind::Ssa), QueryOutput::Native(NativeValue::Ssa(value))) => {
                    capture::check_value(context.document, *value, range)
                        .map_err(zirql::EvaluationError::Host)?
                }
                (
                    D::Sequence(inner) | D::Array(inner),
                    QueryOutput::Native(NativeValue::OperationSequence(ops)),
                ) if matches!(inner.as_ref(), D::Native(program::Kind::Operations)) => {
                    check_operations(context.document, ops, budget, range)?
                }
                (D::Integer, QueryOutput::Count(value)) if i64::try_from(*value).is_ok() => {}
                (D::String, QueryOutput::Native(NativeValue::String(value))) => {
                    budget.charge(value.len(), location.clone())?;
                }
                (D::Sequence(inner) | D::Array(inner), QueryOutput::Values(values))
                    if matches!(inner.as_ref(), D::String) =>
                {
                    for value in values {
                        budget.charge(value.len() + 1, location.clone())?;
                    }
                }
                (D::Tuple(types), QueryOutput::Native(NativeValue::Tuple(tuple)))
                    if types.len() == tuple.values.len() =>
                {
                    for (value, ty) in tuple.values.iter().zip(types) {
                        zirql::admit_value(value, ty, self, context, budget, location.clone())?;
                    }
                }
                (
                    D::Sequence(element) | D::Array(element),
                    QueryOutput::Native(NativeValue::Sequence(sequence)),
                ) if element.as_ref() == sequence.element.as_ref() => {
                    budget.check_items(sequence.values.len(), location.clone())?;
                    for value in sequence.values.iter() {
                        zirql::admit_value(
                            value,
                            element,
                            self,
                            context,
                            budget,
                            location.clone(),
                        )?;
                    }
                }
                (D::Record(fields), QueryOutput::Native(NativeValue::Capture(record))) => {
                    admit_fields(
                        self,
                        record.fields.iter().map(|(n, v)| (n.as_str(), v)),
                        fields,
                        context,
                        budget,
                        &location,
                    )?
                }
                (D::Record(fields), QueryOutput::Native(NativeValue::Map(record))) => admit_fields(
                    self,
                    record.iter().map(|(n, v)| (n.as_str(), v)),
                    fields,
                    context,
                    budget,
                    &location,
                )?,
                (
                    D::Sequence(inner) | D::Array(inner),
                    QueryOutput::Native(NativeValue::Captures(records)),
                ) if matches!(inner.as_ref(), D::Record(_)) => {
                    let D::Record(fields) = inner.as_ref() else {
                        unreachable!()
                    };
                    budget.check_items(records.len(), location.clone())?;
                    for record in records.rows() {
                        admit_fields(
                            self,
                            record.fields.iter().map(|(n, v)| (n.as_str(), v)),
                            fields,
                            context,
                            budget,
                            &location,
                        )?;
                    }
                }
                (
                    D::Native(kind @ (program::Kind::Capture(_) | program::Kind::Captures(_))),
                    value,
                ) => {
                    admit_view_kind(value, kind, context, budget, range)?;
                }
                _ => {
                    return Err(zirql::QueryError::query(
                        range.clone(),
                        "function value does not satisfy its declared type",
                    )
                    .into());
                }
            }
            Ok(())
        }
    }
}
fn admit_view_kind(
    value: &QueryOutput,
    expected: &program::Kind,
    context: &mut EvaluationContext<'_, '_, '_>,
    budget: &mut Budget,
    range: &Range<usize>,
) -> Result<(), zirql::EvaluationError<EvaluationError>> {
    let mut pending = vec![(value, expected)];
    while let Some((value, expected)) = pending.pop() {
        budget.charge(1, ValueLocation::Query(range.clone()))?;
        match (expected, unretained(value)) {
            (
                program::Kind::Operations,
                QueryOutput::Operations(values)
                | QueryOutput::Native(NativeValue::OperationSequence(values)),
            ) => check_operations(context.document, values, budget, range)?,
            (program::Kind::Ssa, QueryOutput::Native(NativeValue::Ssa(value))) => {
                capture::check_value(context.document, *value, range)
                    .map_err(zirql::EvaluationError::Host)?
            }
            (program::Kind::Capture(schema), QueryOutput::Native(NativeValue::Capture(record))) => {
                if schema.fields.len() != record.fields.len() {
                    return Err(zirql::QueryError::query(
                        range.clone(),
                        "native capture shape changed",
                    )
                    .into());
                }
                budget.charge_results(schema.fields.len(), ValueLocation::Query(range.clone()))?;
                for (label, kind) in &schema.fields {
                    let child = record.get(&Located::new(label.as_str(), range.clone()), budget)?;
                    pending.push((child, kind));
                }
            }
            (
                program::Kind::Captures(schema),
                QueryOutput::Native(NativeValue::Captures(records)),
            ) => {
                budget.charge_results(records.len(), ValueLocation::Query(range.clone()))?;
                for record in records.rows() {
                    if schema.fields.len() != record.fields.len() {
                        return Err(zirql::QueryError::query(
                            range.clone(),
                            "native capture shape changed",
                        )
                        .into());
                    }
                    budget
                        .charge_results(schema.fields.len(), ValueLocation::Query(range.clone()))?;
                    for (label, kind) in &schema.fields {
                        let child =
                            record.get(&Located::new(label.as_str(), range.clone()), budget)?;
                        pending.push((child, kind));
                    }
                }
            }
            (kind, value)
                if report::output_kind(value, budget, range)
                    .map_err(zirql::EvaluationError::Host)?
                    == *kind => {}
            _ => {
                return Err(zirql::QueryError::query(
                    range.clone(),
                    "native view does not satisfy its kind",
                )
                .into());
            }
        }
    }
    Ok(())
}

fn check_operations(
    document: &Document,
    operations: &[OperationId],
    budget: &mut Budget,
    range: &Range<usize>,
) -> Result<(), zirql::EvaluationError<EvaluationError>> {
    budget.check_items(operations.len(), ValueLocation::Query(range.clone()))?;
    for &op in operations {
        budget.charge(1, ValueLocation::Query(range.clone()))?;
        document.check_operation(op).map_err(|e| {
            zirql::EvaluationError::Host(EvaluationError::new(e.to_string()).at(range.clone()))
        })?;
    }
    Ok(())
}

pub(super) fn error(
    error: zirql::FunctionError<zirql::EvaluationError<EvaluationError>>,
) -> EvaluationError {
    let mut failure = program::evaluation_error(error.error);
    if !error.calls.is_empty() {
        let calls = error
            .calls
            .into_iter()
            .map(|call| {
                format!(
                    "{} at {}..{}",
                    call.function, call.range.start, call.range.end
                )
            })
            .collect::<Vec<_>>()
            .join(" <- ");
        failure.message = format!("{} (calls: {calls})", failure.message);
    }
    failure
}

#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Primitive {
    DirectChildren,
    CostAnnotation,
    SameOperation,
    UserInfo,
}
pub(super) fn unretained(mut value: &QueryOutput) -> &QueryOutput {
    while let QueryOutput::Native(NativeValue::Retained(inner)) = value {
        value = inner;
    }
    value
}
pub(super) fn primitive(
    primitive: Primitive,
    argument: &QueryOutput,
    context: &mut EvaluationContext<'_, '_, '_>,
    budget: &mut Budget,
    range: &Range<usize>,
) -> Result<QueryOutput, EvaluationError> {
    if primitive == Primitive::SameOperation {
        let QueryOutput::Native(NativeValue::Tuple(tuple)) = unretained(argument) else {
            return Err(
                EvaluationError::new("same_operation requires two Operations").at(range.clone()),
            );
        };
        let [left, right] = tuple.values.as_slice() else {
            return Err(
                EvaluationError::new("same_operation requires two Operations").at(range.clone()),
            );
        };
        let single = |value| match unretained(value) {
            QueryOutput::Operations(values) if values.len() == 1 => Ok(values[0]),
            _ => Err(
                EvaluationError::new("same_operation requires two Operations").at(range.clone()),
            ),
        };
        let left = single(left)?;
        let right = single(right)?;
        check_operations(context.document, &[left, right], budget, range)
            .map_err(program::evaluation_error)?;
        return ConstructedReport::new(
            ConstructedValue::Boolean(left == right),
            range.clone(),
            budget,
        )
        .map(|v| QueryOutput::Native(NativeValue::Constructed(v)));
    }
    let QueryOutput::Operations(operations) = unretained(argument) else {
        return Err(
            EvaluationError::new("native primitive requires one Operation").at(range.clone()),
        );
    };
    if operations.len() != 1 {
        return Err(
            EvaluationError::new("native primitive requires one Operation").at(range.clone()),
        );
    }
    check_operations(context.document, operations, budget, range)
        .map_err(program::evaluation_error)?;
    let operation = operations[0];
    match primitive {
        Primitive::SameOperation => unreachable!("binary primitive handled above"),
        Primitive::UserInfo => {
            if !context.document.is_semantically_complete() {
                return Err(
                    EvaluationError::new("user_info requires complete semantic adjacency")
                        .at(range.clone()),
                );
            }
            let mut targets = Vec::new();
            for result in 0..context
                .document
                .result_types(operation)
                .map_or(0, <[_]>::len)
            {
                let value = ValueId::OperationResult {
                    operation,
                    result: u32::try_from(result).map_err(|_| {
                        EvaluationError::new("result index exceeds u32").at(range.clone())
                    })?,
                };
                let uses = context.document.query_uses(value, |units| {
                    capture::slots::<crate::semantic::UseSite>(units, budget, range)?;
                    budget
                        .charge(units, ValueLocation::Query(range.clone()))
                        .map_err(core_error)?;
                    budget
                        .charge_results(units, ValueLocation::Query(range.clone()))
                        .map_err(core_error)
                })?;
                budget
                    .check_items(
                        targets.len().saturating_add(uses.len()),
                        ValueLocation::Query(range.clone()),
                    )
                    .map_err(core_error)?;
                capture::slots::<OperationId>(uses.len(), budget, range)?;
                targets.reserve(uses.len());
                for site in uses {
                    let user = match site {
                        crate::semantic::UseSite::Operand { operation, .. }
                        | crate::semantic::UseSite::SuccessorArgument { operation, .. } => {
                            operation
                        }
                    };
                    context
                        .document
                        .check_operation(user)
                        .map_err(|e| EvaluationError::new(e.to_string()).at(range.clone()))?;
                    targets.push(user);
                }
            }
            program::charge_results(budget, 3, range)?;
            program::charge_bytes(budget, "targets".len() + 1, range)?;
            Ok(QueryOutput::Native(NativeValue::Capture(
                zirql::NativeCapture {
                    fields: vec![(
                        "targets".to_owned(),
                        QueryOutput::Native(NativeValue::OperationSequence(targets)),
                    )],
                },
            )))
        }
        Primitive::DirectChildren => {
            program::charge_results(budget, 1, range)?;
            evaluate_children(context.document, operations, budget)
                .map(|children| QueryOutput::Native(NativeValue::OperationSequence(children)))
        }
        Primitive::CostAnnotation => {
            program::charge_results(budget, 3, range)?;
            let value = match context
                .document
                .attribute_id(operation, "cost")
                .and_then(|id| context.document.attribute_value(id))
            {
                None => ConstructedValue::Absent,
                Some(attribute) => {
                    let spelling = context
                        .document
                        .attribute_id(operation, "cost")
                        .and_then(|id| context.document.attribute_spelling_value(id))
                        .unwrap_or("");
                    program::charge_bytes(budget, spelling.len() + 1, range)?;
                    let integer = attribute.decoded_integer().ok_or_else(|| {
                        EvaluationError::new("cost annotation must be an i64 integer")
                            .at(range.clone())
                    })?;
                    let negative = integer.digits.starts_with('-');
                    let magnitude = u64::from_str_radix(
                        integer.digits.trim_start_matches(['+', '-']),
                        integer.radix,
                    )
                    .map_err(|_| {
                        EvaluationError::new("cost annotation is outside i64").at(range.clone())
                    })?;
                    let number = if negative {
                        if magnitude == 1u64 << 63 {
                            i64::MIN
                        } else {
                            -i64::try_from(magnitude).map_err(|_| {
                                EvaluationError::new("cost annotation is outside i64")
                                    .at(range.clone())
                            })?
                        }
                    } else {
                        i64::try_from(magnitude).map_err(|_| {
                            EvaluationError::new("cost annotation is outside i64").at(range.clone())
                        })?
                    };
                    ConstructedValue::Integer(number)
                }
            };
            ConstructedReport::with_types(
                value,
                vec![ValueType::Integer, ValueType::Absent],
                range.clone(),
                budget,
            )
            .map(|v| QueryOutput::Native(NativeValue::Constructed(v)))
        }
    }
}

/// Signature-only discovery is safe inside native preparation callbacks. The
/// submitted request separately prepares every complete body in `Session::new`.
pub(super) fn value_kind(
    host: &report::ReportHost<'_>,
    value: &zirql::ValueExpression<report::Operand>,
    relative: program::Kind,
    scope: &BTreeMap<String, program::Kind>,
    budget: &mut Budget,
) -> Result<program::Kind, zirql::QueryError> {
    zirql::pattern_function_value_kind(
        host.functions
            .iter()
            .map(|function| function.declaration.as_ref()),
        host,
        value,
        scope,
        Some(relative),
        budget,
    )
}

/// A checked textual top-level pattern binding. Clone retains its immutable tree.
#[derive(Debug, PartialEq)]
pub struct ParsedBinding {
    pub(super) pattern: Arc<Pattern>,
    pub(super) value: ParsedComprehension,
}
impl Clone for ParsedBinding {
    fn clone(&self) -> Self {
        Self {
            pattern: Arc::clone(&self.pattern),
            value: self.value.clone(),
        }
    }
}
impl Eq for ParsedBinding {}
impl Drop for ParsedBinding {
    fn drop(&mut self) {
        if let Some(pattern) = Arc::get_mut(&mut self.pattern) {
            zirql::dispose_pattern(std::mem::replace(
                pattern,
                Located::new(PatternKind::Wildcard, 0..0),
            ));
        }
    }
}
impl ParsedBinding {
    pub(super) fn new(pattern: Pattern, value: ParsedComprehension) -> Self {
        Self {
            pattern: Arc::new(pattern),
            value,
        }
    }
}

type Entry<'q> = zirql::PreparedFunctionValue<'q, report::Operand, program::Kind>;
/// One submitted request owns this unit and every entry prepared by it. It never
/// stores a document, bindings, budget or result; execution supplies that context.
pub(super) struct Session<'q, 'a, 'd> {
    pub(super) host: &'a report::ReportHost<'q>,
    unit: zirql::PreparedFunctions<'q, 'a, EvaluationContext<'a, 'd, 'q>, report::ReportHost<'q>>,
    entries: BTreeMap<(usize, usize), Entry<'q>>,
    bindings: BTreeMap<usize, zirql::PreparedPatternBinding<'q, report::Operand, program::Kind>>,
    limits: FunctionLimits,
}
impl<'q, 'a, 'd> Session<'q, 'a, 'd> {
    pub(super) fn new(
        functions: &'q [FunctionDefinition],
        host: &'a report::ReportHost<'q>,
        limits: FunctionLimits,
        budget: &mut Budget,
    ) -> Result<Self, EvaluationError> {
        Ok(Self {
            host,
            unit: zirql::PreparedFunctions::prepare_patterns(
                functions.iter().map(|f| f.declaration.as_ref()),
                host,
                budget,
            )
            .map_err(error)?,
            entries: BTreeMap::new(),
            bindings: BTreeMap::new(),
            limits,
        })
    }
    fn prepare_value(
        &mut self,
        stage: &'q model::Stage,
        value: &'q zirql::ValueExpression<report::Operand>,
        input: program::Kind,
        names: &BTreeMap<String, program::Kind>,
        budget: &mut Budget,
    ) -> Result<(), EvaluationError> {
        let entry = self
            .unit
            .prepare_value(value, names, Some(input), budget)
            .map_err(error)?;
        budget
            .charge_results(1, ValueLocation::Query(value.range.clone()))
            .map_err(core_error)?;
        self.entries.insert(
            (stage as *const _ as usize, value as *const _ as usize),
            entry,
        );
        Ok(())
    }
    pub(super) fn prepare_expression(
        &mut self,
        expression: &'q model::Expression,
        input: program::Kind,
        names: &BTreeMap<String, program::Kind>,
        host: &report::ReportHost<'q>,
        budget: &mut Budget,
    ) -> Result<program::Kind, EvaluationError> {
        for stages in std::iter::once(&expression.first)
            .chain(expression.rest.iter().map(|(_, stages)| stages))
        {
            let mut kind = input.clone();
            for stage in stages {
                match stage {
                    model::Stage::Comprehension { value, .. }
                    | model::Stage::FunctionValue { value, .. }
                    | model::Stage::Fixpoint {
                        expression: model::FixedPointBody::Native(value),
                        ..
                    } => {
                        self.prepare_value(stage, &value.expression, kind.clone(), names, budget)?
                    }
                    model::Stage::WhereExists { relation, .. } => {
                        let subject = host
                            .subject_kind(&kind, budget, &program::range(stage.range()))
                            .map_err(core_error)?;
                        self.prepare_value(stage, &relation.expression, subject, names, budget)?;
                    }
                    model::Stage::Projection { value, .. } => {
                        let mut scope = copy_scope(names, budget, &program::range(stage.range()))
                            .map_err(core_error)?;
                        let subject = host
                            .subject_kind(&kind, budget, &value.projection.subject.range)
                            .map_err(core_error)?;
                        scope.insert(value.projection.subject.value.clone(), subject.clone());
                        for (_, value) in &value.projection.fields {
                            self.prepare_value(stage, value, subject.clone(), &scope, budget)?;
                        }
                    }
                    _ => {
                        for argument in host
                            .scoped_value_arguments(
                                stage,
                                &kind,
                                names,
                                budget,
                                &program::range(stage.range()),
                            )
                            .map_err(core_error)?
                        {
                            let mut scope =
                                copy_scope(names, budget, &program::range(stage.range()))
                                    .map_err(core_error)?;
                            scope.extend(
                                argument
                                    .locals
                                    .into_iter()
                                    .map(|(name, kind)| (name.value, kind)),
                            );
                            self.prepare_value(
                                stage,
                                argument.expression,
                                argument.relative.unwrap_or_else(|| kind.clone()),
                                &scope,
                                budget,
                            )?;
                        }
                    }
                }
                for nested in report::nested(stage) {
                    self.prepare_expression(
                        nested,
                        if matches!(
                            stage,
                            model::Stage::Fixpoint { .. } | model::Stage::Group { .. }
                        ) {
                            kind.clone()
                        } else {
                            program::Kind::Operations
                        },
                        names,
                        host,
                        budget,
                    )?;
                }
                kind = program::Validator {
                    host: report::ReportHost {
                        functions: host.functions,
                    },
                }
                .stages(std::slice::from_ref(stage), kind, names, budget)?;
            }
        }
        program::Validator {
            host: report::ReportHost {
                functions: host.functions,
            },
        }
        .expression(expression, input, names, budget)
    }
    pub(super) fn prepare_program(
        &mut self,
        query: &'q Query,
        document_name: Option<&str>,
        host: &report::ReportHost<'q>,
        budget: &mut Budget,
    ) -> Result<(), EvaluationError> {
        let mut names = BTreeMap::new();
        if document_name.is_some() {
            names.insert("document".to_owned(), program::Kind::Strings);
        }
        let mut parameters = query
            .parameters
            .iter()
            .zip(&query.parameter_positions)
            .peekable();
        for (index, statement) in query.statements.iter().enumerate() {
            while parameters.peek().is_some_and(|(_, p)| **p == index) {
                let (d, _) = parameters.next().unwrap();
                names.extend(program::parameter_names(std::slice::from_ref(d), budget)?);
            }
            if let model::Statement::PatternBinding { expression, .. } = statement {
                let [model::Stage::PatternBinding { value, .. }] = expression.first.as_slice()
                else {
                    unreachable!("lowered pattern binding stage");
                };
                let entry = self
                    .unit
                    .prepare_binding(
                        &value.pattern,
                        &value.value.expression,
                        &names,
                        Some(program::Kind::Operations),
                        budget,
                    )
                    .map_err(error)?;
                for (name, kind) in entry.bindings() {
                    budget
                        .charge(
                            name.value.len() + 1,
                            ValueLocation::Query(name.range.clone()),
                        )
                        .map_err(core_error)?;
                    names.insert(name.value.clone(), kind.clone());
                }
                budget
                    .charge_results(1, ValueLocation::Query(program::range(expression.range)))
                    .map_err(core_error)?;
                self.bindings
                    .insert(&expression.first[0] as *const _ as usize, entry);
                continue;
            }
            let expression = match statement {
                model::Statement::Binding { expression, .. }
                | model::Statement::PatternBinding { expression, .. }
                | model::Statement::Do(expression)
                | model::Statement::Query(expression) => expression,
            };
            let kind = self.prepare_expression(
                expression,
                program::Kind::Operations,
                &names,
                host,
                budget,
            )?;
            if let model::Statement::Binding { name, .. } = statement {
                names.insert(name.clone(), kind);
            }
        }
        for (d, _) in parameters {
            names.extend(program::parameter_names(std::slice::from_ref(d), budget)?);
        }
        self.prepare_expression(
            &query.expression,
            program::Kind::Operations,
            &names,
            host,
            budget,
        )?;
        Ok(())
    }
    pub(super) fn run_binding(
        &self,
        context: &mut EvaluationContext<'a, 'd, 'q>,
        input: &QueryOutput,
        bindings: &zirql::Bindings<QueryOutput>,
        budget: &mut Budget,
    ) -> Result<QueryOutput, EvaluationError> {
        let entry = self
            .bindings
            .get(&context.current_stage)
            .ok_or_else(|| EvaluationError::new("pattern binding was not prepared"))?;
        self.unit
            .evaluate_binding(entry, bindings, Some(input), context, budget, self.limits)
            .map(|capture| QueryOutput::Native(NativeValue::Capture(capture)))
            .map_err(error)
    }
    pub(super) fn run_projection(
        &self,
        projection: &zirql::Projection<report::Operand>,
        context: &mut EvaluationContext<'a, 'd, 'q>,
        input: QueryOutput,
        bindings: &zirql::Bindings<QueryOutput>,
        budget: &mut Budget,
    ) -> Result<zirql::ConstructedResult, EvaluationError> {
        capture::slots::<&Entry<'_>>(projection.fields.len(), budget, &projection.subject.range)?;
        let mut fields = Vec::with_capacity(projection.fields.len());
        for (_, value) in &projection.fields {
            fields.push(
                self.entries
                    .get(&(context.current_stage, value as *const _ as usize))
                    .ok_or_else(|| {
                        EvaluationError::new(
                            "written function entry was not prepared in this scope",
                        )
                        .at(value.range.clone())
                    })?,
            );
        }
        self.unit
            .evaluate_projection(
                projection,
                &fields,
                input,
                bindings,
                context,
                budget,
                self.limits,
            )
            .map_err(error)
    }

    pub(super) fn run(
        &self,
        value: &zirql::ValueExpression<report::Operand>,
        context: &mut EvaluationContext<'a, 'd, 'q>,
        input: &QueryOutput,
        bindings: &zirql::Bindings<QueryOutput>,
        budget: &mut Budget,
    ) -> Result<QueryOutput, EvaluationError> {
        let entry = self
            .entries
            .get(&(context.current_stage, value as *const _ as usize))
            .ok_or_else(|| {
                EvaluationError::new("written function entry was not prepared in this scope")
                    .at(value.range.clone())
            })?;
        self.unit
            .evaluate(entry, bindings, Some(input), context, budget, self.limits)
            .map_err(error)
    }
}

pub(super) fn evaluate(
    value: &ParsedComprehension,
    context: &mut EvaluationContext<'_, '_, '_>,
    input: QueryOutput,
    bindings: &zirql::Bindings<QueryOutput>,
    budget: &mut Budget,
) -> Result<QueryOutput, EvaluationError> {
    if let Some(session) = context.functions {
        session.run(&value.expression, context, &input, bindings, budget)
    } else {
        report::evaluate(value, context, input, bindings, budget)
            .map(|v| QueryOutput::Native(NativeValue::Constructed(v)))
    }
}
pub(super) fn owned(
    mut value: QueryOutput,
    budget: &mut Budget,
    range: &Range<usize>,
) -> Result<QueryOutput, EvaluationError> {
    while let QueryOutput::Native(NativeValue::Retained(shared)) = value {
        value = match Arc::try_unwrap(shared) {
            Ok(value) => value,
            Err(shared) => program::copy_value(unretained(&shared), budget, range)?,
        };
    }
    Ok(value)
}
pub(super) fn constructed(
    value: QueryOutput,
    budget: &mut Budget,
    range: &Range<usize>,
) -> Result<ConstructedReport, EvaluationError> {
    match owned(value, budget, range)? {
        QueryOutput::Native(NativeValue::Constructed(value)) => Ok(value),
        value @ QueryOutput::Native(NativeValue::Map(_)) => {
            let value = comprehension::project(&value, budget, range)?;
            ConstructedReport::new(value, range.clone(), budget)
        }
        _ => Err(EvaluationError::new("report requires a constructed value").at(range.clone())),
    }
}

impl FunctionDefinition {
    /// Construct shared declaration data directly, without parsing generated text.
    pub fn new(
        name: impl Into<String>,
        parameters: Vec<FunctionParameter<FunctionNativeType>>,
        result: FunctionType,
        bindings: Vec<(String, ReportExpr)>,
        body: ReportExpr,
    ) -> Result<Self, EvaluationError> {
        Self::with_patterns(
            name,
            parameters
                .into_iter()
                .map(|p| PatternParameter {
                    pattern: Located::new(PatternKind::Name(p.name), 0..0),
                    declaration: p.declaration,
                })
                .collect(),
            result,
            ReportExpr::block(
                bindings
                    .into_iter()
                    .map(|(name, value)| {
                        (
                            Located::new(PatternKind::Name(Located::new(name, 0..0)), 0..0),
                            value,
                        )
                    })
                    .collect(),
                body,
            )?,
        )
    }

    /// Construct whole typed parameter patterns and a pure lexical body.
    /// All arguments are admitted before any parameter pattern installs names.
    pub fn with_patterns(
        name: impl Into<String>,
        parameters: Vec<PatternParameter<FunctionNativeType>>,
        result: FunctionType,
        body: ReportExpr,
    ) -> Result<Self, EvaluationError> {
        let mut budget = Budget::for_program(comprehension::default_limits());
        let mut incoming = parameters.into_iter();
        let mut parameters: Vec<Located<PatternParameter<program::Kind>>> = Vec::new();
        while let Some(parameter) = incoming.next() {
            let declaration = validate_pattern(&parameter.pattern, &mut budget)
                .and_then(|()| native_type(parameter.declaration, 0));
            let declaration = match declaration {
                Ok(declaration) => declaration,
                Err(error) => {
                    zirql::dispose_pattern(parameter.pattern);
                    for parameter in incoming {
                        zirql::dispose_pattern(parameter.pattern);
                    }
                    for parameter in parameters {
                        zirql::dispose_pattern(parameter.value.pattern);
                    }
                    return Err(error);
                }
            };
            parameters.push(Located::new(
                PatternParameter {
                    pattern: parameter.pattern,
                    declaration,
                },
                0..0,
            ));
        }
        let result = match native_type(result, 0) {
            Ok(result) => result,
            Err(error) => {
                for parameter in parameters {
                    zirql::dispose_pattern(parameter.value.pattern);
                }
                return Err(error);
            }
        };
        Ok(Self::parsed(zirql::PatternFunctionDeclaration {
            name: Located::new(name.into(), 0..0),
            parameters,
            result: Located::new(result, 0..0),
            value: normalize(body.into_expression()),
        }))
    }
}

pub(super) fn validate_pattern(
    pattern: &Pattern,
    budget: &mut Budget,
) -> Result<(), EvaluationError> {
    zirql::pattern_names(pattern, budget)
        .map(|_| ())
        .map_err(core_error)
}

fn native_type(ty: FunctionType, depth: usize) -> Result<D<program::Kind>, EvaluationError> {
    if depth >= parser::DEFAULT_NESTING_LIMIT {
        return Err(EvaluationError::new(
            "function signature nesting limit exceeded",
        ));
    }
    Ok(match ty {
        D::Native(FunctionNativeType::Operation) => D::Native(program::Kind::Operations),
        D::Native(FunctionNativeType::SSAValue) => D::Native(program::Kind::Ssa),
        D::Optional(v) => D::Optional(Box::new(native_type(*v, depth + 1)?)),
        D::Sequence(v) => D::Sequence(Box::new(native_type(*v, depth + 1)?)),
        D::Array(v) => D::Array(Box::new(native_type(*v, depth + 1)?)),
        D::Keyed(v) => D::Keyed(Box::new(native_type(*v, depth + 1)?)),
        D::Tuple(v) => D::Tuple(
            v.into_iter()
                .map(|v| native_type(v, depth + 1))
                .collect::<Result<_, _>>()?,
        ),
        D::Record(v) => D::Record(
            v.into_iter()
                .map(|(n, v)| Ok((n, native_type(v, depth + 1)?)))
                .collect::<Result<_, EvaluationError>>()?,
        ),
        D::Boolean => D::Boolean,
        D::Integer => D::Integer,
        D::Float => D::Float,
        D::String => D::String,
        D::Member(v) => D::Member(v),
        D::Set(v) => D::Set(v),
        D::Queue(value) => D::Queue(Box::new(native_type(*value, depth + 1)?)),
        D::IdentitySet(FunctionNativeType::Operation) => D::IdentitySet(program::Kind::Operations),
        D::IdentitySet(FunctionNativeType::SSAValue) => D::IdentitySet(program::Kind::Ssa),
    })
}
// Shared typed values use an explicit source wrapper when another owner keeps
// the tree alive. In a function that wrapper must retain native values too.
pub(super) fn normalize(
    value: zirql::ValueExpression<report::Operand>,
) -> zirql::ValueExpression<report::Operand> {
    normalize_with(value, |_| Ok(())).expect("retained wrapper normalization cannot fail")
}
/// Outer native scalar bindings use the existing explicit projection boundary.
/// Lexical pattern names remain ordinary shared slots; shadowing an outer name
/// is rejected by common preflight before this lowered value can execute.
pub(super) fn normalize_outer(
    value: zirql::ValueExpression<report::Operand>,
    names: &std::collections::HashSet<String>,
    budget: &mut Budget,
) -> Result<zirql::ValueExpression<report::Operand>, zirql::QueryError> {
    normalize_with(value, |value| {
        if let zirql::ValueExpressionKind::NativeQuery(query)
        | zirql::ValueExpressionKind::NativeValue(query) = &mut value.value
        {
            report::retain_tally_continuations(query, budget)?;
        }
        if let zirql::ValueExpressionKind::Name(name) = &value.value
            && names.contains(name)
        {
            budget.charge(name.len() + 2, ValueLocation::Query(value.range.clone()))?;
            budget.charge_results(2, ValueLocation::Query(value.range.clone()))?;
            value.value = zirql::ValueExpressionKind::NativeValue(Box::new(Located::new(
                zirql::ExpressionKind::Binding(name.clone()),
                value.range.clone(),
            )));
        }
        Ok(())
    })
}
fn normalize_with(
    mut value: zirql::ValueExpression<report::Operand>,
    mut lower: impl FnMut(&mut zirql::ValueExpression<report::Operand>) -> Result<(), zirql::QueryError>,
) -> Result<zirql::ValueExpression<report::Operand>, zirql::QueryError> {
    use zirql::ValueExpressionKind as K;
    fn clauses<'v>(
        clauses: &'v mut [Located<zirql::ValueGenerator<report::Operand>>],
        pending: &mut Vec<&'v mut zirql::ValueExpression<report::Operand>>,
    ) {
        for clause in clauses {
            match &mut clause.value {
                zirql::ValueGenerator::In { source, filter, .. }
                | zirql::ValueGenerator::Bind {
                    value: source,
                    filter,
                    ..
                } => {
                    pending.push(source);
                    pending.extend(filter);
                }
            }
        }
    }
    let mut pending = vec![&mut value];
    while let Some(value) = pending.pop() {
        lower(value)?;
        if matches!(&value.value,K::NativeQuery(q) if matches!(&q.value,zirql::ExpressionKind::Sequence{steps,..} if steps.len()==1 && matches!(&steps[0].value,zirql::ExpressionStep::Stage(model::Stage::FunctionValue{..}))))
        {
            let K::NativeQuery(query) =
                std::mem::replace(&mut value.value, K::Literal(ConstructedValue::Absent))
            else {
                unreachable!()
            };
            value.value = K::NativeValue(query);
        }
        match &mut value.value {
            K::Literal(_)
            | K::CurrentInput
            | K::PredicateSubject
            | K::Name(_)
            | K::NativeQuery(_)
            | K::NativeValue(_)
            | K::IdentitySet { .. } => {}
            K::Filter {
                array: subject,
                predicate,
            }
            | K::PredicateScope { subject, predicate }
            | K::SubjectScope {
                subject,
                argument: predicate,
            } => {
                pending.push(subject);
                pending.push(&mut predicate.body);
            }
            K::Block { bindings, value } => {
                pending.extend(bindings.iter_mut().map(|(_, v)| v));
                pending.push(value);
            }
            K::ValueMatch { subject, arms } => {
                pending.push(subject);
                for arm in arms {
                    pending.extend(&mut arm.guard);
                    pending.push(&mut arm.value);
                }
            }
            K::Loop { states, body } => {
                pending.extend(states.iter_mut().map(|(_, v)| v));
                pending.push(body);
            }
            K::Fold { items, initial, .. } | K::Scan { items, initial, .. } => {
                pending.push(items);
                pending.push(initial);
            }
            K::Call { arguments, .. }
            | K::Continue(arguments)
            | K::Array(arguments)
            | K::Tuple(arguments)
            | K::Set(arguments) => pending.extend(arguments),
            K::Queue { items: v, .. }
            | K::PopFront(v)
            | K::Break(v)
            | K::Occurs(v)
            | K::Absent(v)
            | K::One(v)
            | K::IndexSet(v)
            | K::Entries(v)
            | K::Unique(v)
            | K::Tally(v)
            | K::Unary { operand: v, .. }
            | K::Field { value: v, .. }
            | K::TupleAccess { value: v, .. }
            | K::GroupBy { rows: v, .. }
            | K::Reduce { array: v, .. }
            | K::Sort { array: v, .. }
            | K::Extremum { array: v, .. } => pending.push(v),
            K::Record(fields) => pending.extend(fields.iter_mut().map(|(_, v)| v)),
            K::KeyedArray {
                entries,
                declared_axis_sources,
                ..
            } => {
                pending.extend(declared_axis_sources.iter_mut().flatten());
                for (k, v) in entries {
                    pending.push(k);
                    pending.push(v)
                }
            }
            K::Dictionary(entries) => {
                for (k, v) in entries {
                    pending.push(k);
                    pending.push(v)
                }
            }
            K::Lookup { value, key } | K::HasKey { value, key } => {
                pending.push(value);
                pending.push(key)
            }
            K::Default { value, fallback } => {
                pending.push(value);
                pending.push(fallback)
            }
            K::Binary { left, right, .. }
            | K::ZipExact { left, right }
            | K::PushBackAll {
                queue: left,
                items: right,
            }
            | K::Insert {
                set: left,
                item: right,
            } => {
                pending.push(left);
                pending.push(right)
            }
            K::ArrayAccess { array, index } => {
                pending.push(array);
                pending.push(index)
            }
            K::Range { lower, upper } => {
                pending.push(lower);
                pending.push(upper)
            }
            K::Require {
                condition, value, ..
            } => {
                pending.push(condition);
                pending.push(value)
            }
            K::Conditional {
                branches,
                otherwise,
            } => {
                for (c, v) in branches {
                    pending.push(c);
                    pending.push(v)
                }
                pending.push(otherwise)
            }
            K::Comprehension {
                clauses: generators,
                head,
                ..
            } => {
                clauses(generators, &mut pending);
                pending.push(head)
            }
            K::DictionaryComprehension {
                clauses: generators,
                key,
                head,
            } => {
                clauses(generators, &mut pending);
                pending.push(key);
                pending.push(head);
            }
            K::KeyedComprehension {
                clauses: generators,
                key,
                head,
                declared_axis_sources,
                empty_axis_sources,
            } => {
                pending.extend(declared_axis_sources.iter_mut().flatten());
                clauses(generators, &mut pending);
                pending.push(key);
                pending.push(head);
                if let Some(sources) = empty_axis_sources {
                    pending.extend(sources)
                }
            }
        }
    }
    Ok(value)
}

pub(super) fn expression_roots(functions: &[FunctionDefinition]) -> Vec<&model::Expression> {
    let mut roots = Vec::new();
    for function in functions {
        report::visit_value(&function.declaration.value, &mut roots);
    }
    roots
}

fn admit_fields<'v>(
    host: &report::ReportHost<'_>,
    values: impl Iterator<Item = (&'v str, &'v QueryOutput)> + Clone,
    fields: &[(String, D<program::Kind>)],
    context: &mut EvaluationContext<'_, '_, '_>,
    budget: &mut Budget,
    location: &ValueLocation,
) -> Result<(), zirql::EvaluationError<EvaluationError>> {
    let range = match location {
        ValueLocation::Query(r) | ValueLocation::Source(r) => r,
    };
    for (name, _) in values.clone() {
        budget.charge(name.len() + fields.len() + 1, location.clone())?;
        if !fields.iter().any(|(field, _)| field == name) {
            return Err(
                zirql::QueryError::query(range.clone(), "unexpected native record field").into(),
            );
        }
    }
    for (name, ty) in fields {
        budget.charge(name.len() + 1, location.clone())?;
        let mut found = None;
        for (field, value) in values.clone() {
            budget.charge(field.len() + 1, location.clone())?;
            if field == name {
                found = Some(value);
                break;
            }
        }
        match found {
            Some(value) => zirql::admit_value(value, ty, host, context, budget, location.clone())?,
            None if matches!(ty, D::Optional(_)) => {}
            None => {
                return Err(
                    zirql::QueryError::query(range.clone(), "missing native record field").into(),
                );
            }
        }
    }
    Ok(())
}

fn contains_native(
    ty: &D<program::Kind>,
    budget: &mut Budget,
    range: &Range<usize>,
) -> Result<bool, zirql::QueryError> {
    budget.charge(1, ValueLocation::Query(range.clone()))?;
    Ok(match ty {
        D::Native(_) | D::Queue(_) | D::IdentitySet(_) => true,
        D::Optional(value) | D::Sequence(value) | D::Array(value) | D::Keyed(value) => {
            contains_native(value, budget, range)?
        }
        D::Record(fields) => {
            let mut found = false;
            for (name, value) in fields {
                budget.charge(name.len() + 1, ValueLocation::Query(range.clone()))?;
                if contains_native(value, budget, range)? {
                    found = true;
                    break;
                }
            }
            found
        }
        D::Tuple(values) => {
            let mut found = false;
            for value in values {
                if contains_native(value, budget, range)? {
                    found = true;
                    break;
                }
            }
            found
        }
        _ => false,
    })
}
/// Only preparation copies lexical kind metadata; runtime shares value bindings.
pub(super) fn copy_scope(
    names: &BTreeMap<String, program::Kind>,
    budget: &mut Budget,
    range: &Range<usize>,
) -> Result<BTreeMap<String, program::Kind>, zirql::QueryError> {
    budget.charge(
        names.keys().map(|name| name.len() + 1).sum(),
        ValueLocation::Query(range.clone()),
    )?;
    budget.charge_results(names.len(), ValueLocation::Query(range.clone()))?;
    Ok(names.clone())
}