mod form;
mod lift;
#[cfg(test)]
mod tests;
mod write;
use super::{Marks, PassKind, finish};
use crate::engine::budget::Counter;
use crate::engine::{Fin, Runner, Step, Stop};
use crate::expr::{Context, OpCode};
use crate::hash::IdMap;
const MAX_CONE: usize = 1024;
const MAX_LARGE: u32 = 4096;
const MAX_WORK: u64 = 1 << 26;
const SECOND_SLACK: u64 = 1 << 14;
const MAX_LOST: u64 = 1 << 23;
#[derive(Default)]
pub(crate) struct State {
build: write::Build,
covered: Marks,
asked: IdMap<u32, Fin>,
quiet: IdMap<u32, Fin>,
large: u32,
work: u64,
lost: u64,
sums_at: Option<u32>,
pub(crate) turn: bool,
}
impl State {
pub(crate) fn begin(&mut self) {
self.covered.clear();
self.asked.clear();
self.large = 0;
self.sums_at = None;
}
}
struct Answers {
first: Leg,
values: Option<Leg>,
sums: Option<Leg>,
second: bool,
fin: Fin,
}
impl Answers {
fn atoms(&self) -> Option<(&Leg, u32, u32)> {
let l = match &self.values {
Some(v) if self.second => v,
_ => &self.first,
};
l.found.map(|f| (l, f.0, f.1))
}
fn sums(&self) -> Option<(&Leg, u32, u32)> {
let l = self.sums.as_ref()?;
l.found.map(|f| (l, f.0, f.1))
}
fn least(&self) -> Option<(&Leg, u32, u32)> {
match (self.atoms(), self.sums()) {
(Some(a), Some(s)) => Some(if s.2 <= a.2 { s } else { a }),
(a, s) => s.or(a),
}
}
fn of_sums(&self, l: &Leg) -> bool {
self.sums.as_ref().is_some_and(|s| core::ptr::eq(s, l))
}
}
struct Leg {
build: write::Build,
found: Option<(u32, u32)>,
work: u64,
fin: Fin,
forked: bool,
wordy: bool,
}
fn leg(
r: &mut Runner<'_, '_>,
cx: &mut Context,
mut lift: lift::Lift,
mut build: write::Build,
nodes: Vec<u32>,
limit: Option<u64>,
) -> Result<Leg, Stop> {
let mut search = write::Search::new(&mut lift, &mut build, nodes);
if let Some(limit) = limit {
search.limit(limit);
}
let found = search.run(r, cx);
let work = search.work();
r.words.work += work;
let found = found?;
Ok(Leg {
build,
found,
work,
fin: lift.fin.unwrap_or(Fin::FINAL),
forked: lift.alg.forked(),
wordy: lift.alg.wordy(),
})
}
pub(crate) fn asks_first(r: &Runner<'_, '_>, cx: &Context, n: u32) -> bool {
r.words.turn
&& !r.words.covered.contains(n)
&& r.words.large < MAX_LARGE
&& r.words.work < MAX_WORK
&& !matches!(cx.node(n).op, OpCode::Const | OpCode::Sym)
&& !r.quarantined_passes.contains(&PassKind::Words)
}
fn cone(r: &mut Runner<'_, '_>, cx: &Context, n: u32) -> Result<Result<Vec<u32>, bool>, Stop> {
if cx.meta[n as usize].height as usize >= MAX_CONE {
return Ok(Err(false));
}
let mut seen: IdMap<u32, ()> = IdMap::default();
let mut stack = vec![n];
let mut out = Vec::new();
while let Some(i) = stack.pop() {
if seen.insert(i, ()).is_some() {
continue;
}
out.push(i);
if out.len() > MAX_CONE {
r.meter.charge(Counter::PassWork, out.len() as u64)?;
return Ok(Err(true));
}
stack.extend(cx.node(i).children());
}
r.meter.charge(Counter::PassWork, 2 * out.len() as u64)?;
let height = |i: u32| cx.meta[i as usize].height;
out.sort_by(|&a, &b| height(a).cmp(&height(b)).then_with(|| cx.order(a, b)));
Ok(Ok(out))
}
pub(crate) fn first(
r: &mut Runner<'_, '_>,
cx: &mut Context,
n: u32,
) -> Result<Option<(u32, Fin)>, Stop> {
r.words.covered.insert(n);
let nodes = match cone(r, cx, n)? {
Ok(nodes) => nodes,
Err(counted) => {
r.words.large += u32::from(counted);
r.words.asked.insert(n, Fin::FINAL);
return Ok(None);
}
};
for &i in &nodes {
r.words.covered.insert(i);
}
if let Some(&fin) = r.words.quiet.get(&n) {
r.words.asked.insert(n, fin);
return Ok(None);
}
r.stats
.passes
.entry(PassKind::Words.name())
.or_default()
.calls += 1;
let mut build = core::mem::take(&mut r.words.build);
let out = ask(r, cx, &mut build, n, nodes);
r.words.build = build;
let (step, found) = out?;
Ok(match step {
Step::To(e, fin) => {
r.words.covered.remove(e);
Some((e, fin))
}
Step::Normal(fin) => {
if !found {
r.words.quiet.insert(n, fin);
}
r.words.asked.insert(n, fin);
None
}
})
}
fn answers(
r: &mut Runner<'_, '_>,
cx: &mut Context,
build: write::Build,
nodes: Vec<u32>,
with_sums: bool,
) -> Result<Answers, Stop> {
let first = leg(r, cx, lift::Lift::default(), build, nodes.clone(), None)?;
let mut fin = first.fin;
let allow = 2 * first.work + SECOND_SLACK;
let mut forked = first.forked || with_sums;
let mut values = None;
if first.wordy && r.words.lost < MAX_LOST {
let l = leg(
r,
cx,
lift::Lift::values(),
write::Build::default(),
nodes.clone(),
Some(allow),
)?;
fin = fin.and(l.fin);
forked |= l.forked;
values = Some(l);
}
let mut sums = None;
if forked && r.words.lost < MAX_LOST {
let l = leg(
r,
cx,
lift::Lift::plain(),
write::Build::default(),
nodes,
(!with_sums).then_some(allow),
)?;
fin = fin.and(l.fin);
if l.found.is_none() {
r.words.lost += l.work;
}
sums = Some(l);
}
let size = |l: &Leg| l.found.map(|f| f.1);
let second = match (size(&first), values.as_ref().and_then(size)) {
(_, None) => false,
(None, Some(_)) => true,
(Some(a), Some(v)) => v <= a,
};
if let Some(v) = &values
&& !second
{
r.words.lost += v.work;
}
Ok(Answers {
first,
values,
sums,
second,
fin,
})
}
fn chase(
r: &mut Runner<'_, '_>,
cx: &mut Context,
mut e: u32,
alone: bool,
fin: &mut Fin,
) -> Result<u32, Stop> {
let mut with_sums = false;
let mut from: Option<(u32, usize)> = None;
while !matches!(cx.node(e).op, OpCode::Const | OpCode::Sym) {
let nodes = match cone(r, cx, e)? {
Ok(nodes) if from.is_none_or(|(_, size)| nodes.len() < size) => nodes,
_ => {
if let Some((before, _)) = from {
e = before;
}
break;
}
};
if r.words.work >= MAX_WORK {
break;
}
from = Some((e, nodes.len()));
if alone {
let l = leg(
r,
cx,
lift::Lift::plain(),
write::Build::default(),
nodes,
None,
)?;
*fin = fin.and(l.fin);
let Some((root, _)) = l.found else {
break;
};
e = l.build.write(r, cx, root)?;
} else {
let a = answers(r, cx, write::Build::default(), nodes, with_sums)?;
*fin = fin.and(a.fin);
let Some((l, root, _)) = a.least() else {
r.words.quiet.insert(e, a.fin);
break;
};
with_sums = a.of_sums(l);
e = l.build.write(r, cx, root)?;
}
}
Ok(e)
}
fn dag(r: &mut Runner<'_, '_>, cx: &Context, e: u32, or: u32) -> Result<u32, Stop> {
Ok(match cone(r, cx, e)? {
Ok(nodes) => nodes.len() as u32,
Err(_) => or,
})
}
fn unused(r: &mut Runner<'_, '_>, cx: &Context, before: u32, e: u32) -> Result<(), Stop> {
let len = cx.len() as u32;
r.meter
.charge(Counter::PassWork, u64::from(len.saturating_sub(before)))?;
let mut reached: IdMap<u32, ()> = IdMap::default();
let mut stack = vec![e];
while let Some(i) = stack.pop() {
if i >= before && reached.insert(i, ()).is_none() {
stack.extend(cx.node(i).children());
}
}
for i in before..len {
if !reached.contains_key(&i) {
r.retire(cx, i);
}
}
Ok(())
}
fn ask(
r: &mut Runner<'_, '_>,
cx: &mut Context,
build: &mut write::Build,
n: u32,
nodes: Vec<u32>,
) -> Result<(Step, bool), Stop> {
let before = cx.len() as u32;
let with_sums = r.words.sums_at.take() == Some(n);
let a = answers(r, cx, core::mem::take(build), nodes, with_sums)?;
let mut fin = a.fin;
let out = match (a.atoms(), a.sums()) {
(Some((la, ra, sa)), Some((ls, rs, ss))) if sa < ss => {
let es = ls.build.write(r, cx, rs)?;
let asked = r.words.work;
let es = chase(r, cx, es, true, &mut fin)?;
let of_sums = r.words.work - asked;
let (asked, lost) = (r.words.work, r.words.lost);
let ea = la.build.write(r, cx, ra)?;
let ea = chase(r, cx, ea, false, &mut fin)?;
let e = if dag(r, cx, es, ss)? < dag(r, cx, ea, sa)? {
r.words.lost = lost + (r.words.work - asked);
es
} else {
r.words.lost += ls.work + of_sums;
ea
};
unused(r, cx, before, e)?;
(
finish(r, cx, PassKind::Words, n, e, before, &[], fin)?,
true,
)
}
_ => match a.least() {
Some((l, root, _)) => {
let e = l.build.write(r, cx, root)?;
let step = finish(r, cx, PassKind::Words, n, e, before, &[], fin)?;
if let Step::To(e, _) = step
&& a.of_sums(l)
{
r.words.sums_at = Some(e);
}
(step, true)
}
None => {
r.stats
.passes
.entry(PassKind::Words.name())
.or_default()
.noop += 1;
(Step::Normal(fin), false)
}
},
};
*build = a.first.build;
Ok(out)
}
pub(super) fn step(r: &mut Runner<'_, '_>, cx: &Context, n: u32) -> Result<Step, Stop> {
let fin = match r.words.asked.get(&n) {
Some(&fin) => fin,
None if matches!(cx.node(n).op, OpCode::Const | OpCode::Sym) => Fin::FINAL,
None => Fin::PROVISIONAL,
};
Ok(Step::Normal(fin))
}