#![warn(missing_docs)]
#[doc(hidden)]
pub use serde_json;
use std::borrow::Cow;
use std::collections::HashMap;
use std::fmt;
use std::sync::Arc;
use std::sync::atomic::{AtomicU64, Ordering};
mod drive;
mod engine;
pub mod suggest;
pub use drive::{AsyncEffectResolver, DriveOutcome, EffectResolver, drive, drive_async};
pub use engine::{Ast, Engine, ExecError, LoopDecision, NodeKind};
pub use suggest::{NoopSuggester, Suggester, SuggesterHandle, Suggestion, noop_handle};
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub struct NodeId(pub u64);
impl fmt::Display for NodeId {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "n{}", self.0)
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub struct CallFrameId(pub u64);
impl fmt::Display for CallFrameId {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "f{}", self.0)
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub struct Iteration(pub u64);
#[derive(Debug, Clone, PartialEq, Eq, Hash, Default)]
pub struct Path(pub Vec<NodeId>);
impl Path {
#[inline]
pub fn root() -> Self {
Path(Vec::new())
}
pub fn push(&self, node: NodeId) -> Self {
let mut next = self.0.clone();
next.push(node);
Path(next)
}
#[inline]
pub fn depth(&self) -> usize {
self.0.len()
}
pub fn tip(&self) -> Option<NodeId> {
self.0.last().copied()
}
}
impl fmt::Display for Path {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
if self.0.is_empty() {
return write!(f, "/");
}
for id in &self.0 {
write!(f, "/{id}")?;
}
Ok(())
}
}
#[derive(Debug, Default)]
pub struct IdGen {
next: AtomicU64,
}
impl IdGen {
pub const fn new() -> Self {
Self {
next: AtomicU64::new(0),
}
}
pub fn node(&self) -> NodeId {
NodeId(self.next.fetch_add(1, Ordering::Relaxed))
}
pub fn frame(&self) -> CallFrameId {
CallFrameId(self.next.fetch_add(1, Ordering::Relaxed))
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct NodeContext {
pub node: NodeId,
pub path: Path,
pub frame: Option<CallFrameId>,
pub depth: u32,
pub iteration: Option<Iteration>,
}
impl NodeContext {
pub fn at(node: NodeId, path: Path) -> Self {
Self {
node,
path,
frame: None,
depth: 0,
iteration: None,
}
}
}
impl fmt::Display for NodeContext {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "{}", self.node)?;
if let Some(frame) = self.frame {
write!(f, " (frame {}, depth {})", frame, self.depth)?;
}
if let Some(it) = self.iteration {
write!(f, " iter {}", it.0)?;
}
write!(f, " at {}", self.path)
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub struct SuspensionId(pub u64);
impl fmt::Display for SuspensionId {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "s{}", self.0)
}
}
#[derive(Debug, Clone)]
pub struct Pending {
pub id: SuspensionId,
pub reason: SuspendReason,
pub at: NodeContext,
}
#[derive(Debug, Clone)]
#[non_exhaustive]
pub enum SuspendReason {
Call {
spec: CallSpec,
},
Breakpoint,
Cooperative,
User {
tag: Cow<'static, str>,
},
}
impl fmt::Display for SuspendReason {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
SuspendReason::Call { spec } => write!(f, "call({})", spec.label),
SuspendReason::Breakpoint => write!(f, "breakpoint"),
SuspendReason::Cooperative => write!(f, "cooperative"),
SuspendReason::User { tag } => write!(f, "user({tag})"),
}
}
}
#[derive(Debug, Clone)]
pub struct CallSpec {
pub label: String,
pub payload: serde_json::Value,
}
#[derive(Debug, Clone)]
#[non_exhaustive]
pub enum Event {
VisitPre {
at: NodeContext,
},
VisitPost {
at: NodeContext,
},
FrameEnter {
at: NodeContext,
},
FrameLeave {
at: NodeContext,
},
IterationTick {
at: NodeContext,
},
Suspend {
at: NodeContext,
reason: SuspendReason,
},
Resume {
at: NodeContext,
},
Cancel {
id: SuspensionId,
},
}
pub trait EventSink {
fn emit(&mut self, event: &Event);
}
#[derive(Debug, Default)]
pub struct NullSink;
impl EventSink for NullSink {
#[inline]
fn emit(&mut self, _event: &Event) {}
}
#[derive(Debug, Default, Clone, Copy)]
pub struct CountingSink {
pub visit_pre: u32,
pub visit_post: u32,
pub frame_enter: u32,
pub frame_leave: u32,
pub iteration_tick: u32,
pub suspend: u32,
pub resume: u32,
}
impl EventSink for CountingSink {
fn emit(&mut self, event: &Event) {
match event {
Event::VisitPre { .. } => self.visit_pre += 1,
Event::VisitPost { .. } => self.visit_post += 1,
Event::FrameEnter { .. } => self.frame_enter += 1,
Event::FrameLeave { .. } => self.frame_leave += 1,
Event::IterationTick { .. } => self.iteration_tick += 1,
Event::Suspend { .. } => self.suspend += 1,
Event::Resume { .. } => self.resume += 1,
_ => {}
}
}
}
impl CountingSink {
pub fn summarise(&self) -> String {
format!(
"pre={} post={} frame_enter={} frame_leave={} iter={} suspend={} resume={}",
self.visit_pre,
self.visit_post,
self.frame_enter,
self.frame_leave,
self.iteration_tick,
self.suspend,
self.resume,
)
}
}
#[derive(Debug, Default, Clone)]
pub struct BufferingSink {
events: Vec<Event>,
}
impl BufferingSink {
pub fn new() -> Self {
Self { events: Vec::new() }
}
pub fn with_capacity(cap: usize) -> Self {
Self {
events: Vec::with_capacity(cap),
}
}
pub fn snapshot(&self) -> &[Event] {
&self.events
}
pub fn drain(&mut self) -> Vec<Event> {
std::mem::take(&mut self.events)
}
pub fn clear(&mut self) {
self.events.clear();
}
pub fn len(&self) -> usize {
self.events.len()
}
pub fn is_empty(&self) -> bool {
self.events.is_empty()
}
}
impl EventSink for BufferingSink {
fn emit(&mut self, event: &Event) {
self.events.push(event.clone());
}
}
#[derive(Debug, thiserror::Error, miette::Diagnostic)]
#[non_exhaustive]
pub enum EngineError {
#[error("evaluation aborted at {at}: {reason}")]
#[diagnostic(
code(dsl_kit::eval::aborted),
help(
"The interpreter returned an `Aborted` outcome. Inspect the reason and the node context to locate the abort site."
)
)]
Aborted {
at: NodeContext,
reason: String,
},
#[error("evaluator failed at {at}")]
#[diagnostic(
code(dsl_kit::eval::failed),
help(
"The interpreter returned an error while evaluating this node. The `#[source]` chain points at the underlying failure."
)
)]
EvalFailed {
at: NodeContext,
#[source]
source: Box<dyn std::error::Error + Send + Sync>,
},
#[error("malformed AST at {at}: {detail}")]
#[diagnostic(
code(dsl_kit::ast::malformed),
help(
"An AST invariant was violated. This usually means a hand-constructed tree omitted a required child."
)
)]
Malformed {
at: NodeContext,
detail: String,
},
#[error("stepper protocol violation at {at}: {detail}")]
#[diagnostic(
code(dsl_kit::stepper::protocol),
help(
"The stepper's suspend/resume contract was broken. Each `PendingEffect` leaf must be resolved exactly once before further steps observe its value."
)
)]
StepperProtocol {
at: NodeContext,
detail: String,
},
#[error("unknown suspension {id}")]
#[diagnostic(
code(dsl_kit::stepper::unknown_suspension),
help(
"The host called resolve() with a SuspensionId the engine does not know. This is the expected outcome for a late response arriving after the effect's branch was cancelled."
)
)]
UnknownSuspension {
id: SuspensionId,
},
#[error("unknown reducer {id:?}{hint}")]
#[diagnostic(
code(dsl_kit::reducer::unknown),
help(
"The ParFrame's reducer_id was not found in the ReducerRegistry. Register the reducer at Stepper build time or fix the AST to reference a known id."
)
)]
UnknownReducer {
id: ReducerId,
hint: String,
},
#[error("unknown op {id:?}{hint}")]
#[diagnostic(
code(dsl_kit::op::unknown),
help(
"The Apply node's op_id was not found in the OpRegistry. Register the op at Stepper build time (Engine::new_with_ops) or fix the AST to reference a known id."
)
)]
UnknownOp {
id: OpId,
hint: String,
},
}
pub type EngineResult<T> = Result<T, EngineError>;
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ErrorCatalogEntry {
pub code: String,
pub help: String,
}
pub fn engine_error_catalog() -> Vec<ErrorCatalogEntry> {
use miette::Diagnostic;
fn ctx() -> NodeContext {
NodeContext::at(NodeId(0), Path::root())
}
let samples: Vec<EngineError> = vec![
EngineError::Aborted {
at: ctx(),
reason: String::new(),
},
EngineError::EvalFailed {
at: ctx(),
source: Box::new(std::io::Error::other("")),
},
EngineError::Malformed {
at: ctx(),
detail: String::new(),
},
EngineError::StepperProtocol {
at: ctx(),
detail: String::new(),
},
EngineError::UnknownSuspension {
id: SuspensionId(0),
},
EngineError::UnknownReducer {
id: ReducerId(String::new()),
hint: String::new(),
},
EngineError::UnknownOp {
id: OpId(String::new()),
hint: String::new(),
},
];
samples
.into_iter()
.filter_map(|e| {
let code = e.code()?.to_string();
let help = e.help()?.to_string();
Some(ErrorCatalogEntry { code, help })
})
.collect()
}
#[derive(Debug, Clone)]
pub enum StepOutcome<V> {
Ready,
Blocked {
newly_pending: smallvec::SmallVec<[Pending; 1]>,
},
Done(V),
}
pub trait Stepper {
type Value;
type Cursor;
type Delta;
type EffectError: std::error::Error + Send + Sync + 'static;
type Error: From<Self::EffectError> + std::error::Error + Send + Sync + 'static;
fn step(&mut self) -> Result<StepOutcome<Self::Value>, Self::Error>;
fn resolve(
&mut self,
id: SuspensionId,
result: Result<Self::Value, Self::EffectError>,
) -> Result<(), Self::Error>;
fn pending(&self) -> &[Pending];
fn take_cancellations(&mut self) -> Vec<SuspensionId>;
fn frame_tree(&self) -> &FrameTree<Self::Value, Self::Cursor, Self::Delta, Self::EffectError>;
fn is_done(&self) -> bool;
}
pub type ChildIndex = usize;
#[derive(Debug, Clone)]
pub enum CancelReason {
ParPolicyFired,
SiblingFailed,
}
#[derive(Debug)]
pub enum Frame<V, C, D, EE> {
Node {
node: NodeId,
env: EnvRef<D>,
cursor: C,
},
Par(ParFrame<V, D, EE>),
Scope {
label: String,
env: EnvRef<D>,
},
PendingEffect {
id: SuspensionId,
},
Value(V),
Cancelled {
reason: CancelReason,
},
}
#[derive(Debug)]
pub struct FrameTree<V, C, D, EE> {
pub root: Frame<V, C, D, EE>,
pub kids: Vec<FrameTree<V, C, D, EE>>,
}
#[derive(Debug)]
pub struct ParFrame<V, D, EE> {
pub policy: JoinPolicy,
pub slots: Vec<Option<V>>,
pub failures: Vec<Option<EE>>,
pub deltas: Vec<Option<D>>,
pub completion_order: Vec<ChildIndex>,
pub reducer_id: ReducerId,
pub reducer: ReducerHandle<V, D, EE>,
pub joined: bool,
}
#[derive(Debug, Clone, Copy)]
pub struct JoinPolicy {
pub shape: JoinShape,
pub fail: FailPolicy,
}
#[derive(Debug, Clone, Copy)]
pub enum JoinShape {
All,
Any,
FirstK(usize),
}
#[derive(Debug, Clone, Copy)]
pub enum FailPolicy {
FailFast,
CollectAll,
}
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct ReducerId(pub String);
impl fmt::Display for ReducerId {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "{}", self.0)
}
}
impl From<&str> for ReducerId {
fn from(s: &str) -> Self {
ReducerId(s.to_string())
}
}
impl From<String> for ReducerId {
fn from(s: String) -> Self {
ReducerId(s)
}
}
pub trait Reducer<V, D>: Send + Sync {
fn reduce(
&self,
slots: &[Option<V>],
deltas: &[Option<D>],
winners: &[ChildIndex],
) -> Result<(V, D), EngineError>;
}
pub trait ReducerCollectAll<V, D, EffectError>: Send + Sync {
fn reduce(
&self,
slots: &[Option<Result<V, EffectError>>],
deltas: &[Option<D>],
winners: &[ChildIndex],
) -> Result<(V, D), EngineError>;
}
pub enum ReducerHandle<V, D, EE> {
FailFast(Arc<dyn Reducer<V, D>>),
CollectAll(Arc<dyn ReducerCollectAll<V, D, EE>>),
}
impl<V, D, EE> fmt::Debug for ReducerHandle<V, D, EE> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
ReducerHandle::FailFast(_) => f.write_str("ReducerHandle::FailFast(..)"),
ReducerHandle::CollectAll(_) => f.write_str("ReducerHandle::CollectAll(..)"),
}
}
}
impl<V, D, EE> Clone for ReducerHandle<V, D, EE> {
fn clone(&self) -> Self {
match self {
ReducerHandle::FailFast(a) => ReducerHandle::FailFast(a.clone()),
ReducerHandle::CollectAll(a) => ReducerHandle::CollectAll(a.clone()),
}
}
}
pub struct ReducerRegistry<V, D, EffectError> {
fail_fast: HashMap<ReducerId, Arc<dyn Reducer<V, D>>>,
collect_all: HashMap<ReducerId, Arc<dyn ReducerCollectAll<V, D, EffectError>>>,
suggester: crate::suggest::SuggesterHandle,
}
impl<V, D, EE> Default for ReducerRegistry<V, D, EE> {
fn default() -> Self {
Self::new()
}
}
impl<V, D, EE> ReducerRegistry<V, D, EE> {
pub fn new() -> Self {
Self {
fail_fast: HashMap::new(),
collect_all: HashMap::new(),
suggester: crate::suggest::noop_handle(),
}
}
pub fn with_suggester(mut self, suggester: crate::suggest::SuggesterHandle) -> Self {
self.suggester = suggester;
self
}
pub fn register_fail_fast(
&mut self,
id: impl Into<ReducerId>,
reducer: Arc<dyn Reducer<V, D>>,
) {
self.fail_fast.insert(id.into(), reducer);
}
pub fn register_collect_all(
&mut self,
id: impl Into<ReducerId>,
reducer: Arc<dyn ReducerCollectAll<V, D, EE>>,
) {
self.collect_all.insert(id.into(), reducer);
}
pub fn resolve(
&self,
id: &ReducerId,
fail: FailPolicy,
) -> Result<ReducerHandle<V, D, EE>, EngineError> {
let miss = || {
let names: Vec<&str> = match fail {
FailPolicy::FailFast => self.fail_fast.keys().map(|k| k.0.as_str()).collect(),
FailPolicy::CollectAll => self.collect_all.keys().map(|k| k.0.as_str()).collect(),
};
let hint = self
.suggester
.enrich_unknown(&id.0, &names)
.map(|h| format!(" ({h})"))
.unwrap_or_default();
EngineError::UnknownReducer {
id: id.clone(),
hint,
}
};
match fail {
FailPolicy::FailFast => self
.fail_fast
.get(id)
.cloned()
.map(ReducerHandle::FailFast)
.ok_or_else(miss),
FailPolicy::CollectAll => self
.collect_all
.get(id)
.cloned()
.map(ReducerHandle::CollectAll)
.ok_or_else(miss),
}
}
}
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct OpId(pub String);
impl fmt::Display for OpId {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "{}", self.0)
}
}
impl From<&str> for OpId {
fn from(s: &str) -> Self {
OpId(s.to_string())
}
}
impl From<String> for OpId {
fn from(s: String) -> Self {
OpId(s)
}
}
pub trait Op<V>: Send + Sync {
fn apply(&self, node: NodeId, args: &[V]) -> Result<V, EngineError>;
}
pub type OpHandle<V> = Arc<dyn Op<V>>;
pub struct OpRegistry<V> {
ops: HashMap<OpId, OpHandle<V>>,
suggester: crate::suggest::SuggesterHandle,
}
impl<V> Default for OpRegistry<V> {
fn default() -> Self {
Self::new()
}
}
impl<V> OpRegistry<V> {
pub fn new() -> Self {
Self {
ops: HashMap::new(),
suggester: crate::suggest::noop_handle(),
}
}
pub fn with_suggester(mut self, suggester: crate::suggest::SuggesterHandle) -> Self {
self.suggester = suggester;
self
}
pub fn register(&mut self, id: impl Into<OpId>, op: OpHandle<V>) {
self.ops.insert(id.into(), op);
}
pub fn resolve(&self, id: &OpId) -> Result<OpHandle<V>, EngineError> {
self.ops.get(id).cloned().ok_or_else(|| {
let names: Vec<&str> = self.ops.keys().map(|k| k.0.as_str()).collect();
let hint = self
.suggester
.enrich_unknown(&id.0, &names)
.map(|h| format!(" ({h})"))
.unwrap_or_default();
EngineError::UnknownOp {
id: id.clone(),
hint,
}
})
}
}
pub trait DslExec: Walk {
type LitValue: Clone + fmt::Debug;
fn exec_kind(&self) -> NodeKind;
fn exec_literal(&self) -> Option<Self::LitValue>;
}
pub trait DslSemantics {
type Value: Clone + fmt::Debug;
type Delta: Clone + Default + fmt::Debug;
type EffectError: std::error::Error + Clone + Send + Sync + 'static;
type Cursor: Clone + fmt::Debug + Default;
fn unit_value(&self) -> Self::Value;
fn truthy(&self, _value: &Self::Value) -> Option<bool> {
None
}
fn continue_loop(&self, _node: NodeId, _last: &Self::Value, _iteration: usize) -> LoopDecision {
LoopDecision::Break
}
fn bind_delta(&self, _name: &str, _value: &Self::Value) -> Option<Self::Delta> {
None
}
fn lookup(&self, _delta: &Self::Delta, _name: &str) -> Option<Self::Value> {
None
}
}
pub struct DerivedAst<'a, N, S> {
root: &'a N,
by_id: HashMap<NodeId, &'a N>,
sem: S,
}
impl<'a, N: DslExec, S> DerivedAst<'a, N, S> {
pub fn new(root: &'a N, sem: S) -> Self {
fn collect<'a, N: Walk>(node: &'a N, map: &mut HashMap<NodeId, &'a N>) {
map.insert(node.node_id(), node);
for child in node.children() {
collect(child, map);
}
}
let mut by_id = HashMap::new();
collect(root, &mut by_id);
Self { root, by_id, sem }
}
fn node(&self, id: NodeId) -> &'a N {
self.by_id.get(&id).copied().expect("unknown NodeId")
}
}
impl<N, S> Ast for DerivedAst<'_, N, S>
where
N: DslExec,
S: DslSemantics,
S::Value: From<N::LitValue>,
{
type Value = S::Value;
type Delta = S::Delta;
type EffectError = S::EffectError;
type Cursor = S::Cursor;
fn root(&self) -> NodeId {
self.root.node_id()
}
fn node_kind(&self, id: NodeId) -> NodeKind {
self.node(id).exec_kind()
}
fn unit_value(&self) -> Self::Value {
self.sem.unit_value()
}
fn truthy(&self, value: &Self::Value) -> Option<bool> {
self.sem.truthy(value)
}
fn continue_loop(&self, node: NodeId, last: &Self::Value, iteration: usize) -> LoopDecision {
self.sem.continue_loop(node, last, iteration)
}
fn bind_delta(&self, name: &str, value: &Self::Value) -> Option<Self::Delta> {
self.sem.bind_delta(name, value)
}
fn lookup(&self, delta: &Self::Delta, name: &str) -> Option<Self::Value> {
self.sem.lookup(delta, name)
}
fn literal(&self, node: NodeId) -> Option<Self::Value> {
self.node(node).exec_literal().map(S::Value::from)
}
}
#[derive(Debug)]
pub struct EnvRef<D>(pub Arc<Env<D>>);
impl<D> Clone for EnvRef<D> {
fn clone(&self) -> Self {
EnvRef(self.0.clone())
}
}
#[derive(Debug)]
pub struct Env<D> {
pub delta: D,
pub parent: Option<Arc<Env<D>>>,
}
pub trait DslNode {
fn node_id(&self) -> NodeId;
fn variant_name(&self) -> &'static str;
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub struct BreakpointId(pub u64);
impl fmt::Display for BreakpointId {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "bp{}", self.0)
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum BreakCondition {
Node(NodeId),
PathPrefix(Path),
PathExact(Path),
DepthAtLeast(u32),
DepthAtMost(u32),
DepthEquals(u32),
Iteration(u64),
CallFrame(CallFrameId),
Any(Vec<BreakCondition>),
All(Vec<BreakCondition>),
Not(Box<BreakCondition>),
Always,
Never,
}
impl BreakCondition {
pub fn at_node(id: NodeId) -> Self {
Self::Node(id)
}
pub fn under_path(path: Path) -> Self {
Self::PathPrefix(path)
}
pub fn at_path(path: Path) -> Self {
Self::PathExact(path)
}
pub fn at_depth_at_least(n: u32) -> Self {
Self::DepthAtLeast(n)
}
pub fn at_depth_at_most(n: u32) -> Self {
Self::DepthAtMost(n)
}
pub fn at_depth(n: u32) -> Self {
Self::DepthEquals(n)
}
pub fn at_iteration(n: u64) -> Self {
Self::Iteration(n)
}
pub fn in_call_frame(frame: CallFrameId) -> Self {
Self::CallFrame(frame)
}
pub fn and(self, other: Self) -> Self {
match (self, other) {
(Self::All(mut xs), Self::All(ys)) => {
xs.extend(ys);
Self::All(xs)
}
(Self::All(mut xs), other) => {
xs.push(other);
Self::All(xs)
}
(this, Self::All(mut ys)) => {
ys.insert(0, this);
Self::All(ys)
}
(this, other) => Self::All(vec![this, other]),
}
}
pub fn or(self, other: Self) -> Self {
match (self, other) {
(Self::Any(mut xs), Self::Any(ys)) => {
xs.extend(ys);
Self::Any(xs)
}
(Self::Any(mut xs), other) => {
xs.push(other);
Self::Any(xs)
}
(this, Self::Any(mut ys)) => {
ys.insert(0, this);
Self::Any(ys)
}
(this, other) => Self::Any(vec![this, other]),
}
}
pub fn matches(&self, ctx: &NodeContext) -> bool {
match self {
Self::Node(id) => ctx.node == *id,
Self::PathPrefix(prefix) => {
ctx.path.0.len() >= prefix.0.len() && ctx.path.0[..prefix.0.len()] == prefix.0[..]
}
Self::PathExact(path) => ctx.path == *path,
Self::DepthAtLeast(n) => ctx.depth >= *n,
Self::DepthAtMost(n) => ctx.depth <= *n,
Self::DepthEquals(n) => ctx.depth == *n,
Self::Iteration(n) => ctx.iteration.map(|i| i.0 == *n).unwrap_or(false),
Self::CallFrame(frame) => ctx.frame == Some(*frame),
Self::Any(children) => children.iter().any(|c| c.matches(ctx)),
Self::All(children) => children.iter().all(|c| c.matches(ctx)),
Self::Not(inner) => !inner.matches(ctx),
Self::Always => true,
Self::Never => false,
}
}
}
impl std::ops::Not for BreakCondition {
type Output = Self;
fn not(self) -> Self {
Self::Not(Box::new(self))
}
}
#[derive(Debug, Default)]
pub struct BreakpointSet {
next: u64,
entries: Vec<(BreakpointId, BreakCondition)>,
}
impl BreakpointSet {
pub fn new() -> Self {
Self {
next: 1,
entries: Vec::new(),
}
}
pub fn add(&mut self, condition: BreakCondition) -> BreakpointId {
let id = BreakpointId(self.next);
self.next += 1;
self.entries.push((id, condition));
id
}
pub fn remove(&mut self, id: BreakpointId) -> bool {
let before = self.entries.len();
self.entries.retain(|(entry_id, _)| *entry_id != id);
self.entries.len() != before
}
pub fn matches(&self, ctx: &NodeContext) -> Vec<BreakpointId> {
self.entries
.iter()
.filter(|(_, cond)| cond.matches(ctx))
.map(|(id, _)| *id)
.collect()
}
pub fn is_empty(&self) -> bool {
self.entries.is_empty()
}
pub fn len(&self) -> usize {
self.entries.len()
}
pub fn iter(&self) -> impl Iterator<Item = (BreakpointId, &BreakCondition)> {
self.entries.iter().map(|(id, c)| (*id, c))
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Phase {
Pre,
Post,
}
pub trait Walk: DslNode + Sized {
fn children(&self) -> Vec<&Self>;
fn walk<F>(&self, visitor: &mut F)
where
F: FnMut(&Self, Phase),
{
visitor(self, Phase::Pre);
for child in self.children() {
child.walk(visitor);
}
visitor(self, Phase::Post);
}
fn walk_until<F, T>(&self, visitor: &mut F) -> Option<T>
where
F: FnMut(&Self, Phase) -> Option<T>,
{
if let Some(t) = visitor(self, Phase::Pre) {
return Some(t);
}
for child in self.children() {
if let Some(t) = child.walk_until(visitor) {
return Some(t);
}
}
visitor(self, Phase::Post)
}
fn find_by_id(&self, target: NodeId) -> Option<&Self> {
self.walk_until(&mut |node, phase| {
if phase == Phase::Pre && node.node_id() == target {
Some(node as *const Self)
} else {
None
}
})
.map(|ptr| unsafe { &*ptr })
}
}
pub trait WalkMut: DslNode + Sized {
fn children_mut(&mut self) -> Vec<&mut Self>;
fn walk_mut<F>(&mut self, visitor: &mut F)
where
F: FnMut(&mut Self, Phase),
{
visitor(self, Phase::Pre);
for child in self.children_mut() {
child.walk_mut(visitor);
}
visitor(self, Phase::Post);
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn path_push_extends_depth() {
let ids = IdGen::new();
let a = ids.node();
let b = ids.node();
let root = Path::root();
assert_eq!(root.depth(), 0);
let one = root.push(a);
assert_eq!(one.depth(), 1);
let two = one.push(b);
assert_eq!(two.depth(), 2);
assert_eq!(two.tip(), Some(b));
}
#[test]
fn id_generator_yields_distinct_ids() {
let ids = IdGen::new();
let a = ids.node();
let b = ids.node();
assert_ne!(a, b);
}
#[test]
fn null_sink_accepts_events() {
let mut sink = NullSink;
let event = Event::VisitPre {
at: NodeContext::at(NodeId(0), Path::root()),
};
sink.emit(&event);
}
fn ctx_at(node: NodeId, path: Path, depth: u32) -> NodeContext {
NodeContext {
node,
path,
frame: None,
depth,
iteration: None,
}
}
#[test]
fn breakpoint_node_matches_exact_id() {
let cond = BreakCondition::at_node(NodeId(7));
assert!(cond.matches(&ctx_at(NodeId(7), Path::root().push(NodeId(7)), 1)));
assert!(!cond.matches(&ctx_at(NodeId(8), Path::root().push(NodeId(8)), 1)));
}
#[test]
fn breakpoint_set_add_matches_remove() {
let mut set = BreakpointSet::new();
let hit = set.add(BreakCondition::at_node(NodeId(4)));
let miss = set.add(BreakCondition::at_node(NodeId(99)));
let ctx = ctx_at(NodeId(4), Path::root().push(NodeId(4)), 1);
assert_eq!(set.matches(&ctx), vec![hit]);
assert!(set.remove(hit));
assert!(set.matches(&ctx).is_empty());
assert_eq!(set.len(), 1);
assert!(set.iter().any(|(id, _)| id == miss));
}
#[test]
fn engine_error_carries_stable_code() {
let err = EngineError::Aborted {
at: NodeContext::at(NodeId(1), Path::root().push(NodeId(1))),
reason: "user requested".into(),
};
use miette::Diagnostic;
assert_eq!(
err.code().map(|c| c.to_string()).as_deref(),
Some("dsl_kit::eval::aborted")
);
}
#[test]
fn engine_error_catalog_covers_every_variant() {
let entries = engine_error_catalog();
let codes: Vec<&str> = entries.iter().map(|e| e.code.as_str()).collect();
assert!(codes.contains(&"dsl_kit::eval::aborted"));
assert!(codes.contains(&"dsl_kit::eval::failed"));
assert!(codes.contains(&"dsl_kit::ast::malformed"));
assert!(codes.contains(&"dsl_kit::stepper::protocol"));
assert!(codes.contains(&"dsl_kit::stepper::unknown_suspension"));
assert!(codes.contains(&"dsl_kit::reducer::unknown"));
for entry in &entries {
assert!(!entry.help.is_empty(), "help empty for {}", entry.code);
}
}
#[test]
fn reducer_id_from_str_and_string() {
let a: ReducerId = "foo".into();
let b: ReducerId = String::from("foo").into();
assert_eq!(a, b);
}
#[test]
fn reducer_registry_resolves_fail_fast_and_collect_all_independently() {
struct FirstNonNone;
impl Reducer<i64, ()> for FirstNonNone {
fn reduce(
&self,
slots: &[Option<i64>],
_deltas: &[Option<()>],
_winners: &[ChildIndex],
) -> Result<(i64, ()), EngineError> {
let v = slots.iter().find_map(|s| *s).unwrap_or(0);
Ok((v, ()))
}
}
struct CountOk;
impl ReducerCollectAll<i64, (), std::io::Error> for CountOk {
fn reduce(
&self,
slots: &[Option<Result<i64, std::io::Error>>],
_deltas: &[Option<()>],
_winners: &[ChildIndex],
) -> Result<(i64, ()), EngineError> {
let count = slots.iter().filter(|s| matches!(s, Some(Ok(_)))).count();
Ok((count as i64, ()))
}
}
let mut reg: ReducerRegistry<i64, (), std::io::Error> = ReducerRegistry::new();
reg.register_fail_fast("first", Arc::new(FirstNonNone));
reg.register_collect_all("count_ok", Arc::new(CountOk));
let ff = reg.resolve(&"first".into(), FailPolicy::FailFast).unwrap();
assert!(matches!(ff, ReducerHandle::FailFast(_)));
let ca = reg
.resolve(&"count_ok".into(), FailPolicy::CollectAll)
.unwrap();
assert!(matches!(ca, ReducerHandle::CollectAll(_)));
let miss = reg.resolve(&"nope".into(), FailPolicy::FailFast);
assert!(matches!(miss, Err(EngineError::UnknownReducer { .. })));
}
struct FixedSuggester(&'static str);
impl Suggester for FixedSuggester {
fn suggest<'a>(&self, _q: &str, cands: &'a [&str]) -> Vec<Suggestion<'a>> {
cands
.iter()
.find(|c| **c == self.0)
.map(|c| Suggestion {
candidate: c,
score: 1.0,
})
.into_iter()
.collect()
}
}
#[test]
fn unknown_reducer_defaults_to_no_hint() {
struct Noop;
impl Reducer<i64, ()> for Noop {
fn reduce(
&self,
_s: &[Option<i64>],
_d: &[Option<()>],
_w: &[ChildIndex],
) -> Result<(i64, ()), EngineError> {
Ok((0, ()))
}
}
let mut reg: ReducerRegistry<i64, (), std::io::Error> = ReducerRegistry::new();
reg.register_fail_fast("first", Arc::new(Noop));
let miss = reg.resolve(&"frst".into(), FailPolicy::FailFast);
let err = match miss {
Err(e) => e,
Ok(_) => panic!("expected miss"),
};
assert_eq!(err.to_string(), "unknown reducer ReducerId(\"frst\")");
}
#[test]
fn unknown_reducer_with_suggester_appends_hint() {
struct Noop;
impl Reducer<i64, ()> for Noop {
fn reduce(
&self,
_s: &[Option<i64>],
_d: &[Option<()>],
_w: &[ChildIndex],
) -> Result<(i64, ()), EngineError> {
Ok((0, ()))
}
}
let mut reg: ReducerRegistry<i64, (), std::io::Error> = ReducerRegistry::new();
reg.register_fail_fast("first", Arc::new(Noop));
let reg = reg.with_suggester(Arc::new(FixedSuggester("first")));
let miss = reg.resolve(&"frst".into(), FailPolicy::FailFast);
let err = match miss {
Err(e) => e,
Ok(_) => panic!("expected miss"),
};
let msg = err.to_string();
assert!(
msg.contains("did you mean") && msg.contains("first"),
"expected hint, got: {msg}"
);
}
#[test]
fn unknown_op_defaults_to_no_hint() {
struct AddOp;
impl Op<i64> for AddOp {
fn apply(&self, _n: NodeId, args: &[i64]) -> Result<i64, EngineError> {
Ok(args.iter().sum())
}
}
let mut reg: OpRegistry<i64> = OpRegistry::new();
reg.register("add", Arc::new(AddOp));
let miss = reg.resolve(&"ad".into());
let err = match miss {
Err(e) => e,
Ok(_) => panic!("expected miss"),
};
assert_eq!(err.to_string(), "unknown op OpId(\"ad\")");
}
#[test]
fn unknown_op_with_suggester_appends_hint() {
struct AddOp;
impl Op<i64> for AddOp {
fn apply(&self, _n: NodeId, args: &[i64]) -> Result<i64, EngineError> {
Ok(args.iter().sum())
}
}
let mut reg: OpRegistry<i64> = OpRegistry::new();
reg.register("add", Arc::new(AddOp));
let reg = reg.with_suggester(Arc::new(FixedSuggester("add")));
let miss = reg.resolve(&"ad".into());
let err = match miss {
Err(e) => e,
Ok(_) => panic!("expected miss"),
};
let msg = err.to_string();
assert!(
msg.contains("did you mean") && msg.contains("add"),
"expected hint, got: {msg}"
);
}
}