elinvar-engine 0.1.2

The engine of Elinvar, a relational model finder: models, translation, the SAT solver, and verdicts
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
//! The corpus (CORPUS.md): Alloy's example models, translated by hand, each
//! citing its file under `org.alloytools.alloy.extra/extra/models/` at the
//! pinned commit `59ba203` (Alloy 6.2.0). The files are not copied
//! (DESIGN.md section 13).
//!
//! Expected answers are not from running Alloy (no Java here, DESIGN.md
//! section 13). Each says where it comes from: the model's own `expect`
//! line, the comment its authors wrote beside the command, or reasoning
//! written beside it. Alloy's "no counterexample" is `holds` or `vacuous`
//! in Elinvar (CORPUS.md section 4); each case below names which.
//!
//! `cargo x corpus` runs these in a release build and prints each
//! command's time.

#![allow(clippy::unwrap_used)] // test helpers, as clippy.toml allows in tests

use elinvar_engine::logic::{Decl, Expr, Formula, Multiplicity, Variable};
use elinvar_engine::{Command, Model, Verdict};
use std::time::Instant;

#[track_caller]
fn expect(name: &str, cmd: Command<'_>, want: Verdict) {
    let start = Instant::now();
    let out = cmd.solve().unwrap();
    let ms = start.elapsed().as_millis();
    println!(
        "corpus {name}: {} in {ms} ms ({} primary variables, {} gates, {} conflicts)",
        out.verdict, out.stats.primary_variables, out.stats.gates, out.stats.conflicts
    );
    assert_eq!(out.verdict, want, "{name}");
}

fn var(name: &str) -> (Variable, Expr) {
    let v = Variable::new(name);
    let e = Expr::variable(&v);
    (v, e)
}

fn all(decls: &[(&Variable, &Expr)], body: &Formula) -> Formula {
    Formula::all(decls.iter().map(|(v, e)| Decl::new(v, e)).collect(), body)
}

fn some(decls: &[(&Variable, &Expr)], body: &Formula) -> Formula {
    Formula::some(decls.iter().map(|(v, e)| Decl::new(v, e)).collect(), body)
}

fn no(decls: &[(&Variable, &Expr)], body: &Formula) -> Formula {
    Formula::no(decls.iter().map(|(v, e)| Decl::new(v, e)).collect(), body)
}

/// The family of book/chapter4/grandpa1.als to grandpa3.als.
struct Family {
    m: Model,
    person: Expr,
    man: Expr,
    father: Expr,
    mother: Expr,
    wife: Expr,
    husband: Expr,
}

fn family() -> Family {
    let mut m = Model::new();
    let person = m.abstract_set("Person");
    let man = m.extends("Man", &person);
    let woman = m.extends("Woman", &person);
    let father = m.field_with("father", &person, Multiplicity::Lone, &man);
    let mother = m.field_with("mother", &person, Multiplicity::Lone, &woman);
    let wife = m.field_with("wife", &man, Multiplicity::Lone, &woman);
    let husband = m.field_with("husband", &woman, Multiplicity::Lone, &man);
    let (p, pe) = var("p");
    // fact { no p: Person | p in p.^(mother+father)  wife = ~husband }
    m.fact(no(
        &[(&p, &person)],
        &pe.is_in(&pe.join(&mother.union(&father).closure())),
    ));
    m.fact(wife.equals(&husband.transpose()));
    Family {
        m,
        person,
        man,
        father,
        mother,
        wife,
        husband,
    }
}

impl Family {
    fn no_self_father(&self) -> Formula {
        let (x, xe) = var("m");
        no(&[(&x, &self.man)], &xe.equals(&xe.join(&self.father)))
    }

    fn own_grandpa(&self, grandpas: &dyn Fn(&Expr) -> Expr) -> Formula {
        let (p, pe) = var("p");
        some(&[(&p, &self.person)], &pe.is_in(&grandpas(&pe)))
    }

    /// grandpa2 and grandpa3: parents include step-parents.
    fn step_grandpas(&self, p: &Expr) -> Expr {
        let parent = self
            .mother
            .union(&self.father)
            .union(&self.father.join(&self.wife))
            .union(&self.mother.join(&self.husband));
        p.join(&parent).join(&parent).intersection(&self.man)
    }
}

#[test]
fn grandpa1() {
    // book/chapter4/grandpa1.als
    let f = family();
    let grandpas = |p: &Expr| p.join(&f.mother.union(&f.father)).join(&f.father);
    // "This should not find any counterexample." The facts allow cases.
    expect(
        "grandpa1 check NoSelfFather",
        f.m.check(&f.no_self_father()).scope(3),
        Verdict::Holds,
    );
    // "This should not find any instance."
    expect(
        "grandpa1 run ownGrandpa for 4 Person",
        f.m.run(&f.own_grandpa(&grandpas)).scope(4),
        Verdict::None,
    );
    // "This should not find any counterexample"
    let (p, pe) = var("p");
    let no_self_grandpa = no(&[(&p, &f.person)], &pe.is_in(&grandpas(&pe)));
    expect(
        "grandpa1 check NoSelfGrandpa for 4 Person",
        f.m.check(&no_self_grandpa).scope(4),
        Verdict::Holds,
    );
}

#[test]
fn grandpa2() {
    // book/chapter4/grandpa2.als
    let f = family();
    expect(
        "grandpa2 check NoSelfFather",
        f.m.check(&f.no_self_father()).scope(3),
        Verdict::Holds,
    );
    // "This generates an instance similar to Fig 4.2"
    expect(
        "grandpa2 run ownGrandpa for 4 Person",
        f.m.run(&f.own_grandpa(&|p| f.step_grandpas(p))).scope(4),
        Verdict::Found,
    );
}

#[test]
fn grandpa3() {
    // book/chapter4/grandpa3.als
    let mut f = family();
    let parent = f.mother.union(&f.father);
    let married = f.wife.union(&f.husband);
    // fact SocialConvention { no (wife+husband) & ^(mother+father) }
    f.m.fact(married.intersection(&parent.closure()).no());
    expect(
        "grandpa3 check NoSelfFather",
        f.m.check(&f.no_self_father()).scope(3),
        Verdict::Holds,
    );
    // "This generates an instance similar to Fig 4.3"
    expect(
        "grandpa3 run ownGrandpa for 4 Person",
        f.m.run(&f.own_grandpa(&|p| f.step_grandpas(p))).scope(4),
        Verdict::Found,
    );
    // assert Same { SocialConvention1 iff SocialConvention2 }
    // "This should not find any counterexample"
    let convention1 = married.intersection(&parent.closure()).no();
    let (x, xe) = var("m");
    let (w, we) = var("w");
    let woman = f.person.difference(&f.man);
    let convention2 = no(
        &[(&x, &f.man)],
        &xe.join(&f.wife).some().and(
            &xe.join(&f.wife)
                .is_in(&xe.join(&parent.reflexive_closure()).join(&f.mother)),
        ),
    )
    .and(&no(
        &[(&w, &woman)],
        &we.join(&f.husband).some().and(
            &we.join(&f.husband)
                .is_in(&we.join(&parent.reflexive_closure()).join(&f.father)),
        ),
    ));
    expect(
        "grandpa3 check Same",
        f.m.check(&convention1.iff(&convention2)).scope(3),
        Verdict::Holds,
    );
}

#[test]
fn filesystem() {
    // book/chapter4/filesystem.als
    let mut m = Model::new();
    let object = m.abstract_set("Object");
    let dir = m.extends("Dir", &object);
    let root = m.extends("Root", &dir);
    let file = m.extends("File", &object);
    let contents = m.field("contents", &dir, &object);
    m.fact(root.one()); // one sig Root
    // fact { Object in Root.*contents }
    m.fact(object.is_in(&root.join(&contents.reflexive_closure())));
    let (o, oe) = var("o");
    // check SomeDir // This assertion is valid
    let some_dir = all(
        &[(&o, &object.difference(&root))],
        &contents.join(&oe).some(),
    );
    expect(
        "filesystem check SomeDir",
        m.check(&some_dir).scope(3),
        Verdict::Holds,
    );
    // check RootTop // This assertion should produce a counterexample
    let root_top = no(&[(&o, &object)], &root.is_in(&oe.join(&contents)));
    expect(
        "filesystem check RootTop",
        m.check(&root_top).scope(3),
        Verdict::Counterexample,
    );
    // check FileInDir // This assertion is valid
    let (f, fe) = var("f");
    let file_in_dir = all(&[(&f, &file)], &contents.join(&fe).some());
    expect(
        "filesystem check FileInDir",
        m.check(&file_in_dir).scope(3),
        Verdict::Holds,
    );
}

fn closed(set: &Expr, elements: &Expr) -> Formula {
    let (s0, s0e) = var("s0");
    let (s1, s1e) = var("s1");
    let (s2, s2e) = var("s2");
    all(
        &[(&s0, set), (&s1, set)],
        &some(
            &[(&s2, set)],
            &s2e.join(elements)
                .equals(&s0e.join(elements).union(&s1e.join(elements))),
        ),
    )
}

#[test]
fn sets1() {
    // book/chapter5/sets1.als: check Closed. Reasoning: two sets with
    // different single elements and no third set holding both break it,
    // and scope 3 allows that, so there is a counterexample.
    let mut m = Model::new();
    let set = m.set("Set");
    let _element = m.set("Element");
    let elements = m.field("elements", &set, &_element);
    expect(
        "sets1 check Closed",
        m.check(&closed(&set, &elements)).scope(3),
        Verdict::Counterexample,
    );
}

#[test]
fn sets2() {
    // book/chapter5/sets2.als: check Closed for 4 Element, 16 Set.
    // Reasoning: the generator puts the empty set in, and with every set
    // the set with one more element, so all 16 subsets of 4 elements are
    // there and unions are closed; the generator is satisfiable at that
    // scope, so the verdict is holds.
    let mut m = Model::new();
    let set = m.set("Set");
    let element = m.set("Element");
    let elements = m.field("elements", &set, &element);
    let (s, se) = var("s");
    let (e, ee) = var("e");
    let (s2, s2e) = var("s2");
    m.fact(some(&[(&s, &set)], &se.join(&elements).no()));
    m.fact(all(
        &[(&s, &set), (&e, &element)],
        &some(
            &[(&s2, &set)],
            &s2e.join(&elements).equals(&se.join(&elements).union(&ee)),
        ),
    ));
    expect(
        "sets2 check Closed for 4 Element, 16 Set",
        m.check(&closed(&set, &elements))
            .scope_of(&element, 4)
            .scope_of(&set, 16),
        Verdict::Holds,
    );
}

#[test]
fn lists() {
    // book/chapter5/lists.als: check FalseAssertion. Reasoning: the
    // generator asks, for every list and element, a list with that rest;
    // the empty list then needs an endless chain of predecessors, so no
    // finite case satisfies the facts. Alloy reports no counterexample;
    // Elinvar says why: vacuous.
    let mut m = Model::new();
    let element = m.set("Element");
    let list = m.abstract_set("List");
    let empty = m.extends("EmptyList", &list);
    let nonempty = m.extends("NonEmptyList", &list);
    let elem = m.field_with("element", &nonempty, Multiplicity::One, &element);
    let rest = m.field_with("rest", &nonempty, Multiplicity::One, &list);
    m.fact(element.some()); // some sig Element
    m.fact(empty.one()); // one sig EmptyList
    let (l, le) = var("list");
    let (e, ee) = var("e");
    let (l2, l2e) = var("list2");
    m.fact(all(
        &[(&l, &list), (&e, &element)],
        &some(
            &[(&l2, &list)],
            &l2e.join(&rest)
                .equals(&le)
                .and(&l2e.join(&elem).equals(&ee)),
        ),
    ));
    let false_assertion = all(&[(&l, &list)], &le.equals(&le).not());
    expect(
        "lists check FalseAssertion",
        m.check(&false_assertion).scope(3),
        Verdict::Vacuous,
    );
}

#[test]
fn ceilings_and_floors() {
    // examples/toys/ceilingsAndFloors.als, with its `expect` lines.
    let mut m = Model::new();
    let platform = m.set("Platform");
    let man = m.set("Man");
    let ceiling = m.field_with("ceiling", &man, Multiplicity::One, &platform);
    let floor = m.field_with("floor", &man, Multiplicity::One, &platform);
    let above = |a: &Expr, b: &Expr| a.join(&floor).equals(&b.join(&ceiling));
    let (x, xe) = var("m");
    let (y, ye) = var("n");
    // fact PaulSimon {all m: Man | some n: Man | n.Above[m]}
    m.fact(all(&[(&x, &man)], &some(&[(&y, &man)], &above(&ye, &xe))));
    let below_too = all(&[(&x, &man)], &some(&[(&y, &man)], &above(&xe, &ye)));
    let geometry = no(&[(&x, &man)], &xe.join(&floor).equals(&xe.join(&ceiling)));
    let no_sharing = no(
        &[(&x, &man), (&y, &man)],
        &xe.equals(&ye).not().and(
            &xe.join(&floor)
                .equals(&ye.join(&floor))
                .or(&xe.join(&ceiling).equals(&ye.join(&ceiling))),
        ),
    );
    expect(
        "ceilingsAndFloors check BelowToo for 2 expect 1",
        m.check(&below_too).scope(2),
        Verdict::Counterexample,
    );
    // expect 0: no counterexample, and no men at all satisfies the fact,
    // so the rules allow cases: holds.
    expect(
        "ceilingsAndFloors check BelowToo' for 2 expect 0",
        m.check(&geometry.implies(&below_too)).scope(2),
        Verdict::Holds,
    );
    expect(
        "ceilingsAndFloors check BelowToo' for 3 expect 1",
        m.check(&geometry.implies(&below_too)).scope(3),
        Verdict::Counterexample,
    );
    expect(
        "ceilingsAndFloors check BelowToo'' for 6 expect 0",
        m.check(&no_sharing.implies(&below_too)).scope(6),
        Verdict::Holds,
    );
}

/// examples/toys/ceilingsAndFloors.als: `check BelowToo'' for 10 expect 0`.
/// Proving it is a counting argument, close to the pigeonhole principle,
/// and takes Elinvar's solver one to two minutes in a release build
/// (CORPUS.md section 6). `cargo x corpus` runs it; `cargo x test` does
/// not.
#[test]
fn ceilings_and_floors_scope_10() {
    let mut m = Model::new();
    let platform = m.set("Platform");
    let man = m.set("Man");
    let ceiling = m.field_with("ceiling", &man, Multiplicity::One, &platform);
    let floor = m.field_with("floor", &man, Multiplicity::One, &platform);
    let above = |a: &Expr, b: &Expr| a.join(&floor).equals(&b.join(&ceiling));
    let (x, xe) = var("m");
    let (y, ye) = var("n");
    m.fact(all(&[(&x, &man)], &some(&[(&y, &man)], &above(&ye, &xe))));
    let below_too = all(&[(&x, &man)], &some(&[(&y, &man)], &above(&xe, &ye)));
    let no_sharing = no(
        &[(&x, &man), (&y, &man)],
        &xe.equals(&ye).not().and(
            &xe.join(&floor)
                .equals(&ye.join(&floor))
                .or(&xe.join(&ceiling).equals(&ye.join(&ceiling))),
        ),
    );
    expect(
        "ceilingsAndFloors check BelowToo'' for 10 expect 0",
        m.check(&no_sharing.implies(&below_too)).scope(10),
        Verdict::Holds,
    );
}

#[test]
fn address_book_1a() {
    // book/chapter2/addressBook1a.als: run show for 3 but 1 Book. An empty
    // predicate: any case will do.
    let mut m = Model::new();
    let name = m.set("Name");
    let addr = m.set("Addr");
    let book = m.set("Book");
    let addr_rel = m.relation("addr", &[&book, &name, &addr]);
    let (b, be) = var("b");
    let (n, ne) = var("n");
    // addr: Name -> lone Addr
    m.fact(all(
        &[(&b, &book), (&n, &name)],
        &ne.join(&be.join(&addr_rel)).lone(),
    ));
    expect(
        "addressBook1a run show for 3 but 1 Book",
        m.run(&Formula::truth()).scope(3).scope_of(&book, 1),
        Verdict::Found,
    );
}

#[test]
fn mark_sweep_gc() {
    // examples/systems/marksweepgc.als, with its `expect 0` lines. The
    // facts are empty, so the rules allow cases: holds.
    let mut m = Model::new();
    let node = m.set("Node");
    let heap = m.set("HeapState");
    let left = m.relation("left", &[&heap, &node, &node]);
    let right = m.relation("right", &[&heap, &node, &node]);
    let marked = m.field("marked", &heap, &node);
    let free_list = m.field_with("freeList", &heap, Multiplicity::Lone, &node);
    let (h, he) = var("hs");
    let (n, ne) = var("n");
    for rel in [&left, &right] {
        // left, right : Node -> lone Node
        m.fact(all(
            &[(&h, &heap), (&n, &node)],
            &ne.join(&he.join(rel)).lone(),
        ));
    }
    let l = |hs: &Expr| hs.join(&left);
    let r = |hs: &Expr| hs.join(&right);
    let reachable = |hs: &Expr, x: &Expr| x.union(&x.join(&l(hs).union(&r(hs)).closure()));
    let clear_marks = |hs: &Expr, hs2: &Expr| {
        Formula::and_all([
            hs2.join(&marked).no(),
            l(hs2).equals(&l(hs)),
            r(hs2).equals(&r(hs)),
        ])
    };
    let mark = |hs: &Expr, from: &Expr, hs2: &Expr| {
        Formula::and_all([
            hs2.join(&marked).equals(&reachable(hs, from)),
            l(hs2).equals(&l(hs)),
            r(hs2).equals(&r(hs)),
        ])
    };
    let set_free_list = |hs: &Expr, hs2: &Expr| {
        let (k, ke) = var("k");
        let chain = hs2.join(&free_list).join(&l(hs2).reflexive_closure());
        let unmarked = ke.is_in(&hs.join(&marked)).not();
        let then = Formula::and_all([
            ke.join(&r(hs2)).no(),
            ke.join(&l(hs2)).is_in(&chain),
            ke.is_in(&chain),
        ]);
        let otherwise = ke
            .join(&l(hs2))
            .equals(&ke.join(&l(hs)))
            .and(&ke.join(&r(hs2)).equals(&ke.join(&r(hs))));
        Formula::and_all([
            chain.is_in(&node.difference(&hs.join(&marked))),
            all(
                &[(&k, &node)],
                &unmarked
                    .implies(&then)
                    .and(&unmarked.not().implies(&otherwise)),
            ),
            hs2.join(&marked).equals(&hs.join(&marked)),
        ])
    };
    let (h1, h1e) = var("hs1");
    let (h2, h2e) = var("hs2");
    let gc = |hs: &Expr, root: &Expr, hs3: &Expr| {
        some(
            &[(&h1, &heap), (&h2, &heap)],
            &Formula::and_all([
                clear_marks(hs, &h1e),
                mark(&h1e, root, &h2e),
                set_free_list(&h2e, hs3),
            ]),
        )
    };
    let (a, ae) = var("h");
    let (b, be) = var("h'");
    let (root, roote) = var("root");
    let (live, livee) = var("live");
    let decls = [(&a, &heap), (&b, &heap), (&root, &node)];
    let soundness1 = all(
        &decls,
        &gc(&ae, &roote, &be).implies(&all(
            &[(&live, &reachable(&ae, &roote))],
            &livee
                .join(&l(&be))
                .equals(&livee.join(&l(&ae)))
                .and(&livee.join(&r(&be)).equals(&livee.join(&r(&ae)))),
        )),
    );
    let soundness2 = all(
        &decls,
        &gc(&ae, &roote, &be).implies(
            &reachable(&be, &roote)
                .intersection(&reachable(&be, &be.join(&free_list)))
                .no(),
        ),
    );
    let completeness = all(
        &decls,
        &gc(&ae, &roote, &be).implies(
            &node
                .difference(&reachable(&be, &roote))
                .is_in(&reachable(&be, &be.join(&free_list))),
        ),
    );
    expect(
        "marksweepgc check Soundness1 for 3 expect 0",
        m.check(&soundness1).scope(3),
        Verdict::Holds,
    );
    expect(
        "marksweepgc check Soundness2 for 3 expect 0",
        m.check(&soundness2).scope(3),
        Verdict::Holds,
    );
    expect(
        "marksweepgc check Completeness for 3 expect 0",
        m.check(&completeness).scope(3),
        Verdict::Holds,
    );
}

#[test]
fn trash() {
    // examples/temporal/trash.als. Reasoning: a file enters the trash only
    // by `delete`, leaves it by `restore` or `empty`, and `empty` is the
    // only step that removes files, so every assertion holds; the facts
    // allow traces, so the verdicts are holds. Its `for 1.. steps`
    // commands ask for unbounded traces, which Elinvar does not do
    // (REQUIREMENTS.md section 6); they are run here with the default limit
    // of 10 steps.
    let mut m = Model::new();
    let file = m.changing_set("File");
    let trash = m.changing_subset("Trash", &file);
    m.fact(trash.no());
    let delete = m.action("delete", [&file], |s, [f]| {
        s.when(f.is_in(&trash).not());
        s.add(&trash, f);
    });
    let restore = m.action("restore", [&file], |s, [f]| {
        s.when(f.is_in(&trash));
        s.remove(&trash, f);
    });
    let empty = m.action("empty", [], |s, []| {
        s.when(trash.some());
        s.set(&trash, Expr::none());
        s.set(&file, file.difference(&trash));
    });
    expect(
        "trash run example",
        m.run(&Formula::truth()).scope(3),
        Verdict::Found,
    );
    let (f, fe) = var("f");
    let restore_after_delete = all(
        &[(&f, &file)],
        &restore
            .happens(&[&fe])
            .implies(&delete.happens(&[&fe]).once()),
    )
    .always();
    expect(
        "trash check restoreAfterDelete for 10 steps",
        m.check(&restore_after_delete).scope(3).steps(10),
        Verdict::Holds,
    );
    let delete_all = file
        .is_in(&trash)
        .and(&empty.happens(&[]))
        .implies(&file.no().always().after())
        .always();
    expect(
        "trash check deleteAll",
        m.check(&delete_all).scope(3),
        Verdict::Holds,
    );
    expect(
        "trash check Exercise1",
        m.check(&file.prime().is_in(&file).always()).scope(3),
        Verdict::Holds,
    );
    expect(
        "trash check Exercise2",
        m.check(
            &file
                .prime()
                .equals(&file)
                .not()
                .implies(&empty.happens(&[]))
                .always(),
        )
        .scope(3),
        Verdict::Holds,
    );
    let never_delete = all(&[(&f, &file)], &delete.happens(&[&fe]).not()).always();
    expect(
        "trash check Exercise3",
        m.check(&never_delete.implies(&empty.happens(&[]).not().always()))
            .scope(3),
        Verdict::Holds,
    );
    expect(
        "trash check Exercise4",
        m.check(&file.no().implies(&file.no().always()).always())
            .scope(3),
        Verdict::Holds,
    );
    // restoreEnabled[f] is f in Trash.
    let possible = all(
        &[(&f, &file)],
        &delete.happens(&[&fe]).implies(
            &empty
                .happens(&[])
                .or(&restore.happens(&[&fe]))
                .releases(&fe.is_in(&trash))
                .after(),
        ),
    )
    .always();
    expect(
        "trash check restoreIsPossibleBeforeEmpty for 3 but 10 steps",
        m.check(&possible).scope(3),
        Verdict::Holds,
    );
}

/// examples/temporal/buffer.als, as a model with its actions.
struct Buffer {
    m: Model,
    value: Expr,
    read: Expr,
    content: Expr,
    send: elinvar_engine::Action,
    receive: elinvar_engine::Action,
}

fn buffer_model() -> Buffer {
    let mut m = Model::new();
    let value = m.set("Value");
    let buffer = m.set("Buffer");
    let succ = m.field_with("succ", &buffer, Multiplicity::One, &buffer);
    let content = m.changing_field_with("content", &buffer, Multiplicity::Lone, &value);
    let read = m.changing_subset("read", &buffer);
    let write = m.changing_subset("write", &buffer);
    m.fact(read.one().and(&write.one()).always());
    let (b, be) = var("b");
    m.fact(all(
        &[(&b, &buffer)],
        &buffer.is_in(&be.join(&succ.closure())),
    ));
    m.fact(read.equals(&write).and(&content.no()));
    let send = m.action("send", [&value], |s, [v]| {
        s.when(write.join(&content).no());
        s.add(&content, write.product(&v));
        s.set(&write, write.join(&succ));
    });
    let receive = m.action("receive", [&value], |s, [v]| {
        s.when(read.join(&content).some());
        s.when(v.equals(&read.join(&content)));
        s.remove(&content, read.product(&v));
        s.set(&read, read.join(&succ));
    });
    Buffer {
        m,
        value,
        read,
        content,
        send,
        receive,
    }
}

impl Buffer {
    /// receiveWeakFairness
    fn fairness(&self, v: &Variable, ve: &Expr) -> Formula {
        let enabled = self
            .read
            .join(&self.content)
            .some()
            .and(&self.read.join(&self.content).equals(ve));
        all(
            &[(v, &self.value)],
            &enabled
                .always()
                .eventually()
                .implies(&self.receive.happens(&[ve]).eventually().always()),
        )
    }
}

#[test]
fn buffer_runs() {
    // examples/temporal/buffer.als: the facts allow traces, and weak
    // fairness is satisfiable.
    let b = buffer_model();
    expect(
        "buffer run",
        b.m.run(&Formula::truth()).scope(3),
        Verdict::Found,
    );
    let (v, ve) = var("v");
    expect(
        "buffer run receiveWeakFairness",
        b.m.run(&b.fairness(&v, &ve)).scope(3),
        Verdict::Found,
    );
}

/// examples/temporal/buffer.als, its checks. Reasoning: a cell is written
/// only when empty and read in the order written, so values leave in the
/// order they came, and only values that were sent; with weak fairness on
/// receiving, a value sent is received. Every assertion holds. Each takes
/// several seconds in a release build (CORPUS.md section 6).
#[test]
#[ignore = "slow: about 20 s in a release build; run by `cargo x corpus`"]
fn buffer_checks() {
    let b = buffer_model();
    let (m, value, send, receive) = (&b.m, &b.value, &b.send, &b.receive);
    let (v, ve) = var("v");
    let received_was_sent = all(
        &[(&v, value)],
        &receive
            .happens(&[&ve])
            .implies(&send.happens(&[&ve]).once())
            .always(),
    );
    expect(
        "buffer check everyReceivedValueWasSent for 4",
        m.check(&received_was_sent).scope(4),
        Verdict::Holds,
    );
    let (x, xe) = var("x");
    let (y, ye) = var("y");
    let order = all(
        &[(&x, value), (&y, value)],
        &receive
            .happens(&[&xe])
            .and(&receive.happens(&[&ye]).once())
            .implies(
                &send
                    .happens(&[&xe])
                    .and(&send.happens(&[&ye]).once())
                    .once(),
            )
            .always(),
    );
    expect(
        "buffer check orderIsPreserved for 3",
        m.check(&order).scope(3),
        Verdict::Holds,
    );
    let delivered = b.fairness(&v, &ve).implies(&all(
        &[(&v, value)],
        &send
            .happens(&[&ve])
            .implies(&receive.happens(&[&ve]).eventually())
            .always(),
    ));
    expect(
        "buffer check everySentValueWillBeReceived for 3",
        m.check(&delivered).scope(3),
        Verdict::Holds,
    );
}