1#![warn(missing_docs)]
27
28#[doc(hidden)]
31pub use serde_json;
32
33use std::borrow::Cow;
34use std::collections::HashMap;
35use std::fmt;
36use std::sync::Arc;
37use std::sync::atomic::{AtomicU64, Ordering};
38
39mod drive;
40mod engine;
41pub mod suggest;
42pub use drive::{AsyncEffectResolver, DriveOutcome, EffectResolver, drive, drive_async};
43pub use engine::{Ast, Engine, ExecError, LoopDecision, NodeKind};
44pub use suggest::{NoopSuggester, Suggester, SuggesterHandle, Suggestion, noop_handle};
45
46#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
54pub struct NodeId(pub u64);
55
56impl fmt::Display for NodeId {
57 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
58 write!(f, "n{}", self.0)
59 }
60}
61
62#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
64pub struct CallFrameId(pub u64);
65
66impl fmt::Display for CallFrameId {
67 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
68 write!(f, "f{}", self.0)
69 }
70}
71
72#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
74pub struct Iteration(pub u64);
75
76#[derive(Debug, Clone, PartialEq, Eq, Hash, Default)]
79pub struct Path(pub Vec<NodeId>);
80
81impl Path {
82 #[inline]
84 pub fn root() -> Self {
85 Path(Vec::new())
86 }
87
88 pub fn push(&self, node: NodeId) -> Self {
90 let mut next = self.0.clone();
91 next.push(node);
92 Path(next)
93 }
94
95 #[inline]
97 pub fn depth(&self) -> usize {
98 self.0.len()
99 }
100
101 pub fn tip(&self) -> Option<NodeId> {
103 self.0.last().copied()
104 }
105}
106
107impl fmt::Display for Path {
108 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
109 if self.0.is_empty() {
110 return write!(f, "/");
111 }
112 for id in &self.0 {
113 write!(f, "/{id}")?;
114 }
115 Ok(())
116 }
117}
118
119#[derive(Debug, Default)]
121pub struct IdGen {
122 next: AtomicU64,
123}
124
125impl IdGen {
126 pub const fn new() -> Self {
128 Self {
129 next: AtomicU64::new(0),
130 }
131 }
132
133 pub fn node(&self) -> NodeId {
135 NodeId(self.next.fetch_add(1, Ordering::Relaxed))
136 }
137
138 pub fn frame(&self) -> CallFrameId {
140 CallFrameId(self.next.fetch_add(1, Ordering::Relaxed))
141 }
142}
143
144#[derive(Debug, Clone, PartialEq, Eq)]
146pub struct NodeContext {
147 pub node: NodeId,
149 pub path: Path,
151 pub frame: Option<CallFrameId>,
153 pub depth: u32,
155 pub iteration: Option<Iteration>,
157}
158
159impl NodeContext {
160 pub fn at(node: NodeId, path: Path) -> Self {
162 Self {
163 node,
164 path,
165 frame: None,
166 depth: 0,
167 iteration: None,
168 }
169 }
170}
171
172impl fmt::Display for NodeContext {
173 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
174 write!(f, "{}", self.node)?;
175 if let Some(frame) = self.frame {
176 write!(f, " (frame {}, depth {})", frame, self.depth)?;
177 }
178 if let Some(it) = self.iteration {
179 write!(f, " iter {}", it.0)?;
180 }
181 write!(f, " at {}", self.path)
182 }
183}
184
185#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
195pub struct SuspensionId(pub u64);
196
197impl fmt::Display for SuspensionId {
198 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
199 write!(f, "s{}", self.0)
200 }
201}
202
203#[derive(Debug, Clone)]
205pub struct Pending {
206 pub id: SuspensionId,
208 pub reason: SuspendReason,
210 pub at: NodeContext,
212}
213
214#[derive(Debug, Clone)]
221#[non_exhaustive]
222pub enum SuspendReason {
223 Call {
225 spec: CallSpec,
227 },
228 Breakpoint,
230 Cooperative,
232 User {
234 tag: Cow<'static, str>,
236 },
237}
238
239impl fmt::Display for SuspendReason {
240 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
241 match self {
242 SuspendReason::Call { spec } => write!(f, "call({})", spec.label),
243 SuspendReason::Breakpoint => write!(f, "breakpoint"),
244 SuspendReason::Cooperative => write!(f, "cooperative"),
245 SuspendReason::User { tag } => write!(f, "user({tag})"),
246 }
247 }
248}
249
250#[derive(Debug, Clone)]
252pub struct CallSpec {
253 pub label: String,
256 pub payload: serde_json::Value,
259}
260
261#[derive(Debug, Clone)]
265#[non_exhaustive]
266pub enum Event {
267 VisitPre {
269 at: NodeContext,
271 },
272 VisitPost {
274 at: NodeContext,
276 },
277 FrameEnter {
279 at: NodeContext,
281 },
282 FrameLeave {
284 at: NodeContext,
286 },
287 IterationTick {
289 at: NodeContext,
291 },
292 Suspend {
294 at: NodeContext,
296 reason: SuspendReason,
298 },
299 Resume {
301 at: NodeContext,
303 },
304 Cancel {
307 id: SuspensionId,
309 },
310}
311
312pub trait EventSink {
314 fn emit(&mut self, event: &Event);
316}
317
318#[derive(Debug, Default)]
321pub struct NullSink;
322
323impl EventSink for NullSink {
324 #[inline]
325 fn emit(&mut self, _event: &Event) {}
326}
327
328#[derive(Debug, Default, Clone, Copy)]
333pub struct CountingSink {
334 pub visit_pre: u32,
336 pub visit_post: u32,
338 pub frame_enter: u32,
340 pub frame_leave: u32,
342 pub iteration_tick: u32,
344 pub suspend: u32,
346 pub resume: u32,
348}
349
350impl EventSink for CountingSink {
351 fn emit(&mut self, event: &Event) {
352 match event {
353 Event::VisitPre { .. } => self.visit_pre += 1,
354 Event::VisitPost { .. } => self.visit_post += 1,
355 Event::FrameEnter { .. } => self.frame_enter += 1,
356 Event::FrameLeave { .. } => self.frame_leave += 1,
357 Event::IterationTick { .. } => self.iteration_tick += 1,
358 Event::Suspend { .. } => self.suspend += 1,
359 Event::Resume { .. } => self.resume += 1,
360 _ => {}
361 }
362 }
363}
364
365impl CountingSink {
366 pub fn summarise(&self) -> String {
368 format!(
369 "pre={} post={} frame_enter={} frame_leave={} iter={} suspend={} resume={}",
370 self.visit_pre,
371 self.visit_post,
372 self.frame_enter,
373 self.frame_leave,
374 self.iteration_tick,
375 self.suspend,
376 self.resume,
377 )
378 }
379}
380
381#[derive(Debug, Default, Clone)]
388pub struct BufferingSink {
389 events: Vec<Event>,
390}
391
392impl BufferingSink {
393 pub fn new() -> Self {
395 Self { events: Vec::new() }
396 }
397
398 pub fn with_capacity(cap: usize) -> Self {
403 Self {
404 events: Vec::with_capacity(cap),
405 }
406 }
407
408 pub fn snapshot(&self) -> &[Event] {
410 &self.events
411 }
412
413 pub fn drain(&mut self) -> Vec<Event> {
415 std::mem::take(&mut self.events)
416 }
417
418 pub fn clear(&mut self) {
420 self.events.clear();
421 }
422
423 pub fn len(&self) -> usize {
425 self.events.len()
426 }
427
428 pub fn is_empty(&self) -> bool {
430 self.events.is_empty()
431 }
432}
433
434impl EventSink for BufferingSink {
435 fn emit(&mut self, event: &Event) {
436 self.events.push(event.clone());
437 }
438}
439
440#[derive(Debug, thiserror::Error, miette::Diagnostic)]
450#[non_exhaustive]
451pub enum EngineError {
452 #[error("evaluation aborted at {at}: {reason}")]
454 #[diagnostic(
455 code(dsl_kit::eval::aborted),
456 help(
457 "The interpreter returned an `Aborted` outcome. Inspect the reason and the node context to locate the abort site."
458 )
459 )]
460 Aborted {
461 at: NodeContext,
463 reason: String,
465 },
466
467 #[error("evaluator failed at {at}")]
469 #[diagnostic(
470 code(dsl_kit::eval::failed),
471 help(
472 "The interpreter returned an error while evaluating this node. The `#[source]` chain points at the underlying failure."
473 )
474 )]
475 EvalFailed {
476 at: NodeContext,
478 #[source]
480 source: Box<dyn std::error::Error + Send + Sync>,
481 },
482
483 #[error("malformed AST at {at}: {detail}")]
486 #[diagnostic(
487 code(dsl_kit::ast::malformed),
488 help(
489 "An AST invariant was violated. This usually means a hand-constructed tree omitted a required child."
490 )
491 )]
492 Malformed {
493 at: NodeContext,
495 detail: String,
497 },
498
499 #[error("stepper protocol violation at {at}: {detail}")]
502 #[diagnostic(
503 code(dsl_kit::stepper::protocol),
504 help(
505 "The stepper's suspend/resume contract was broken. Each `PendingEffect` leaf must be resolved exactly once before further steps observe its value."
506 )
507 )]
508 StepperProtocol {
509 at: NodeContext,
511 detail: String,
513 },
514
515 #[error("unknown suspension {id}")]
521 #[diagnostic(
522 code(dsl_kit::stepper::unknown_suspension),
523 help(
524 "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."
525 )
526 )]
527 UnknownSuspension {
528 id: SuspensionId,
530 },
531
532 #[error("unknown reducer {id:?}{hint}")]
535 #[diagnostic(
536 code(dsl_kit::reducer::unknown),
537 help(
538 "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."
539 )
540 )]
541 UnknownReducer {
542 id: ReducerId,
544 hint: String,
550 },
551
552 #[error("unknown op {id:?}{hint}")]
555 #[diagnostic(
556 code(dsl_kit::op::unknown),
557 help(
558 "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."
559 )
560 )]
561 UnknownOp {
562 id: OpId,
564 hint: String,
568 },
569}
570
571pub type EngineResult<T> = Result<T, EngineError>;
573
574#[derive(Debug, Clone, PartialEq, Eq)]
577pub struct ErrorCatalogEntry {
578 pub code: String,
580 pub help: String,
582}
583
584pub fn engine_error_catalog() -> Vec<ErrorCatalogEntry> {
586 use miette::Diagnostic;
587
588 fn ctx() -> NodeContext {
589 NodeContext::at(NodeId(0), Path::root())
590 }
591
592 let samples: Vec<EngineError> = vec![
593 EngineError::Aborted {
594 at: ctx(),
595 reason: String::new(),
596 },
597 EngineError::EvalFailed {
598 at: ctx(),
599 source: Box::new(std::io::Error::other("")),
600 },
601 EngineError::Malformed {
602 at: ctx(),
603 detail: String::new(),
604 },
605 EngineError::StepperProtocol {
606 at: ctx(),
607 detail: String::new(),
608 },
609 EngineError::UnknownSuspension {
610 id: SuspensionId(0),
611 },
612 EngineError::UnknownReducer {
613 id: ReducerId(String::new()),
614 hint: String::new(),
615 },
616 EngineError::UnknownOp {
617 id: OpId(String::new()),
618 hint: String::new(),
619 },
620 ];
621
622 samples
623 .into_iter()
624 .filter_map(|e| {
625 let code = e.code()?.to_string();
626 let help = e.help()?.to_string();
627 Some(ErrorCatalogEntry { code, help })
628 })
629 .collect()
630}
631
632#[derive(Debug, Clone)]
651pub enum StepOutcome<V> {
652 Ready,
654 Blocked {
658 newly_pending: smallvec::SmallVec<[Pending; 1]>,
660 },
661 Done(V),
663}
664
665pub trait Stepper {
671 type Value;
673 type Cursor;
675 type Delta;
678 type EffectError: std::error::Error + Send + Sync + 'static;
680 type Error: From<Self::EffectError> + std::error::Error + Send + Sync + 'static;
682
683 fn step(&mut self) -> Result<StepOutcome<Self::Value>, Self::Error>;
685
686 fn resolve(
692 &mut self,
693 id: SuspensionId,
694 result: Result<Self::Value, Self::EffectError>,
695 ) -> Result<(), Self::Error>;
696
697 fn pending(&self) -> &[Pending];
701
702 fn take_cancellations(&mut self) -> Vec<SuspensionId>;
706
707 fn frame_tree(&self) -> &FrameTree<Self::Value, Self::Cursor, Self::Delta, Self::EffectError>;
709
710 fn is_done(&self) -> bool;
712}
713
714pub type ChildIndex = usize;
718
719#[derive(Debug, Clone)]
721pub enum CancelReason {
722 ParPolicyFired,
725 SiblingFailed,
727}
728
729#[derive(Debug)]
731pub enum Frame<V, C, D, EE> {
732 Node {
734 node: NodeId,
736 env: EnvRef<D>,
738 cursor: C,
740 },
741 Par(ParFrame<V, D, EE>),
743 Scope {
745 label: String,
747 env: EnvRef<D>,
749 },
750 PendingEffect {
752 id: SuspensionId,
754 },
755 Value(V),
758 Cancelled {
761 reason: CancelReason,
763 },
764}
765
766#[derive(Debug)]
770pub struct FrameTree<V, C, D, EE> {
771 pub root: Frame<V, C, D, EE>,
773 pub kids: Vec<FrameTree<V, C, D, EE>>,
775}
776
777#[derive(Debug)]
783pub struct ParFrame<V, D, EE> {
784 pub policy: JoinPolicy,
786 pub slots: Vec<Option<V>>,
792 pub failures: Vec<Option<EE>>,
796 pub deltas: Vec<Option<D>>,
798 pub completion_order: Vec<ChildIndex>,
800 pub reducer_id: ReducerId,
802 pub reducer: ReducerHandle<V, D, EE>,
805 pub joined: bool,
807}
808
809#[derive(Debug, Clone, Copy)]
814pub struct JoinPolicy {
815 pub shape: JoinShape,
817 pub fail: FailPolicy,
819}
820
821#[derive(Debug, Clone, Copy)]
823pub enum JoinShape {
824 All,
826 Any,
828 FirstK(usize),
831}
832
833#[derive(Debug, Clone, Copy)]
835pub enum FailPolicy {
836 FailFast,
838 CollectAll,
841}
842
843#[derive(Debug, Clone, PartialEq, Eq, Hash)]
847pub struct ReducerId(pub String);
848
849impl fmt::Display for ReducerId {
850 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
851 write!(f, "{}", self.0)
852 }
853}
854
855impl From<&str> for ReducerId {
856 fn from(s: &str) -> Self {
857 ReducerId(s.to_string())
858 }
859}
860
861impl From<String> for ReducerId {
862 fn from(s: String) -> Self {
863 ReducerId(s)
864 }
865}
866
867pub trait Reducer<V, D>: Send + Sync {
869 fn reduce(
871 &self,
872 slots: &[Option<V>],
873 deltas: &[Option<D>],
874 winners: &[ChildIndex],
875 ) -> Result<(V, D), EngineError>;
876}
877
878pub trait ReducerCollectAll<V, D, EffectError>: Send + Sync {
880 fn reduce(
883 &self,
884 slots: &[Option<Result<V, EffectError>>],
885 deltas: &[Option<D>],
886 winners: &[ChildIndex],
887 ) -> Result<(V, D), EngineError>;
888}
889
890pub enum ReducerHandle<V, D, EE> {
897 FailFast(Arc<dyn Reducer<V, D>>),
899 CollectAll(Arc<dyn ReducerCollectAll<V, D, EE>>),
901}
902
903impl<V, D, EE> fmt::Debug for ReducerHandle<V, D, EE> {
904 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
905 match self {
906 ReducerHandle::FailFast(_) => f.write_str("ReducerHandle::FailFast(..)"),
907 ReducerHandle::CollectAll(_) => f.write_str("ReducerHandle::CollectAll(..)"),
908 }
909 }
910}
911
912impl<V, D, EE> Clone for ReducerHandle<V, D, EE> {
913 fn clone(&self) -> Self {
914 match self {
915 ReducerHandle::FailFast(a) => ReducerHandle::FailFast(a.clone()),
916 ReducerHandle::CollectAll(a) => ReducerHandle::CollectAll(a.clone()),
917 }
918 }
919}
920
921pub struct ReducerRegistry<V, D, EffectError> {
927 fail_fast: HashMap<ReducerId, Arc<dyn Reducer<V, D>>>,
928 collect_all: HashMap<ReducerId, Arc<dyn ReducerCollectAll<V, D, EffectError>>>,
929 suggester: crate::suggest::SuggesterHandle,
930}
931
932impl<V, D, EE> Default for ReducerRegistry<V, D, EE> {
933 fn default() -> Self {
934 Self::new()
935 }
936}
937
938impl<V, D, EE> ReducerRegistry<V, D, EE> {
939 pub fn new() -> Self {
941 Self {
942 fail_fast: HashMap::new(),
943 collect_all: HashMap::new(),
944 suggester: crate::suggest::noop_handle(),
945 }
946 }
947
948 pub fn with_suggester(mut self, suggester: crate::suggest::SuggesterHandle) -> Self {
958 self.suggester = suggester;
959 self
960 }
961
962 pub fn register_fail_fast(
964 &mut self,
965 id: impl Into<ReducerId>,
966 reducer: Arc<dyn Reducer<V, D>>,
967 ) {
968 self.fail_fast.insert(id.into(), reducer);
969 }
970
971 pub fn register_collect_all(
973 &mut self,
974 id: impl Into<ReducerId>,
975 reducer: Arc<dyn ReducerCollectAll<V, D, EE>>,
976 ) {
977 self.collect_all.insert(id.into(), reducer);
978 }
979
980 pub fn resolve(
986 &self,
987 id: &ReducerId,
988 fail: FailPolicy,
989 ) -> Result<ReducerHandle<V, D, EE>, EngineError> {
990 let miss = || {
991 let names: Vec<&str> = match fail {
995 FailPolicy::FailFast => self.fail_fast.keys().map(|k| k.0.as_str()).collect(),
996 FailPolicy::CollectAll => self.collect_all.keys().map(|k| k.0.as_str()).collect(),
997 };
998 let hint = self
999 .suggester
1000 .enrich_unknown(&id.0, &names)
1001 .map(|h| format!(" ({h})"))
1002 .unwrap_or_default();
1003 EngineError::UnknownReducer {
1004 id: id.clone(),
1005 hint,
1006 }
1007 };
1008 match fail {
1009 FailPolicy::FailFast => self
1010 .fail_fast
1011 .get(id)
1012 .cloned()
1013 .map(ReducerHandle::FailFast)
1014 .ok_or_else(miss),
1015 FailPolicy::CollectAll => self
1016 .collect_all
1017 .get(id)
1018 .cloned()
1019 .map(ReducerHandle::CollectAll)
1020 .ok_or_else(miss),
1021 }
1022 }
1023}
1024
1025#[derive(Debug, Clone, PartialEq, Eq, Hash)]
1029pub struct OpId(pub String);
1030
1031impl fmt::Display for OpId {
1032 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1033 write!(f, "{}", self.0)
1034 }
1035}
1036
1037impl From<&str> for OpId {
1038 fn from(s: &str) -> Self {
1039 OpId(s.to_string())
1040 }
1041}
1042
1043impl From<String> for OpId {
1044 fn from(s: String) -> Self {
1045 OpId(s)
1046 }
1047}
1048
1049pub trait Op<V>: Send + Sync {
1058 fn apply(&self, node: NodeId, args: &[V]) -> Result<V, EngineError>;
1063}
1064
1065pub type OpHandle<V> = Arc<dyn Op<V>>;
1067
1068pub struct OpRegistry<V> {
1080 ops: HashMap<OpId, OpHandle<V>>,
1081 suggester: crate::suggest::SuggesterHandle,
1082}
1083
1084impl<V> Default for OpRegistry<V> {
1085 fn default() -> Self {
1086 Self::new()
1087 }
1088}
1089
1090impl<V> OpRegistry<V> {
1091 pub fn new() -> Self {
1093 Self {
1094 ops: HashMap::new(),
1095 suggester: crate::suggest::noop_handle(),
1096 }
1097 }
1098
1099 pub fn with_suggester(mut self, suggester: crate::suggest::SuggesterHandle) -> Self {
1108 self.suggester = suggester;
1109 self
1110 }
1111
1112 pub fn register(&mut self, id: impl Into<OpId>, op: OpHandle<V>) {
1114 self.ops.insert(id.into(), op);
1115 }
1116
1117 pub fn resolve(&self, id: &OpId) -> Result<OpHandle<V>, EngineError> {
1120 self.ops.get(id).cloned().ok_or_else(|| {
1121 let names: Vec<&str> = self.ops.keys().map(|k| k.0.as_str()).collect();
1122 let hint = self
1123 .suggester
1124 .enrich_unknown(&id.0, &names)
1125 .map(|h| format!(" ({h})"))
1126 .unwrap_or_default();
1127 EngineError::UnknownOp {
1128 id: id.clone(),
1129 hint,
1130 }
1131 })
1132 }
1133}
1134
1135pub trait DslExec: Walk {
1146 type LitValue: Clone + fmt::Debug;
1149
1150 fn exec_kind(&self) -> NodeKind;
1152
1153 fn exec_literal(&self) -> Option<Self::LitValue>;
1155}
1156
1157pub trait DslSemantics {
1162 type Value: Clone + fmt::Debug;
1164 type Delta: Clone + Default + fmt::Debug;
1167 type EffectError: std::error::Error + Clone + Send + Sync + 'static;
1169 type Cursor: Clone + fmt::Debug + Default;
1171
1172 fn unit_value(&self) -> Self::Value;
1174
1175 fn truthy(&self, _value: &Self::Value) -> Option<bool> {
1177 None
1178 }
1179
1180 fn continue_loop(&self, _node: NodeId, _last: &Self::Value, _iteration: usize) -> LoopDecision {
1182 LoopDecision::Break
1183 }
1184
1185 fn bind_delta(&self, _name: &str, _value: &Self::Value) -> Option<Self::Delta> {
1187 None
1188 }
1189
1190 fn lookup(&self, _delta: &Self::Delta, _name: &str) -> Option<Self::Value> {
1192 None
1193 }
1194}
1195
1196pub struct DerivedAst<'a, N, S> {
1203 root: &'a N,
1204 by_id: HashMap<NodeId, &'a N>,
1205 sem: S,
1206}
1207
1208impl<'a, N: DslExec, S> DerivedAst<'a, N, S> {
1209 pub fn new(root: &'a N, sem: S) -> Self {
1211 fn collect<'a, N: Walk>(node: &'a N, map: &mut HashMap<NodeId, &'a N>) {
1212 map.insert(node.node_id(), node);
1213 for child in node.children() {
1214 collect(child, map);
1215 }
1216 }
1217 let mut by_id = HashMap::new();
1218 collect(root, &mut by_id);
1219 Self { root, by_id, sem }
1220 }
1221
1222 fn node(&self, id: NodeId) -> &'a N {
1223 self.by_id.get(&id).copied().expect("unknown NodeId")
1224 }
1225}
1226
1227impl<N, S> Ast for DerivedAst<'_, N, S>
1228where
1229 N: DslExec,
1230 S: DslSemantics,
1231 S::Value: From<N::LitValue>,
1232{
1233 type Value = S::Value;
1234 type Delta = S::Delta;
1235 type EffectError = S::EffectError;
1236 type Cursor = S::Cursor;
1237
1238 fn root(&self) -> NodeId {
1239 self.root.node_id()
1240 }
1241
1242 fn node_kind(&self, id: NodeId) -> NodeKind {
1243 self.node(id).exec_kind()
1244 }
1245
1246 fn unit_value(&self) -> Self::Value {
1247 self.sem.unit_value()
1248 }
1249
1250 fn truthy(&self, value: &Self::Value) -> Option<bool> {
1251 self.sem.truthy(value)
1252 }
1253
1254 fn continue_loop(&self, node: NodeId, last: &Self::Value, iteration: usize) -> LoopDecision {
1255 self.sem.continue_loop(node, last, iteration)
1256 }
1257
1258 fn bind_delta(&self, name: &str, value: &Self::Value) -> Option<Self::Delta> {
1259 self.sem.bind_delta(name, value)
1260 }
1261
1262 fn lookup(&self, delta: &Self::Delta, name: &str) -> Option<Self::Value> {
1263 self.sem.lookup(delta, name)
1264 }
1265
1266 fn literal(&self, node: NodeId) -> Option<Self::Value> {
1267 self.node(node).exec_literal().map(S::Value::from)
1268 }
1269}
1270
1271#[derive(Debug)]
1278pub struct EnvRef<D>(pub Arc<Env<D>>);
1279
1280impl<D> Clone for EnvRef<D> {
1281 fn clone(&self) -> Self {
1282 EnvRef(self.0.clone())
1283 }
1284}
1285
1286#[derive(Debug)]
1289pub struct Env<D> {
1290 pub delta: D,
1292 pub parent: Option<Arc<Env<D>>>,
1294}
1295
1296pub trait DslNode {
1300 fn node_id(&self) -> NodeId;
1302
1303 fn variant_name(&self) -> &'static str;
1314}
1315
1316#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
1320pub struct BreakpointId(pub u64);
1321
1322impl fmt::Display for BreakpointId {
1323 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1324 write!(f, "bp{}", self.0)
1325 }
1326}
1327
1328#[derive(Debug, Clone, PartialEq, Eq)]
1331pub enum BreakCondition {
1332 Node(NodeId),
1334 PathPrefix(Path),
1336 PathExact(Path),
1338 DepthAtLeast(u32),
1340 DepthAtMost(u32),
1342 DepthEquals(u32),
1344 Iteration(u64),
1346 CallFrame(CallFrameId),
1348 Any(Vec<BreakCondition>),
1350 All(Vec<BreakCondition>),
1352 Not(Box<BreakCondition>),
1354 Always,
1356 Never,
1358}
1359
1360impl BreakCondition {
1361 pub fn at_node(id: NodeId) -> Self {
1363 Self::Node(id)
1364 }
1365
1366 pub fn under_path(path: Path) -> Self {
1368 Self::PathPrefix(path)
1369 }
1370
1371 pub fn at_path(path: Path) -> Self {
1373 Self::PathExact(path)
1374 }
1375
1376 pub fn at_depth_at_least(n: u32) -> Self {
1378 Self::DepthAtLeast(n)
1379 }
1380
1381 pub fn at_depth_at_most(n: u32) -> Self {
1383 Self::DepthAtMost(n)
1384 }
1385
1386 pub fn at_depth(n: u32) -> Self {
1388 Self::DepthEquals(n)
1389 }
1390
1391 pub fn at_iteration(n: u64) -> Self {
1393 Self::Iteration(n)
1394 }
1395
1396 pub fn in_call_frame(frame: CallFrameId) -> Self {
1398 Self::CallFrame(frame)
1399 }
1400
1401 pub fn and(self, other: Self) -> Self {
1403 match (self, other) {
1404 (Self::All(mut xs), Self::All(ys)) => {
1405 xs.extend(ys);
1406 Self::All(xs)
1407 }
1408 (Self::All(mut xs), other) => {
1409 xs.push(other);
1410 Self::All(xs)
1411 }
1412 (this, Self::All(mut ys)) => {
1413 ys.insert(0, this);
1414 Self::All(ys)
1415 }
1416 (this, other) => Self::All(vec![this, other]),
1417 }
1418 }
1419
1420 pub fn or(self, other: Self) -> Self {
1422 match (self, other) {
1423 (Self::Any(mut xs), Self::Any(ys)) => {
1424 xs.extend(ys);
1425 Self::Any(xs)
1426 }
1427 (Self::Any(mut xs), other) => {
1428 xs.push(other);
1429 Self::Any(xs)
1430 }
1431 (this, Self::Any(mut ys)) => {
1432 ys.insert(0, this);
1433 Self::Any(ys)
1434 }
1435 (this, other) => Self::Any(vec![this, other]),
1436 }
1437 }
1438
1439 pub fn matches(&self, ctx: &NodeContext) -> bool {
1441 match self {
1442 Self::Node(id) => ctx.node == *id,
1443 Self::PathPrefix(prefix) => {
1444 ctx.path.0.len() >= prefix.0.len() && ctx.path.0[..prefix.0.len()] == prefix.0[..]
1445 }
1446 Self::PathExact(path) => ctx.path == *path,
1447 Self::DepthAtLeast(n) => ctx.depth >= *n,
1448 Self::DepthAtMost(n) => ctx.depth <= *n,
1449 Self::DepthEquals(n) => ctx.depth == *n,
1450 Self::Iteration(n) => ctx.iteration.map(|i| i.0 == *n).unwrap_or(false),
1451 Self::CallFrame(frame) => ctx.frame == Some(*frame),
1452 Self::Any(children) => children.iter().any(|c| c.matches(ctx)),
1453 Self::All(children) => children.iter().all(|c| c.matches(ctx)),
1454 Self::Not(inner) => !inner.matches(ctx),
1455 Self::Always => true,
1456 Self::Never => false,
1457 }
1458 }
1459}
1460
1461impl std::ops::Not for BreakCondition {
1462 type Output = Self;
1463
1464 fn not(self) -> Self {
1466 Self::Not(Box::new(self))
1467 }
1468}
1469
1470#[derive(Debug, Default)]
1472pub struct BreakpointSet {
1473 next: u64,
1474 entries: Vec<(BreakpointId, BreakCondition)>,
1475}
1476
1477impl BreakpointSet {
1478 pub fn new() -> Self {
1480 Self {
1481 next: 1,
1482 entries: Vec::new(),
1483 }
1484 }
1485
1486 pub fn add(&mut self, condition: BreakCondition) -> BreakpointId {
1488 let id = BreakpointId(self.next);
1489 self.next += 1;
1490 self.entries.push((id, condition));
1491 id
1492 }
1493
1494 pub fn remove(&mut self, id: BreakpointId) -> bool {
1496 let before = self.entries.len();
1497 self.entries.retain(|(entry_id, _)| *entry_id != id);
1498 self.entries.len() != before
1499 }
1500
1501 pub fn matches(&self, ctx: &NodeContext) -> Vec<BreakpointId> {
1503 self.entries
1504 .iter()
1505 .filter(|(_, cond)| cond.matches(ctx))
1506 .map(|(id, _)| *id)
1507 .collect()
1508 }
1509
1510 pub fn is_empty(&self) -> bool {
1512 self.entries.is_empty()
1513 }
1514
1515 pub fn len(&self) -> usize {
1517 self.entries.len()
1518 }
1519
1520 pub fn iter(&self) -> impl Iterator<Item = (BreakpointId, &BreakCondition)> {
1522 self.entries.iter().map(|(id, c)| (*id, c))
1523 }
1524}
1525
1526#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1530pub enum Phase {
1531 Pre,
1533 Post,
1535}
1536
1537pub trait Walk: DslNode + Sized {
1539 fn children(&self) -> Vec<&Self>;
1541
1542 fn walk<F>(&self, visitor: &mut F)
1544 where
1545 F: FnMut(&Self, Phase),
1546 {
1547 visitor(self, Phase::Pre);
1548 for child in self.children() {
1549 child.walk(visitor);
1550 }
1551 visitor(self, Phase::Post);
1552 }
1553
1554 fn walk_until<F, T>(&self, visitor: &mut F) -> Option<T>
1556 where
1557 F: FnMut(&Self, Phase) -> Option<T>,
1558 {
1559 if let Some(t) = visitor(self, Phase::Pre) {
1560 return Some(t);
1561 }
1562 for child in self.children() {
1563 if let Some(t) = child.walk_until(visitor) {
1564 return Some(t);
1565 }
1566 }
1567 visitor(self, Phase::Post)
1568 }
1569
1570 fn find_by_id(&self, target: NodeId) -> Option<&Self> {
1572 self.walk_until(&mut |node, phase| {
1573 if phase == Phase::Pre && node.node_id() == target {
1574 Some(node as *const Self)
1575 } else {
1576 None
1577 }
1578 })
1579 .map(|ptr| unsafe { &*ptr })
1580 }
1581}
1582
1583pub trait WalkMut: DslNode + Sized {
1585 fn children_mut(&mut self) -> Vec<&mut Self>;
1587
1588 fn walk_mut<F>(&mut self, visitor: &mut F)
1590 where
1591 F: FnMut(&mut Self, Phase),
1592 {
1593 visitor(self, Phase::Pre);
1594 for child in self.children_mut() {
1595 child.walk_mut(visitor);
1596 }
1597 visitor(self, Phase::Post);
1598 }
1599}
1600
1601#[cfg(test)]
1602mod tests {
1603 use super::*;
1604
1605 #[test]
1606 fn path_push_extends_depth() {
1607 let ids = IdGen::new();
1608 let a = ids.node();
1609 let b = ids.node();
1610
1611 let root = Path::root();
1612 assert_eq!(root.depth(), 0);
1613
1614 let one = root.push(a);
1615 assert_eq!(one.depth(), 1);
1616
1617 let two = one.push(b);
1618 assert_eq!(two.depth(), 2);
1619 assert_eq!(two.tip(), Some(b));
1620 }
1621
1622 #[test]
1623 fn id_generator_yields_distinct_ids() {
1624 let ids = IdGen::new();
1625 let a = ids.node();
1626 let b = ids.node();
1627 assert_ne!(a, b);
1628 }
1629
1630 #[test]
1631 fn null_sink_accepts_events() {
1632 let mut sink = NullSink;
1633 let event = Event::VisitPre {
1634 at: NodeContext::at(NodeId(0), Path::root()),
1635 };
1636 sink.emit(&event);
1637 }
1638
1639 fn ctx_at(node: NodeId, path: Path, depth: u32) -> NodeContext {
1640 NodeContext {
1641 node,
1642 path,
1643 frame: None,
1644 depth,
1645 iteration: None,
1646 }
1647 }
1648
1649 #[test]
1650 fn breakpoint_node_matches_exact_id() {
1651 let cond = BreakCondition::at_node(NodeId(7));
1652 assert!(cond.matches(&ctx_at(NodeId(7), Path::root().push(NodeId(7)), 1)));
1653 assert!(!cond.matches(&ctx_at(NodeId(8), Path::root().push(NodeId(8)), 1)));
1654 }
1655
1656 #[test]
1657 fn breakpoint_set_add_matches_remove() {
1658 let mut set = BreakpointSet::new();
1659 let hit = set.add(BreakCondition::at_node(NodeId(4)));
1660 let miss = set.add(BreakCondition::at_node(NodeId(99)));
1661
1662 let ctx = ctx_at(NodeId(4), Path::root().push(NodeId(4)), 1);
1663 assert_eq!(set.matches(&ctx), vec![hit]);
1664
1665 assert!(set.remove(hit));
1666 assert!(set.matches(&ctx).is_empty());
1667 assert_eq!(set.len(), 1);
1668 assert!(set.iter().any(|(id, _)| id == miss));
1669 }
1670
1671 #[test]
1672 fn engine_error_carries_stable_code() {
1673 let err = EngineError::Aborted {
1674 at: NodeContext::at(NodeId(1), Path::root().push(NodeId(1))),
1675 reason: "user requested".into(),
1676 };
1677 use miette::Diagnostic;
1678 assert_eq!(
1679 err.code().map(|c| c.to_string()).as_deref(),
1680 Some("dsl_kit::eval::aborted")
1681 );
1682 }
1683
1684 #[test]
1685 fn engine_error_catalog_covers_every_variant() {
1686 let entries = engine_error_catalog();
1687 let codes: Vec<&str> = entries.iter().map(|e| e.code.as_str()).collect();
1688 assert!(codes.contains(&"dsl_kit::eval::aborted"));
1689 assert!(codes.contains(&"dsl_kit::eval::failed"));
1690 assert!(codes.contains(&"dsl_kit::ast::malformed"));
1691 assert!(codes.contains(&"dsl_kit::stepper::protocol"));
1692 assert!(codes.contains(&"dsl_kit::stepper::unknown_suspension"));
1693 assert!(codes.contains(&"dsl_kit::reducer::unknown"));
1694 for entry in &entries {
1695 assert!(!entry.help.is_empty(), "help empty for {}", entry.code);
1696 }
1697 }
1698
1699 #[test]
1700 fn reducer_id_from_str_and_string() {
1701 let a: ReducerId = "foo".into();
1702 let b: ReducerId = String::from("foo").into();
1703 assert_eq!(a, b);
1704 }
1705
1706 #[test]
1707 fn reducer_registry_resolves_fail_fast_and_collect_all_independently() {
1708 struct FirstNonNone;
1711 impl Reducer<i64, ()> for FirstNonNone {
1712 fn reduce(
1713 &self,
1714 slots: &[Option<i64>],
1715 _deltas: &[Option<()>],
1716 _winners: &[ChildIndex],
1717 ) -> Result<(i64, ()), EngineError> {
1718 let v = slots.iter().find_map(|s| *s).unwrap_or(0);
1719 Ok((v, ()))
1720 }
1721 }
1722
1723 struct CountOk;
1725 impl ReducerCollectAll<i64, (), std::io::Error> for CountOk {
1726 fn reduce(
1727 &self,
1728 slots: &[Option<Result<i64, std::io::Error>>],
1729 _deltas: &[Option<()>],
1730 _winners: &[ChildIndex],
1731 ) -> Result<(i64, ()), EngineError> {
1732 let count = slots.iter().filter(|s| matches!(s, Some(Ok(_)))).count();
1733 Ok((count as i64, ()))
1734 }
1735 }
1736
1737 let mut reg: ReducerRegistry<i64, (), std::io::Error> = ReducerRegistry::new();
1738 reg.register_fail_fast("first", Arc::new(FirstNonNone));
1739 reg.register_collect_all("count_ok", Arc::new(CountOk));
1740
1741 let ff = reg.resolve(&"first".into(), FailPolicy::FailFast).unwrap();
1742 assert!(matches!(ff, ReducerHandle::FailFast(_)));
1743 let ca = reg
1744 .resolve(&"count_ok".into(), FailPolicy::CollectAll)
1745 .unwrap();
1746 assert!(matches!(ca, ReducerHandle::CollectAll(_)));
1747
1748 let miss = reg.resolve(&"nope".into(), FailPolicy::FailFast);
1749 assert!(matches!(miss, Err(EngineError::UnknownReducer { .. })));
1750 }
1751
1752 struct FixedSuggester(&'static str);
1758 impl Suggester for FixedSuggester {
1759 fn suggest<'a>(&self, _q: &str, cands: &'a [&str]) -> Vec<Suggestion<'a>> {
1760 cands
1761 .iter()
1762 .find(|c| **c == self.0)
1763 .map(|c| Suggestion {
1764 candidate: c,
1765 score: 1.0,
1766 })
1767 .into_iter()
1768 .collect()
1769 }
1770 }
1771
1772 #[test]
1773 fn unknown_reducer_defaults_to_no_hint() {
1774 struct Noop;
1777 impl Reducer<i64, ()> for Noop {
1778 fn reduce(
1779 &self,
1780 _s: &[Option<i64>],
1781 _d: &[Option<()>],
1782 _w: &[ChildIndex],
1783 ) -> Result<(i64, ()), EngineError> {
1784 Ok((0, ()))
1785 }
1786 }
1787 let mut reg: ReducerRegistry<i64, (), std::io::Error> = ReducerRegistry::new();
1788 reg.register_fail_fast("first", Arc::new(Noop));
1789 let miss = reg.resolve(&"frst".into(), FailPolicy::FailFast);
1790 let err = match miss {
1791 Err(e) => e,
1792 Ok(_) => panic!("expected miss"),
1793 };
1794 assert_eq!(err.to_string(), "unknown reducer ReducerId(\"frst\")");
1798 }
1799
1800 #[test]
1801 fn unknown_reducer_with_suggester_appends_hint() {
1802 struct Noop;
1803 impl Reducer<i64, ()> for Noop {
1804 fn reduce(
1805 &self,
1806 _s: &[Option<i64>],
1807 _d: &[Option<()>],
1808 _w: &[ChildIndex],
1809 ) -> Result<(i64, ()), EngineError> {
1810 Ok((0, ()))
1811 }
1812 }
1813 let mut reg: ReducerRegistry<i64, (), std::io::Error> = ReducerRegistry::new();
1814 reg.register_fail_fast("first", Arc::new(Noop));
1815 let reg = reg.with_suggester(Arc::new(FixedSuggester("first")));
1816 let miss = reg.resolve(&"frst".into(), FailPolicy::FailFast);
1817 let err = match miss {
1818 Err(e) => e,
1819 Ok(_) => panic!("expected miss"),
1820 };
1821 let msg = err.to_string();
1822 assert!(
1823 msg.contains("did you mean") && msg.contains("first"),
1824 "expected hint, got: {msg}"
1825 );
1826 }
1827
1828 #[test]
1829 fn unknown_op_defaults_to_no_hint() {
1830 struct AddOp;
1831 impl Op<i64> for AddOp {
1832 fn apply(&self, _n: NodeId, args: &[i64]) -> Result<i64, EngineError> {
1833 Ok(args.iter().sum())
1834 }
1835 }
1836 let mut reg: OpRegistry<i64> = OpRegistry::new();
1837 reg.register("add", Arc::new(AddOp));
1838 let miss = reg.resolve(&"ad".into());
1839 let err = match miss {
1840 Err(e) => e,
1841 Ok(_) => panic!("expected miss"),
1842 };
1843 assert_eq!(err.to_string(), "unknown op OpId(\"ad\")");
1844 }
1845
1846 #[test]
1847 fn unknown_op_with_suggester_appends_hint() {
1848 struct AddOp;
1849 impl Op<i64> for AddOp {
1850 fn apply(&self, _n: NodeId, args: &[i64]) -> Result<i64, EngineError> {
1851 Ok(args.iter().sum())
1852 }
1853 }
1854 let mut reg: OpRegistry<i64> = OpRegistry::new();
1855 reg.register("add", Arc::new(AddOp));
1856 let reg = reg.with_suggester(Arc::new(FixedSuggester("add")));
1857 let miss = reg.resolve(&"ad".into());
1858 let err = match miss {
1859 Err(e) => e,
1860 Ok(_) => panic!("expected miss"),
1861 };
1862 let msg = err.to_string();
1863 assert!(
1864 msg.contains("did you mean") && msg.contains("add"),
1865 "expected hint, got: {msg}"
1866 );
1867 }
1868}