use super::{Accept, By, Fin, PassKind, Reject, Runner, Step, Stop, discard, facts};
use crate::BitVec;
use crate::engine::budget::Counter;
use crate::expr::{Context, OpCode};
use crate::facts::Facts;
use crate::hash::IdMap;
use crate::invert::monotone::{self, Inner, Order};
use crate::invert::{self, MAX_SPLIT, Oracle, Solved};
use crate::ops::{BinOp, CmpOp};
struct Calls<'x, 'r, 'a> {
r: &'x mut Runner<'r, 'a>,
fin: Fin,
}
impl Oracle for Calls<'_, '_, '_> {
type Err = Stop;
fn facts(&mut self, cx: &mut Context, i: u32) -> Result<Option<Facts>, Stop> {
let (f, fin) = facts(self.r, cx, i)?;
self.fin = self.fin.and(fin);
Ok(f)
}
fn charge(&mut self, units: u64) -> Result<(), Stop> {
self.r.meter.charge(Counter::PassWork, units)?;
Ok(())
}
}
fn count<'x>(r: &'x mut Runner<'_, '_>) -> &'x mut crate::engine::PassCounts {
r.stats.passes.entry(PassKind::Invert.name()).or_default()
}
pub(super) fn step(r: &mut Runner<'_, '_>, cx: &mut Context, n: u32) -> Result<Step, Stop> {
let node = cx.node(n);
let Some(op) = node.op.as_cmp() else {
return Ok(Step::Normal(Fin::FINAL));
};
let before = cx.len() as u32;
let mut o = Calls { r, fin: Fin::FINAL };
let e = if op.is_commutative() {
match cx.const_val(node.b) {
Some(c) => {
let join = cx.node(node.a).op;
if (join == OpCode::Or && c.is_zero()) || (join == OpCode::And && c.is_ones()) {
split(cx, &mut o, op, n, node.a, &c, before)?
} else {
match solve(cx, &mut o, op, node.a, &c)? {
Some(e) => Some(e),
None => match narrowed(cx, &mut o, node.a)? {
Some(a) => solve(cx, &mut o, op, a, &c)?,
None => None,
}
.filter(|&e| smaller(cx, e, n)),
}
}
}
None => match cancel(cx, &mut o, op, node.a, node.b)? {
Some(e) => Some(e),
None => match (narrowed(cx, &mut o, node.a)?, narrowed(cx, &mut o, node.b)?) {
(Some(a), Some(b)) => cancel(cx, &mut o, op, a, b)?,
_ => None,
}
.filter(|&e| smaller(cx, e, n)),
},
}
} else {
match (cx.const_val(node.a), cx.const_val(node.b)) {
(_, Some(c)) => solve_order(cx, &mut o, op, node.a, &c, false)?,
(Some(c), None) => solve_order(cx, &mut o, op, node.b, &c, true)?,
(None, None) => cancel_order(cx, &mut o, op, node.a, node.b)?,
}
};
let fin = o.fin;
let e = match e {
Some(e) if e != n => e,
_ => {
discard(r, cx, before);
count(r).noop += 1;
return Ok(Step::Normal(fin));
}
};
match r.accept(cx, By::Pass(PassKind::Invert.name()), true, n, e, fin.rel)? {
Accept::Yes => {
count(r).changed += 1;
Ok(Step::To(e, fin))
}
Accept::Vetoed => {
count(r).rejected += 1;
discard(r, cx, before);
Ok(Step::Normal(fin))
}
Accept::Rejected(reason) => {
count(r).rejected += 1;
discard(r, cx, before);
if matches!(reason, Reject::Width | Reject::Verify | Reject::Tripwire) {
r.quarantined_passes.push(PassKind::Invert);
r.stats.quarantined += 1;
}
Ok(Step::Normal(fin))
}
}
}
fn narrowed(cx: &mut Context, o: &mut Calls<'_, '_, '_>, s: u32) -> Result<Option<u32>, Stop> {
let node = cx.node(s);
if node.op != OpCode::Extract {
return Ok(None);
}
let Some((e, fin)) = super::casts::narrowed(o.r, cx, node.a, node.b as u16, node.width)? else {
return Ok(None);
};
o.fin = o.fin.and(fin);
Ok((e != s).then_some(e))
}
fn smaller(cx: &Context, e: u32, n: u32) -> bool {
let size = |i: u32| cx.tree_size(cx.handle(i)).unwrap_or(u32::MAX);
size(e) < size(n)
}
fn truth(o: &mut Calls<'_, '_, '_>, cx: &mut Context, v: bool) -> Result<u32, Stop> {
o.r.build(cx, |cx| cx.mk_const(&BitVec::from_bool(v)))
}
fn compare(
o: &mut Calls<'_, '_, '_>,
cx: &mut Context,
op: CmpOp,
x: u32,
v: &BitVec,
) -> Result<u32, Stop> {
let v = *v;
o.r.build(cx, |cx| {
let k = cx.mk_const(&v)?;
cx.c_cmp(op, x, k)
})
}
fn leaves(
cx: &Context,
o: &mut Calls<'_, '_, '_>,
a: u32,
b: u32,
) -> Result<Option<(Vec<u32>, bool)>, Stop> {
let mut out = Vec::new();
let mut seen = false;
let mut stack = vec![b, a];
while let Some(i) = stack.pop() {
o.charge(1)?;
let node = cx.node(i);
if node.op == OpCode::Select {
seen = true;
stack.push(node.c);
stack.push(node.b);
} else if out.contains(&i) {
} else if out.len() >= MAX_SPLIT {
return Ok(None);
} else {
out.push(i);
}
}
Ok(Some((out, seen)))
}
fn relabel(
cx: &mut Context,
o: &mut Calls<'_, '_, '_>,
t: u32,
map: &IdMap<u32, u32>,
) -> Result<u32, Stop> {
if let Some(&x) = map.get(&t) {
return Ok(x);
}
let node = cx.node(t);
debug_assert_eq!(node.op, OpCode::Select);
let (c, p, q) = (node.a, node.b, node.c);
let p = relabel(cx, o, p, map)?;
let q = relabel(cx, o, q, map)?;
o.r.build(cx, |cx| cx.c_select(c, p, q))
}
fn relabelled(
cx: &mut Context,
o: &mut Calls<'_, '_, '_>,
a: u32,
b: u32,
leaves: &[u32],
inners: &[Inner],
) -> Result<(u32, u32), Stop> {
let mut map = IdMap::default();
for (&l, x) in leaves.iter().zip(inners) {
let x = match x {
Inner::Node(x) => *x,
Inner::Const(v) => {
let v = *v;
o.r.build(cx, |cx| cx.mk_const(&v))?
}
};
map.insert(l, x);
}
Ok((relabel(cx, o, a, &map)?, relabel(cx, o, b, &map)?))
}
fn cancel(
cx: &mut Context,
o: &mut Calls<'_, '_, '_>,
op: CmpOp,
a: u32,
b: u32,
) -> Result<Option<u32>, Stop> {
let (mut x, mut y) = (a, b);
let mut peeled = false;
while let Some((p, q)) = invert::cancel_layer(cx, o, x, y)? {
o.charge(1)?;
(x, y) = (p, q);
peeled = true;
}
if !peeled {
while let Some((ls, true)) = leaves(cx, o, x, y)? {
let Some(inners) = invert::cancel_leaves(cx, o, &ls)? else {
break;
};
(x, y) = relabelled(cx, o, x, y, &ls, &inners)?;
peeled = true;
}
}
if !peeled {
return Ok(None);
}
Ok(Some(o.r.build(cx, |cx| cx.c_cmp(op, x, y))?))
}
fn solve(
cx: &mut Context,
o: &mut Calls<'_, '_, '_>,
op: CmpOp,
lhs: u32,
c: &BitVec,
) -> Result<Option<u32>, Stop> {
let mut peels = Vec::new();
let explaining = o.r.explaining();
let solved = invert::solve_eq_peels(cx, o, lhs, c, explaining.then_some(&mut peels))?;
if explaining && solved.is_some() {
let layers = peels
.into_iter()
.map(|(node, l, preimage)| crate::engine::Peel {
node: cx.handle(node),
inner: cx.handle(l.inner),
map: l.map.spelling(),
bijective: l.kind == invert::Kind::Bijective,
preimage,
})
.collect();
o.r.explain_with(|| crate::engine::Explanation::Invert { layers });
}
Ok(match solved {
None => None,
Some(Solved::Const(eq)) => Some(truth(o, cx, eq == (op == CmpOp::Eq))?),
Some(Solved::Eq(x, v)) => Some(compare(o, cx, op, x, &v)?),
})
}
fn cancel_order(
cx: &mut Context,
o: &mut Calls<'_, '_, '_>,
op: CmpOp,
a: u32,
b: u32,
) -> Result<Option<u32>, Stop> {
let Some((mut order, strict)) = Order::of(op) else {
return Ok(None);
};
let (mut x, mut y) = (a, b);
let mut peeled = false;
while let Some((ls, _)) = leaves(cx, o, x, y)? {
let Some((inners, m)) = monotone::cancel_many(cx, o, &ls, order)? else {
break;
};
let (p, q) = relabelled(cx, o, x, y, &ls, &inners)?;
(x, y) = if m.increasing { (p, q) } else { (q, p) };
order = m.input;
peeled = true;
}
if !peeled {
return Ok(None);
}
Ok(Some(o.r.build(cx, |cx| cx.c_cmp(order.cmp(strict), x, y))?))
}
fn solve_order(
cx: &mut Context,
o: &mut Calls<'_, '_, '_>,
op: CmpOp,
lhs: u32,
c: &BitVec,
const_left: bool,
) -> Result<Option<u32>, Stop> {
Ok(match monotone::solve(cx, o, op, lhs, c, const_left)? {
None => None,
Some(monotone::Solved::Const(v)) => Some(truth(o, cx, v)?),
Some(monotone::Solved::Cmp {
op,
x,
t,
const_left,
}) => Some(o.r.build(cx, |cx| {
let t = cx.mk_const(&t)?;
if const_left {
cx.c_cmp(op, t, x)
} else {
cx.c_cmp(op, x, t)
}
})?),
})
}
fn split(
cx: &mut Context,
o: &mut Calls<'_, '_, '_>,
op: CmpOp,
n: u32,
lhs: u32,
c: &BitVec,
before: u32,
) -> Result<Option<u32>, Stop> {
let join = cx.node(lhs).op;
let mut leaves = Vec::new();
let mut stack = vec![lhs];
while let Some(i) = stack.pop() {
o.charge(1)?;
let node = cx.node(i);
if node.op == join {
stack.push(node.b);
stack.push(node.a);
} else if leaves.len() >= MAX_SPLIT {
return Ok(None);
} else {
leaves.push(i);
}
}
let eq = op == CmpOp::Eq;
let mut conj: Vec<(u32, BitVec)> = Vec::new();
let mut solved = false;
for leaf in leaves {
let (x, v) = match invert::solve_eq(cx, o, leaf, c)? {
Some(Solved::Const(false)) => return Ok(Some(truth(o, cx, !eq)?)),
Some(Solved::Const(true)) => {
solved = true;
continue;
}
Some(Solved::Eq(x, v)) => {
solved = true;
(x, v)
}
None => (leaf, *c),
};
match conj.iter().find(|(y, _)| *y == x) {
Some((_, w)) if *w != v => return Ok(Some(truth(o, cx, !eq)?)),
Some(_) => {}
None => conj.push((x, v)),
}
}
if !solved {
return Ok(None);
}
let mut out: Option<u32> = None;
for (x, v) in &conj {
let t = compare(o, cx, op, *x, v)?;
out = Some(match out {
None => t,
Some(acc) => {
let join = if eq { BinOp::And } else { BinOp::Or };
o.r.build(cx, |cx| cx.c_bin(join, acc, t))?
}
});
}
let e = match out {
Some(e) => e,
None => truth(o, cx, eq)?,
};
let tree = |i: u32| cx.meta[i as usize].tree;
if tree(n) == u32::MAX || tree(e) >= tree(n) {
discard(o.r, cx, before);
return Ok(None);
}
Ok(Some(e))
}