zirql 0.1.0

Bounded native query programs and nominal/keyed value comprehensions
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
use std::ops::Range;

use crate::{
    ArrayType, Budget, ConstructedValue, EvaluationError, Located, Location, NominalTypeId,
    ProgramHost, QueryError, QueryErrorCategory, SetElementType, ValueType, constructed_value_type,
};

/// An opt-in interface contract, distinct from discovered [`ValueType`] facts.
/// Arrays admit positional or keyed storage with homogeneous elements; sequences
/// and keyed declarations restrict that storage. Tuples have fixed positions and
/// records have the declared labels in any stored order, with optional fields
/// allowed to be omitted. Keyed axes
/// remain runtime facts. Sets use the existing supported scalar identities.
/// `Native` uses the adapter's own kind identity, without erasing its values.
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum DeclaredType<K> {
    Optional(Box<Self>),
    Boolean,
    Integer,
    Float,
    String,
    Member(NominalTypeId),
    /// Homogeneous elements in either positional or keyed storage.
    Array(Box<Self>),
    Sequence(Box<Self>),
    Tuple(Vec<Self>),
    Record(Vec<(String, Self)>),
    Set(SetElementType),
    Keyed(Box<Self>),
    Native(K),
    /// Computational FIFO; its elements retain this whole declaration.
    Queue(Box<Self>),
    /// Computational set of exact host identities for one native kind.
    IdentitySet(K),
}

/// Contracts for one ordinary trusted Rust adapter operation.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct OperationSignature<K> {
    pub parameters: Vec<DeclaredType<K>>,
    pub result: DeclaredType<K>,
}

/// Optional runtime admission for a [`ProgramHost`]. Existing hosts need not
/// implement this trait or the projection interface.
pub trait RuntimeTypeHost<C>: ProgramHost<C> {
    type Kind;

    /// Borrow a constructed wrapper for shared language checks. Native values
    /// stay native and return `None`.
    fn constructed_value<'v>(&self, _value: &'v Self::Value) -> Option<&'v ConstructedValue> {
        None
    }

    /// Check the actual native representation against the whole declaration,
    /// including containers of native values. Check every member in the current
    /// context, including owner, source coordinates and stale handles.
    /// A stream's kind tag alone does not establish these facts. Charge scans,
    /// comparisons and diagnostic bytes to `budget`; retain native errors.
    fn admit_native(
        &self,
        value: &Self::Value,
        expected: &DeclaredType<Self::Kind>,
        context: &mut C,
        budget: &mut Budget,
        location: Location,
    ) -> Result<(), EvaluationError<Self::Error>>;
}

/// Check arity, declarations and actual arguments in written order, invoke the
/// trusted operation once, then check its actual result before returning it.
/// `arguments` can be a borrowed slice or an owned vector; the operation receives
/// that same representation without a core value copy or result charge.
///
/// The operation uses the same context and budget and must admit fresh outputs
/// before allocating them. This is a Rust adapter boundary, not a registry,
/// language callback or effect-policy check.
///
/// # Errors
/// Arity, declaration and result errors use `call_range`; argument errors use
/// their written range. Native errors retain their original type/location.
/// Work and nesting refusals restore active evaluation state, not spending.
pub fn checked_invoke<C, H, A>(
    signature: &OperationSignature<H::Kind>,
    arguments: A,
    host: &H,
    context: &mut C,
    budget: &mut Budget,
    call_range: Range<usize>,
    operation: impl FnOnce(A, &mut C, &mut Budget) -> Result<H::Value, EvaluationError<H::Error>>,
) -> Result<H::Value, EvaluationError<H::Error>>
where
    H: RuntimeTypeHost<C>,
    A: AsRef<[Located<H::Value>]>,
{
    let location = Location::Query(call_range);
    budget.within_evaluation(0, location.clone(), |budget| {
        budget.charge(1, location.clone())?;
        if signature.parameters.len() != arguments.as_ref().len() {
            return Err(refusal("operation argument count mismatch", budget, &location)?.into());
        }
        for parameter in &signature.parameters {
            validate_declaration(parameter, budget, &location)?;
        }
        validate_declaration(&signature.result, budget, &location)?;
        for (argument, expected) in arguments.as_ref().iter().zip(&signature.parameters) {
            admit_host_value(
                &argument.value,
                expected,
                host,
                context,
                budget,
                Location::Query(argument.range.clone()),
            )?;
        }
        let result = operation(arguments, context, budget)?;
        admit_host_value(&result, &signature.result, host, context, budget, location)?;
        Ok(result)
    })
}

/// Admit a borrowed native or constructed host value against a declaration.
/// No native `Clone`, `Send`, `Sync` or `'static` bound is required.
///
/// # Errors
/// Language mismatches and malformed declarations use `location`; native
/// admission preserves the adapter's error and source coordinates.
pub fn admit_value<C, H: RuntimeTypeHost<C>>(
    value: &H::Value,
    expected: &DeclaredType<H::Kind>,
    host: &H,
    context: &mut C,
    budget: &mut Budget,
    location: Location,
) -> Result<(), EvaluationError<H::Error>> {
    validate_declaration(expected, budget, &location)?;
    admit_host_value(value, expected, host, context, budget, location)
}

/// Check actual constructed data, including all nested elements and the current
/// finite-float, label, nominal, set and keyed-shape invariants. Caller-supplied
/// type summaries are never admission evidence. Typed empty sets retain their
/// element identity; an untyped empty set does not establish that identity.
///
/// Successful admission remains valid for this immutable value and declaration.
/// It does not admit future values or replace producer allocation charges,
/// native ownership checks, nominal resolution or data-dependent access checks.
/// This function stores no admission facts or execution cache.
///
/// # Errors
/// Malformed declarations/data, incompatible types and allowance exhaustion
/// retain `location`. Mismatch messages identify nested fields and positions.
pub fn admit_constructed<K>(
    value: &ConstructedValue,
    expected: &DeclaredType<K>,
    budget: &mut Budget,
    location: Location,
) -> Result<(), QueryError> {
    validate_declaration(expected, budget, &location)?;
    admit_constructed_value(value, expected, budget, location)
}

/// Admit an actual constructed value and retain its declaration through ordinary
/// bindings, access, copying and evaluation. Native declarations belong to hosts.
///
/// ```
/// use zirql::{Budget, ConstructedValue as V, DeclaredType as D, Location,
///             ProgramLimits, declare_constructed, copy_constructed_value};
/// let mut budget = Budget::for_program(ProgramLimits {
///     work: 10_000, results: 1_000, nesting: 64, stream_items: 100,
/// });
/// let row = declare_constructed(
///     V::Record(vec![("id".into(), V::Integer(4))]),
///     D::Record(vec![
///         ("id".into(), D::Integer),
///         ("caption".into(), D::Optional(Box::new(D::String))),
///     ]),
///     &mut budget, Location::Query(0..20),
/// )?;
/// let copy = copy_constructed_value(&row, &mut budget, Location::Query(21..24))?;
/// assert_eq!(row, copy);
/// assert!(matches!(row.data(), V::Record(fields) if fields.len() == 1));
/// # Ok::<(), zirql::QueryError>(())
/// ```
///
/// # Errors
/// Returns the same located admission failures as [`admit_constructed`].
/// `Native(())` is not a constructed declaration and is refused at any depth.
pub fn declare_constructed(
    value: ConstructedValue,
    declaration: DeclaredType<()>,
    budget: &mut Budget,
    location: Location,
) -> Result<ConstructedValue, QueryError> {
    admit_constructed(&value, &declaration, budget, location.clone())?;
    reject_native(&declaration, budget, &location)?;
    annotate(value, declaration, budget, &location)
}

pub(crate) fn annotate(
    value: ConstructedValue,
    declaration: DeclaredType<()>,
    budget: &mut Budget,
    location: &Location,
) -> Result<ConstructedValue, QueryError> {
    let mut value = value;
    while let ConstructedValue::Declared {
        value: inner,
        declaration: previous,
    } = value
    {
        if !compatible_declarations(&previous, &declaration, budget, location)? {
            return Err(refusal(
                "incompatible declared underlying types",
                budget,
                location,
            )?);
        }
        value = *inner;
    }
    budget.charge(1, location.clone())?;
    budget.charge_results(1, location.clone())?;
    Ok(ConstructedValue::Declared {
        value: Box::new(value),
        declaration,
    })
}

fn reject_native(
    declaration: &DeclaredType<()>,
    budget: &mut Budget,
    location: &Location,
) -> Result<(), QueryError> {
    budget.within_evaluation(1, location.clone(), |budget| {
        budget.charge(1, location.clone())?;
        match declaration {
            DeclaredType::Native(()) | DeclaredType::Queue(_) | DeclaredType::IdentitySet(()) => {
                return Err(refusal(
                    "native declaration requires a host",
                    budget,
                    location,
                )?);
            }
            DeclaredType::Optional(child)
            | DeclaredType::Array(child)
            | DeclaredType::Sequence(child)
            | DeclaredType::Keyed(child) => reject_native(child, budget, location)?,
            DeclaredType::Tuple(children) => {
                for child in children {
                    reject_native(child, budget, location)?;
                }
            }
            DeclaredType::Record(fields) => {
                for (_, child) in fields {
                    reject_native(child, budget, location)?;
                }
            }
            _ => {}
        }
        Ok(())
    })
}

pub(crate) fn copy_declaration<K: Clone>(
    declaration: &DeclaredType<K>,
    budget: &mut Budget,
    location: &Location,
) -> Result<DeclaredType<K>, QueryError> {
    budget.within_evaluation(1, location.clone(), |budget| {
        budget.charge(1, location.clone())?;
        Ok(match declaration {
            DeclaredType::Optional(child) => {
                DeclaredType::Optional(Box::new(copy_declaration(child, budget, location)?))
            }
            DeclaredType::Array(child) => {
                DeclaredType::Array(Box::new(copy_declaration(child, budget, location)?))
            }
            DeclaredType::Sequence(child) => {
                DeclaredType::Sequence(Box::new(copy_declaration(child, budget, location)?))
            }
            DeclaredType::Queue(child) => {
                DeclaredType::Queue(Box::new(copy_declaration(child, budget, location)?))
            }
            DeclaredType::Keyed(child) => {
                DeclaredType::Keyed(Box::new(copy_declaration(child, budget, location)?))
            }
            DeclaredType::Tuple(children) => {
                budget.charge(children.len(), location.clone())?;
                let mut copied = Vec::with_capacity(children.len());
                for child in children {
                    copied.push(copy_declaration(child, budget, location)?);
                }
                DeclaredType::Tuple(copied)
            }
            DeclaredType::Record(fields) => {
                budget.charge(fields.len(), location.clone())?;
                let mut copied = Vec::with_capacity(fields.len());
                for (label, child) in fields {
                    budget.charge(label.len(), location.clone())?;
                    copied.push((label.clone(), copy_declaration(child, budget, location)?));
                }
                DeclaredType::Record(copied)
            }
            other => other.clone(),
        })
    })
}

pub(crate) fn compatible_declarations<K>(
    left: &DeclaredType<()>,
    right: &DeclaredType<K>,
    budget: &mut Budget,
    location: &Location,
) -> Result<bool, QueryError> {
    compatible_declarations_with(left, right, budget, location, &|_, _| false)
}

pub(crate) fn compatible_state<K: PartialEq>(
    left: &DeclaredType<K>,
    right: &DeclaredType<K>,
    budget: &mut Budget,
    location: &Location,
) -> Result<bool, QueryError> {
    compatible_declarations_with(left, right, budget, location, &|a, b| a == b)
}

fn compatible_declarations_with<A, B>(
    left: &DeclaredType<A>,
    right: &DeclaredType<B>,
    budget: &mut Budget,
    location: &Location,
    native: &impl Fn(&A, &B) -> bool,
) -> Result<bool, QueryError> {
    budget.within_evaluation(1, location.clone(), |budget| {
        budget.charge(1, location.clone())?;
        Ok(match (left, right) {
            (DeclaredType::Optional(left), right) => {
                compatible_declarations_with(left, right, budget, location, native)?
            }
            (left, DeclaredType::Optional(right)) => {
                compatible_declarations_with(left, right, budget, location, native)?
            }
            (DeclaredType::Boolean, DeclaredType::Boolean)
            | (DeclaredType::Integer, DeclaredType::Integer)
            | (DeclaredType::Float, DeclaredType::Float)
            | (DeclaredType::String, DeclaredType::String) => true,
            (DeclaredType::Native(a), DeclaredType::Native(b))
            | (DeclaredType::IdentitySet(a), DeclaredType::IdentitySet(b)) => native(a, b),
            (DeclaredType::Member(a), DeclaredType::Member(b)) => a == b,
            (DeclaredType::Set(a), DeclaredType::Set(b)) => a == b,
            (DeclaredType::Array(a), DeclaredType::Array(b))
            | (DeclaredType::Array(a), DeclaredType::Sequence(b) | DeclaredType::Keyed(b))
            | (DeclaredType::Sequence(a) | DeclaredType::Keyed(a), DeclaredType::Array(b))
            | (DeclaredType::Sequence(a), DeclaredType::Sequence(b))
            | (DeclaredType::Keyed(a), DeclaredType::Keyed(b))
            | (DeclaredType::Queue(a), DeclaredType::Queue(b)) => {
                compatible_declarations_with(a, b, budget, location, native)?
            }
            (DeclaredType::Tuple(a), DeclaredType::Tuple(b)) => {
                if a.len() != b.len() {
                    return Ok(false);
                }
                for (a, b) in a.iter().zip(b) {
                    if !compatible_declarations_with(a, b, budget, location, native)? {
                        return Ok(false);
                    }
                }
                true
            }
            (DeclaredType::Record(a), DeclaredType::Record(b)) => {
                if a.len() != b.len() {
                    return Ok(false);
                }
                for (label, a) in a {
                    let mut found = None;
                    for (other, b) in b {
                        budget.charge(1 + label.len().min(other.len()), location.clone())?;
                        if label == other {
                            found = Some(b);
                            break;
                        }
                    }
                    let Some(b) = found else {
                        return Ok(false);
                    };
                    if !compatible_declarations_with(a, b, budget, location, native)? {
                        return Ok(false);
                    }
                }
                true
            }
            _ => false,
        })
    })
}

fn admit_host_value<C, H: RuntimeTypeHost<C>>(
    value: &H::Value,
    expected: &DeclaredType<H::Kind>,
    host: &H,
    context: &mut C,
    budget: &mut Budget,
    location: Location,
) -> Result<(), EvaluationError<H::Error>> {
    budget.within_evaluation(0, location.clone(), |budget| {
        budget.charge(1, location.clone())?;
        if let Some(value) = host.constructed_value(value) {
            return Ok(admit_constructed_value(value, expected, budget, location)?);
        }
        host.admit_native(value, expected, context, budget, location)
    })
}

fn admit_constructed_value<K>(
    value: &ConstructedValue,
    expected: &DeclaredType<K>,
    budget: &mut Budget,
    location: Location,
) -> Result<(), QueryError> {
    budget.within_evaluation(0, location.clone(), |budget| {
        if let ConstructedValue::Declared { value, declaration } = value {
            reject_native(declaration, budget, &location)?;
            admit_constructed_value(value, declaration, budget, location.clone())?;
            if !compatible_declarations(declaration, expected, budget, &location)? {
                return Err(refusal(
                    "incompatible declared underlying types",
                    budget,
                    &location,
                )?);
            }
            return admit_constructed_value(value, expected, budget, location);
        }
        // These facts are freshly discovered from actual data, never supplied tags.
        let actual = constructed_value_type(value, budget, location.clone())?;
        check_type(&actual, expected, budget, &location)
    })
}

pub(crate) fn validate_declaration<K>(
    expected: &DeclaredType<K>,
    budget: &mut Budget,
    location: &Location,
) -> Result<(), QueryError> {
    budget.within_evaluation(1, location.clone(), |budget| {
        budget.charge(1, location.clone())?;
        match expected {
            DeclaredType::Optional(element)
            | DeclaredType::Array(element)
            | DeclaredType::Sequence(element)
            | DeclaredType::Keyed(element)
            | DeclaredType::Queue(element) => {
                validate_declaration(element, budget, location)?;
            }
            DeclaredType::Tuple(elements) => {
                for element in elements {
                    validate_declaration(element, budget, location)?;
                }
            }
            DeclaredType::Record(fields) => {
                for (index, (label, _)) in fields.iter().enumerate() {
                    for (previous, _) in &fields[..index] {
                        budget.charge(1 + label.len().min(previous.len()), location.clone())?;
                        if label == previous {
                            return Err(refusal("duplicate record label", budget, location)?);
                        }
                    }
                }
                for (label, field) in fields {
                    budget.charge(label.len(), location.clone())?;
                    validate_declaration(field, budget, location)?;
                }
            }
            DeclaredType::Boolean
            | DeclaredType::Integer
            | DeclaredType::Float
            | DeclaredType::String
            | DeclaredType::Member(_)
            | DeclaredType::Set(_)
            | DeclaredType::Native(_)
            | DeclaredType::IdentitySet(_) => {}
        }
        Ok(())
    })
}

fn check_type<K>(
    actual: &ValueType,
    expected: &DeclaredType<K>,
    budget: &mut Budget,
    location: &Location,
) -> Result<(), QueryError> {
    check_type_facts(actual, expected, false, budget, location)
}

pub(crate) fn check_known_type(
    actual: &ValueType,
    expected: &DeclaredType<()>,
    budget: &mut Budget,
    location: &Location,
) -> Result<(), QueryError> {
    check_type_facts(actual, expected, true, budget, location)
}

fn check_type_facts<K>(
    actual: &ValueType,
    expected: &DeclaredType<K>,
    deferred: bool,
    budget: &mut Budget,
    location: &Location,
) -> Result<(), QueryError> {
    budget.within_evaluation(1, location.clone(), |budget| {
        budget.charge(1, location.clone())?;
        match (actual, expected) {
            (ValueType::Unestablished, _) if deferred => Ok(()),
            (
                ValueType::ScalarKind,
                DeclaredType::Boolean
                | DeclaredType::Integer
                | DeclaredType::Float
                | DeclaredType::String,
            ) if deferred => Ok(()),
            (ValueType::RecordKind, DeclaredType::Record(_))
            | (ValueType::TupleKind, DeclaredType::Tuple(_))
            | (ValueType::Set(None), DeclaredType::Set(_))
                if deferred =>
            {
                Ok(())
            }
            (
                ValueType::ArrayKind(elements),
                DeclaredType::Array(element)
                | DeclaredType::Sequence(element)
                | DeclaredType::Keyed(element),
            ) if deferred => check_elements(
                elements,
                element,
                "array element",
                deferred,
                budget,
                location,
            ),
            (ValueType::Array(ArrayType::Elements(elements)), DeclaredType::Sequence(element))
                if deferred =>
            {
                check_elements(
                    elements,
                    element,
                    "sequence element",
                    deferred,
                    budget,
                    location,
                )
            }
            (
                ValueType::Declared {
                    actual,
                    declaration,
                },
                expected,
            ) => {
                if !compatible_declarations(declaration, expected, budget, location)? {
                    return Err(refusal(
                        "incompatible declared underlying types",
                        budget,
                        location,
                    )?);
                }
                check_type_facts(actual, expected, deferred, budget, location)
            }
            (ValueType::Absent, DeclaredType::Optional(_)) => Ok(()),
            (actual, DeclaredType::Optional(element)) => {
                check_type_facts(actual, element, deferred, budget, location)
            }
            (ValueType::Boolean, DeclaredType::Boolean)
            | (ValueType::Integer, DeclaredType::Integer)
            | (ValueType::Float, DeclaredType::Float)
            | (ValueType::String, DeclaredType::String) => Ok(()),
            (ValueType::Member(actual), DeclaredType::Member(expected)) if actual == expected => {
                Ok(())
            }
            (ValueType::Set(actual), DeclaredType::Set(expected)) if *actual == Some(*expected) => {
                Ok(())
            }
            (
                ValueType::Array(ArrayType::Positions(elements) | ArrayType::Elements(elements)),
                DeclaredType::Array(element),
            ) => check_elements(
                elements,
                element,
                "array element",
                deferred,
                budget,
                location,
            ),
            (ValueType::Array(ArrayType::Positions(elements)), DeclaredType::Sequence(element)) => {
                check_elements(
                    elements,
                    element,
                    "sequence element",
                    deferred,
                    budget,
                    location,
                )
            }
            (
                ValueType::KeyedArray(actual),
                DeclaredType::Array(element) | DeclaredType::Keyed(element),
            ) => check_elements(
                &actual.elements,
                element,
                "keyed cell",
                deferred,
                budget,
                location,
            ),
            (ValueType::Tuple(actual), DeclaredType::Tuple(expected)) => {
                if actual.len() != expected.len() {
                    return Err(refusal("tuple length mismatch", budget, location)?);
                }
                for (index, (actual, expected)) in actual.iter().zip(expected).enumerate() {
                    check_type_facts(actual, expected, deferred, budget, location).map_err(
                        |error| nested_error(error, "tuple position", Some(index), budget),
                    )?;
                }
                Ok(())
            }
            (ValueType::Record(actual), DeclaredType::Record(expected)) => {
                for (label, _) in actual {
                    let mut declared = false;
                    for (candidate, _) in expected {
                        budget.charge(1 + label.len().min(candidate.len()), location.clone())?;
                        declared |= label == candidate;
                    }
                    if !declared {
                        return Err(refusal(
                            "record label outside declared schema",
                            budget,
                            location,
                        )?);
                    }
                }
                for (label, expected) in expected {
                    let mut found = None;
                    for (candidate, actual) in actual {
                        budget.charge(1 + label.len().min(candidate.len()), location.clone())?;
                        if label == candidate {
                            found = Some(actual);
                            break;
                        }
                    }
                    let Some(actual) = found else {
                        if matches!(expected, DeclaredType::Optional(_)) {
                            continue;
                        }
                        return Err(nested_error(
                            refusal("missing declared record field", budget, location)?,
                            label,
                            None,
                            budget,
                        ));
                    };
                    check_type_facts(actual, expected, deferred, budget, location)
                        .map_err(|error| nested_error(error, label, None, budget))?;
                }
                Ok(())
            }
            _ => Err(refusal(expected.description(), budget, location)?),
        }
    })
}

fn check_elements<K>(
    elements: &[ValueType],
    expected: &DeclaredType<K>,
    label: &str,
    deferred: bool,
    budget: &mut Budget,
    location: &Location,
) -> Result<(), QueryError> {
    for (index, actual) in elements.iter().enumerate() {
        check_type_facts(actual, expected, deferred, budget, location)
            .map_err(|error| nested_error(error, label, Some(index), budget))?;
    }
    Ok(())
}

impl<K> DeclaredType<K> {
    fn description(&self) -> &'static str {
        match self {
            Self::Optional(_) => "expected optional value",
            Self::Boolean => "expected Boolean",
            Self::Integer => "expected integer",
            Self::Float => "expected finite float",
            Self::String => "expected string",
            Self::Member(_) => "expected member of declared nominal type",
            Self::Array(_) => "expected array",
            Self::Sequence(_) => "expected positional sequence",
            Self::Tuple(_) => "expected tuple",
            Self::Record(_) => "expected record",
            Self::Set(_) => "expected set of declared element type",
            Self::Keyed(_) => "expected keyed array",
            Self::Native(_) => "expected native value",
            Self::Queue(_) => "expected computational queue",
            Self::IdentitySet(_) => "expected native identity set",
        }
    }
}

fn refusal(
    message: &str,
    budget: &mut Budget,
    location: &Location,
) -> Result<QueryError, QueryError> {
    budget.charge(message.len(), location.clone())?;
    Ok(QueryError {
        location: location.clone(),
        message: message.to_owned(),
        category: QueryErrorCategory::Other,
    })
}

fn nested_error(
    mut error: QueryError,
    label: &str,
    index: Option<usize>,
    budget: &mut Budget,
) -> QueryError {
    // Preserve allowance failures without allocating a growing diagnostic path.
    if error.category != QueryErrorCategory::Other {
        return error;
    }
    let bytes = error
        .message
        .len()
        .saturating_add(label.len())
        .saturating_add(24);
    if let Err(limit) = budget.charge(bytes, error.location.clone()) {
        return limit;
    }
    error.message = match index {
        Some(index) => format!("{label} {}: {}", index + 1, error.message),
        None => format!("field {label}: {}", error.message),
    };
    error
}

// Exact return obligations, unlike the intentionally weaker admission compatibility.
pub(crate) fn same_declaration<K: PartialEq>(
    a: &DeclaredType<K>,
    b: &DeclaredType<K>,
    budget: &mut Budget,
    location: &Location,
) -> Result<bool, QueryError> {
    budget.within_evaluation(1, location.clone(), |budget| {
        budget.charge(1, location.clone())?;
        Ok(match (a, b) {
            (DeclaredType::Optional(a), DeclaredType::Optional(b))
            | (DeclaredType::Array(a), DeclaredType::Array(b))
            | (DeclaredType::Sequence(a), DeclaredType::Sequence(b))
            | (DeclaredType::Keyed(a), DeclaredType::Keyed(b))
            | (DeclaredType::Queue(a), DeclaredType::Queue(b)) => {
                same_declaration(a, b, budget, location)?
            }
            (DeclaredType::Tuple(a), DeclaredType::Tuple(b)) if a.len() == b.len() => {
                for (a, b) in a.iter().zip(b) {
                    if !same_declaration(a, b, budget, location)? {
                        return Ok(false);
                    }
                }
                true
            }
            (DeclaredType::Record(a), DeclaredType::Record(b)) if a.len() == b.len() => {
                for (label, a) in a {
                    let mut found = None;
                    for (name, b) in b {
                        budget.charge(1 + label.len().min(name.len()), location.clone())?;
                        if label == name {
                            found = Some(b);
                            break;
                        }
                    }
                    if let Some(b) = found {
                        if !same_declaration(a, b, budget, location)? {
                            return Ok(false);
                        }
                    } else {
                        return Ok(false);
                    }
                }
                true
            }
            (DeclaredType::Native(a), DeclaredType::Native(b))
            | (DeclaredType::IdentitySet(a), DeclaredType::IdentitySet(b)) => a == b,
            (DeclaredType::Member(a), DeclaredType::Member(b)) => a == b,
            (DeclaredType::Set(a), DeclaredType::Set(b)) => a == b,
            (DeclaredType::Boolean, DeclaredType::Boolean)
            | (DeclaredType::Integer, DeclaredType::Integer)
            | (DeclaredType::Float, DeclaredType::Float)
            | (DeclaredType::String, DeclaredType::String) => true,
            _ => false,
        })
    })
}
pub(crate) fn constructed_declaration<K>(
    declaration: &DeclaredType<K>,
    budget: &mut Budget,
    location: &Location,
) -> Result<DeclaredType<()>, QueryError> {
    budget.within_evaluation(1, location.clone(), |budget| {
        budget.charge(1, location.clone())?;
        Ok(match declaration {
            DeclaredType::Optional(c) => {
                DeclaredType::Optional(Box::new(constructed_declaration(c, budget, location)?))
            }
            DeclaredType::Array(c) => {
                DeclaredType::Array(Box::new(constructed_declaration(c, budget, location)?))
            }
            DeclaredType::Sequence(c) => {
                DeclaredType::Sequence(Box::new(constructed_declaration(c, budget, location)?))
            }
            DeclaredType::Keyed(c) => {
                DeclaredType::Keyed(Box::new(constructed_declaration(c, budget, location)?))
            }
            DeclaredType::Tuple(c) => {
                budget.charge(c.len(), location.clone())?;
                DeclaredType::Tuple(
                    c.iter()
                        .map(|c| constructed_declaration(c, budget, location))
                        .collect::<Result<_, _>>()?,
                )
            }
            DeclaredType::Record(c) => {
                budget.charge(c.len(), location.clone())?;
                DeclaredType::Record(
                    c.iter()
                        .map(|(s, c)| {
                            budget.charge(s.len(), location.clone())?;
                            Ok((s.clone(), constructed_declaration(c, budget, location)?))
                        })
                        .collect::<Result<_, QueryError>>()?,
                )
            }
            DeclaredType::Boolean => DeclaredType::Boolean,
            DeclaredType::Integer => DeclaredType::Integer,
            DeclaredType::Float => DeclaredType::Float,
            DeclaredType::String => DeclaredType::String,
            DeclaredType::Member(id) => DeclaredType::Member(*id),
            DeclaredType::Set(t) => DeclaredType::Set(*t),
            DeclaredType::Native(_) | DeclaredType::Queue(_) | DeclaredType::IdentitySet(_) => {
                return Err(QueryError::query(
                    match location {
                        Location::Query(r) | Location::Source(r) => r.clone(),
                    },
                    "native declaration requires a native value",
                ));
            }
        })
    })
}

pub(crate) fn contains_native<K>(
    declaration: &DeclaredType<K>,
    budget: &mut Budget,
    location: &Location,
) -> Result<bool, QueryError> {
    budget.within_evaluation(1, location.clone(), |budget| {
        budget.charge(1, location.clone())?;
        Ok(match declaration {
            DeclaredType::Native(_) | DeclaredType::Queue(_) | DeclaredType::IdentitySet(_) => true,
            DeclaredType::Optional(child)
            | DeclaredType::Array(child)
            | DeclaredType::Sequence(child)
            | DeclaredType::Keyed(child) => contains_native(child, budget, location)?,
            DeclaredType::Tuple(children) => {
                for child in children {
                    if contains_native(child, budget, location)? {
                        return Ok(true);
                    }
                }
                false
            }
            DeclaredType::Record(children) => {
                for (_, child) in children {
                    if contains_native(child, budget, location)? {
                        return Ok(true);
                    }
                }
                false
            }
            _ => false,
        })
    })
}

/// Whether a contract contains a computational value at any position.
pub(crate) fn contains_computational<K>(
    declaration: &DeclaredType<K>,
    budget: &mut Budget,
    location: &Location,
) -> Result<bool, QueryError> {
    budget.within_evaluation(1, location.clone(), |budget| {
        budget.charge(1, location.clone())?;
        Ok(match declaration {
            DeclaredType::Queue(_) | DeclaredType::IdentitySet(_) => true,
            DeclaredType::Optional(c)
            | DeclaredType::Array(c)
            | DeclaredType::Sequence(c)
            | DeclaredType::Keyed(c) => contains_computational(c, budget, location)?,
            DeclaredType::Tuple(c) => {
                for c in c {
                    if contains_computational(c, budget, location)? {
                        return Ok(true);
                    }
                }
                false
            }
            DeclaredType::Record(c) => {
                for (_, c) in c {
                    if contains_computational(c, budget, location)? {
                        return Ok(true);
                    }
                }
                false
            }
            _ => false,
        })
    })
}