use fx::{FxHashMap, FxHashSet};
use std::cell::Cell;
use std::collections::hash_map::Entry;
use std::fmt::Debug;
use std::hash;
use std::marker::PhantomData;
mod node_index;
use self::node_index::NodeIndex;
#[cfg(test)]
mod test;
pub trait ForestObligation : Clone + Debug {
type Predicate : Clone + hash::Hash + Eq + Debug;
fn as_predicate(&self) -> &Self::Predicate;
}
pub trait ObligationProcessor {
type Obligation : ForestObligation;
type Error : Debug;
fn process_obligation(&mut self,
obligation: &mut Self::Obligation)
-> Result<Option<Vec<Self::Obligation>>, Self::Error>;
fn process_backedge<'c, I>(&mut self,
cycle: I,
_marker: PhantomData<&'c Self::Obligation>)
where I: Clone + Iterator<Item=&'c Self::Obligation>;
}
pub struct ObligationForest<O: ForestObligation> {
nodes: Vec<Node<O>>,
done_cache: FxHashSet<O::Predicate>,
waiting_cache: FxHashMap<O::Predicate, NodeIndex>,
cache_list: Vec<O::Predicate>,
scratch: Option<Vec<usize>>,
}
#[derive(Debug)]
struct Node<O> {
obligation: O,
state: Cell<NodeState>,
dependents: Vec<NodeIndex>,
parent: Option<NodeIndex>,
}
#[derive(Debug, Copy, Clone, PartialEq, Eq)]
enum NodeState {
Pending,
Success,
Waiting,
Done,
Error,
OnDfsStack,
}
#[derive(Debug)]
pub struct Outcome<O, E> {
pub completed: Vec<O>,
pub errors: Vec<Error<O, E>>,
pub stalled: bool,
}
#[derive(Debug, PartialEq, Eq)]
pub struct Error<O, E> {
pub error: E,
pub backtrace: Vec<O>,
}
impl<O: ForestObligation> ObligationForest<O> {
pub fn new() -> ObligationForest<O> {
ObligationForest {
nodes: vec![],
done_cache: FxHashSet(),
waiting_cache: FxHashMap(),
cache_list: vec![],
scratch: Some(vec![]),
}
}
pub fn len(&self) -> usize {
self.nodes.len()
}
pub fn register_obligation(&mut self, obligation: O) {
let _ = self.register_obligation_at(obligation, None);
}
fn register_obligation_at(&mut self, obligation: O, parent: Option<NodeIndex>)
-> Result<(), ()>
{
if self.done_cache.contains(obligation.as_predicate()) {
return Ok(())
}
match self.waiting_cache.entry(obligation.as_predicate().clone()) {
Entry::Occupied(o) => {
debug!("register_obligation_at({:?}, {:?}) - duplicate of {:?}!",
obligation, parent, o.get());
if let Some(parent) = parent {
if self.nodes[o.get().get()].dependents.contains(&parent) {
debug!("register_obligation_at({:?}, {:?}) - duplicate subobligation",
obligation, parent);
} else {
self.nodes[o.get().get()].dependents.push(parent);
}
}
if let NodeState::Error = self.nodes[o.get().get()].state.get() {
Err(())
} else {
Ok(())
}
}
Entry::Vacant(v) => {
debug!("register_obligation_at({:?}, {:?}) - ok, new index is {}",
obligation, parent, self.nodes.len());
v.insert(NodeIndex::new(self.nodes.len()));
self.cache_list.push(obligation.as_predicate().clone());
self.nodes.push(Node::new(parent, obligation));
Ok(())
}
}
}
pub fn to_errors<E: Clone>(&mut self, error: E) -> Vec<Error<O, E>> {
let mut errors = vec![];
for index in 0..self.nodes.len() {
if let NodeState::Pending = self.nodes[index].state.get() {
let backtrace = self.error_at(index);
errors.push(Error {
error: error.clone(),
backtrace,
});
}
}
let successful_obligations = self.compress();
assert!(successful_obligations.is_empty());
errors
}
pub fn pending_obligations(&self) -> Vec<O>
where O: Clone
{
self.nodes
.iter()
.filter(|n| n.state.get() == NodeState::Pending)
.map(|n| n.obligation.clone())
.collect()
}
pub fn process_obligations<P>(&mut self, processor: &mut P) -> Outcome<O, P::Error>
where P: ObligationProcessor<Obligation=O>
{
debug!("process_obligations(len={})", self.nodes.len());
let mut errors = vec![];
let mut stalled = true;
for index in 0..self.nodes.len() {
debug!("process_obligations: node {} == {:?}",
index,
self.nodes[index]);
let result = match self.nodes[index] {
Node { state: ref _state, ref mut obligation, .. }
if _state.get() == NodeState::Pending =>
{
processor.process_obligation(obligation)
}
_ => continue
};
debug!("process_obligations: node {} got result {:?}",
index,
result);
match result {
Ok(None) => {
}
Ok(Some(children)) => {
stalled = false;
self.nodes[index].state.set(NodeState::Success);
for child in children {
let st = self.register_obligation_at(
child,
Some(NodeIndex::new(index))
);
if let Err(()) = st {
self.error_at(index);
}
}
}
Err(err) => {
stalled = false;
let backtrace = self.error_at(index);
errors.push(Error {
error: err,
backtrace,
});
}
}
}
if stalled {
return Outcome {
completed: vec![],
errors,
stalled,
};
}
self.mark_as_waiting();
self.process_cycles(processor);
let completed_obligations = self.compress();
debug!("process_obligations: complete");
Outcome {
completed: completed_obligations,
errors,
stalled,
}
}
fn process_cycles<P>(&mut self, processor: &mut P)
where P: ObligationProcessor<Obligation=O>
{
let mut stack = self.scratch.take().unwrap();
debug_assert!(stack.is_empty());
debug!("process_cycles()");
for index in 0..self.nodes.len() {
let state = self.nodes[index].state.get();
match state {
NodeState::Waiting | NodeState::Pending | NodeState::Done | NodeState::Error => {},
_ => self.find_cycles_from_node(&mut stack, processor, index),
}
}
debug!("process_cycles: complete");
debug_assert!(stack.is_empty());
self.scratch = Some(stack);
}
fn find_cycles_from_node<P>(&self, stack: &mut Vec<usize>,
processor: &mut P, index: usize)
where P: ObligationProcessor<Obligation=O>
{
let node = &self.nodes[index];
let state = node.state.get();
match state {
NodeState::OnDfsStack => {
let index =
stack.iter().rposition(|n| *n == index).unwrap();
processor.process_backedge(stack[index..].iter().map(GetObligation(&self.nodes)),
PhantomData);
}
NodeState::Success => {
node.state.set(NodeState::OnDfsStack);
stack.push(index);
if let Some(parent) = node.parent {
self.find_cycles_from_node(stack, processor, parent.get());
}
for dependent in &node.dependents {
self.find_cycles_from_node(stack, processor, dependent.get());
}
stack.pop();
node.state.set(NodeState::Done);
},
NodeState::Waiting | NodeState::Pending => {
}
NodeState::Done | NodeState::Error => {
}
};
}
fn error_at(&mut self, p: usize) -> Vec<O> {
let mut error_stack = self.scratch.take().unwrap();
let mut trace = vec![];
let mut n = p;
loop {
self.nodes[n].state.set(NodeState::Error);
trace.push(self.nodes[n].obligation.clone());
error_stack.extend(self.nodes[n].dependents.iter().map(|x| x.get()));
match self.nodes[n].parent {
Some(q) => n = q.get(),
None => break
}
}
loop {
let i = match error_stack.pop() {
Some(i) => i,
None => break
};
let node = &self.nodes[i];
match node.state.get() {
NodeState::Error => continue,
_ => node.state.set(NodeState::Error)
}
error_stack.extend(
node.dependents.iter().cloned().chain(node.parent).map(|x| x.get())
);
}
self.scratch = Some(error_stack);
trace
}
#[inline]
fn mark_neighbors_as_waiting_from(&self, node: &Node<O>) {
if let Some(parent) = node.parent {
self.mark_as_waiting_from(&self.nodes[parent.get()]);
}
for dependent in &node.dependents {
self.mark_as_waiting_from(&self.nodes[dependent.get()]);
}
}
fn mark_as_waiting(&self) {
for node in &self.nodes {
if node.state.get() == NodeState::Waiting {
node.state.set(NodeState::Success);
}
}
for node in &self.nodes {
if node.state.get() == NodeState::Pending {
self.mark_neighbors_as_waiting_from(node);
}
}
}
fn mark_as_waiting_from(&self, node: &Node<O>) {
match node.state.get() {
NodeState::Waiting | NodeState::Error | NodeState::OnDfsStack => return,
NodeState::Success => node.state.set(NodeState::Waiting),
NodeState::Pending | NodeState::Done => {},
}
self.mark_neighbors_as_waiting_from(node);
}
#[inline(never)]
fn compress(&mut self) -> Vec<O> {
let nodes_len = self.nodes.len();
let mut node_rewrites: Vec<_> = self.scratch.take().unwrap();
node_rewrites.extend(0..nodes_len);
let mut dead_nodes = 0;
for i in 0..self.nodes.len() {
match self.nodes[i].state.get() {
NodeState::Pending | NodeState::Waiting => {
if dead_nodes > 0 {
self.nodes.swap(i, i - dead_nodes);
node_rewrites[i] -= dead_nodes;
}
}
NodeState::Done => {
self.waiting_cache.remove(self.nodes[i].obligation.as_predicate());
self.done_cache.insert(self.nodes[i].obligation.as_predicate().clone());
node_rewrites[i] = nodes_len;
dead_nodes += 1;
}
NodeState::Error => {
self.waiting_cache.remove(self.nodes[i].obligation.as_predicate());
node_rewrites[i] = nodes_len;
dead_nodes += 1;
}
NodeState::OnDfsStack | NodeState::Success => unreachable!()
}
}
if dead_nodes == 0 {
node_rewrites.truncate(0);
self.scratch = Some(node_rewrites);
return vec![];
}
let successful = (0..dead_nodes)
.map(|_| self.nodes.pop().unwrap())
.flat_map(|node| {
match node.state.get() {
NodeState::Error => None,
NodeState::Done => Some(node.obligation),
_ => unreachable!()
}
})
.collect();
self.apply_rewrites(&node_rewrites);
node_rewrites.truncate(0);
self.scratch = Some(node_rewrites);
successful
}
fn apply_rewrites(&mut self, node_rewrites: &[usize]) {
let nodes_len = node_rewrites.len();
for node in &mut self.nodes {
if let Some(index) = node.parent {
let new_index = node_rewrites[index.get()];
if new_index >= nodes_len {
node.parent = None;
} else {
node.parent = Some(NodeIndex::new(new_index));
}
}
let mut i = 0;
while i < node.dependents.len() {
let new_index = node_rewrites[node.dependents[i].get()];
if new_index >= nodes_len {
node.dependents.swap_remove(i);
} else {
node.dependents[i] = NodeIndex::new(new_index);
i += 1;
}
}
}
let mut kill_list = vec![];
for (predicate, index) in self.waiting_cache.iter_mut() {
let new_index = node_rewrites[index.get()];
if new_index >= nodes_len {
kill_list.push(predicate.clone());
} else {
*index = NodeIndex::new(new_index);
}
}
for predicate in kill_list { self.waiting_cache.remove(&predicate); }
}
}
impl<O> Node<O> {
fn new(parent: Option<NodeIndex>, obligation: O) -> Node<O> {
Node {
obligation,
parent,
state: Cell::new(NodeState::Pending),
dependents: vec![],
}
}
}
#[derive(Clone)]
struct GetObligation<'a, O: 'a>(&'a [Node<O>]);
impl<'a, 'b, O> FnOnce<(&'b usize,)> for GetObligation<'a, O> {
type Output = &'a O;
extern "rust-call" fn call_once(self, args: (&'b usize,)) -> &'a O {
&self.0[*args.0].obligation
}
}
impl<'a, 'b, O> FnMut<(&'b usize,)> for GetObligation<'a, O> {
extern "rust-call" fn call_mut(&mut self, args: (&'b usize,)) -> &'a O {
&self.0[*args.0].obligation
}
}