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
//! Universes, tuples, and tuple sets (LOGIC.md section 1).

use crate::error::Error;
use serde::ser::{Serialize, SerializeSeq, Serializer};
use std::collections::BTreeSet;
use std::fmt;
use std::sync::Arc;

/// A list of named atoms. An atom is its position in the list, from 0.
/// It also has a bitwidth, and some of its atoms may stand for integers
/// (LOGIC.md 16.1).
///
/// Two universes are the same when they have the same names in the same
/// order, the same bitwidth, and the same integer atoms (LOGIC.md section 1).
#[derive(Clone)]
pub struct Universe(Arc<Atoms>);

#[derive(PartialEq, Eq)]
struct Atoms {
    names: Vec<String>,
    bitwidth: u32,
    /// Each atom's integer, if it has one.
    ints: Vec<Option<i64>>,
}

/// The bitwidth of a universe made from atom names alone, Kodkod's default
/// (LOGIC.md 16.1).
pub const DEFAULT_BITWIDTH: u32 = 4;

impl PartialEq for Universe {
    fn eq(&self, other: &Universe) -> bool {
        Arc::ptr_eq(&self.0, &other.0) || self.0 == other.0
    }
}

impl Eq for Universe {}

impl fmt::Debug for Universe {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_list().entries(self.0.names.iter()).finish()
    }
}

impl Serialize for Universe {
    fn serialize<S: Serializer>(&self, s: S) -> Result<S::Ok, S::Error> {
        self.0.names.serialize(s)
    }
}

/// `n^k`, the number of tuples of arity `k` over `n` atoms, if it is at
/// most `2^64 - 1` (LOGIC.md section 1).
pub(crate) fn capacity(n: usize, k: usize) -> Option<u64> {
    let k = u32::try_from(k).ok()?;
    (n as u64).checked_pow(k)
}

pub(crate) fn capacity_error(n: usize, k: usize) -> Error {
    Error::new(
        "universe.capacity",
        format!("{n} atoms and arity {k} give more than 2^64 - 1 tuples"),
    )
}

impl Universe {
    /// A universe of the given atom names, in order.
    ///
    /// Errors: `universe.empty`, `universe.duplicate_atom`.
    pub fn new<I, S>(atoms: I) -> Result<Universe, Error>
    where
        I: IntoIterator<Item = S>,
        S: Into<String>,
    {
        let atoms: Vec<String> = atoms.into_iter().map(Into::into).collect();
        if atoms.is_empty() {
            return Err(Error::new("universe.empty", "the universe has no atoms"));
        }
        let mut seen = BTreeSet::new();
        for a in &atoms {
            if !seen.insert(a.as_str()) {
                return Err(Error::new(
                    "universe.duplicate_atom",
                    format!("the atom `{a}` appears twice"),
                ));
            }
        }
        let ints = vec![None; atoms.len()];
        Ok(Universe(Arc::new(Atoms {
            names: atoms,
            bitwidth: DEFAULT_BITWIDTH,
            ints,
        })))
    }

    /// The same atoms with bitwidth `bitwidth`, each atom named in `ints`
    /// standing for its integer (LOGIC.md 16.1).
    ///
    /// Errors: `universe.bitwidth`, `universe.int`, `universe.unknown_atom`.
    pub fn with_ints(&self, bitwidth: u32, ints: &[(&str, i64)]) -> Result<Universe, Error> {
        if !(1..=32).contains(&bitwidth) {
            return Err(Error::new(
                "universe.bitwidth",
                format!("a bitwidth of {bitwidth}, outside 1 to 32"),
            ));
        }
        let (lo, hi) = (-(1i64 << (bitwidth - 1)), (1i64 << (bitwidth - 1)) - 1);
        let mut out = vec![None; self.size()];
        let mut seen = BTreeSet::new();
        for &(name, value) in ints {
            let Some(atom) = self.index_of(name) else {
                return Err(Error::new(
                    "universe.unknown_atom",
                    format!("no atom named `{name}` in the universe"),
                ));
            };
            if !(lo..=hi).contains(&value) {
                return Err(Error::new(
                    "universe.int",
                    format!(
                        "the integer {value} of `{name}` is outside {lo} to {hi}, at bitwidth {bitwidth}"
                    ),
                ));
            }
            if out[atom].is_some() {
                return Err(Error::new(
                    "universe.int",
                    format!("the atom `{name}` is given two integers"),
                ));
            }
            if !seen.insert(value) {
                return Err(Error::new(
                    "universe.int",
                    format!("the integer {value} is given to two atoms"),
                ));
            }
            out[atom] = Some(value);
        }
        Ok(Universe(Arc::new(Atoms {
            names: self.0.names.clone(),
            bitwidth,
            ints: out,
        })))
    }

    /// The bitwidth (LOGIC.md 16.1).
    pub fn bitwidth(&self) -> u32 {
        self.0.bitwidth
    }

    /// The integer the atom at `index` stands for, if it is an integer atom.
    pub fn int_of(&self, index: usize) -> Option<i64> {
        self.0.ints.get(index).copied().flatten()
    }

    /// The integer atom of `value`, if there is one.
    pub fn atom_of_int(&self, value: i64) -> Option<usize> {
        self.0.ints.iter().position(|&i| i == Some(value))
    }

    /// The integer atoms with their integers, in index order.
    pub fn int_atoms(&self) -> impl Iterator<Item = (usize, i64)> + '_ {
        self.0
            .ints
            .iter()
            .enumerate()
            .filter_map(|(a, i)| i.map(|v| (a, v)))
    }

    /// `value` wrapped at the bitwidth: its low bits in two's complement,
    /// read back as a signed number (LOGIC.md 16.1).
    pub fn wrap(&self, value: i64) -> i64 {
        wrap_bits(value, self.0.bitwidth)
    }

    /// The number of atoms.
    pub fn size(&self) -> usize {
        self.0.names.len()
    }

    /// The name of the atom at `index`, if there is one.
    pub fn atom(&self, index: usize) -> Option<&str> {
        self.0.names.get(index).map(String::as_str)
    }

    /// The position of the atom named `name`.
    pub fn index_of(&self, name: &str) -> Option<usize> {
        self.0.names.iter().position(|a| a == name)
    }

    /// The atom names, in order.
    pub fn atoms(&self) -> impl Iterator<Item = &str> {
        self.0.names.iter().map(String::as_str)
    }

    /// A tuple of the named atoms.
    ///
    /// Errors: `arity.zero`, `universe.unknown_atom`.
    pub fn tuple(&self, names: &[&str]) -> Result<Tuple, Error> {
        if names.is_empty() {
            return Err(Error::new("arity.zero", "a tuple of no atoms"));
        }
        let mut atoms = Vec::with_capacity(names.len());
        for name in names {
            match self.index_of(name) {
                Some(i) => atoms.push(i),
                None => {
                    return Err(Error::new(
                        "universe.unknown_atom",
                        format!("the universe has no atom `{name}`"),
                    ));
                }
            }
        }
        Ok(Tuple {
            universe: self.clone(),
            atoms,
        })
    }

    /// A tuple set of the given arity holding the named tuples.
    ///
    /// Errors: those of [`Universe::tuple`] and [`TupleSet::empty`], and
    /// `tuples.arity`.
    pub fn tuple_set(&self, arity: usize, tuples: &[&[&str]]) -> Result<TupleSet, Error> {
        let mut set = TupleSet::empty(self, arity)?;
        for names in tuples {
            set.insert(&self.tuple(names)?)?;
        }
        Ok(set)
    }

    /// The set of every tuple of the given arity.
    ///
    /// Errors: those of [`TupleSet::empty`].
    pub fn all(&self, arity: usize) -> Result<TupleSet, Error> {
        let mut set = TupleSet::empty(self, arity)?;
        let cap = capacity(self.size(), arity).expect("checked by TupleSet::empty");
        set.indices = (0..cap).collect();
        Ok(set)
    }
}

/// A sequence of atoms of one universe.
#[derive(Clone, PartialEq, Eq)]
pub struct Tuple {
    universe: Universe,
    atoms: Vec<usize>,
}

impl Tuple {
    /// The atoms, as positions in the universe.
    pub fn atoms(&self) -> &[usize] {
        &self.atoms
    }

    /// The number of atoms.
    pub fn arity(&self) -> usize {
        self.atoms.len()
    }

    /// The universe the atoms belong to.
    pub fn universe(&self) -> &Universe {
        &self.universe
    }

    /// The names of the atoms.
    pub fn names(&self) -> Vec<&str> {
        self.atoms
            .iter()
            .map(|&a| self.universe.0.names[a].as_str())
            .collect()
    }
}

impl fmt::Debug for Tuple {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "{self}")
    }
}

impl fmt::Display for Tuple {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        let names = self.names();
        if names.len() == 1 {
            write!(f, "{}", names[0])
        } else {
            write!(f, "({})", names.join(", "))
        }
    }
}

/// The index of a tuple: its atoms read as digits in base `n`, first atom
/// most significant (LOGIC.md section 1).
pub(crate) fn index_of_atoms(n: usize, atoms: &[usize]) -> u64 {
    atoms.iter().fold(0u64, |acc, &a| acc * n as u64 + a as u64)
}

/// The atoms of the tuple with the given index and arity.
pub(crate) fn atoms_of_index(n: usize, arity: usize, mut index: u64) -> Vec<usize> {
    let mut atoms = vec![0; arity];
    for slot in atoms.iter_mut().rev() {
        *slot = (index % n as u64) as usize;
        index /= n as u64;
    }
    atoms
}

/// A set of tuples of one arity over one universe, ordered by index.
#[derive(Clone, PartialEq, Eq)]
pub struct TupleSet {
    universe: Universe,
    arity: usize,
    pub(crate) indices: BTreeSet<u64>,
}

impl TupleSet {
    /// The empty tuple set of the given arity.
    ///
    /// Errors: `arity.zero`, `universe.capacity`.
    pub fn empty(universe: &Universe, arity: usize) -> Result<TupleSet, Error> {
        if arity == 0 {
            return Err(Error::new("arity.zero", "a tuple set of arity 0"));
        }
        if capacity(universe.size(), arity).is_none() {
            return Err(capacity_error(universe.size(), arity));
        }
        Ok(TupleSet {
            universe: universe.clone(),
            arity,
            indices: BTreeSet::new(),
        })
    }

    pub(crate) fn from_indices(
        universe: &Universe,
        arity: usize,
        indices: BTreeSet<u64>,
    ) -> TupleSet {
        TupleSet {
            universe: universe.clone(),
            arity,
            indices,
        }
    }

    /// Adds a tuple. Returns whether it was new.
    ///
    /// Errors: `tuples.arity`, `tuples.other_universe`.
    pub fn insert(&mut self, tuple: &Tuple) -> Result<bool, Error> {
        if tuple.arity() != self.arity {
            return Err(Error::new(
                "tuples.arity",
                format!(
                    "a tuple of arity {} given to a tuple set of arity {}",
                    tuple.arity(),
                    self.arity
                ),
            ));
        }
        if tuple.universe != self.universe {
            return Err(Error::new(
                "tuples.other_universe",
                "the tuple is over a different universe",
            ));
        }
        Ok(self
            .indices
            .insert(index_of_atoms(self.universe.size(), &tuple.atoms)))
    }

    /// Adds the tuple with the given index (LOGIC.md section 1). Returns
    /// whether it was new.
    ///
    /// Errors: `tuples.index`, for an index of no tuple of this arity.
    pub fn insert_index(&mut self, index: u64) -> Result<bool, Error> {
        let cap = capacity(self.universe.size(), self.arity).expect("checked by TupleSet::empty");
        if index >= cap {
            return Err(Error::new(
                "tuples.index",
                format!(
                    "index {index} is past the last of the {cap} tuples of arity {}",
                    self.arity
                ),
            ));
        }
        Ok(self.indices.insert(index))
    }

    /// Whether the set holds the tuple with the given index.
    pub fn contains_index(&self, index: u64) -> bool {
        self.indices.contains(&index)
    }

    /// Whether the set holds the tuple.
    pub fn contains(&self, tuple: &Tuple) -> bool {
        tuple.universe == self.universe
            && tuple.arity() == self.arity
            && self
                .indices
                .contains(&index_of_atoms(self.universe.size(), &tuple.atoms))
    }

    /// Whether every tuple of `self` is in `other`. Sets of different
    /// arities or universes are never inside one another.
    pub fn is_subset(&self, other: &TupleSet) -> bool {
        self.arity == other.arity
            && self.universe == other.universe
            && self.indices.is_subset(&other.indices)
    }

    /// The arity.
    pub fn arity(&self) -> usize {
        self.arity
    }

    /// The universe.
    pub fn universe(&self) -> &Universe {
        &self.universe
    }

    /// The number of tuples.
    pub fn len(&self) -> usize {
        self.indices.len()
    }

    /// Whether there are no tuples.
    pub fn is_empty(&self) -> bool {
        self.indices.is_empty()
    }

    /// The tuples, in index order.
    pub fn iter(&self) -> impl Iterator<Item = Tuple> + '_ {
        self.indices.iter().map(|&i| Tuple {
            universe: self.universe.clone(),
            atoms: atoms_of_index(self.universe.size(), self.arity, i),
        })
    }

    /// The tuples' indices, in order (LOGIC.md section 1).
    pub fn indices(&self) -> impl Iterator<Item = u64> + '_ {
        self.indices.iter().copied()
    }
}

impl fmt::Display for TupleSet {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "{{")?;
        for (i, t) in self.iter().enumerate() {
            if i > 0 {
                write!(f, ", ")?;
            }
            write!(f, "{t}")?;
        }
        write!(f, "}}")
    }
}

impl fmt::Debug for TupleSet {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "{self}")
    }
}

/// A tuple set is written as a list of tuples, each a list of atom names.
impl Serialize for TupleSet {
    fn serialize<S: Serializer>(&self, s: S) -> Result<S::Ok, S::Error> {
        let mut seq = s.serialize_seq(Some(self.len()))?;
        for t in self.iter() {
            seq.serialize_element(&t.names())?;
        }
        seq.end()
    }
}

/// Wraps `value` into signed two's-complement `bitwidth` bits (LOGIC.md 16.2).
pub(crate) fn wrap_bits(value: i64, bitwidth: u32) -> i64 {
    let shift = 64 - bitwidth;
    value.wrapping_shl(shift).wrapping_shr(shift)
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn tuple_atoms_returns_exact_indices() {
        let u = Universe::new(["A", "B", "C"]).expect("valid universe");
        let t = u.tuple(&["B", "C"]).expect("valid tuple");
        assert_eq!(t.atoms(), &[1, 2]);
        assert_eq!(t.names(), vec!["B", "C"]);
    }
}

#[cfg(kani)]
mod kani_proofs {
    use super::*;

    #[kani::proof]
    fn kani_tuple_index_roundtrip() {
        let n: usize = kani::any();
        kani::assume(n >= 1 && n <= 8);
        let a0: usize = kani::any();
        let a1: usize = kani::any();
        kani::assume(a0 < n && a1 < n);
        let idx = (a0 as u64) * (n as u64) + (a1 as u64);
        let decoded = atoms_of_index(n, 2, idx);
        assert_eq!(decoded.len(), 2);
        assert_eq!(decoded[0], a0);
        assert_eq!(decoded[1], a1);
    }
}