use super::int::Int;
use core::cmp::Ordering;
use core::hash::BuildHasher;
use hashbrown::HashTable;
use crate::hash::{IdBuild, IdMap, combine};
pub(super) type AtomId = u32;
pub(super) type FormId = u32;
#[derive(Debug)]
pub(super) struct Over;
pub(super) type R<T> = Result<T, Over>;
std::thread_local! {
static WIDE: core::cell::Cell<bool> = const { core::cell::Cell::new(false) };
}
pub(super) struct Wide(bool);
impl Wide {
pub(super) fn set(on: bool) -> Wide {
Wide(WIDE.with(|w| w.replace(on)))
}
}
impl Drop for Wide {
fn drop(&mut self) {
WIDE.with(|w| w.set(self.0));
}
}
fn wide() -> bool {
WIDE.with(core::cell::Cell::get)
}
fn big() -> Int {
Int::pow2(if wide() { 228 } else { 100 })
}
pub(super) fn max_shift() -> u32 {
if wide() { 224 } else { 96 }
}
pub(super) fn room() -> u32 {
if wide() { 228 } else { 100 }
}
const MAX_TERMS: usize = 256;
const PLAIN_TERMS: usize = 40;
const MAX_ATOMS: usize = 1 << 17;
const MAX_DEPTH: u32 = 48;
const BOUND_DEPTH: u8 = 3;
const MAX_XOR: usize = 256;
const MAX_SETTLE: u32 = 16;
const LEAF: u8 = 0;
const SEL: u8 = 1;
const XOR: u8 = 2;
const AND: u8 = 3;
const FLOOR: u8 = 4;
fn ck(c: Int) -> R<Int> {
if let Some(v) = c.to_i128()
&& v.unsigned_abs() < 1 << 100
{
return Ok(c);
}
let big = big();
if c > -big && c < big {
Ok(c)
} else {
Err(Over)
}
}
fn mul(a: impl Into<Int>, b: Int) -> R<Int> {
let a = a.into();
if b == Int::ONE {
return ck(a);
}
if a == Int::ONE {
return ck(b);
}
a.checked_mul(b).ok_or(Over).and_then(ck)
}
fn plus(a: Int, b: Int) -> R<Int> {
a.checked_add(b).ok_or(Over).and_then(ck)
}
pub(super) fn bit_len(v: Int) -> u32 {
debug_assert!(v >= 0);
256 - v.leading_zeros()
}
#[derive(Clone, PartialEq, Eq, Debug, Default)]
pub(super) struct Form {
pub(super) c: Int,
pub(super) t: Vec<(AtomId, Int)>,
}
impl core::hash::Hash for Form {
#[inline]
fn hash<H: core::hash::Hasher>(&self, state: &mut H) {
const K: u64 = 0x9e37_79b9_7f4a_7c15;
let mut h = (self.t.len() as u64 ^ self.c.fold64()).wrapping_mul(K);
for &(a, k) in &self.t {
h = (h.rotate_left(26) ^ u64::from(a)).wrapping_mul(K);
h = (h.rotate_left(26) ^ k.fold64()).wrapping_mul(K);
}
state.write_u64(h);
}
}
impl Form {
pub(super) fn konst(c: Int) -> Form {
Form { c, t: Vec::new() }
}
pub(super) fn is_const(&self) -> bool {
self.t.is_empty()
}
pub(super) fn single(&self) -> Option<AtomId> {
match self.t[..] {
[(a, k)] if k == 1 && self.c == 0 => Some(a),
_ => None,
}
}
pub(super) fn coeff(&self, a: AtomId) -> Int {
self.t
.iter()
.find(|x| x.0 == a)
.map_or(Int::from(0), |x| x.1)
}
pub(super) fn without(&self, a: AtomId) -> Form {
Form {
c: self.c,
t: self.t.iter().copied().filter(|x| x.0 != a).collect(),
}
}
}
#[derive(Clone, Copy, PartialEq, Eq, Hash, Debug)]
pub(super) enum Atom {
Leaf(u32),
Floor(FormId, u8),
And(u8, FormId, FormId),
Sel(FormId, FormId, FormId),
Xor(u8, u32),
}
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
pub(super) struct Iv {
pub(super) lo: Option<Int>,
pub(super) hi: Option<Int>,
}
impl Iv {
pub(super) const ALL: Iv = Iv { lo: None, hi: None };
pub(super) fn new(lo: impl Into<Int>, hi: Int) -> Iv {
Iv {
lo: Some(lo.into()),
hi: Some(hi),
}
}
pub(super) fn point(c: impl Into<Int>) -> Iv {
let c = c.into();
Iv::new(c, c)
}
pub(super) fn meet(self, o: Iv) -> Iv {
let lo = match (self.lo, o.lo) {
(Some(a), Some(b)) => Some(a.max(b)),
(a, b) => a.or(b),
};
let hi = match (self.hi, o.hi) {
(Some(a), Some(b)) => Some(a.min(b)),
(a, b) => a.or(b),
};
Iv { lo, hi }
}
fn hull(self, o: Iv) -> Iv {
Iv {
lo: self.lo.zip(o.lo).map(|(a, b)| a.min(b)),
hi: self.hi.zip(o.hi).map(|(a, b)| a.max(b)),
}
}
fn scaled(self, c: Int) -> Iv {
if c == Int::ONE {
return self;
}
let m = |x: Option<Int>| x.and_then(|x| x.checked_mul(c));
if c >= 0 {
Iv {
lo: m(self.lo),
hi: m(self.hi),
}
} else {
Iv {
lo: m(self.hi),
hi: m(self.lo),
}
}
}
fn plus(self, o: Iv) -> Iv {
Iv {
lo: self.lo.zip(o.lo).and_then(|(a, b)| a.checked_add(b)),
hi: self.hi.zip(o.hi).and_then(|(a, b)| a.checked_add(b)),
}
}
fn floored(self, k: u32) -> Iv {
Iv {
lo: self.lo.map(|x| x >> k),
hi: self.hi.map(|x| x >> k),
}
}
pub(super) fn within(self, lo: impl Into<Int>, hi: Int) -> bool {
let lo = lo.into();
self.lo.is_some_and(|x| x >= lo) && self.hi.is_some_and(|x| x <= hi)
}
fn value(self) -> Option<Int> {
match (self.lo, self.hi) {
(Some(a), Some(b)) if a == b => Some(a),
_ => None,
}
}
pub(super) fn bits(self) -> Option<u32> {
match (self.lo, self.hi) {
(Some(l), Some(h)) if l >= 0 && h >= l => Some(bit_len(h).max(1)),
_ => None,
}
}
}
#[derive(Default)]
pub(super) struct Algebra {
atoms: Vec<Atom>,
key: Vec<(u8, u64)>,
linked: Vec<bool>,
xor: Vec<bool>,
bounds: Vec<Iv>,
ids: IdMap<Atom, AtomId>,
forms: Vec<Form>,
hashes: Vec<u64>,
form_ids: HashTable<(u64, FormId)>,
found: IdMap<Form, (Iv, u8)>,
given: IdMap<Form, Iv>,
depth: u32,
pub(super) plain: bool,
pub(super) values: bool,
forked: bool,
wordy: bool,
linking: u32,
pub(super) work: u64,
lists: Vec<(Vec<FormId>, Int)>,
list_ids: IdMap<(Vec<FormId>, Int), u32>,
whole: IdMap<AtomId, (Form, Form)>,
rel: IdMap<AtomId, Option<(Form, Option<AtomId>)>>,
split: IdMap<(AtomId, AtomId), Vec<AtomId>>,
}
impl Algebra {
pub(super) fn atom(&self, a: AtomId) -> Atom {
self.atoms[a as usize]
}
pub(super) fn form(&self, f: FormId) -> &Form {
&self.forms[f as usize]
}
pub(super) fn bounds(&self, a: AtomId) -> Iv {
self.bounds[a as usize]
}
pub(super) fn forked(&self) -> bool {
self.forked
}
pub(super) fn wordy(&self) -> bool {
self.wordy
}
pub(super) fn fork(&mut self) {
self.forked = true;
}
pub(super) fn place(&mut self, f: &Form) -> R<(u64, FormId)> {
let i = self.intern(f)?;
Ok((self.hashes[i as usize], i))
}
pub(super) fn mark(&mut self, f: &Form) {
self.forked |= self.xored(f);
}
fn xored(&self, f: &Form) -> bool {
f.t.iter().any(|x| self.xor[x.0 as usize])
}
pub(super) fn order(&self, a: AtomId, b: AtomId) -> Ordering {
self.key[a as usize]
.cmp(&self.key[b as usize])
.then(a.cmp(&b))
}
fn hash_of(&self, f: &Form) -> u64 {
let mut h = combine(0x666f_726d, f.c.low_u64());
h = combine(h, (f.c >> 64).low_u64());
for &(a, c) in &f.t {
h = combine(h, self.key[a as usize].1);
h = combine(h, c.low_u64());
h = combine(h, (c >> 64).low_u64());
}
h
}
pub(super) fn intern(&mut self, f: &Form) -> R<FormId> {
let hash = IdBuild.hash_one(f);
if let Some(&(_, i)) = self
.form_ids
.find(hash, |&(_, i)| self.forms[i as usize] == *f)
{
return Ok(i);
}
if self.forms.len() >= MAX_ATOMS {
return Err(Over);
}
let i = self.forms.len() as FormId;
self.hashes.push(self.hash_of(f));
self.forms.push(f.clone());
self.form_ids.insert_unique(hash, (hash, i), |&(h, _)| h);
Ok(i)
}
fn make(&mut self, a: Atom, hash: u64, iv: Iv) -> R<AtomId> {
if let Some(&i) = self.ids.get(&a) {
let b = &mut self.bounds[i as usize];
let met = b.meet(iv);
if !matches!((met.lo, met.hi), (Some(l), Some(h)) if l > h) {
*b = met;
}
return Ok(i);
}
if self.atoms.len() >= MAX_ATOMS {
return Err(Over);
}
let under = |s: &Self, i: FormId| s.xored(&s.forms[i as usize]);
let (rank, xor) = match a {
Atom::Leaf(_) => (LEAF, false),
Atom::Sel(c, x, y) => (SEL, under(self, c) || under(self, x) || under(self, y)),
Atom::Xor(..) => (XOR, true),
Atom::And(_, x, y) => (AND, under(self, x) || under(self, y)),
Atom::Floor(e, _) => (FLOOR, under(self, e)),
};
let i = self.atoms.len() as AtomId;
self.atoms.push(a);
self.key.push((rank, hash));
self.linked.push(false);
self.xor.push(xor);
self.bounds.push(iv);
self.ids.insert(a, i);
Ok(i)
}
pub(super) fn leaf(&mut self, n: u32, shash: u64, iv: Iv) -> R<Form> {
let a = self.make(Atom::Leaf(n), combine(0x6c65_6166, shash), iv)?;
Ok(Form {
c: Int::from(0),
t: vec![(a, Int::from(1))],
})
}
fn one(a: AtomId) -> Form {
Form {
c: Int::from(0),
t: vec![(a, Int::from(1))],
}
}
pub(super) fn add(&mut self, x: &Form, y: &Form, m: impl Into<Int>) -> R<Form> {
let f = self.sum(x, y, m)?;
self.settle(f)
}
pub(super) fn sum(&mut self, x: &Form, y: &Form, m: impl Into<Int>) -> R<Form> {
let m = m.into();
if m == 0 {
return Ok(x.clone());
}
let mut t = Vec::with_capacity(x.t.len() + y.t.len());
let (mut i, mut j) = (0, 0);
while i < x.t.len() || j < y.t.len() {
let o = if i == x.t.len() {
Ordering::Greater
} else if j == y.t.len() {
Ordering::Less
} else {
self.order(x.t[i].0, y.t[j].0)
};
match o {
Ordering::Less => {
t.push(x.t[i]);
i += 1;
}
Ordering::Greater => {
t.push((y.t[j].0, mul(y.t[j].1, m)?));
j += 1;
}
Ordering::Equal => {
let c = plus(x.t[i].1, mul(y.t[j].1, m)?)?;
if c != 0 {
t.push((x.t[i].0, c));
}
i += 1;
j += 1;
}
}
}
self.work += t.len() as u64 + 1;
if t.len() > PLAIN_TERMS {
if self.plain || t.len() > MAX_TERMS {
return Err(Over);
}
self.forked |= self.linking == 0;
}
Ok(Form {
c: plus(x.c, mul(y.c, m)?)?,
t,
})
}
pub(super) fn scale(&mut self, x: &Form, m: impl Into<Int>) -> R<Form> {
let f = self.scaled(x, m)?;
self.settle(f)
}
fn scaled(&mut self, x: &Form, m: impl Into<Int>) -> R<Form> {
let m = m.into();
if m == 0 {
return Ok(Form::default());
}
let mut t = Vec::with_capacity(x.t.len());
for &(a, c) in &x.t {
t.push((a, mul(c, m)?));
}
Ok(Form { c: mul(x.c, m)?, t })
}
fn link(&mut self, a: AtomId) -> Option<(Form, Option<AtomId>)> {
if self.plain {
return None;
}
if let Some(l) = self.rel.get(&a) {
return l.clone();
}
self.rel.insert(a, None);
self.linking += 1;
let l = self.link_of(a);
self.linking -= 1;
self.rel.insert(a, l.clone());
l
}
fn link_of(&mut self, a: AtomId) -> Option<(Form, Option<AtomId>)> {
let (x, y) = self.whole.get(&a)?.clone();
let xor = self.xor_values(&x, &y).ok()?;
let s = self.add(&x, &y, 1).ok()?;
let d = self.add(&s, &xor, -1).ok().filter(|d| d.coeff(a) == 0)?;
let b = xor
.single()
.filter(|&b| matches!(self.atom(b), Atom::Xor(..)));
Some((d, b))
}
fn relation(&mut self, a: AtomId) -> Option<Form> {
self.link(a).map(|l| l.0)
}
pub(super) fn whole(&self, a: AtomId) -> Option<&(Form, Form)> {
self.whole.get(&a)
}
fn xor_values(&mut self, x: &Form, y: &Form) -> R<Form> {
let bits = self.range(x).bits().zip(self.range(y).bits());
let p = bits.map(|(a, b)| a.max(b)).ok_or(Over)?;
self.bxor(p, &[x.clone(), y.clone()])
}
fn range(&mut self, f: &Form) -> Iv {
let iv = self.interval(f);
match self.given.get(f) {
Some(&g) => {
let met = iv.meet(g);
if matches!((met.lo, met.hi), (Some(l), Some(h)) if l > h) {
g
} else {
met
}
}
None => iv,
}
}
fn exact(&mut self, f: &Form, p: u32) -> Option<Form> {
let top = (Int::ONE << p) - 1;
if f.is_const() {
return Some(Form::konst(f.c & top));
}
self.range(f).within(0, top).then(|| f.clone())
}
fn modulo(&mut self, f: &Form, p: u32) -> R<Form> {
if let Some(e) = self.exact(f, p) {
return Ok(e);
}
if self.linking > 0 {
return Err(Over);
}
let w = self.wrap(f, p, None)?;
if self.interval(&w).within(0, (Int::ONE << p) - 1) {
Ok(w)
} else {
Err(Over)
}
}
fn split(&mut self, x: AtomId, u: AtomId) -> Vec<AtomId> {
if let Some(s) = self.split.get(&(x, u)) {
return s.clone();
}
self.split.insert((x, u), Vec::new());
let s = self.split_of(x, u).unwrap_or_default();
self.split.insert((x, u), s.clone());
s
}
fn split_of(&mut self, x: AtomId, u: AtomId) -> R<Vec<AtomId>> {
let Atom::Xor(q, li) = self.atom(x) else {
return Ok(Vec::new());
};
let (ops, k) = self.lists[li as usize].clone();
let mut parts: Vec<(Vec<FormId>, Int)> = Vec::new();
if let Atom::Xor(_, l2) = self.atom(u) {
let (inner, k2) = self.lists[l2 as usize].clone();
if !inner.is_empty() && inner.iter().all(|i| ops.contains(i)) {
parts.push((inner, k2));
}
}
for &i in &ops {
if self.form(i).t.first().is_some_and(|t| t.0 == u) {
parts.push((vec![i], Int::ZERO));
}
}
let mut out = Vec::new();
for (part, kp) in parts {
let (mut pf, mut rest): (Vec<Form>, Vec<Form>) = (Vec::new(), Vec::new());
for &i in &ops {
let f = self.form(i).clone();
if part.contains(&i) {
pf.push(f);
} else {
rest.push(f);
}
}
if rest.is_empty() && k == kp {
continue;
}
pf.push(Form::konst(kp));
rest.push(Form::konst(k ^ kp));
let p = u32::from(q);
let (g, h) = (self.bxor(p, &pf)?, self.bxor(p, &rest)?);
if g.is_const() || h.is_const() && h.c == 0 {
continue;
}
let and = self.band(p, &g, &h)?;
if let Some(a) = and.single()
&& matches!(self.atom(a), Atom::And(..))
&& !out.contains(&a)
{
out.push(a);
}
}
Ok(out)
}
fn settle(&mut self, f: Form) -> R<Form> {
let related = |s: &Self, f: &Form| {
f.t.iter()
.any(|x| s.key[x.0 as usize].0 == XOR || s.linked[x.0 as usize])
};
if !related(self, &f) {
return Ok(f);
}
let mut f = f;
for _ in 0..MAX_SETTLE {
let mut ands: Vec<AtomId> = Vec::new();
for i in 0..f.t.len() {
let a = f.t[i].0;
match self.key[a as usize].0 {
AND if self.linked[a as usize] => ands.push(a),
XOR => {
for j in 0..f.t.len() {
let u = f.t[j].0;
if u == a {
continue;
}
for and in self.split(a, u) {
if f.coeff(and) == 0 && !ands.contains(&and) {
ands.push(and);
}
}
}
}
_ => {}
}
}
self.work += f.t.len() as u64 + 1;
let mut moved = None;
for a in ands {
let Some(d) = self.relation(a) else {
continue;
};
if let Some(m) = self.best_move(&f, a, &d)
&& m != 0
{
moved = Some((a, d, m));
break;
}
}
let Some((a, d, m)) = moved else {
return Ok(f);
};
let g = self.sum(&f, &Self::one(a), mul(-2, m)?)?;
f = self.sum(&g, &d, m)?;
self.forked |= self.linking == 0;
}
Ok(f)
}
fn best_move(&self, f: &Form, a: AtomId, d: &Form) -> Option<Int> {
let g = f.coeff(a);
let cs: Vec<(Int, Int, u8)> =
d.t.iter()
.map(|&(t, dt)| (f.coeff(t), dt, self.key[t as usize].0))
.collect();
let mut ms: Vec<Int> = Vec::with_capacity(cs.len() + 1);
if g % 2 == 0 {
ms.push(g / 2);
}
for &(c, dt, _) in &cs {
if c % dt == 0 {
ms.push(-(c / dt));
}
}
let mut best: Option<((u32, u32, Int, bool), Int)> = None;
for m in ms {
let Some(ga) = m.checked_mul(Int::from(2)).and_then(|x| g.checked_sub(x)) else {
continue;
};
let (mut terms, mut xors, mut over) = (2 * u32::from(ga != 0), 0u32, false);
for &(c, dt, rank) in &cs {
match m.checked_mul(dt).and_then(|x| c.checked_add(x)) {
Some(v) if v == 0 => {}
Some(v) if v > -big() && v < big() => {
terms += if rank == AND { 2 } else { 1 };
xors += u32::from(rank == XOR);
}
_ => over = true,
}
}
if over || ga <= -big() || ga >= big() {
continue;
}
let key = (terms, xors, ga.abs(), ga < 0);
if best.is_none_or(|b| key < b.0) {
best = Some((key, m));
}
}
best.map(|b| b.1)
}
pub(super) fn xor_of(&mut self, a: AtomId) -> Option<AtomId> {
self.link(a).and_then(|l| l.1)
}
#[cfg(test)]
pub(super) fn eval(&self, f: &Form, leaf: &dyn Fn(u32) -> Int) -> Int {
let of = |i: FormId| self.eval(self.form(i), leaf);
let mut v = f.c;
for &(a, c) in &f.t {
v += c * match self.atom(a) {
Atom::Leaf(n) => leaf(n),
Atom::Floor(ri, k) => of(ri) >> u32::from(k),
Atom::And(p, xi, yi) => of(xi) & of(yi) & ((Int::ONE << u32::from(p)) - 1),
Atom::Sel(ci, ai, bi) => {
if of(ci) != 0 {
of(ai)
} else {
of(bi)
}
}
Atom::Xor(_, li) => {
let (ops, k) = self.xor_list(li);
ops.iter().fold(k, |x, &i| x ^ of(i))
}
};
}
v
}
pub(super) fn xor_list(&self, li: u32) -> (&[FormId], Int) {
let (ops, k) = &self.lists[li as usize];
(ops, *k)
}
pub(super) fn bxor(&mut self, p: u32, ops: &[Form]) -> R<Form> {
self.enter()?;
let r = self.bxor_in(p, ops);
self.depth -= 1;
r
}
fn bxor_in(&mut self, p: u32, ops: &[Form]) -> R<Form> {
if p == 0 {
return Ok(Form::default());
}
if p > max_shift() {
return Err(Over);
}
if p == 1 {
let mut acc = Form::default();
for o in ops {
let o = self.wrap(o, 1, None)?;
let and = self.band(1, &acc, &o)?;
let sum = self.add(&acc, &o, 1)?;
acc = self.add(&sum, &and, -2)?;
}
return Ok(acc);
}
if self.plain {
let mut acc: Option<Form> = None;
for o in ops {
acc = Some(match acc {
None => o.clone(),
Some(a) => {
let sum = self.add(&a, o, 1)?;
let and = self.band(p, &a, o)?;
self.add(&sum, &and, -2)?
}
});
}
return Ok(acc.unwrap_or_default());
}
let top = (Int::ONE << p) - 1;
let mut mods: Vec<Form> = Vec::with_capacity(ops.len());
for o in ops {
mods.push(self.modulo(o, p)?);
}
let ones = mods
.iter()
.filter(|f| f.is_const())
.fold(Int::ZERO, |k, f| k ^ f.c);
let mut others = mods.iter().filter(|f| !f.is_const());
if let (Some(f), None) = (others.next(), others.next())
&& ones != 0
&& (ones >> ones.trailing_zeros()) & ((ones >> ones.trailing_zeros()) + 1) == 0
{
let f = f.clone();
let and = self.band(p, &f, &Form::konst(ones))?;
let sum = self.shift(&f, ones)?;
return self.add(&sum, &and, -2);
}
let (mut k, mut neg) = (Int::ZERO, false);
let mut exact: Vec<Form> = Vec::with_capacity(ops.len());
let mut q = 1;
for mut f in mods {
if !f.is_const() && f.t[0].1 < 0 {
let g = self.scaled(&f, -1)?;
f = self.shift(&g, top)?;
neg = !neg;
}
if f.is_const() {
k ^= f.c;
continue;
}
q = q.max(self.range(&f).bits().map_or(p, |b| b.min(p)));
exact.push(f);
}
if k == top {
neg = !neg;
k = Int::ZERO;
}
q = q.max(bit_len(k));
let low = (Int::ONE << q) - 1;
let mut flat: Vec<FormId> = Vec::new();
for e in exact {
let r = self.rep(&e, q);
if let Some(a) = r.single()
&& let Atom::Xor(_, li) = self.atom(a)
{
let (inner, ik) = self.lists[li as usize].clone();
k ^= ik & low;
flat.extend(inner);
} else {
flat.push(self.intern(&r)?);
}
if flat.len() > MAX_XOR {
return Err(Over);
}
}
self.work += flat.len() as u64 + 1;
flat.sort_unstable_by_key(|&i| (self.hashes[i as usize], i));
let mut list: Vec<FormId> = Vec::with_capacity(flat.len());
for i in flat {
if list.last() == Some(&i) {
list.pop();
} else {
list.push(i);
}
}
let mut run = Int::ZERO;
if k != 0 {
let r = k >> k.trailing_zeros();
if r & (r + 1) == 0 {
run = k;
k = Int::ZERO;
}
}
let core = if list.is_empty() {
Form::konst(k)
} else if list.len() == 1 && k == 0 {
self.form(list[0]).clone()
} else if let Some(h) = self.hoisted(q, &list, k)? {
h
} else {
self.xor_atom(list, k)?
};
let mut core = self.modulo(&core, q)?;
if run != 0 {
let and = self.band(q, &core, &Form::konst(run))?;
let sum = self.shift(&core, run)?;
core = self.add(&sum, &and, -2)?;
}
if neg {
let m = self.scale(&core, -1)?;
core = self.shift(&m, top)?;
}
Ok(core)
}
fn rep(&mut self, e: &Form, q: u32) -> Form {
let r = self.reduce(e, q);
if r == *e || !self.interval(&r).within(0, (Int::ONE << max_shift()) - 1) {
return e.clone();
}
self.wordy |= self.linking == 0;
if self.values { e.clone() } else { r }
}
fn hoisted(&mut self, p: u32, list: &[FormId], k: Int) -> R<Option<Form>> {
let mut common: Option<(u32, Option<u32>)> = None;
let mut inner: Vec<Form> = Vec::with_capacity(list.len() + 1);
for &i in list {
let f = self.form(i).clone();
let Some((Some(e), lo, len)) = self.shape(&f) else {
return Ok(None);
};
if lo == 0 {
return Ok(None);
}
match common {
None => common = Some((lo, len)),
Some(c) if c == (lo, len) => {}
_ => return Ok(None),
}
inner.push(e);
}
let Some((lo, len)) = common else {
return Ok(None);
};
let width = len.unwrap_or(p).min(p);
if lo + width > max_shift() {
return Ok(None);
}
let low = (Int::ONE << width) - 1;
inner.push(Form::konst((k & low) << lo));
let x = self.bxor(lo + width, &inner)?;
let out = match len {
None => self.floor(&x, lo, None)?,
Some(len) => self.slice(&x, lo, len, None)?,
};
let out = self.wrap(&out, p, None)?;
Ok(Some(self.shift(&out, k & !low)?))
}
fn xor_atom(&mut self, list: Vec<FormId>, k: Int) -> R<Form> {
let mut q = if k == 0 { 1 } else { bit_len(k) };
for &i in &list {
let f = self.form(i).clone();
q = q.max(self.range(&f).bits().ok_or(Over)?);
}
if q > max_shift() {
return Err(Over);
}
let mut hash = combine(combine(0x0078_6f72, u64::from(q)), k.low_u64());
hash = combine(hash, (k >> 64).low_u64());
for &i in &list {
hash = combine(hash, self.hashes[i as usize]);
}
let key = (list, k);
let li = match self.list_ids.get(&key) {
Some(&li) => li,
None => {
if self.lists.len() >= MAX_ATOMS {
return Err(Over);
}
let li = self.lists.len() as u32;
self.lists.push(key.clone());
self.list_ids.insert(key, li);
li
}
};
let a = self.make(
Atom::Xor(q as u8, li),
hash,
Iv::new(0, (Int::ONE << q) - 1),
)?;
Ok(Self::one(a))
}
pub(super) fn shift(&mut self, x: &Form, c: impl Into<Int>) -> R<Form> {
Ok(Form {
c: plus(x.c, c.into())?,
t: x.t.clone(),
})
}
pub(super) fn reduce(&mut self, f: &Form, p: u32) -> Form {
if p > max_shift() {
return f.clone();
}
let m = (Int::ONE << p) - 1;
let half = Int::ONE << (p - 1);
let mut t = Vec::with_capacity(f.t.len());
for &(a, c) in &f.t {
let mut r = c & m;
if r > half {
r -= Int::ONE << p;
}
if r != 0 {
t.push((a, r));
}
}
self.work += f.t.len() as u64 + 1;
Form { c: f.c & m, t }
}
pub(super) fn interval(&mut self, f: &Form) -> Iv {
self.interval_at(f, 0)
}
pub(super) fn bound(&mut self, f: &Form, iv: Iv) {
if f.t.is_empty() || self.plain {
return;
}
let met = self.given.get(f).map_or(iv, |old| old.meet(iv));
if matches!((met.lo, met.hi), (Some(l), Some(h)) if l > h) {
return;
}
self.given.insert(f.clone(), met);
}
fn interval_at(&mut self, f: &Form, depth: u8) -> Iv {
if f.t.is_empty() {
return Iv::point(f.c);
}
if let Some(&(iv, d)) = self.found.get(f)
&& d <= depth
{
return iv;
}
let iv = self.search(f, depth);
if self.found.len() >= MAX_ATOMS {
self.found.clear();
}
self.found.insert(f.clone(), (iv, depth));
iv
}
fn search(&mut self, f: &Form, depth: u8) -> Iv {
let mut iv = Iv::point(f.c);
for &(a, c) in &f.t {
iv = iv.plus(self.bounds[a as usize].scaled(c));
}
self.work += f.t.len() as u64 + 1;
if depth >= BOUND_DEPTH || iv.value().is_some() {
return iv;
}
let mut tried = 0;
for &(m, g) in &f.t {
let Atom::And(p, xi, yi) = self.atom(m) else {
continue;
};
let xor = self.xor_of(m).filter(|&a| f.coeff(a) != 0);
let dl = xor.map_or(Int::ZERO, |a| f.coeff(a));
let whole = xor.and_then(|_| self.whole.get(&m).cloned());
let top = match whole {
Some(_) => (Int::ONE << max_shift()) - 1,
None => (Int::ONE << u32::from(p)) - 1,
};
let known = whole.is_some();
let mut ops = match whole {
Some((x, y)) => [x, y],
None => [self.form(xi).clone(), self.form(yi).clone()],
};
let mut ivs = [Iv::point(0); 2];
for (z, iz) in ops.iter_mut().zip(&mut ivs) {
*iz = match known {
true => self.range(z),
false => self.interval_at(z, depth + 1),
};
if !known
&& !iz.within(0, top)
&& z.single().is_some()
&& depth + 1 < BOUND_DEPTH
&& let Ok(low) = self.wrap(z, u32::from(p), None)
{
*iz = self.interval_at(&low, depth + 1);
*z = low;
}
}
let [x, y] = ops;
let [ix, iy] = ivs;
if !ix.within(Int::from(0), top) || !iy.within(Int::from(0), top) {
continue;
}
tried += 1;
if tried > 2 {
break;
}
let lead = |z: &Form| match z.t.first() {
Some(&(a0, z0)) => {
let c = f.coeff(a0);
if c % z0 == 0 { c / z0 } else { Int::from(0) }
}
None => Int::from(0),
};
let half = if g % 2 == 0 { -(g / 2) } else { Int::from(0) };
let mut cands = [(lead(&x), lead(&y)), (-g, -g), (half, half)];
cands.sort_unstable();
for (k, &(al, be)) in cands.iter().enumerate() {
if k > 0 && cands[k - 1] == (al, be) {
continue;
}
let Ok(rest) = self.sum(f, &x, -al).and_then(|r| self.sum(&r, &y, -be)) else {
continue;
};
let mut rest = rest.without(m);
if let Some(a) = xor {
rest = rest.without(a);
}
if rest.t.len() >= f.t.len() {
continue;
}
let ir = self.interval_at(&rest, depth + 1);
let (xh, yh) = (ix.hi.unwrap_or(Int::from(0)), iy.hi.unwrap_or(Int::from(0)));
let bits = bit_len(xh).max(bit_len(yh));
let (mut lo, mut hi) = (Some(Int::ZERO), Some(Int::ZERO));
let (xl, yl) = (bit_len(xh), bit_len(yh));
let of = |z: &Form, len: u32, i: u32| -> (bool, bool) {
if z.is_const() {
let b = (z.c >> i).low_u64() & 1 == 1;
(b, b)
} else {
(false, len > i)
}
};
let corners = |(x0, x1): (bool, bool), (y0, y1): (bool, bool)| {
let (mut least, mut most) = (Int::MAX, Int::MIN);
for xb in [x0, x1] {
for yb in [y0, y1] {
let mut v = Some(Int::ZERO);
for (on, c) in [(xb, al), (yb, be), (xb & yb, g), (xb ^ yb, dl)] {
if on {
v = v.and_then(|s| s.checked_add(c));
}
}
match v {
Some(v) => {
least = least.min(v);
most = most.max(v);
}
None => {
least = Int::MIN;
most = Int::MAX;
}
}
}
}
(least, most)
};
let mut from = 0;
while from < bits {
let key = (of(&x, xl, from), of(&y, yl, from));
let mut to = from + 1;
while to < bits && (of(&x, xl, to), of(&y, yl, to)) == key {
to += 1;
}
let (least, most) = corners(key.0, key.1);
let weight = (Int::ONE << to) - (Int::ONE << from);
let at = |acc: Option<Int>, v: Int| {
acc.and_then(|a| v.checked_mul(weight).and_then(|v| a.checked_add(v)))
};
lo = if least == Int::MIN {
None
} else {
at(lo, least)
};
hi = if most == Int::MAX { None } else { at(hi, most) };
from = to;
}
iv = iv.meet(ir.plus(Iv { lo, hi }));
}
}
let mut tried = 0;
for &(a, g) in &f.t {
let Atom::Floor(ri, k) = self.atom(a) else {
continue;
};
if g % (Int::ONE << u32::from(k)) != 0 {
continue;
}
let lam = -(g >> u32::from(k));
let r = self.form(ri).clone();
let Ok(rest) = self.sum(f, &r, -lam) else {
continue;
};
let rest = rest.without(a);
let rest = self.settle(rest.clone()).unwrap_or(rest);
tried += 1;
if tried > 3 {
break;
}
let ir = self.interval_at(&rest, depth + 1);
let digit = Iv::new(Int::from(0), (Int::ONE << u32::from(k)) - 1).scaled(lam);
iv = iv.meet(ir.plus(digit));
}
let mut tried = 0;
'digits: for &(hi, g) in &f.t {
let Atom::Floor(ri, b) = self.atom(hi) else {
continue;
};
for &(lo, _) in &f.t {
let Atom::Floor(rj, a) = self.atom(lo) else {
continue;
};
if rj != ri || a >= b || g % (Int::ONE << u32::from(b - a)) != 0 {
continue;
}
let lam = -(g >> u32::from(b - a));
let Ok(rest) = self.sum(f, &Self::one(lo), -lam) else {
continue;
};
let rest = rest.without(hi);
let rest = self.settle(rest.clone()).unwrap_or(rest);
tried += 1;
if tried > 3 {
break 'digits;
}
let ir = self.interval_at(&rest, depth + 1);
let digit = Iv::new(Int::from(0), (Int::ONE << u32::from(b - a)) - 1).scaled(lam);
iv = iv.meet(ir.plus(digit));
}
}
iv
}
fn enter(&mut self) -> R<()> {
if self.depth >= MAX_DEPTH {
return Err(Over);
}
self.depth += 1;
Ok(())
}
pub(super) fn floor(&mut self, f: &Form, k: u32, hint: Option<Iv>) -> R<Form> {
self.enter()?;
let r = self.floor_in(f, k, hint);
self.depth -= 1;
r
}
fn floor_in(&mut self, f: &Form, mut k: u32, hint: Option<Iv>) -> R<Form> {
if k == 0 {
return Ok(f.clone());
}
if k > max_shift() {
return Err(Over);
}
let m = (Int::ONE << k) - 1;
let half = Int::ONE << (k - 1);
let mut out = Form::konst(f.c >> k);
let mut rest: Vec<(AtomId, Int)> = Vec::new();
for &(a, c) in &f.t {
let (mut q, mut r) = (c >> k, c & m);
if r > half {
q += Int::from(1);
r -= Int::ONE << k;
}
if q != 0 {
out.t.push((a, q));
}
if r != 0 {
rest.push((a, r));
}
}
self.work += f.t.len() as u64 + 1;
if rest.is_empty() {
return Ok(out);
}
let whole = out.t.is_empty();
let shift = k;
let mut rc = f.c & m;
let t = rest.iter().map(|x| x.1.trailing_zeros()).min().unwrap_or(0);
if t > 0 {
for x in &mut rest {
x.1 >>= t;
}
rc >>= t;
k -= t;
}
let r = Form { c: rc, t: rest };
if !self.plain
&& let Some((c, hi, lo)) = self.cases(&r)?
{
let (fh, fl) = (self.floor(&hi, k, None)?, self.floor(&lo, k, None)?);
let s = self.sel(&c, &fh, &fl)?;
self.forked |= self.linking == 0;
return self.add(&out, &s, 1);
}
if r.t[0].1 < 0 {
let e = self.scale(&r, Int::from(-1))?;
let e = self.shift(&e, Int::from(-1))?;
let neg = self.floor(&e, k, None)?;
let out = self.shift(&out, Int::from(-1))?;
return self.add(&out, &neg, Int::from(-1));
}
let mut iv = self.interval(&r);
if let Some(h) = hint
&& whole
{
let base = out.c.checked_mul(Int::ONE << shift);
let of = |x: Option<Int>| {
x.zip(base)
.and_then(|(x, b)| x.checked_sub(b))
.map(|x| x >> t)
};
iv = iv.meet(Iv {
lo: of(h.lo),
hi: of(h.hi),
});
}
let fl = iv.floored(k);
if let Some(v) = fl.value() {
return self.shift(&out, v);
}
if let [(a, ra)] = r.t[..]
&& let (Some(l), Some(h)) = (self.bounds(a).lo, self.bounds(a).hi)
&& h == l + 1
{
let at = |x: Int| mul(ra, x).and_then(|p| plus(r.c, p)).map(|v| v >> k);
let (v0, v1) = (at(l)?, at(h)?);
let d = v1 - v0;
let out = self.shift(&out, plus(v0, -mul(d, l)?)?)?;
return self.add(&out, &Self::one(a), d);
}
let inner = r.t.iter().find_map(|&(a, c)| match self.atom(a) {
Atom::Floor(e, ak) if c == 1 => Some((a, e, u32::from(ak))),
_ => None,
});
if let Some((a, e, ak)) = inner {
let e = self.form(e).clone();
let others = r.without(a);
let g = self.add(&e, &others, Int::ONE << ak)?;
let fl = self.floor(&g, ak + k, None)?;
return self.add(&out, &fl, Int::from(1));
}
if let Some(a) = r.single()
&& let Atom::And(q, xi, yi) = self.atom(a)
{
let (x, y) = (self.form(xi).clone(), self.form(yi).clone());
let (x, y) = if x.is_const() { (y, x) } else { (x, y) };
if y.is_const() {
let q = u32::from(q);
if q <= k {
return Ok(out);
}
let fx = self.floor(&x, k, None)?;
let and = self.band(q - k, &fx, &Form::konst(y.c >> k))?;
return self.add(&out, &and, Int::from(1));
}
}
if let Some(a) = r.single()
&& let Atom::Xor(q, li) = self.atom(a)
{
let (ops, kk) = self.lists[li as usize].clone();
let mut kept: Vec<Form> = Vec::with_capacity(ops.len() + 1);
for &i in &ops {
let g = self.form(i).clone();
if self.interval(&g).bits().is_none_or(|b| b > k) {
kept.push(g);
}
}
if kept.len() < ops.len() {
kept.push(Form::konst(kk));
let x = self.bxor(u32::from(q), &kept)?;
let fl = self.floor(&x, k, None)?;
return self.add(&out, &fl, 1);
}
}
let ri = self.intern(&r)?;
let hash = combine(combine(0x666c_6f6f, self.hashes[ri as usize]), u64::from(k));
let a = self.make(Atom::Floor(ri, k as u8), hash, fl)?;
self.add(&out, &Self::one(a), Int::from(1))
}
pub(super) fn slice(&mut self, f: &Form, lo: u32, len: u32, hint: Option<Iv>) -> R<Form> {
if len > max_shift() {
return Err(Over);
}
let a = self.floor(f, lo, hint)?;
let b = self.floor(f, lo + len, hint)?;
self.add(&a, &b, -(Int::ONE << len))
}
pub(super) fn wrap(&mut self, f: &Form, w: u32, hint: Option<Iv>) -> R<Form> {
if w > max_shift() {
return Err(Over);
}
let fl = self.floor(f, w, hint)?;
self.add(f, &fl, -(Int::ONE << w))
}
fn as_floors(&mut self, f: &Form) -> R<Vec<(u32, Form)>> {
let mut out: Vec<(u32, Form)> = Vec::new();
for &(a, c) in &f.t {
if c != 1 {
continue;
}
let Atom::Floor(ri, k) = self.atom(a) else {
continue;
};
let k = u32::from(k);
if out.iter().any(|x| x.0 == k) {
continue;
}
let r = self.form(ri).clone();
let q = f.without(a);
let Ok(e) = self.add(&r, &q, Int::ONE << k) else {
continue;
};
out.push((k, e));
}
Ok(out)
}
pub(super) fn band(&mut self, p: u32, x: &Form, y: &Form) -> R<Form> {
self.enter()?;
let r = self.band_in(p, x, y);
self.depth -= 1;
if !self.plain
&& let Ok(f) = &r
&& let Some(a) = f.single()
&& matches!(self.atom(a), Atom::And(q, ..) if q >= 2)
&& !self.whole.contains_key(&a)
&& let Some(w) = self.operands(p, x, y)
{
self.whole.insert(a, w);
self.linked[a as usize] = self.link(a).is_some();
}
r
}
fn operands(&mut self, p: u32, x: &Form, y: &Form) -> Option<(Form, Form)> {
let top = (Int::ONE << p) - 1;
let big = (Int::ONE << max_shift()) - 1;
if !self.values {
let (rx, ry) = (self.reduce(x, p), self.reduce(y, p));
let (ix, iy) = (self.interval(&rx), self.interval(&ry));
if ix.within(0, big) && iy.within(0, big) && (ix.within(0, top) || iy.within(0, top)) {
self.wordy |= self.linking == 0 && (rx != *x || ry != *y);
return Some((rx, ry));
}
}
self.exact(x, p).zip(self.exact(y, p))
}
fn band_in(&mut self, p: u32, x: &Form, y: &Form) -> R<Form> {
if p == 0 {
return Ok(Form::default());
}
if p > max_shift() {
return Err(Over);
}
let (mut x, mut y) = (self.reduce(x, p), self.reduce(y, p));
if x.is_const() && y.is_const() {
return Ok(Form::konst(x.c & y.c));
}
if x.is_const() {
core::mem::swap(&mut x, &mut y);
}
if y.is_const() {
let c = y.c;
if c == 0 {
return Ok(Form::default());
}
let lo = c.trailing_zeros();
let run = c >> lo;
if run & (run + 1) == 0 {
let s = self.slice(&x, lo, bit_len(run), None)?;
return self.scale(&s, Int::ONE << lo);
}
}
if x == y {
return self.wrap(&x, p, None);
}
let (ix, iy) = (self.interval(&x), self.interval(&y));
let q = [ix, iy].iter().filter_map(|i| i.bits()).fold(p, u32::min);
if q < p {
return self.band_in(q, &x, &y);
}
if !y.is_const() {
let (fx, fy) = (self.as_floors(&x)?, self.as_floors(&y)?);
let common = fx
.iter()
.filter_map(|(k, ex)| fy.iter().find(|f| f.0 == *k).map(|f| (*k, ex, &f.1)))
.max_by_key(|c| c.0);
if let Some((k, ex, ey)) = common {
let and = self.band(p + k, ex, ey)?;
return self.floor(&and, k, None);
}
}
let (xi, yi) = (self.intern(&x)?, self.intern(&y)?);
let (hx, hy) = (self.hashes[xi as usize], self.hashes[yi as usize]);
let (xi, yi, hx, hy) = if (hy, yi) < (hx, xi) {
(yi, xi, hy, hx)
} else {
(xi, yi, hx, hy)
};
let mut hi = (Int::ONE << p) - 1;
for i in [ix, iy] {
if let (Some(l), Some(h)) = (i.lo, i.hi)
&& l >= 0
{
hi = hi.min(h);
}
}
let hash = combine(combine(combine(0x0061_6e64, u64::from(p)), hx), hy);
let a = self.make(Atom::And(p as u8, xi, yi), hash, Iv::new(Int::from(0), hi))?;
Ok(Self::one(a))
}
fn shape(&mut self, f: &Form) -> Option<(Option<Form>, u32, Option<u32>)> {
if f.is_const() {
return (f.c == 0).then_some((None, 0, None));
}
if f.c == 0 {
match f.t[..] {
[(a, k)] if k == 1 => {
if let Atom::Floor(e, k) = self.atom(a) {
return Some((Some(self.form(e).clone()), u32::from(k), None));
}
}
[(a, ca), (b, cb)] => {
let ((a, ca), (b, cb)) = if ca == 1 {
((a, ca), (b, cb))
} else {
((b, cb), (a, ca))
};
if let (Atom::Floor(ea, ka), Atom::Floor(eb, kb)) = (self.atom(a), self.atom(b))
&& ca == 1
&& ea == eb
&& kb > ka
{
let len = u32::from(kb - ka);
if cb == -(Int::ONE << len) {
return Some((Some(self.form(ea).clone()), u32::from(ka), Some(len)));
}
}
}
_ => {}
}
}
for i in 0..f.t.len() {
let (a, c) = f.t[i];
let Atom::Floor(_, k) = self.atom(a) else {
continue;
};
let len = u32::from(k);
if c != -(Int::ONE << len) {
continue;
}
let g = f.without(a);
if self.floor(&g, len, None).ok().and_then(|fl| fl.single()) == Some(a) {
return Some((Some(g), 0, Some(len)));
}
}
None
}
fn cases(&mut self, r: &Form) -> R<Option<(Form, Form, Form)>> {
for &(s, lam) in &r.t {
let Atom::Sel(ci, ai, bi) = self.atom(s) else {
continue;
};
let (c, a, b) = (
self.form(ci).clone(),
self.form(ai).clone(),
self.form(bi).clone(),
);
let none = |x: &Form| x.is_const() && x.c == 0;
if none(&a) == none(&b) {
continue;
}
let Some(&(a0, c0)) = c.t.first() else {
continue;
};
let have = r.coeff(a0);
if have == 0 || have % c0 != 0 {
continue;
}
let mu = have / c0;
let rest = self.sum(r, &c, -mu)?.without(s);
if !rest.is_const() {
continue;
}
let hi = self.scaled(&a, lam)?;
let hi = self.shift(&hi, plus(rest.c, mu)?)?;
let lo = self.scaled(&b, lam)?;
let lo = self.shift(&lo, rest.c)?;
return Ok(Some((c, hi, lo)));
}
Ok(None)
}
pub(super) fn sel(&mut self, c: &Form, a: &Form, b: &Form) -> R<Form> {
self.enter()?;
let r = self.sel_in(c, a, b);
self.depth -= 1;
r
}
fn sel_in(&mut self, c: &Form, a: &Form, b: &Form) -> R<Form> {
if c.is_const() {
return Ok(if c.c != 0 { a.clone() } else { b.clone() });
}
if a == b {
return Ok(a.clone());
}
let d = self.add(a, b, Int::from(-1))?;
if d.is_const() {
return self.add(b, c, d.c);
}
if !self.plain {
let zero = Form::default();
if a.is_const() && a.c != 0 {
let s = self.sel(c, &zero, b)?;
self.forked |= self.linking == 0;
return self.add(&s, c, a.c);
}
if b.is_const() && b.c != 0 {
let s = self.sel(c, a, &zero)?;
self.forked |= self.linking == 0;
let t = self.add(&s, c, -b.c)?;
return self.shift(&t, b.c);
}
}
if let (Some(sa), Some(sb)) = (self.shape(a), self.shape(b))
&& (sa.0.is_some() || sb.0.is_some())
{
let k = match (&sa.0, &sb.0) {
(Some(_), Some(_)) => sa.1.min(sb.1),
(Some(_), None) => sa.1,
_ => sb.1,
};
let len = [&sa, &sb].iter().find_map(|s| s.0.as_ref().and(s.2));
let (ia, ib) = (self.interval(a), self.interval(b));
let fits = |s: &(Option<Form>, u32, Option<u32>), iv: Iv| {
s.0.is_none()
|| s.2 == len
|| (s.2.is_none()
&& len.is_some_and(|l| iv.within(Int::from(0), (Int::ONE << l) - 1)))
};
let (fa, fb) = (fits(&sa, ia), fits(&sb, ib));
if (k > 0 || len.is_some()) && fa && fb {
let mut arms = [Form::default(), Form::default()];
for (arm, s) in arms.iter_mut().zip([sa, sb]) {
*arm = match s.0 {
None => Form::default(),
Some(e) if s.1 == k => e,
Some(e) => self.floor(&e, s.1 - k, None)?,
};
}
let s = self.sel(c, &arms[0], &arms[1])?;
return match len {
None => self.floor(&s, k, None),
Some(len) => self.slice(&s, k, len, None),
};
}
}
let iv = self.interval(a).hull(self.interval(b));
let (ci, ai, bi) = (self.intern(c)?, self.intern(a)?, self.intern(b)?);
let hash = combine(
combine(
combine(0x0073_656c, self.hashes[ci as usize]),
self.hashes[ai as usize],
),
self.hashes[bi as usize],
);
let s = self.make(Atom::Sel(ci, ai, bi), hash, iv)?;
Ok(Self::one(s))
}
}