use crate::config::AuIds;
use crate::containers::{
AppendOnlyVec, DenseId, IndexLike, MapToken, ShrinkPolicy, SpMap, VecToken,
};
use super::{AuIds31, Span};
crate::containers::define_id31! {
pub struct OrId / StoredOrId, "or";
}
crate::containers::define_id31! {
pub struct ActionId / StoredActionId, "act";
}
crate::containers::define_id31! {
pub struct CtxId / StoredCtxId, "ctx";
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]
pub enum CycleMode {
#[default]
AncestorOnly,
CurrentInclusive,
Pair,
}
pub struct ContextStore<A: AuIds = AuIds31, T = <A as AuIds>::Class>
where
T: Copy + Ord + core::hash::Hash,
{
spans: AppendOnlyVec<Span<A::ContextElem>, A::Index>,
items: AppendOnlyVec<T, A::Index>,
index: SpMap<Vec<T>, A::Context, A::Index>,
}
#[derive(Clone, Copy, Debug)]
pub struct ContextStoreToken {
spans: VecToken,
items: VecToken,
index: MapToken,
}
impl<A: AuIds, T> ContextStore<A, T>
where
T: Copy + Ord + core::hash::Hash,
{
pub fn new() -> Self {
let mut store = ContextStore {
spans: AppendOnlyVec::new(),
items: AppendOnlyVec::new(),
index: SpMap::new(),
};
store.intern(&[]);
store
}
pub fn empty(&self) -> A::Context {
A::Context::from_usize(0)
}
pub fn intern(&mut self, sorted_items: &[T]) -> A::Context {
if let Some(log_idx) = self.index.id_of(&sorted_items.to_vec()) {
return *self.index.get_val(log_idx);
}
let id: A::Context = crate::id::id_at_index(self.spans.len());
let start = self.items.len().as_usize();
for &item in sorted_items {
self.items
.try_push(item)
.expect("AU arena sized by its index word");
}
self.spans
.try_push(Span::new(start, sorted_items.len()))
.expect("AU arena sized by its index word");
self.index
.try_insert(sorted_items.to_vec(), id)
.expect("AU arena sized by its index word");
id
}
#[inline]
pub fn get(&self, id: A::Context) -> &[T] {
let span = *self.spans.get(id.to_index());
let start = span.start_usize();
let len = span.len_usize();
&self.items.as_slice()[start..start + len]
}
#[inline]
pub fn contains(&self, id: A::Context, item: T) -> bool {
self.get(id).binary_search(&item).is_ok()
}
pub fn len(&self) -> A::Index {
self.spans.len()
}
pub fn is_empty(&self) -> bool {
self.spans.is_empty()
}
pub fn mark(&mut self) -> ContextStoreToken {
ContextStoreToken {
spans: self
.spans
.try_mark(ShrinkPolicy::Never)
.expect("mark: depth bounded by the search driver"),
items: self
.items
.try_mark(ShrinkPolicy::Never)
.expect("mark: depth bounded by the search driver"),
index: self
.index
.try_mark(ShrinkPolicy::Never)
.expect("mark: depth bounded by the search driver"),
}
}
pub fn is_valid_token(&self, token: &ContextStoreToken) -> bool {
self.spans.is_valid_token(&token.spans)
&& self.items.is_valid_token(&token.items)
&& self.index.is_valid_token(&token.index)
}
pub fn restore(&mut self, token: ContextStoreToken) {
self.index
.try_restore(token.index)
.expect("restore: token minted by this container's own mark");
self.items
.try_restore(token.items)
.expect("restore: token minted by this container's own mark");
self.spans
.try_restore(token.spans)
.expect("restore: token minted by this container's own mark");
}
}
impl<A: AuIds, T> Default for ContextStore<A, T>
where
T: Copy + Ord + core::hash::Hash,
{
fn default() -> Self {
Self::new()
}
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub(crate) enum CycleContext<C> {
Sides { left: Vec<C>, right: Vec<C> },
Pairs(Vec<(C, C)>),
}
pub struct OrArena<A: AuIds = AuIds31> {
pub left: AppendOnlyVec<A::Class, A::Index>,
pub right: AppendOnlyVec<A::Class, A::Index>,
pub left_ctx: AppendOnlyVec<A::Context, A::Index>,
pub right_ctx: AppendOnlyVec<A::Context, A::Index>,
pub terminal: AppendOnlyVec<bool, A::Index>,
pub left_best_size: AppendOnlyVec<u32, A::Index>,
pub right_best_size: AppendOnlyVec<u32, A::Index>,
pub by_key: SpMap<(A::Class, A::Class, A::Context, A::Context), A::Or, A::Index>,
}
#[derive(Clone, Copy, Debug)]
pub struct OrArenaToken {
left: VecToken,
right: VecToken,
left_ctx: VecToken,
right_ctx: VecToken,
terminal: VecToken,
left_best_size: VecToken,
right_best_size: VecToken,
by_key: MapToken,
}
impl<A: AuIds> OrArena<A> {
pub fn new() -> Self {
OrArena {
left: AppendOnlyVec::new(),
right: AppendOnlyVec::new(),
left_ctx: AppendOnlyVec::new(),
right_ctx: AppendOnlyVec::new(),
terminal: AppendOnlyVec::new(),
left_best_size: AppendOnlyVec::new(),
right_best_size: AppendOnlyVec::new(),
by_key: SpMap::new(),
}
}
pub fn len(&self) -> A::Index {
self.left.len()
}
pub fn is_empty(&self) -> bool {
self.left.is_empty()
}
pub fn mark(&mut self) -> OrArenaToken {
OrArenaToken {
left: self
.left
.try_mark(ShrinkPolicy::Never)
.expect("mark: depth bounded by the search driver"),
right: self
.right
.try_mark(ShrinkPolicy::Never)
.expect("mark: depth bounded by the search driver"),
left_ctx: self
.left_ctx
.try_mark(ShrinkPolicy::Never)
.expect("mark: depth bounded by the search driver"),
right_ctx: self
.right_ctx
.try_mark(ShrinkPolicy::Never)
.expect("mark: depth bounded by the search driver"),
terminal: self
.terminal
.try_mark(ShrinkPolicy::Never)
.expect("mark: depth bounded by the search driver"),
left_best_size: self
.left_best_size
.try_mark(ShrinkPolicy::Never)
.expect("mark: depth bounded by the search driver"),
right_best_size: self
.right_best_size
.try_mark(ShrinkPolicy::Never)
.expect("mark: depth bounded by the search driver"),
by_key: self
.by_key
.try_mark(ShrinkPolicy::Never)
.expect("mark: depth bounded by the search driver"),
}
}
pub fn restore(&mut self, token: OrArenaToken) {
self.by_key
.try_restore(token.by_key)
.expect("restore: token minted by this container's own mark");
self.right_best_size
.try_restore(token.right_best_size)
.expect("restore: token minted by this container's own mark");
self.left_best_size
.try_restore(token.left_best_size)
.expect("restore: token minted by this container's own mark");
self.terminal
.try_restore(token.terminal)
.expect("restore: token minted by this container's own mark");
self.right_ctx
.try_restore(token.right_ctx)
.expect("restore: token minted by this container's own mark");
self.left_ctx
.try_restore(token.left_ctx)
.expect("restore: token minted by this container's own mark");
self.right
.try_restore(token.right)
.expect("restore: token minted by this container's own mark");
self.left
.try_restore(token.left)
.expect("restore: token minted by this container's own mark");
}
pub fn is_valid_token(&self, token: &OrArenaToken) -> bool {
self.left.is_valid_token(&token.left)
}
}
impl<A: AuIds> Default for OrArena<A> {
fn default() -> Self {
Self::new()
}
}
#[derive(Clone, Copy, Debug)]
pub struct SpaceToken {
or_arena: OrArenaToken,
contexts: ContextStoreToken,
pair_contexts: ContextStoreToken,
}
pub struct SearchSpace<A: AuIds = AuIds31> {
pub or_arena: OrArena<A>,
pub contexts: ContextStore<A>,
pub pair_contexts: ContextStore<A, (A::Class, A::Class)>,
pub cycle_mode: CycleMode,
}
impl<A: AuIds> SearchSpace<A> {
pub fn new(cycle_mode: CycleMode) -> Self {
SearchSpace {
or_arena: OrArena::new(),
contexts: ContextStore::new(),
pair_contexts: ContextStore::new(),
cycle_mode,
}
}
pub fn empty_contexts(&self) -> (A::Context, A::Context) {
match self.cycle_mode {
CycleMode::Pair => (self.pair_contexts.empty(), self.pair_contexts.empty()),
CycleMode::AncestorOnly | CycleMode::CurrentInclusive => {
(self.contexts.empty(), self.contexts.empty())
}
}
}
pub(crate) fn cycle_context(&self, or_id: A::Or) -> CycleContext<A::Class> {
let ctx_l = *self.or_arena.left_ctx.get(or_id.to_index());
let ctx_r = *self.or_arena.right_ctx.get(or_id.to_index());
match self.cycle_mode {
CycleMode::Pair => CycleContext::Pairs(self.pair_contexts.get(ctx_l).to_vec()),
CycleMode::AncestorOnly | CycleMode::CurrentInclusive => CycleContext::Sides {
left: self.contexts.get(ctx_l).to_vec(),
right: self.contexts.get(ctx_r).to_vec(),
},
}
}
pub(crate) fn intern_cycle_context(
&mut self,
context: &CycleContext<A::Class>,
) -> (A::Context, A::Context) {
match (self.cycle_mode, context) {
(
CycleMode::AncestorOnly | CycleMode::CurrentInclusive,
CycleContext::Sides { left, right },
) => (self.contexts.intern(left), self.contexts.intern(right)),
(CycleMode::Pair, CycleContext::Pairs(pairs)) => {
(self.pair_contexts.intern(pairs), self.pair_contexts.empty())
}
_ => panic!("cycle context does not match the search space's cycle mode"),
}
}
pub fn get_or_insert_or_node(
&mut self,
l: A::Class,
r: A::Class,
ctx_l: A::Context,
ctx_r: A::Context,
left_best_size: u32,
right_best_size: u32,
) -> (A::Or, bool) {
let key = (l, r, ctx_l, ctx_r);
if let Some(log_idx) = self.or_arena.by_key.id_of(&key) {
return (*self.or_arena.by_key.get_val(log_idx), false);
}
let id: A::Or = crate::id::id_at_index(self.or_arena.len());
self.or_arena
.left
.try_push(l)
.expect("AU arena sized by its index word");
self.or_arena
.right
.try_push(r)
.expect("AU arena sized by its index word");
self.or_arena
.left_ctx
.try_push(ctx_l)
.expect("AU arena sized by its index word");
self.or_arena
.right_ctx
.try_push(ctx_r)
.expect("AU arena sized by its index word");
self.or_arena
.terminal
.try_push(l == r)
.expect("AU arena sized by its index word");
self.or_arena
.left_best_size
.try_push(left_best_size)
.expect("AU arena sized by its index word");
self.or_arena
.right_best_size
.try_push(right_best_size)
.expect("AU arena sized by its index word");
self.or_arena
.by_key
.try_insert(key, id)
.expect("AU arena sized by its index word");
(id, true)
}
pub fn derive_child_context(
&mut self,
parent_ctx: A::Context,
parent_class: A::Class,
is_reachable_from_child: impl Fn(A::Class) -> bool,
) -> A::Context {
let parent_classes = self.contexts.get(parent_ctx);
let mut result: Vec<A::Class> = Vec::new();
for &c in parent_classes {
if is_reachable_from_child(c) {
result.push(c);
}
}
if is_reachable_from_child(parent_class) && result.binary_search(&parent_class).is_err() {
result.push(parent_class);
result.sort_unstable();
}
self.contexts.intern(&result)
}
pub fn derive_child_contexts(
&mut self,
parent_or: A::Or,
_child_l: A::Class,
_child_r: A::Class,
is_left_reachable: impl Fn(A::Class) -> bool,
is_right_reachable: impl Fn(A::Class) -> bool,
) -> (A::Context, A::Context) {
let index = parent_or.to_index();
let parent_l = *self.or_arena.left.get(index);
let parent_r = *self.or_arena.right.get(index);
let ctx_l = *self.or_arena.left_ctx.get(index);
let ctx_r = *self.or_arena.right_ctx.get(index);
match self.cycle_mode {
CycleMode::AncestorOnly | CycleMode::CurrentInclusive => (
self.derive_child_context(ctx_l, parent_l, is_left_reachable),
self.derive_child_context(ctx_r, parent_r, is_right_reachable),
),
CycleMode::Pair => {
let mut result: Vec<(A::Class, A::Class)> = self
.pair_contexts
.get(ctx_l)
.iter()
.copied()
.filter(|(left, right)| is_left_reachable(*left) && is_right_reachable(*right))
.collect();
let parent = (parent_l, parent_r);
if is_left_reachable(parent_l)
&& is_right_reachable(parent_r)
&& result.binary_search(&parent).is_err()
{
result.push(parent);
result.sort_unstable();
}
(
self.pair_contexts.intern(&result),
self.pair_contexts.empty(),
)
}
}
}
pub fn extend_context(&mut self, ctx: A::Context, class: A::Class) -> A::Context {
if self.contexts.contains(ctx, class) {
return ctx;
}
let mut classes: Vec<A::Class> = self.contexts.get(ctx).to_vec();
classes.push(class);
classes.sort_unstable();
self.contexts.intern(&classes)
}
pub fn extend_child_contexts(
&mut self,
ctx_l: A::Context,
ctx_r: A::Context,
class: A::Class,
) -> (A::Context, A::Context) {
match self.cycle_mode {
CycleMode::Pair => (ctx_l, ctx_r),
CycleMode::AncestorOnly | CycleMode::CurrentInclusive => (
self.extend_context(ctx_l, class),
self.extend_context(ctx_r, class),
),
}
}
pub fn is_cycle_blocked(&self, or_id: A::Or, child_l: A::Class, child_r: A::Class) -> bool {
let ctx_l = *self.or_arena.left_ctx.get(or_id.to_index());
let ctx_r = *self.or_arena.right_ctx.get(or_id.to_index());
match self.cycle_mode {
CycleMode::AncestorOnly => {
self.contexts.contains(ctx_l, child_l) || self.contexts.contains(ctx_r, child_r)
}
CycleMode::CurrentInclusive => {
if self.contexts.contains(ctx_l, child_l) || self.contexts.contains(ctx_r, child_r)
{
return true;
}
let l = *self.or_arena.left.get(or_id.to_index());
let r = *self.or_arena.right.get(or_id.to_index());
child_l == l || child_r == r
}
CycleMode::Pair => {
if self.pair_contexts.contains(ctx_l, (child_l, child_r)) {
return true;
}
let l = *self.or_arena.left.get(or_id.to_index());
let r = *self.or_arena.right.get(or_id.to_index());
child_l == l && child_r == r
}
}
}
pub fn mark(&mut self) -> SpaceToken {
SpaceToken {
or_arena: self.or_arena.mark(),
contexts: self.contexts.mark(),
pair_contexts: self.pair_contexts.mark(),
}
}
pub fn is_valid_token(&self, token: &SpaceToken) -> bool {
self.or_arena.is_valid_token(&token.or_arena)
&& self.contexts.is_valid_token(&token.contexts)
&& self.pair_contexts.is_valid_token(&token.pair_contexts)
}
pub fn restore(&mut self, token: SpaceToken) {
self.or_arena.restore(token.or_arena);
self.contexts.restore(token.contexts);
self.pair_contexts.restore(token.pair_contexts);
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::au::AuClassId;
#[test]
fn context_interner_empty() {
let store: ContextStore = ContextStore::new();
assert_eq!(store.empty(), CtxId::from_usize(0));
assert_eq!(store.get(store.empty()), &[]);
assert!(!store.contains(store.empty(), AuClassId::from_usize(0)));
}
#[test]
fn context_interner_dedup() {
let mut store: ContextStore = ContextStore::new();
let c0 = AuClassId::from_usize(0);
let c1 = AuClassId::from_usize(1);
let c2 = AuClassId::from_usize(2);
let ctx_a = store.intern(&[c0, c1]);
let ctx_b = store.intern(&[c0, c1]);
assert_eq!(ctx_a, ctx_b);
let ctx_c = store.intern(&[c0, c1, c2]);
assert_ne!(ctx_a, ctx_c);
assert!(store.contains(ctx_a, c0));
assert!(store.contains(ctx_a, c1));
assert!(!store.contains(ctx_a, c2));
assert!(store.contains(ctx_c, c2));
}
#[test]
fn or_node_dedup() {
let mut space: SearchSpace = SearchSpace::new(CycleMode::AncestorOnly);
let c0 = AuClassId::from_usize(0);
let c1 = AuClassId::from_usize(1);
let ctx = space.contexts.empty();
let (id1, new1) = space.get_or_insert_or_node(c0, c1, ctx, ctx, 1, 1);
assert!(new1);
let (id2, new2) = space.get_or_insert_or_node(c0, c1, ctx, ctx, 1, 1);
assert!(!new2);
assert_eq!(id1, id2);
let (id3, new3) = space.get_or_insert_or_node(c1, c0, ctx, ctx, 1, 1);
assert!(new3);
assert_ne!(id1, id3);
}
#[test]
fn derive_child_context_acyclic() {
let mut space: SearchSpace = SearchSpace::new(CycleMode::AncestorOnly);
let parent_ctx = space.contexts.empty();
let parent_class = AuClassId::from_usize(0);
let child_ctx = space.derive_child_context(parent_ctx, parent_class, |_| false);
assert_eq!(child_ctx, space.contexts.empty());
}
#[test]
fn derive_child_context_cyclic() {
let mut space: SearchSpace = SearchSpace::new(CycleMode::AncestorOnly);
let c0 = AuClassId::from_usize(0);
let c1 = AuClassId::from_usize(1);
let parent_ctx = space.contexts.intern(&[c0]);
let parent_class = c1;
let child_ctx =
space.derive_child_context(parent_ctx, parent_class, |c| c == c0 || c == c1);
let ctx_classes = space.contexts.get(child_ctx);
assert_eq!(ctx_classes, &[c0, c1]);
}
#[test]
fn cycle_blocking_ancestor_only() {
let mut space: SearchSpace = SearchSpace::new(CycleMode::AncestorOnly);
let c0 = AuClassId::from_usize(0);
let c1 = AuClassId::from_usize(1);
let c2 = AuClassId::from_usize(2);
let ctx_l = space.contexts.intern(&[c0]);
let ctx_r = space.contexts.empty();
let (or_id, _) = space.get_or_insert_or_node(c1, c2, ctx_l, ctx_r, 1, 1);
assert!(space.is_cycle_blocked(or_id, c0, c2));
assert!(!space.is_cycle_blocked(or_id, c1, c2));
assert!(!space.is_cycle_blocked(or_id, c1, c2));
}
#[test]
fn cycle_blocking_current_inclusive() {
let mut space: SearchSpace = SearchSpace::new(CycleMode::CurrentInclusive);
let c0 = AuClassId::from_usize(0);
let c1 = AuClassId::from_usize(1);
let c2 = AuClassId::from_usize(2);
let ctx_l = space.contexts.empty();
let ctx_r = space.contexts.empty();
let (or_id, _) = space.get_or_insert_or_node(c1, c2, ctx_l, ctx_r, 1, 1);
assert!(space.is_cycle_blocked(or_id, c1, c0));
assert!(space.is_cycle_blocked(or_id, c0, c2));
assert!(!space.is_cycle_blocked(or_id, c0, c0));
}
#[test]
fn cycle_blocking_pair_preserves_one_sided_revisits() {
let mut space: SearchSpace = SearchSpace::new(CycleMode::Pair);
let c0 = AuClassId::from_usize(0);
let c1 = AuClassId::from_usize(1);
let c2 = AuClassId::from_usize(2);
let (empty_l, empty_r) = space.empty_contexts();
let (root, _) = space.get_or_insert_or_node(c1, c2, empty_l, empty_r, 1, 1);
assert!(space.is_cycle_blocked(root, c1, c2));
assert!(!space.is_cycle_blocked(root, c1, c0));
assert!(!space.is_cycle_blocked(root, c0, c2));
let (child_l, child_r) = space.derive_child_contexts(root, c1, c0, |_| true, |_| true);
let (child, _) = space.get_or_insert_or_node(c1, c0, child_l, child_r, 1, 1);
assert!(space.is_cycle_blocked(child, c1, c2));
assert!(!space.is_cycle_blocked(child, c1, c1));
assert_eq!(
space.cycle_context(child),
CycleContext::Pairs(vec![(c1, c2)])
);
}
#[test]
fn terminal_when_l_eq_r() {
let mut space: SearchSpace = SearchSpace::new(CycleMode::AncestorOnly);
let c0 = AuClassId::from_usize(0);
let ctx = space.contexts.empty();
let (or_id, _) = space.get_or_insert_or_node(c0, c0, ctx, ctx, 1, 1);
assert!(*space.or_arena.terminal.get(or_id.to_index()));
}
#[test]
fn mark_restore_truncates() {
let mut space: SearchSpace = SearchSpace::new(CycleMode::AncestorOnly);
let c0 = AuClassId::from_usize(0);
let c1 = AuClassId::from_usize(1);
let c2 = AuClassId::from_usize(2);
let ctx = space.contexts.empty();
let (id1, _) = space.get_or_insert_or_node(c0, c1, ctx, ctx, 1, 1);
let token = space.mark();
let (_id2, _) = space.get_or_insert_or_node(c1, c2, ctx, ctx, 1, 1);
assert_eq!(space.or_arena.len(), 2);
space.restore(token);
assert_eq!(space.or_arena.len(), 1);
let (id1b, new) = space.get_or_insert_or_node(c0, c1, ctx, ctx, 1, 1);
assert!(!new);
assert_eq!(id1, id1b);
let (_, new) = space.get_or_insert_or_node(c1, c2, ctx, ctx, 1, 1);
assert!(new);
}
#[test]
fn mark_restore_truncates_pair_contexts() {
let mut space: SearchSpace = SearchSpace::new(CycleMode::Pair);
let c0 = AuClassId::from_usize(0);
let c1 = AuClassId::from_usize(1);
let c2 = AuClassId::from_usize(2);
let (empty_l, empty_r) = space.empty_contexts();
let (root, _) = space.get_or_insert_or_node(c0, c1, empty_l, empty_r, 1, 1);
let token = space.mark();
let (child_l, child_r) = space.derive_child_contexts(root, c1, c2, |_| true, |_| true);
let (child, _) = space.get_or_insert_or_node(c1, c2, child_l, child_r, 1, 1);
assert_eq!(
space.cycle_context(child),
CycleContext::Pairs(vec![(c0, c1)])
);
assert_eq!(space.pair_contexts.len().as_usize(), 2);
space.restore(token);
assert_eq!(space.or_arena.len(), 1);
assert_eq!(space.pair_contexts.len().as_usize(), 1);
assert_eq!(space.cycle_context(root), CycleContext::Pairs(Vec::new()));
let (child_l, child_r) = space.derive_child_contexts(root, c1, c2, |_| true, |_| true);
let (_, new) = space.get_or_insert_or_node(c1, c2, child_l, child_r, 1, 1);
assert!(new);
}
}