elinvar-logic 0.1.2

The relational logic of Elinvar and its evaluator, the referee for every answer
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
//! The evaluator: the referee for every answer (LOGIC.md section 7,
//! AGENTS.md law 12).
//!
//! It computes each definition of LOGIC.md sections 3 to 5 as written, on
//! sorted sets of tuple indices. No caching, no shortcut, no optimization.

use crate::ast::{
    BinaryOp, Decl, Expr, ExprKind, Formula, FormulaKind, IntExpr, IntExprKind, IntOp,
    Multiplicity, Quantifier, TemporalBinaryOp, TemporalOp, UnaryOp,
};
use crate::bounds::Instance;
use crate::check::{Against, check_expr, check_formula, check_int};
use crate::error::Error;
use crate::relation::Variable;
use crate::trace::Trace;
use crate::universe::{TupleSet, capacity};
use std::collections::BTreeSet;

/// The truth value of a formula with no free variables in an instance.
///
/// Every error is returned, together, before anything is computed
/// (LOGIC.md section 7).
pub fn evaluate(instance: &Instance, formula: &Formula) -> Result<bool, Vec<Error>> {
    let errors = check_formula(formula, Against::Instance(instance));
    if !errors.is_empty() {
        return Err(errors);
    }
    evaluate_checked(instance, formula).map_err(|e| vec![e])
}

/// The truth value of a formula with no free variables on a trace: whether
/// it holds at position 0 (LOGIC.md 13.2).
pub fn evaluate_trace(trace: &Trace, formula: &Formula) -> Result<bool, Vec<Error>> {
    let errors = check_formula(formula, Against::Trace(trace));
    if !errors.is_empty() {
        return Err(errors);
    }
    evaluate_trace_checked(trace.fixed(), trace.states(), trace.loop_to(), formula)
        .map_err(|e| vec![e])
}

/// The tuple set an expression with no free variables denotes in an
/// instance.
pub fn evaluate_expr(instance: &Instance, expr: &Expr) -> Result<TupleSet, Vec<Error>> {
    let errors = check_expr(expr, Against::Instance(instance));
    if !errors.is_empty() {
        return Err(errors);
    }
    let mut ev = Evaluator::new(instance, &[], 0, 0);
    let set = ev.expr(expr);
    ev.done(TupleSet::from_indices(
        instance.universe(),
        set.arity,
        set.indices,
    ))
    .map_err(|e| vec![e])
}

/// The value of an integer expression with no free variables in an
/// instance (LOGIC.md 16.2).
pub fn evaluate_int(instance: &Instance, n: &IntExpr) -> Result<i64, Vec<Error>> {
    let errors = check_int(n, Against::Instance(instance));
    if !errors.is_empty() {
        return Err(errors);
    }
    let mut ev = Evaluator::new(instance, &[], 0, 0);
    let v = ev.int(n);
    ev.done(v).map_err(|e| vec![e])
}

/// The value of an integer expression with no free variables on a trace at
/// position `position` (for `elinvar eval`).
pub fn evaluate_trace_int_at(
    trace: &Trace,
    n: &IntExpr,
    position: usize,
) -> Result<i64, Vec<Error>> {
    let errors = check_int(n, Against::Trace(trace));
    if !errors.is_empty() {
        return Err(errors);
    }
    let mut ev = Evaluator::on_trace(trace, crate::ast::past_depth_int(n), position);
    let v = ev.int(n);
    ev.done(v).map_err(|e| vec![e])
}

/// Evaluates a formula already checked against an instance with the same
/// relations.
pub(crate) fn evaluate_checked(instance: &Instance, formula: &Formula) -> Result<bool, Error> {
    let mut ev = Evaluator::new(instance, &[], 0, formula.past_depth());
    let v = ev.formula(formula);
    ev.done(v)
}

/// Whether a formula holds on a trace at position `position`, with each
/// variable of `bindings` bound to an atom (LOGIC.md 13.5, for labelling
/// the steps of a trace). Its free variables must all be bound there.
pub fn evaluate_trace_at(
    trace: &Trace,
    formula: &Formula,
    position: usize,
    bindings: &[(Variable, usize)],
) -> Result<bool, Vec<Error>> {
    let vars: Vec<Variable> = bindings.iter().map(|(v, _)| v.clone()).collect();
    let errors = crate::check::check_formula_bound(formula, Against::Trace(trace), &vars);
    if !errors.is_empty() {
        return Err(errors);
    }
    let mut ev = Evaluator::on_trace(trace, formula.past_depth(), position);
    ev.env = bindings
        .iter()
        .map(|(v, a)| (v.clone(), BTreeSet::from([*a as u64])))
        .collect();
    let v = ev.formula(formula);
    ev.done(v).map_err(|e| vec![e])
}

/// The tuple set an expression with no free variables denotes on a trace
/// at position `position` (for `elinvar eval`).
pub fn evaluate_trace_expr_at(
    trace: &Trace,
    expr: &Expr,
    position: usize,
) -> Result<TupleSet, Vec<Error>> {
    let errors = check_expr(expr, Against::Trace(trace));
    if !errors.is_empty() {
        return Err(errors);
    }
    let mut ev = Evaluator::on_trace(trace, crate::ast::past_depth_expr(expr), position);
    let set = ev.expr(expr);
    ev.done(TupleSet::from_indices(
        trace.universe(),
        set.arity,
        set.indices,
    ))
    .map_err(|e| vec![e])
}

/// Evaluates a formula already checked against a trace with the same
/// relations.
pub(crate) fn evaluate_trace_checked(
    fixed: &Instance,
    states: &[Instance],
    loop_to: usize,
    formula: &Formula,
) -> Result<bool, Error> {
    let mut ev = Evaluator::new(fixed, states, loop_to, formula.past_depth());
    let v = ev.formula(formula);
    ev.done(v)
}

struct Set {
    arity: usize,
    indices: BTreeSet<u64>,
}

/// The evaluator works on the positions `0` to `positions - 1` of LOGIC.md
/// 13.3. A static instance is a trace of one state looping to itself, with
/// every relation in `fixed` and no states.
struct Evaluator<'a> {
    fixed: &'a Instance,
    states: &'a [Instance],
    len: usize,
    loop_to: usize,
    period: usize,
    positions: usize,
    pos: usize,
    n: u64,
    /// Each bound variable's value: one atom, or a set of tuples.
    env: Vec<(Variable, BTreeSet<u64>)>,
    /// A declaration over sets whose range was too large to enumerate.
    too_large: Option<Error>,
}

impl<'a> Evaluator<'a> {
    /// An evaluator of `trace` standing at `position`. Positions past the
    /// evaluator's own range repeat its last period (LOGIC.md 13.3).
    fn on_trace(trace: &'a Trace, past_depth: usize, position: usize) -> Evaluator<'a> {
        let mut ev = Evaluator::new(trace.fixed(), trace.states(), trace.loop_to(), past_depth);
        let mut p = position;
        while p >= ev.positions {
            p -= ev.period;
        }
        ev.pos = p;
        ev
    }

    fn new(
        fixed: &'a Instance,
        states: &'a [Instance],
        loop_to: usize,
        past_depth: usize,
    ) -> Evaluator<'a> {
        let len = states.len().max(1);
        let period = len - loop_to;
        Evaluator {
            fixed,
            states,
            len,
            loop_to,
            period,
            positions: loop_to + (past_depth + 1) * period,
            pos: 0,
            n: fixed.universe().size() as u64,
            env: Vec::new(),
            too_large: None,
        }
    }

    /// The value, or the error that stopped the evaluation from being
    /// complete.
    fn done<T>(&mut self, value: T) -> Result<T, Error> {
        match self.too_large.take() {
            Some(e) => Err(e),
            None => Ok(value),
        }
    }

    fn next(&self, p: usize) -> usize {
        if p + 1 < self.positions {
            p + 1
        } else {
            self.positions - self.period
        }
    }

    fn state_at(&self, p: usize) -> usize {
        if p < self.len {
            p
        } else {
            self.loop_to + (p - self.loop_to) % self.period
        }
    }

    /// The positions from `p` on, until one repeats.
    fn forward(&self, p: usize) -> Vec<usize> {
        let mut seq = vec![p];
        let mut q = p;
        loop {
            q = self.next(q);
            if seq.contains(&q) {
                return seq;
            }
            seq.push(q);
        }
    }

    fn at<T>(&mut self, p: usize, f: impl FnOnce(&mut Self) -> T) -> T {
        let old = self.pos;
        self.pos = p;
        let out = f(self);
        self.pos = old;
        out
    }

    /// `n^k`. Capacity was checked for every arity in the formula.
    fn pow(&self, k: usize) -> u64 {
        capacity(self.n as usize, k).expect("capacity is checked before evaluation")
    }

    fn arity(e: &Expr) -> usize {
        e.arity()
            .expect("ill-formed nodes are rejected before evaluation")
    }

    fn expr(&mut self, e: &Expr) -> Set {
        let n = self.n;
        let arity = Self::arity(e);
        let indices: BTreeSet<u64> = match e.kind() {
            ExprKind::Relation(r) => self
                .states
                .get(self.state_at(self.pos))
                .and_then(|s| s.get(r))
                .or_else(|| self.fixed.get(r))
                .expect("missing relations are rejected before evaluation")
                .indices
                .clone(),
            ExprKind::Variable(v) => self
                .env
                .iter()
                .rev()
                .find(|(w, _)| w == v)
                .map(|(_, a)| a.clone())
                .expect("free variables are rejected before evaluation"),
            ExprKind::None => BTreeSet::new(),
            ExprKind::Univ => (0..n).collect(),
            ExprKind::Iden => (0..n).map(|a| a * n + a).collect(),
            ExprKind::Binary(op, a, b) => {
                let sa = self.expr(a);
                let sb = self.expr(b);
                self.binary(*op, &sa, &sb)
            }
            ExprKind::Unary(op, a) => {
                let sa = self.expr(a);
                match op {
                    UnaryOp::Transpose => transpose(n, &sa.indices),
                    UnaryOp::Closure => self.closure(&sa),
                    UnaryOp::ReflexiveClosure => {
                        // LOGIC.md 3: *a is ^a + iden, over the whole universe.
                        let mut t = self.closure(&sa);
                        t.extend((0..n).map(|x| x * n + x));
                        t
                    }
                }
            }
            ExprKind::Comprehension(decls, body) => {
                let mut out = BTreeSet::new();
                let mut chosen = Vec::new();
                self.bindings(decls, &mut chosen, &mut |ev, atoms| {
                    if ev.formula(body) {
                        out.insert(atoms.iter().fold(0u64, |acc, &x| acc * n + x));
                    }
                });
                out
            }
            ExprKind::IfThenElse(c, a, b) => {
                if self.formula(c) {
                    self.expr(a).indices
                } else {
                    self.expr(b).indices
                }
            }
            ExprKind::Prime(a) => {
                let next = self.next(self.pos);
                self.at(next, |ev| ev.expr(a)).indices
            }
            ExprKind::IntToSet(v) => {
                // LOGIC.md 16.3: the integer atom of the value, if any.
                let value = self.int(v);
                self.fixed
                    .universe()
                    .atom_of_int(value)
                    .map(|a| a as u64)
                    .into_iter()
                    .collect()
            }
        };
        Set { arity, indices }
    }

    /// The value of an integer expression, wrapped (LOGIC.md 16.2).
    fn int(&mut self, v: &IntExpr) -> i64 {
        let u = self.fixed.universe().clone();
        let value = match v.kind() {
            IntExprKind::Constant(k) => *k,
            IntExprKind::Count(e) => self.expr(e).indices.len() as i64,
            IntExprKind::Sum(e) => self
                .expr(e)
                .indices
                .iter()
                .filter_map(|&a| u.int_of(a as usize))
                .fold(0i64, i64::wrapping_add),
            IntExprKind::Binary(op, a, b) => {
                let (x, y) = (self.int(a), self.int(b));
                match op {
                    IntOp::Plus => x.wrapping_add(y),
                    IntOp::Minus => x.wrapping_sub(y),
                    IntOp::Times => x.wrapping_mul(y),
                    // LOGIC.md 16.2: toward zero; by 0, minus the sign of x.
                    IntOp::Divide if y == 0 => -x.signum(),
                    IntOp::Divide => x.wrapping_div(y),
                    // By 0, x itself; otherwise with the sign of x.
                    IntOp::Remainder if y == 0 => x,
                    IntOp::Remainder => x.wrapping_rem(y),
                    // LOGIC.md 16.2: the amount is b's m low bits, unsigned,
                    // m the bits of w - 1, as Pardinus has it; from w on,
                    // every bit of a is shifted out.
                    IntOp::ShiftLeft | IntOp::ShiftRight | IntOp::UnsignedShiftRight => {
                        let w = i64::from(u.bitwidth());
                        let mask = (1i64 << w) - 1;
                        let m = 64 - (w - 1).leading_zeros();
                        let n = y & ((1i64 << m) - 1);
                        match op {
                            IntOp::ShiftLeft if n < w => x << n,
                            // a is within w bits, so shifting by w leaves its sign.
                            IntOp::ShiftRight => x >> n.min(w),
                            IntOp::UnsignedShiftRight if n < w => (x & mask) >> n,
                            _ => 0,
                        }
                    }
                }
            }
            IntExprKind::Negate(a) => self.int(a).wrapping_neg(),
            IntExprKind::IfThenElse(c, a, b) => {
                if self.formula(c) {
                    self.int(a)
                } else {
                    self.int(b)
                }
            }
            IntExprKind::SumOver(decls, body) => {
                let mut total = 0i64;
                let mut chosen = Vec::new();
                self.bindings(decls, &mut chosen, &mut |ev, _| {
                    total = total.wrapping_add(ev.int(body));
                });
                total
            }
        };
        u.wrap(value)
    }

    fn binary(&self, op: BinaryOp, a: &Set, b: &Set) -> BTreeSet<u64> {
        let n = self.n;
        match op {
            BinaryOp::Union => a.indices.union(&b.indices).copied().collect(),
            BinaryOp::Intersection => a.indices.intersection(&b.indices).copied().collect(),
            BinaryOp::Difference => a.indices.difference(&b.indices).copied().collect(),
            BinaryOp::Join => self.join(a, b),
            BinaryOp::Product => {
                let shift = self.pow(b.arity);
                let mut out = BTreeSet::new();
                for &x in &a.indices {
                    for &y in &b.indices {
                        out.insert(x * shift + y);
                    }
                }
                out
            }
            BinaryOp::Override => {
                // LOGIC.md 3: keep the tuples of A whose first atom is the
                // first atom of no tuple of B, and every tuple of B.
                let row = self.pow(a.arity - 1);
                let firsts: BTreeSet<u64> = b.indices.iter().map(|y| y / row).collect();
                let mut out: BTreeSet<u64> = a
                    .indices
                    .iter()
                    .copied()
                    .filter(|x| !firsts.contains(&(x / row)))
                    .collect();
                out.extend(b.indices.iter().copied());
                out
            }
            BinaryOp::DomainRestriction => {
                let row = self.pow(b.arity - 1);
                b.indices
                    .iter()
                    .copied()
                    .filter(|y| a.indices.contains(&(y / row)))
                    .collect()
            }
            BinaryOp::RangeRestriction => a
                .indices
                .iter()
                .copied()
                .filter(|x| b.indices.contains(&(x % n)))
                .collect(),
        }
    }

    /// LOGIC.md 3: `(a1, ..., a(i-1), b2, ..., bj)` for every pair with
    /// `ai = b1`.
    fn join(&self, a: &Set, b: &Set) -> BTreeSet<u64> {
        let n = self.n;
        let tail = self.pow(b.arity - 1);
        let mut out = BTreeSet::new();
        for &x in &a.indices {
            let last = x % n;
            let prefix = x / n;
            for &y in &b.indices {
                if y / tail == last {
                    out.insert(prefix * tail + y % tail);
                }
            }
        }
        out
    }

    /// LOGIC.md 7: start from `T = A` and replace `T` by `T + T . A` until
    /// it stops growing.
    fn closure(&self, a: &Set) -> BTreeSet<u64> {
        let mut t = Set {
            arity: 2,
            indices: a.indices.clone(),
        };
        loop {
            let step = self.join(&t, a);
            let next: BTreeSet<u64> = t.indices.union(&step).copied().collect();
            if next.len() == t.indices.len() {
                return next;
            }
            t.indices = next;
        }
    }

    /// Calls `visit` once per binding of the declarations, first
    /// declaration outermost, each in tuple order (LOGIC.md section 7).
    fn bindings(
        &mut self,
        decls: &[Decl],
        chosen: &mut Vec<u64>,
        visit: &mut dyn FnMut(&mut Evaluator<'a>, &[u64]),
    ) {
        let k = chosen.len();
        if k == decls.len() {
            visit(self, chosen);
            return;
        }
        let d = &decls[k];
        let range = self.expr(&d.expr);
        if d.is_first_order() {
            for atom in range.indices {
                self.env.push((d.var.clone(), BTreeSet::from([atom])));
                chosen.push(atom);
                self.bindings(decls, chosen, visit);
                chosen.pop();
                self.env.pop();
            }
            return;
        }
        // LOGIC.md 5: over sets or relations, every subset of the range
        // with as many tuples as the multiplicity allows, by bit pattern.
        let items: Vec<u64> = range.indices.into_iter().collect();
        if items.len() > 63 {
            if self.too_large.is_none() {
                self.too_large = Some(Error::new(
                    "enumerate.too_large",
                    format!(
                        "`{}` ranges over the subsets of {} tuples, more than 63",
                        d.var,
                        items.len()
                    ),
                ));
            }
            return;
        }
        for mask in 0..(1u64 << items.len()) {
            if !d.mult.allows(mask.count_ones() as usize) {
                continue;
            }
            let value: BTreeSet<u64> = items
                .iter()
                .enumerate()
                .filter(|(i, _)| (mask >> i) & 1 == 1)
                .map(|(_, &t)| t)
                .collect();
            self.env.push((d.var.clone(), value));
            chosen.push(mask);
            self.bindings(decls, chosen, visit);
            chosen.pop();
            self.env.pop();
        }
    }

    fn formula(&mut self, f: &Formula) -> bool {
        match f.kind() {
            FormulaKind::Constant(b) => *b,
            FormulaKind::Subset(a, b) => {
                let sa = self.expr(a);
                let sb = self.expr(b);
                sa.indices.is_subset(&sb.indices)
            }
            FormulaKind::Equal(a, b) => {
                let sa = self.expr(a);
                let sb = self.expr(b);
                sa.indices == sb.indices
            }
            FormulaKind::Multiplicity(m, a) => {
                let len = self.expr(a).indices.len();
                match m {
                    Multiplicity::Some => len >= 1,
                    Multiplicity::No => len == 0,
                    Multiplicity::One => len == 1,
                    Multiplicity::Lone => len <= 1,
                }
            }
            FormulaKind::Not(g) => !self.formula(g),
            FormulaKind::And(fs) => fs.iter().all(|g| self.formula(g)),
            FormulaKind::Or(fs) => fs.iter().any(|g| self.formula(g)),
            FormulaKind::Implies(a, b) => !self.formula(a) || self.formula(b),
            FormulaKind::Iff(a, b) => self.formula(a) == self.formula(b),
            FormulaKind::Quantified(q, decls, body) => {
                // LOGIC.md 5: bindings are counted as tuples.
                let mut total = 0u64;
                let mut true_count = 0u64;
                let mut chosen = Vec::new();
                self.bindings(decls, &mut chosen, &mut |ev, _| {
                    total += 1;
                    if ev.formula(body) {
                        true_count += 1;
                    }
                });
                match q {
                    Quantifier::All => true_count == total,
                    Quantifier::Some => true_count >= 1,
                    Quantifier::No => true_count == 0,
                    Quantifier::One => true_count == 1,
                    Quantifier::Lone => true_count <= 1,
                }
            }
            FormulaKind::Temporal(op, g) => self.temporal(*op, g),
            FormulaKind::TemporalBinary(op, a, b) => self.temporal_binary(*op, a, b),
            FormulaKind::IntCompare(op, a, b) => {
                let (x, y) = (self.int(a), self.int(b));
                op.holds(x, y)
            }
        }
    }

    /// LOGIC.md 13.2, on the positions of 13.3.
    fn temporal(&mut self, op: TemporalOp, g: &Formula) -> bool {
        let p = self.pos;
        match op {
            TemporalOp::After => {
                let q = self.next(p);
                self.at(q, |ev| ev.formula(g))
            }
            TemporalOp::Always => self
                .forward(p)
                .into_iter()
                .all(|q| self.at(q, |ev| ev.formula(g))),
            TemporalOp::Eventually => self
                .forward(p)
                .into_iter()
                .any(|q| self.at(q, |ev| ev.formula(g))),
            TemporalOp::Before => p > 0 && self.at(p - 1, |ev| ev.formula(g)),
            TemporalOp::Historically => (0..=p).all(|q| self.at(q, |ev| ev.formula(g))),
            TemporalOp::Once => (0..=p).any(|q| self.at(q, |ev| ev.formula(g))),
        }
    }

    fn temporal_binary(&mut self, op: TemporalBinaryOp, f: &Formula, g: &Formula) -> bool {
        let p = self.pos;
        match op {
            TemporalBinaryOp::Until => {
                for q in self.forward(p) {
                    if self.at(q, |ev| ev.formula(g)) {
                        return true;
                    }
                    if !self.at(q, |ev| ev.formula(f)) {
                        return false;
                    }
                }
                false
            }
            TemporalBinaryOp::Releases => {
                // LOGIC.md 13.2: not (not f until not g).
                for q in self.forward(p) {
                    if !self.at(q, |ev| ev.formula(g)) {
                        return false;
                    }
                    if self.at(q, |ev| ev.formula(f)) {
                        return true;
                    }
                }
                true
            }
            TemporalBinaryOp::Since => {
                for q in (0..=p).rev() {
                    if self.at(q, |ev| ev.formula(g)) {
                        return true;
                    }
                    if !self.at(q, |ev| ev.formula(f)) {
                        return false;
                    }
                }
                false
            }
            TemporalBinaryOp::Triggered => {
                // LOGIC.md 13.2: not (not f since not g).
                for q in (0..=p).rev() {
                    if !self.at(q, |ev| ev.formula(g)) {
                        return false;
                    }
                    if self.at(q, |ev| ev.formula(f)) {
                        return true;
                    }
                }
                true
            }
        }
    }
}

fn transpose(n: u64, a: &BTreeSet<u64>) -> BTreeSet<u64> {
    a.iter().map(|x| (x % n) * n + x / n).collect()
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::ast::{Decl, Expr, Formula};
    use crate::relation::{Relation, Variable};
    use crate::universe::{TupleSet, Universe};

    /// LOGIC.md 13.1/13.2: non-zero `loop_to` with `period >= 2` and
    /// `past_depth > 0` exercises `Evaluator::next` wraparound and `state_at`
    /// modulo arithmetic.
    #[test]
    fn past_operators_on_nonzero_loop_period_two() {
        let u = Universe::new(["A", "B", "C"]).expect("valid universe");
        let r = Relation::changing("r", 1);
        let fixed = Instance::new(&u);
        let mk = |name: &str| {
            let mut inst = Instance::new(&u);
            let mut ts = TupleSet::empty(&u, 1).expect("valid arity");
            ts.insert(&u.tuple(&[name]).expect("valid tuple"))
                .expect("valid insert");
            inst.set(&r, ts).expect("valid set");
            inst
        };
        // Trace: state 0 = {A}, state 1 = {B}, state 2 = {C}, loop_to = 1 (period 2).
        // Infinite sequence: A, B, C, B, C, B, C, ...
        let trace = Trace::new(fixed, vec![mk("A"), mk("B"), mk("C")], 1).expect("valid trace");
        let re = Expr::relation(&r);
        let a = Variable::new("a");
        // At state 0, `r` is {A}; after 1 step, `r` is {B}; after 2 steps, `r` is {C}.
        // `always (once (after r = r))` is false (r alternates B, C), while
        // `always (after (after r) = r)` is false at 0 (C != A) and true from 1 onward.
        let r_next2_eq_r = re.prime().prime().equals(&re);
        assert!(
            !evaluate_trace(&trace, &r_next2_eq_r.always()).expect("eval"),
            "fails at position 0 because state 2 is C != A"
        );
        // `after (always (after (after r) = r))` holds across the loop B, C, B, C...
        // Adding a `once` wrapper forces `past_depth >= 1` so `positions = 1 + 2*2 = 5`.
        let loop_periodic = r_next2_eq_r.and(&re.some().once()).always().after();
        assert!(evaluate_trace(&trace, &loop_periodic).expect("eval"));

        // `always (once (r' = r))` is false because consecutive states always differ.
        let never_stutter = re.prime().equals(&re).once().always();
        assert!(!evaluate_trace(&trace, &never_stutter).expect("eval"));

        // Nested quantifiers over two declarations exercise `bindings` base case & recursion.
        let b = Variable::new("b");
        let both = Formula::some(
            vec![Decl::new(&a, &re), Decl::new(&b, &re.prime())],
            &Expr::variable(&a).equals(&Expr::variable(&b)).not(),
        );
        assert!(evaluate_trace(&trace, &both.always()).expect("eval"));
    }

    /// LOGIC.md 16.2: on bitwidth 4, `m = bits(4 - 1) = 2`, so shifting by 4
    /// reads low 2 bits (`0`) rather than 3 bits (`4`), killing `w - 1 -> w / 1`.
    #[test]
    fn shift_mask_uses_bitwidth_minus_one() {
        let u = Universe::new(["N0"])
            .expect("valid")
            .with_ints(4, &[("N0", 0)])
            .expect("valid ints");
        let inst = Instance::new(&u);
        let one = IntExpr::constant(1);
        let four = IntExpr::constant(4);
        let shifted = one.shift_left(&four);
        assert!(evaluate(&inst, &shifted.equals(&one)).expect("eval"));
    }

    /// LOGIC.md 5: higher-order bindings over >63 items return `eval.too_large`
    /// (65 items kills `items.len() > 63 -> items.len() == 63`).
    #[test]
    fn higher_order_bindings_over_65_items_refused() {
        let names: Vec<String> = (0..65).map(|i| format!("A{i}")).collect();
        let u = Universe::new(names).expect("valid");
        let inst = Instance::new(&u);
        let s = Variable::new("s");
        let f = Formula::some(
            vec![Decl::with(&s, crate::ast::DeclMult::Set, &Expr::univ())],
            &Expr::variable(&s).some(),
        );
        let err = evaluate(&inst, &f).expect_err("over 63 items");
        assert_eq!(err[0].code, "enumerate.too_large");
    }
}

#[cfg(kani)]
mod kani_proofs {
    use crate::universe::wrap_bits;

    #[kani::proof]
    fn kani_int_wrap_and_div_rem() {
        let width: u32 = kani::any();
        kani::assume(width >= 1 && width <= 8);
        let x: i64 = kani::any();
        let y: i64 = kani::any();
        let w = i64::from(width);
        let min_v = -(1i64 << (w - 1));
        let max_v = (1i64 << (w - 1)) - 1;
        let wx = wrap_bits(x, width);
        let wy = wrap_bits(y, width);
        assert!(wx >= min_v && wx <= max_v);
        assert!(wy >= min_v && wy <= max_v);
        // Kodkod division and remainder rules never panic, including y == 0 and MIN / -1.
        let q = if wy == 0 {
            -wx.signum()
        } else {
            wx.wrapping_div(wy)
        };
        let r = if wy == 0 { wx } else { wx.wrapping_rem(wy) };
        let wq = wrap_bits(q, width);
        let wr = wrap_bits(r, width);
        assert!(wq >= min_v && wq <= max_v);
        assert!(wr >= min_v && wr <= max_v);
    }
}