use crate::simd::{
and_words, andnot_words, is_all_zero_words, not_words, or_and_assign_words, or_assign_words,
or_words,
};
use elinvar_logic::{
Against, BinaryOp, Bounds, Decl, Error, Expr, ExprKind, Formula, FormulaKind, Multiplicity,
Quantifier, Relation, UnaryOp, Variable, check_formula, count as plain_count,
};
use std::collections::BTreeMap;
const WORDS: usize = 64;
const LANES: u64 = (WORDS * 64) as u64;
#[derive(Clone, PartialEq, Eq)]
struct Mask(Vec<u64>);
impl Mask {
fn zeros() -> Mask {
Mask(vec![0; WORDS])
}
fn ones() -> Mask {
Mask(vec![u64::MAX; WORDS])
}
fn and(&self, o: &Mask) -> Mask {
let mut d = Mask::zeros();
and_words(&mut d.0, &self.0, &o.0);
d
}
fn or(&self, o: &Mask) -> Mask {
let mut d = Mask::zeros();
or_words(&mut d.0, &self.0, &o.0);
d
}
fn or_assign(&mut self, o: &Mask) {
or_assign_words(&mut self.0, &o.0);
}
fn or_and_assign(&mut self, a: &Mask, b: &Mask) {
or_and_assign_words(&mut self.0, &a.0, &b.0);
}
fn andnot(&self, o: &Mask) -> Mask {
let mut d = Mask::zeros();
andnot_words(&mut d.0, &self.0, &o.0);
d
}
fn not(&self) -> Mask {
let mut d = Mask::zeros();
not_words(&mut d.0, &self.0);
d
}
fn is_zero(&self) -> bool {
is_all_zero_words(&self.0)
}
fn count(&self) -> u64 {
self.0.iter().map(|w| u64::from(w.count_ones())).sum()
}
}
type Table = BTreeMap<u64, Mask>;
fn get(t: &Table, i: u64) -> Mask {
t.get(&i).cloned().unwrap_or_else(Mask::zeros)
}
fn put(t: &mut Table, i: u64, m: Mask) {
if !m.is_zero() {
t.insert(i, m);
}
}
fn supported(f: &Formula) -> bool {
fn expr(e: &Expr) -> bool {
match e.kind() {
ExprKind::Binary(_, a, b) => expr(a) && expr(b),
ExprKind::Unary(_, a) => expr(a),
ExprKind::Comprehension(decls, body) => decls_ok(decls) && formula(body),
ExprKind::IfThenElse(c, a, b) => formula(c) && expr(a) && expr(b),
ExprKind::Prime(_) | ExprKind::IntToSet(_) => false,
ExprKind::Relation(r) => !r.is_changing(),
ExprKind::Variable(_) | ExprKind::None | ExprKind::Univ | ExprKind::Iden => true,
}
}
fn decls_ok(decls: &[Decl]) -> bool {
decls.iter().all(|d| d.is_first_order() && expr(&d.expr))
}
fn formula(f: &Formula) -> bool {
match f.kind() {
FormulaKind::Constant(_) => true,
FormulaKind::Subset(a, b) | FormulaKind::Equal(a, b) => expr(a) && expr(b),
FormulaKind::Multiplicity(_, a) => expr(a),
FormulaKind::Not(g) => formula(g),
FormulaKind::And(fs) | FormulaKind::Or(fs) => fs.iter().all(formula),
FormulaKind::Implies(a, b) | FormulaKind::Iff(a, b) => formula(a) && formula(b),
FormulaKind::Quantified(_, decls, body) => decls_ok(decls) && formula(body),
FormulaKind::Temporal(..)
| FormulaKind::TemporalBinary(..)
| FormulaKind::IntCompare(..) => false,
}
}
formula(f)
}
struct Block<'a> {
n: u64,
relations: &'a [(Relation, Table)],
env: Vec<(Variable, u64)>,
}
impl Block<'_> {
fn pow(&self, k: usize) -> u64 {
self.n.pow(k as u32)
}
fn arity(e: &Expr) -> usize {
e.arity().expect("checked before counting")
}
fn expr(&mut self, e: &Expr) -> Table {
let n = self.n;
let mut out = Table::new();
match e.kind() {
ExprKind::Relation(r) => {
return self
.relations
.iter()
.find(|(s, _)| s == r)
.map(|(_, t)| t.clone())
.expect("checked before counting");
}
ExprKind::Variable(v) => {
let a = self
.env
.iter()
.rev()
.find(|(w, _)| w == v)
.map(|(_, a)| *a)
.expect("checked before counting");
out.insert(a, Mask::ones());
}
ExprKind::None => {}
ExprKind::Univ => {
for a in 0..n {
out.insert(a, Mask::ones());
}
}
ExprKind::Iden => {
for a in 0..n {
out.insert(a * n + a, Mask::ones());
}
}
ExprKind::Binary(op, a, b) => {
let (ta, tb) = (self.expr(a), self.expr(b));
return self.binary(*op, &ta, &tb, Self::arity(a), Self::arity(b));
}
ExprKind::Unary(op, a) => {
let ta = self.expr(a);
return match op {
UnaryOp::Transpose => ta
.into_iter()
.map(|(i, m)| ((i % n) * n + i / n, m))
.collect(),
UnaryOp::Closure => self.closure(&ta),
UnaryOp::ReflexiveClosure => {
let mut t = self.closure(&ta);
for x in 0..n {
t.insert(x * n + x, Mask::ones());
}
t
}
};
}
ExprKind::Comprehension(decls, body) => {
let mut values: Table = Table::new();
let mut chosen = Vec::new();
self.bindings(decls, &mut chosen, Mask::ones(), &mut |b, atoms, guard| {
let v = guard.and(&b.formula(body));
if !v.is_zero() {
let idx = atoms.iter().fold(0u64, |acc, &x| acc * n + x);
values.entry(idx).or_insert_with(Mask::zeros).or_assign(&v);
}
});
return values;
}
ExprKind::IfThenElse(c, a, b) => {
let cv = self.formula(c);
let (ta, tb) = (self.expr(a), self.expr(b));
let keys: std::collections::BTreeSet<u64> =
ta.keys().chain(tb.keys()).copied().collect();
for i in keys {
let v = get(&ta, i).and(&cv).or(&get(&tb, i).andnot(&cv));
put(&mut out, i, v);
}
}
ExprKind::Prime(_) | ExprKind::IntToSet(_) => {
unreachable!("not supported, so not counted here")
}
}
out
}
fn join(&self, a: &Table, b: &Table, bk: usize) -> Table {
let n = self.n;
let tail = self.pow(bk - 1);
let mut out = Table::new();
for (&x, ma) in a {
for (&y, mb) in b {
if y / tail == x % n {
let i = (x / n) * tail + y % tail;
out.entry(i)
.or_insert_with(Mask::zeros)
.or_and_assign(ma, mb);
}
}
}
out.retain(|_, m| !m.is_zero());
out
}
fn binary(&self, op: BinaryOp, a: &Table, b: &Table, ak: usize, bk: usize) -> Table {
let n = self.n;
let mut out = Table::new();
match op {
BinaryOp::Union => {
let keys: std::collections::BTreeSet<u64> =
a.keys().chain(b.keys()).copied().collect();
for i in keys {
put(&mut out, i, get(a, i).or(&get(b, i)));
}
}
BinaryOp::Intersection => {
for (&i, m) in a {
put(&mut out, i, m.and(&get(b, i)));
}
}
BinaryOp::Difference => {
for (&i, m) in a {
put(&mut out, i, m.andnot(&get(b, i)));
}
}
BinaryOp::Join => return self.join(a, b, bk),
BinaryOp::Product => {
let shift = self.pow(bk);
for (&x, ma) in a {
for (&y, mb) in b {
put(&mut out, x * shift + y, ma.and(mb));
}
}
}
BinaryOp::Override => {
let row = self.pow(ak - 1);
let mut rows: BTreeMap<u64, Mask> = BTreeMap::new();
for (&y, m) in b {
let cur = rows.get(&(y / row)).cloned().unwrap_or_else(Mask::zeros);
rows.insert(y / row, cur.or(m));
}
let keys: std::collections::BTreeSet<u64> =
a.keys().chain(b.keys()).copied().collect();
for i in keys {
let blocked = rows.get(&(i / row)).cloned().unwrap_or_else(Mask::zeros);
put(&mut out, i, get(a, i).andnot(&blocked).or(&get(b, i)));
}
}
BinaryOp::DomainRestriction => {
let row = self.pow(bk - 1);
for (&y, m) in b {
put(&mut out, y, m.and(&get(a, y / row)));
}
}
BinaryOp::RangeRestriction => {
for (&x, m) in a {
put(&mut out, x, m.and(&get(b, x % n)));
}
}
}
out
}
fn closure(&self, a: &Table) -> Table {
let mut t = a.clone();
loop {
let step = self.join(&t, a, 2);
let next = self.binary(BinaryOp::Union, &t, &step, 2, 2);
if next == t {
return t;
}
t = next;
}
}
fn bindings(
&mut self,
decls: &[Decl],
chosen: &mut Vec<u64>,
guard: Mask,
visit: &mut dyn FnMut(&mut Self, &[u64], &Mask),
) {
let k = chosen.len();
if k == decls.len() {
visit(self, chosen, &guard);
return;
}
let range = self.expr(&decls[k].expr);
for (atom, m) in range {
let g = guard.and(&m);
if g.is_zero() {
continue;
}
self.env.push((decls[k].var.clone(), atom));
chosen.push(atom);
self.bindings(decls, chosen, g, visit);
chosen.pop();
self.env.pop();
}
}
fn count(m: Multiplicity, values: &[Mask]) -> Mask {
let mut seen = Mask::zeros();
let mut two = Mask::zeros();
for v in values {
two = two.or(&seen.and(v));
seen = seen.or(v);
}
match m {
Multiplicity::Some => seen,
Multiplicity::No => seen.not(),
Multiplicity::Lone => two.not(),
Multiplicity::One => seen.andnot(&two),
}
}
fn formula(&mut self, f: &Formula) -> Mask {
match f.kind() {
FormulaKind::Constant(true) => Mask::ones(),
FormulaKind::Constant(false) => Mask::zeros(),
FormulaKind::Subset(a, b) => {
let (ta, tb) = (self.expr(a), self.expr(b));
let mut all = Mask::ones();
for (&i, m) in &ta {
all = all.andnot(&m.andnot(&get(&tb, i)));
}
all
}
FormulaKind::Equal(a, b) => {
let (ta, tb) = (self.expr(a), self.expr(b));
let keys: std::collections::BTreeSet<u64> =
ta.keys().chain(tb.keys()).copied().collect();
let mut all = Mask::ones();
for i in keys {
let (x, y) = (get(&ta, i), get(&tb, i));
all = all.andnot(&x.andnot(&y)).andnot(&y.andnot(&x));
}
all
}
FormulaKind::Multiplicity(m, a) => {
let values: Vec<Mask> = self.expr(a).into_values().collect();
Self::count(*m, &values)
}
FormulaKind::Not(g) => self.formula(g).not(),
FormulaKind::And(fs) => fs
.iter()
.fold(Mask::ones(), |acc, g| acc.and(&self.formula(g))),
FormulaKind::Or(fs) => fs
.iter()
.fold(Mask::zeros(), |acc, g| acc.or(&self.formula(g))),
FormulaKind::Implies(a, b) => {
let (x, y) = (self.formula(a), self.formula(b));
x.not().or(&y)
}
FormulaKind::Iff(a, b) => {
let (x, y) = (self.formula(a), self.formula(b));
x.and(&y).or(&x.not().and(&y.not()))
}
FormulaKind::Quantified(q, decls, body) => {
let mut cases: Vec<(Mask, Mask)> = Vec::new();
let mut chosen = Vec::new();
self.bindings(decls, &mut chosen, Mask::ones(), &mut |b, _, guard| {
let v = b.formula(body);
cases.push((guard.clone(), v));
});
match q {
Quantifier::All => cases
.iter()
.fold(Mask::ones(), |acc, (g, v)| acc.andnot(&g.andnot(v))),
_ => {
let values: Vec<Mask> = cases.iter().map(|(g, v)| g.and(v)).collect();
let m = match q {
Quantifier::Some => Multiplicity::Some,
Quantifier::No => Multiplicity::No,
Quantifier::One => Multiplicity::One,
Quantifier::Lone | Quantifier::All => Multiplicity::Lone,
};
Self::count(m, &values)
}
}
}
FormulaKind::Temporal(..)
| FormulaKind::TemporalBinary(..)
| FormulaKind::IntCompare(..) => {
unreachable!("not supported, so not counted here")
}
}
}
}
pub fn count_bitsliced(bounds: &Bounds, formula: &Formula, cap: usize) -> Result<u64, Vec<Error>> {
let errors = check_formula(formula, Against::Bounds(bounds));
if !errors.is_empty() {
return Err(errors);
}
if !supported(formula) || bounds.relations().any(Relation::is_changing) {
return plain_count(bounds, formula, cap);
}
let mut free = Vec::new();
for (pos, (_, lower, upper)) in bounds.entries().enumerate() {
for i in upper.indices() {
if !lower.contains_index(i) {
free.push((pos, i));
}
}
}
let m = free.len();
if m > cap || m > 63 {
return Err(vec![Error::new(
"enumerate.too_large",
format!("{m} free tuples, and the cap is {}", cap.min(63)),
)]);
}
let total = 1u64 << m;
let lane_bits = LANES.trailing_zeros() as usize;
let pattern = |b: usize| -> Mask {
Mask(
(0..WORDS)
.map(|w| {
(0..64u64).fold(0u64, |acc, k| {
let lane = (w as u64) * 64 + k;
acc | (((lane >> b) & 1) << k)
})
})
.collect(),
)
};
let patterns: Vec<Mask> = (0..lane_bits.min(m)).map(pattern).collect();
let mut counted = 0u64;
let mut base = 0u64;
while base < total {
let relations: Vec<(Relation, Table)> = bounds
.entries()
.enumerate()
.map(|(pos, (r, lower, _))| {
let mut t = Table::new();
for i in lower.indices() {
t.insert(i, Mask::ones());
}
for (bit, &(p, i)) in free.iter().enumerate() {
if p != pos {
continue;
}
let mask = if bit < lane_bits {
patterns[bit].clone()
} else if (base >> bit) & 1 == 1 {
Mask::ones()
} else {
Mask::zeros()
};
put(&mut t, i, mask);
}
(r.clone(), t)
})
.collect();
let mut block = Block {
n: bounds.universe().size() as u64,
relations: &relations,
env: Vec::new(),
};
let mut holds = block.formula(formula);
let valid = (total - base).min(LANES);
if valid < LANES {
let mut keep = Mask::zeros();
for lane in 0..valid {
keep.0[(lane / 64) as usize] |= 1 << (lane % 64);
}
holds = holds.and(&keep);
}
counted += holds.count();
base += LANES;
}
Ok(counted)
}