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::{
45 Applicability, FixSuggestion, NoopSuggester, PatchPart, Suggester, SuggesterHandle, Suggestion,
46 noop_handle,
47};
48
49#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
57pub struct NodeId(pub u64);
58
59impl fmt::Display for NodeId {
60 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
61 write!(f, "n{}", self.0)
62 }
63}
64
65#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
67pub struct CallFrameId(pub u64);
68
69impl fmt::Display for CallFrameId {
70 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
71 write!(f, "f{}", self.0)
72 }
73}
74
75#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
77pub struct Iteration(pub u64);
78
79#[derive(Debug, Clone, PartialEq, Eq, Hash, Default)]
82pub struct Path(pub Vec<NodeId>);
83
84impl Path {
85 #[inline]
87 pub fn root() -> Self {
88 Path(Vec::new())
89 }
90
91 pub fn push(&self, node: NodeId) -> Self {
93 let mut next = self.0.clone();
94 next.push(node);
95 Path(next)
96 }
97
98 #[inline]
100 pub fn depth(&self) -> usize {
101 self.0.len()
102 }
103
104 pub fn tip(&self) -> Option<NodeId> {
106 self.0.last().copied()
107 }
108}
109
110impl fmt::Display for Path {
111 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
112 if self.0.is_empty() {
113 return write!(f, "/");
114 }
115 for id in &self.0 {
116 write!(f, "/{id}")?;
117 }
118 Ok(())
119 }
120}
121
122#[derive(Debug, Default)]
124pub struct IdGen {
125 next: AtomicU64,
126}
127
128impl IdGen {
129 pub const fn new() -> Self {
131 Self {
132 next: AtomicU64::new(0),
133 }
134 }
135
136 pub fn node(&self) -> NodeId {
138 NodeId(self.next.fetch_add(1, Ordering::Relaxed))
139 }
140
141 pub fn frame(&self) -> CallFrameId {
143 CallFrameId(self.next.fetch_add(1, Ordering::Relaxed))
144 }
145}
146
147#[derive(Debug, Clone, PartialEq, Eq)]
149pub struct NodeContext {
150 pub node: NodeId,
152 pub path: Path,
154 pub frame: Option<CallFrameId>,
156 pub depth: u32,
158 pub iteration: Option<Iteration>,
160}
161
162impl NodeContext {
163 pub fn at(node: NodeId, path: Path) -> Self {
165 Self {
166 node,
167 path,
168 frame: None,
169 depth: 0,
170 iteration: None,
171 }
172 }
173}
174
175impl fmt::Display for NodeContext {
176 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
177 write!(f, "{}", self.node)?;
178 if let Some(frame) = self.frame {
179 write!(f, " (frame {}, depth {})", frame, self.depth)?;
180 }
181 if let Some(it) = self.iteration {
182 write!(f, " iter {}", it.0)?;
183 }
184 write!(f, " at {}", self.path)
185 }
186}
187
188#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
198pub struct SuspensionId(pub u64);
199
200impl fmt::Display for SuspensionId {
201 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
202 write!(f, "s{}", self.0)
203 }
204}
205
206#[derive(Debug, Clone)]
208pub struct Pending {
209 pub id: SuspensionId,
211 pub reason: SuspendReason,
213 pub at: NodeContext,
215}
216
217#[derive(Debug, Clone)]
224#[non_exhaustive]
225pub enum SuspendReason {
226 Call {
228 spec: CallSpec,
230 },
231 Breakpoint,
233 Cooperative,
235 User {
237 tag: Cow<'static, str>,
239 },
240}
241
242impl fmt::Display for SuspendReason {
243 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
244 match self {
245 SuspendReason::Call { spec } => write!(f, "call({})", spec.label),
246 SuspendReason::Breakpoint => write!(f, "breakpoint"),
247 SuspendReason::Cooperative => write!(f, "cooperative"),
248 SuspendReason::User { tag } => write!(f, "user({tag})"),
249 }
250 }
251}
252
253#[derive(Debug, Clone)]
255pub struct CallSpec {
256 pub label: String,
259 pub payload: serde_json::Value,
262}
263
264#[derive(Debug, Clone)]
268#[non_exhaustive]
269pub enum Event {
270 VisitPre {
272 at: NodeContext,
274 },
275 VisitPost {
277 at: NodeContext,
279 },
280 FrameEnter {
282 at: NodeContext,
284 },
285 FrameLeave {
287 at: NodeContext,
289 },
290 IterationTick {
292 at: NodeContext,
294 },
295 Suspend {
297 at: NodeContext,
299 reason: SuspendReason,
301 },
302 Resume {
304 at: NodeContext,
306 },
307 Cancel {
310 id: SuspensionId,
312 },
313}
314
315pub trait EventSink {
317 fn emit(&mut self, event: &Event);
319}
320
321#[derive(Debug, Default)]
324pub struct NullSink;
325
326impl EventSink for NullSink {
327 #[inline]
328 fn emit(&mut self, _event: &Event) {}
329}
330
331#[derive(Debug, Default, Clone, Copy)]
336pub struct CountingSink {
337 pub visit_pre: u32,
339 pub visit_post: u32,
341 pub frame_enter: u32,
343 pub frame_leave: u32,
345 pub iteration_tick: u32,
347 pub suspend: u32,
349 pub resume: u32,
351}
352
353impl EventSink for CountingSink {
354 fn emit(&mut self, event: &Event) {
355 match event {
356 Event::VisitPre { .. } => self.visit_pre += 1,
357 Event::VisitPost { .. } => self.visit_post += 1,
358 Event::FrameEnter { .. } => self.frame_enter += 1,
359 Event::FrameLeave { .. } => self.frame_leave += 1,
360 Event::IterationTick { .. } => self.iteration_tick += 1,
361 Event::Suspend { .. } => self.suspend += 1,
362 Event::Resume { .. } => self.resume += 1,
363 _ => {}
364 }
365 }
366}
367
368impl CountingSink {
369 pub fn summarise(&self) -> String {
371 format!(
372 "pre={} post={} frame_enter={} frame_leave={} iter={} suspend={} resume={}",
373 self.visit_pre,
374 self.visit_post,
375 self.frame_enter,
376 self.frame_leave,
377 self.iteration_tick,
378 self.suspend,
379 self.resume,
380 )
381 }
382}
383
384#[derive(Debug, Default, Clone)]
391pub struct BufferingSink {
392 events: Vec<Event>,
393}
394
395impl BufferingSink {
396 pub fn new() -> Self {
398 Self { events: Vec::new() }
399 }
400
401 pub fn with_capacity(cap: usize) -> Self {
406 Self {
407 events: Vec::with_capacity(cap),
408 }
409 }
410
411 pub fn snapshot(&self) -> &[Event] {
413 &self.events
414 }
415
416 pub fn drain(&mut self) -> Vec<Event> {
418 std::mem::take(&mut self.events)
419 }
420
421 pub fn clear(&mut self) {
423 self.events.clear();
424 }
425
426 pub fn len(&self) -> usize {
428 self.events.len()
429 }
430
431 pub fn is_empty(&self) -> bool {
433 self.events.is_empty()
434 }
435}
436
437impl EventSink for BufferingSink {
438 fn emit(&mut self, event: &Event) {
439 self.events.push(event.clone());
440 }
441}
442
443#[derive(Debug, thiserror::Error, miette::Diagnostic)]
453#[non_exhaustive]
454pub enum EngineError {
455 #[error("evaluation aborted at {at}: {reason}")]
457 #[diagnostic(
458 code(dsl_kit::eval::aborted),
459 help(
460 "The interpreter returned an `Aborted` outcome. Inspect the reason and the node context to locate the abort site."
461 )
462 )]
463 Aborted {
464 at: NodeContext,
466 reason: String,
468 },
469
470 #[error("evaluator failed at {at}")]
472 #[diagnostic(
473 code(dsl_kit::eval::failed),
474 help(
475 "The interpreter returned an error while evaluating this node. The `#[source]` chain points at the underlying failure."
476 )
477 )]
478 EvalFailed {
479 at: NodeContext,
481 #[source]
483 source: Box<dyn std::error::Error + Send + Sync>,
484 },
485
486 #[error("malformed AST at {at}: {detail}")]
489 #[diagnostic(
490 code(dsl_kit::ast::malformed),
491 help(
492 "An AST invariant was violated. This usually means a hand-constructed tree omitted a required child."
493 )
494 )]
495 Malformed {
496 at: NodeContext,
498 detail: String,
500 },
501
502 #[error("stepper protocol violation at {at}: {detail}")]
505 #[diagnostic(
506 code(dsl_kit::stepper::protocol),
507 help(
508 "The stepper's suspend/resume contract was broken. Each `PendingEffect` leaf must be resolved exactly once before further steps observe its value."
509 )
510 )]
511 StepperProtocol {
512 at: NodeContext,
514 detail: String,
516 },
517
518 #[error("unknown suspension {id}")]
524 #[diagnostic(
525 code(dsl_kit::stepper::unknown_suspension),
526 help(
527 "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."
528 )
529 )]
530 UnknownSuspension {
531 id: SuspensionId,
533 },
534
535 #[error("unknown reducer {id:?}{hint}")]
538 #[diagnostic(
539 code(dsl_kit::reducer::unknown),
540 help(
541 "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."
542 )
543 )]
544 UnknownReducer {
545 id: ReducerId,
547 hint: String,
553 },
554
555 #[error("unknown op {id:?}{hint}")]
558 #[diagnostic(
559 code(dsl_kit::op::unknown),
560 help(
561 "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."
562 )
563 )]
564 UnknownOp {
565 id: OpId,
567 hint: String,
571 },
572}
573
574pub type EngineResult<T> = Result<T, EngineError>;
576
577#[derive(Debug, Clone, PartialEq, Eq)]
580pub struct ErrorCatalogEntry {
581 pub code: String,
583 pub help: String,
585}
586
587pub fn engine_error_catalog() -> Vec<ErrorCatalogEntry> {
589 use miette::Diagnostic;
590
591 fn ctx() -> NodeContext {
592 NodeContext::at(NodeId(0), Path::root())
593 }
594
595 let samples: Vec<EngineError> = vec![
596 EngineError::Aborted {
597 at: ctx(),
598 reason: String::new(),
599 },
600 EngineError::EvalFailed {
601 at: ctx(),
602 source: Box::new(std::io::Error::other("")),
603 },
604 EngineError::Malformed {
605 at: ctx(),
606 detail: String::new(),
607 },
608 EngineError::StepperProtocol {
609 at: ctx(),
610 detail: String::new(),
611 },
612 EngineError::UnknownSuspension {
613 id: SuspensionId(0),
614 },
615 EngineError::UnknownReducer {
616 id: ReducerId(String::new()),
617 hint: String::new(),
618 },
619 EngineError::UnknownOp {
620 id: OpId(String::new()),
621 hint: String::new(),
622 },
623 ];
624
625 samples
626 .into_iter()
627 .filter_map(|e| {
628 let code = e.code()?.to_string();
629 let help = e.help()?.to_string();
630 Some(ErrorCatalogEntry { code, help })
631 })
632 .collect()
633}
634
635#[derive(Debug, Clone)]
654pub enum StepOutcome<V> {
655 Ready,
657 Blocked {
661 newly_pending: smallvec::SmallVec<[Pending; 1]>,
663 },
664 Done(V),
666}
667
668pub trait Stepper {
674 type Value;
676 type Cursor;
678 type Delta;
681 type EffectError: std::error::Error + Send + Sync + 'static;
683 type Error: From<Self::EffectError> + std::error::Error + Send + Sync + 'static;
685
686 fn step(&mut self) -> Result<StepOutcome<Self::Value>, Self::Error>;
688
689 fn resolve(
695 &mut self,
696 id: SuspensionId,
697 result: Result<Self::Value, Self::EffectError>,
698 ) -> Result<(), Self::Error>;
699
700 fn pending(&self) -> &[Pending];
704
705 fn take_cancellations(&mut self) -> Vec<SuspensionId>;
709
710 fn frame_tree(&self) -> &FrameTree<Self::Value, Self::Cursor, Self::Delta, Self::EffectError>;
712
713 fn is_done(&self) -> bool;
715}
716
717pub type ChildIndex = usize;
721
722#[derive(Debug, Clone)]
724pub enum CancelReason {
725 ParPolicyFired,
728 SiblingFailed,
730}
731
732#[derive(Debug)]
734pub enum Frame<V, C, D, EE> {
735 Node {
737 node: NodeId,
739 env: EnvRef<D>,
741 cursor: C,
743 },
744 Par(ParFrame<V, D, EE>),
746 Scope {
748 label: String,
750 env: EnvRef<D>,
752 },
753 PendingEffect {
755 id: SuspensionId,
757 },
758 Value(V),
761 Cancelled {
764 reason: CancelReason,
766 },
767}
768
769#[derive(Debug)]
773pub struct FrameTree<V, C, D, EE> {
774 pub root: Frame<V, C, D, EE>,
776 pub kids: Vec<FrameTree<V, C, D, EE>>,
778}
779
780#[derive(Debug)]
786pub struct ParFrame<V, D, EE> {
787 pub policy: JoinPolicy,
789 pub slots: Vec<Option<V>>,
795 pub failures: Vec<Option<EE>>,
799 pub deltas: Vec<Option<D>>,
801 pub completion_order: Vec<ChildIndex>,
803 pub reducer_id: ReducerId,
805 pub reducer: ReducerHandle<V, D, EE>,
808 pub joined: bool,
810}
811
812#[derive(Debug, Clone, Copy)]
817pub struct JoinPolicy {
818 pub shape: JoinShape,
820 pub fail: FailPolicy,
822}
823
824#[derive(Debug, Clone, Copy)]
826pub enum JoinShape {
827 All,
829 Any,
831 FirstK(usize),
834}
835
836#[derive(Debug, Clone, Copy)]
838pub enum FailPolicy {
839 FailFast,
841 CollectAll,
844}
845
846#[derive(Debug, Clone, PartialEq, Eq, Hash)]
850pub struct ReducerId(pub String);
851
852impl fmt::Display for ReducerId {
853 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
854 write!(f, "{}", self.0)
855 }
856}
857
858impl From<&str> for ReducerId {
859 fn from(s: &str) -> Self {
860 ReducerId(s.to_string())
861 }
862}
863
864impl From<String> for ReducerId {
865 fn from(s: String) -> Self {
866 ReducerId(s)
867 }
868}
869
870pub trait Reducer<V, D>: Send + Sync {
872 fn reduce(
874 &self,
875 slots: &[Option<V>],
876 deltas: &[Option<D>],
877 winners: &[ChildIndex],
878 ) -> Result<(V, D), EngineError>;
879}
880
881pub trait ReducerCollectAll<V, D, EffectError>: Send + Sync {
883 fn reduce(
886 &self,
887 slots: &[Option<Result<V, EffectError>>],
888 deltas: &[Option<D>],
889 winners: &[ChildIndex],
890 ) -> Result<(V, D), EngineError>;
891}
892
893pub enum ReducerHandle<V, D, EE> {
900 FailFast(Arc<dyn Reducer<V, D>>),
902 CollectAll(Arc<dyn ReducerCollectAll<V, D, EE>>),
904}
905
906impl<V, D, EE> fmt::Debug for ReducerHandle<V, D, EE> {
907 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
908 match self {
909 ReducerHandle::FailFast(_) => f.write_str("ReducerHandle::FailFast(..)"),
910 ReducerHandle::CollectAll(_) => f.write_str("ReducerHandle::CollectAll(..)"),
911 }
912 }
913}
914
915impl<V, D, EE> Clone for ReducerHandle<V, D, EE> {
916 fn clone(&self) -> Self {
917 match self {
918 ReducerHandle::FailFast(a) => ReducerHandle::FailFast(a.clone()),
919 ReducerHandle::CollectAll(a) => ReducerHandle::CollectAll(a.clone()),
920 }
921 }
922}
923
924pub struct ReducerRegistry<V, D, EffectError> {
930 fail_fast: HashMap<ReducerId, Arc<dyn Reducer<V, D>>>,
931 collect_all: HashMap<ReducerId, Arc<dyn ReducerCollectAll<V, D, EffectError>>>,
932 suggester: crate::suggest::SuggesterHandle,
933}
934
935impl<V, D, EE> Default for ReducerRegistry<V, D, EE> {
936 fn default() -> Self {
937 Self::new()
938 }
939}
940
941impl<V, D, EE> ReducerRegistry<V, D, EE> {
942 pub fn new() -> Self {
944 Self {
945 fail_fast: HashMap::new(),
946 collect_all: HashMap::new(),
947 suggester: crate::suggest::noop_handle(),
948 }
949 }
950
951 pub fn with_suggester(mut self, suggester: crate::suggest::SuggesterHandle) -> Self {
961 self.suggester = suggester;
962 self
963 }
964
965 pub fn register_fail_fast(
967 &mut self,
968 id: impl Into<ReducerId>,
969 reducer: Arc<dyn Reducer<V, D>>,
970 ) {
971 self.fail_fast.insert(id.into(), reducer);
972 }
973
974 pub fn register_collect_all(
976 &mut self,
977 id: impl Into<ReducerId>,
978 reducer: Arc<dyn ReducerCollectAll<V, D, EE>>,
979 ) {
980 self.collect_all.insert(id.into(), reducer);
981 }
982
983 pub fn resolve(
989 &self,
990 id: &ReducerId,
991 fail: FailPolicy,
992 ) -> Result<ReducerHandle<V, D, EE>, EngineError> {
993 let miss = || {
994 let names: Vec<&str> = match fail {
998 FailPolicy::FailFast => self.fail_fast.keys().map(|k| k.0.as_str()).collect(),
999 FailPolicy::CollectAll => self.collect_all.keys().map(|k| k.0.as_str()).collect(),
1000 };
1001 let hint = self
1002 .suggester
1003 .enrich_unknown(&id.0, &names)
1004 .map(|h| format!(" ({h})"))
1005 .unwrap_or_default();
1006 EngineError::UnknownReducer {
1007 id: id.clone(),
1008 hint,
1009 }
1010 };
1011 match fail {
1012 FailPolicy::FailFast => self
1013 .fail_fast
1014 .get(id)
1015 .cloned()
1016 .map(ReducerHandle::FailFast)
1017 .ok_or_else(miss),
1018 FailPolicy::CollectAll => self
1019 .collect_all
1020 .get(id)
1021 .cloned()
1022 .map(ReducerHandle::CollectAll)
1023 .ok_or_else(miss),
1024 }
1025 }
1026}
1027
1028#[derive(Debug, Clone, PartialEq, Eq, Hash)]
1032pub struct OpId(pub String);
1033
1034impl fmt::Display for OpId {
1035 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1036 write!(f, "{}", self.0)
1037 }
1038}
1039
1040impl From<&str> for OpId {
1041 fn from(s: &str) -> Self {
1042 OpId(s.to_string())
1043 }
1044}
1045
1046impl From<String> for OpId {
1047 fn from(s: String) -> Self {
1048 OpId(s)
1049 }
1050}
1051
1052pub trait Op<V>: Send + Sync {
1061 fn apply(&self, node: NodeId, args: &[V]) -> Result<V, EngineError>;
1066}
1067
1068pub type OpHandle<V> = Arc<dyn Op<V>>;
1070
1071pub struct OpRegistry<V> {
1083 ops: HashMap<OpId, OpHandle<V>>,
1084 suggester: crate::suggest::SuggesterHandle,
1085}
1086
1087impl<V> Default for OpRegistry<V> {
1088 fn default() -> Self {
1089 Self::new()
1090 }
1091}
1092
1093impl<V> OpRegistry<V> {
1094 pub fn new() -> Self {
1096 Self {
1097 ops: HashMap::new(),
1098 suggester: crate::suggest::noop_handle(),
1099 }
1100 }
1101
1102 pub fn with_suggester(mut self, suggester: crate::suggest::SuggesterHandle) -> Self {
1111 self.suggester = suggester;
1112 self
1113 }
1114
1115 pub fn register(&mut self, id: impl Into<OpId>, op: OpHandle<V>) {
1117 self.ops.insert(id.into(), op);
1118 }
1119
1120 pub fn resolve(&self, id: &OpId) -> Result<OpHandle<V>, EngineError> {
1123 self.ops.get(id).cloned().ok_or_else(|| {
1124 let names: Vec<&str> = self.ops.keys().map(|k| k.0.as_str()).collect();
1125 let hint = self
1126 .suggester
1127 .enrich_unknown(&id.0, &names)
1128 .map(|h| format!(" ({h})"))
1129 .unwrap_or_default();
1130 EngineError::UnknownOp {
1131 id: id.clone(),
1132 hint,
1133 }
1134 })
1135 }
1136}
1137
1138pub trait DslExec: Walk {
1149 type LitValue: Clone + fmt::Debug;
1152
1153 fn exec_kind(&self) -> NodeKind;
1155
1156 fn exec_literal(&self) -> Option<Self::LitValue>;
1158}
1159
1160pub trait DslSemantics {
1165 type Value: Clone + fmt::Debug;
1167 type Delta: Clone + Default + fmt::Debug;
1170 type EffectError: std::error::Error + Clone + Send + Sync + 'static;
1172 type Cursor: Clone + fmt::Debug + Default;
1174
1175 fn unit_value(&self) -> Self::Value;
1177
1178 fn truthy(&self, _value: &Self::Value) -> Option<bool> {
1180 None
1181 }
1182
1183 fn continue_loop(&self, _node: NodeId, _last: &Self::Value, _iteration: usize) -> LoopDecision {
1185 LoopDecision::Break
1186 }
1187
1188 fn bind_delta(&self, _name: &str, _value: &Self::Value) -> Option<Self::Delta> {
1190 None
1191 }
1192
1193 fn lookup(&self, _delta: &Self::Delta, _name: &str) -> Option<Self::Value> {
1195 None
1196 }
1197}
1198
1199pub struct DerivedAst<'a, N, S> {
1213 root: &'a N,
1214 by_id: HashMap<NodeId, &'a N>,
1215 sem: S,
1216}
1217
1218impl<'a, N: DslExec, S> DerivedAst<'a, N, S> {
1219 pub fn new(root: &'a N, sem: S) -> Self {
1221 fn collect<'a, N: Walk>(node: &'a N, map: &mut HashMap<NodeId, &'a N>) {
1222 map.insert(node.node_id(), node);
1223 for child in node.children() {
1224 collect(child, map);
1225 }
1226 }
1227 let mut by_id = HashMap::new();
1228 collect(root, &mut by_id);
1229 Self { root, by_id, sem }
1230 }
1231
1232 fn node(&self, id: NodeId) -> &'a N {
1233 self.by_id.get(&id).copied().expect("unknown NodeId")
1234 }
1235}
1236
1237impl<N, S> Ast for DerivedAst<'_, N, S>
1238where
1239 N: DslExec,
1240 S: DslSemantics,
1241 S::Value: From<N::LitValue>,
1242{
1243 type Value = S::Value;
1244 type Delta = S::Delta;
1245 type EffectError = S::EffectError;
1246 type Cursor = S::Cursor;
1247
1248 fn root(&self) -> NodeId {
1249 self.root.node_id()
1250 }
1251
1252 fn node_kind(&self, id: NodeId) -> NodeKind {
1253 self.node(id).exec_kind()
1254 }
1255
1256 fn unit_value(&self) -> Self::Value {
1257 self.sem.unit_value()
1258 }
1259
1260 fn truthy(&self, value: &Self::Value) -> Option<bool> {
1261 self.sem.truthy(value)
1262 }
1263
1264 fn continue_loop(&self, node: NodeId, last: &Self::Value, iteration: usize) -> LoopDecision {
1265 self.sem.continue_loop(node, last, iteration)
1266 }
1267
1268 fn bind_delta(&self, name: &str, value: &Self::Value) -> Option<Self::Delta> {
1269 self.sem.bind_delta(name, value)
1270 }
1271
1272 fn lookup(&self, delta: &Self::Delta, name: &str) -> Option<Self::Value> {
1273 self.sem.lookup(delta, name)
1274 }
1275
1276 fn literal(&self, node: NodeId) -> Option<Self::Value> {
1277 self.node(node).exec_literal().map(S::Value::from)
1278 }
1279}
1280
1281pub struct OwnedDerivedAst<L, S> {
1303 root: NodeId,
1304 nodes: HashMap<NodeId, OwnedNode<L>>,
1305 sem: S,
1306}
1307
1308#[derive(Clone)]
1312struct OwnedNode<L> {
1313 kind: NodeKind,
1314 literal: Option<L>,
1315}
1316
1317impl<L, S> OwnedDerivedAst<L, S> {
1318 pub fn new<N>(root: &N, sem: S) -> Self
1322 where
1323 N: DslExec<LitValue = L>,
1324 {
1325 fn collect<N: DslExec>(node: &N, map: &mut HashMap<NodeId, OwnedNode<N::LitValue>>) {
1326 map.insert(
1327 node.node_id(),
1328 OwnedNode {
1329 kind: node.exec_kind(),
1330 literal: node.exec_literal(),
1331 },
1332 );
1333 for child in node.children() {
1334 collect(child, map);
1335 }
1336 }
1337 let mut nodes = HashMap::new();
1338 collect(root, &mut nodes);
1339 Self {
1340 root: root.node_id(),
1341 nodes,
1342 sem,
1343 }
1344 }
1345
1346 fn node(&self, id: NodeId) -> &OwnedNode<L> {
1347 self.nodes.get(&id).expect("unknown NodeId")
1348 }
1349}
1350
1351impl<L, S> Clone for OwnedDerivedAst<L, S>
1352where
1353 L: Clone,
1354 S: Clone,
1355{
1356 fn clone(&self) -> Self {
1357 Self {
1358 root: self.root,
1359 nodes: self.nodes.clone(),
1360 sem: self.sem.clone(),
1361 }
1362 }
1363}
1364
1365impl<L, S> Ast for OwnedDerivedAst<L, S>
1366where
1367 L: Clone + fmt::Debug,
1368 S: DslSemantics,
1369 S::Value: From<L>,
1370{
1371 type Value = S::Value;
1372 type Delta = S::Delta;
1373 type EffectError = S::EffectError;
1374 type Cursor = S::Cursor;
1375
1376 fn root(&self) -> NodeId {
1377 self.root
1378 }
1379
1380 fn node_kind(&self, id: NodeId) -> NodeKind {
1381 self.node(id).kind.clone()
1382 }
1383
1384 fn unit_value(&self) -> Self::Value {
1385 self.sem.unit_value()
1386 }
1387
1388 fn truthy(&self, value: &Self::Value) -> Option<bool> {
1389 self.sem.truthy(value)
1390 }
1391
1392 fn continue_loop(&self, node: NodeId, last: &Self::Value, iteration: usize) -> LoopDecision {
1393 self.sem.continue_loop(node, last, iteration)
1394 }
1395
1396 fn bind_delta(&self, name: &str, value: &Self::Value) -> Option<Self::Delta> {
1397 self.sem.bind_delta(name, value)
1398 }
1399
1400 fn lookup(&self, delta: &Self::Delta, name: &str) -> Option<Self::Value> {
1401 self.sem.lookup(delta, name)
1402 }
1403
1404 fn literal(&self, node: NodeId) -> Option<Self::Value> {
1405 self.node(node).literal.clone().map(S::Value::from)
1406 }
1407}
1408
1409#[derive(Debug)]
1416pub struct EnvRef<D>(pub Arc<Env<D>>);
1417
1418impl<D> Clone for EnvRef<D> {
1419 fn clone(&self) -> Self {
1420 EnvRef(self.0.clone())
1421 }
1422}
1423
1424#[derive(Debug)]
1427pub struct Env<D> {
1428 pub delta: D,
1430 pub parent: Option<Arc<Env<D>>>,
1432}
1433
1434pub trait DslNode {
1438 fn node_id(&self) -> NodeId;
1440
1441 fn variant_name(&self) -> &'static str;
1452}
1453
1454#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
1458pub struct BreakpointId(pub u64);
1459
1460impl fmt::Display for BreakpointId {
1461 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1462 write!(f, "bp{}", self.0)
1463 }
1464}
1465
1466#[derive(Debug, Clone, PartialEq, Eq)]
1469pub enum BreakCondition {
1470 Node(NodeId),
1472 PathPrefix(Path),
1474 PathExact(Path),
1476 DepthAtLeast(u32),
1478 DepthAtMost(u32),
1480 DepthEquals(u32),
1482 Iteration(u64),
1484 CallFrame(CallFrameId),
1486 Any(Vec<BreakCondition>),
1488 All(Vec<BreakCondition>),
1490 Not(Box<BreakCondition>),
1492 Always,
1494 Never,
1496}
1497
1498impl BreakCondition {
1499 pub fn at_node(id: NodeId) -> Self {
1501 Self::Node(id)
1502 }
1503
1504 pub fn under_path(path: Path) -> Self {
1506 Self::PathPrefix(path)
1507 }
1508
1509 pub fn at_path(path: Path) -> Self {
1511 Self::PathExact(path)
1512 }
1513
1514 pub fn at_depth_at_least(n: u32) -> Self {
1516 Self::DepthAtLeast(n)
1517 }
1518
1519 pub fn at_depth_at_most(n: u32) -> Self {
1521 Self::DepthAtMost(n)
1522 }
1523
1524 pub fn at_depth(n: u32) -> Self {
1526 Self::DepthEquals(n)
1527 }
1528
1529 pub fn at_iteration(n: u64) -> Self {
1531 Self::Iteration(n)
1532 }
1533
1534 pub fn in_call_frame(frame: CallFrameId) -> Self {
1536 Self::CallFrame(frame)
1537 }
1538
1539 pub fn and(self, other: Self) -> Self {
1541 match (self, other) {
1542 (Self::All(mut xs), Self::All(ys)) => {
1543 xs.extend(ys);
1544 Self::All(xs)
1545 }
1546 (Self::All(mut xs), other) => {
1547 xs.push(other);
1548 Self::All(xs)
1549 }
1550 (this, Self::All(mut ys)) => {
1551 ys.insert(0, this);
1552 Self::All(ys)
1553 }
1554 (this, other) => Self::All(vec![this, other]),
1555 }
1556 }
1557
1558 pub fn or(self, other: Self) -> Self {
1560 match (self, other) {
1561 (Self::Any(mut xs), Self::Any(ys)) => {
1562 xs.extend(ys);
1563 Self::Any(xs)
1564 }
1565 (Self::Any(mut xs), other) => {
1566 xs.push(other);
1567 Self::Any(xs)
1568 }
1569 (this, Self::Any(mut ys)) => {
1570 ys.insert(0, this);
1571 Self::Any(ys)
1572 }
1573 (this, other) => Self::Any(vec![this, other]),
1574 }
1575 }
1576
1577 pub fn matches(&self, ctx: &NodeContext) -> bool {
1579 match self {
1580 Self::Node(id) => ctx.node == *id,
1581 Self::PathPrefix(prefix) => {
1582 ctx.path.0.len() >= prefix.0.len() && ctx.path.0[..prefix.0.len()] == prefix.0[..]
1583 }
1584 Self::PathExact(path) => ctx.path == *path,
1585 Self::DepthAtLeast(n) => ctx.depth >= *n,
1586 Self::DepthAtMost(n) => ctx.depth <= *n,
1587 Self::DepthEquals(n) => ctx.depth == *n,
1588 Self::Iteration(n) => ctx.iteration.map(|i| i.0 == *n).unwrap_or(false),
1589 Self::CallFrame(frame) => ctx.frame == Some(*frame),
1590 Self::Any(children) => children.iter().any(|c| c.matches(ctx)),
1591 Self::All(children) => children.iter().all(|c| c.matches(ctx)),
1592 Self::Not(inner) => !inner.matches(ctx),
1593 Self::Always => true,
1594 Self::Never => false,
1595 }
1596 }
1597}
1598
1599impl std::ops::Not for BreakCondition {
1600 type Output = Self;
1601
1602 fn not(self) -> Self {
1604 Self::Not(Box::new(self))
1605 }
1606}
1607
1608#[derive(Debug, Default)]
1610pub struct BreakpointSet {
1611 next: u64,
1612 entries: Vec<(BreakpointId, BreakCondition)>,
1613}
1614
1615impl BreakpointSet {
1616 pub fn new() -> Self {
1618 Self {
1619 next: 1,
1620 entries: Vec::new(),
1621 }
1622 }
1623
1624 pub fn add(&mut self, condition: BreakCondition) -> BreakpointId {
1626 let id = BreakpointId(self.next);
1627 self.next += 1;
1628 self.entries.push((id, condition));
1629 id
1630 }
1631
1632 pub fn remove(&mut self, id: BreakpointId) -> bool {
1634 let before = self.entries.len();
1635 self.entries.retain(|(entry_id, _)| *entry_id != id);
1636 self.entries.len() != before
1637 }
1638
1639 pub fn matches(&self, ctx: &NodeContext) -> Vec<BreakpointId> {
1641 self.entries
1642 .iter()
1643 .filter(|(_, cond)| cond.matches(ctx))
1644 .map(|(id, _)| *id)
1645 .collect()
1646 }
1647
1648 pub fn is_empty(&self) -> bool {
1650 self.entries.is_empty()
1651 }
1652
1653 pub fn len(&self) -> usize {
1655 self.entries.len()
1656 }
1657
1658 pub fn iter(&self) -> impl Iterator<Item = (BreakpointId, &BreakCondition)> {
1660 self.entries.iter().map(|(id, c)| (*id, c))
1661 }
1662}
1663
1664#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1668pub enum Phase {
1669 Pre,
1671 Post,
1673}
1674
1675pub trait Walk: DslNode + Sized {
1677 fn children(&self) -> Vec<&Self>;
1679
1680 fn walk<F>(&self, visitor: &mut F)
1682 where
1683 F: FnMut(&Self, Phase),
1684 {
1685 visitor(self, Phase::Pre);
1686 for child in self.children() {
1687 child.walk(visitor);
1688 }
1689 visitor(self, Phase::Post);
1690 }
1691
1692 fn walk_until<F, T>(&self, visitor: &mut F) -> Option<T>
1694 where
1695 F: FnMut(&Self, Phase) -> Option<T>,
1696 {
1697 if let Some(t) = visitor(self, Phase::Pre) {
1698 return Some(t);
1699 }
1700 for child in self.children() {
1701 if let Some(t) = child.walk_until(visitor) {
1702 return Some(t);
1703 }
1704 }
1705 visitor(self, Phase::Post)
1706 }
1707
1708 fn find_by_id(&self, target: NodeId) -> Option<&Self> {
1710 self.walk_until(&mut |node, phase| {
1711 if phase == Phase::Pre && node.node_id() == target {
1712 Some(node as *const Self)
1713 } else {
1714 None
1715 }
1716 })
1717 .map(|ptr| unsafe { &*ptr })
1718 }
1719}
1720
1721pub trait WalkMut: DslNode + Sized {
1723 fn children_mut(&mut self) -> Vec<&mut Self>;
1725
1726 fn walk_mut<F>(&mut self, visitor: &mut F)
1728 where
1729 F: FnMut(&mut Self, Phase),
1730 {
1731 visitor(self, Phase::Pre);
1732 for child in self.children_mut() {
1733 child.walk_mut(visitor);
1734 }
1735 visitor(self, Phase::Post);
1736 }
1737}
1738
1739#[cfg(test)]
1740mod tests {
1741 use super::*;
1742
1743 #[test]
1744 fn path_push_extends_depth() {
1745 let ids = IdGen::new();
1746 let a = ids.node();
1747 let b = ids.node();
1748
1749 let root = Path::root();
1750 assert_eq!(root.depth(), 0);
1751
1752 let one = root.push(a);
1753 assert_eq!(one.depth(), 1);
1754
1755 let two = one.push(b);
1756 assert_eq!(two.depth(), 2);
1757 assert_eq!(two.tip(), Some(b));
1758 }
1759
1760 #[test]
1761 fn id_generator_yields_distinct_ids() {
1762 let ids = IdGen::new();
1763 let a = ids.node();
1764 let b = ids.node();
1765 assert_ne!(a, b);
1766 }
1767
1768 #[test]
1769 fn null_sink_accepts_events() {
1770 let mut sink = NullSink;
1771 let event = Event::VisitPre {
1772 at: NodeContext::at(NodeId(0), Path::root()),
1773 };
1774 sink.emit(&event);
1775 }
1776
1777 fn ctx_at(node: NodeId, path: Path, depth: u32) -> NodeContext {
1778 NodeContext {
1779 node,
1780 path,
1781 frame: None,
1782 depth,
1783 iteration: None,
1784 }
1785 }
1786
1787 #[test]
1788 fn breakpoint_node_matches_exact_id() {
1789 let cond = BreakCondition::at_node(NodeId(7));
1790 assert!(cond.matches(&ctx_at(NodeId(7), Path::root().push(NodeId(7)), 1)));
1791 assert!(!cond.matches(&ctx_at(NodeId(8), Path::root().push(NodeId(8)), 1)));
1792 }
1793
1794 #[test]
1795 fn breakpoint_set_add_matches_remove() {
1796 let mut set = BreakpointSet::new();
1797 let hit = set.add(BreakCondition::at_node(NodeId(4)));
1798 let miss = set.add(BreakCondition::at_node(NodeId(99)));
1799
1800 let ctx = ctx_at(NodeId(4), Path::root().push(NodeId(4)), 1);
1801 assert_eq!(set.matches(&ctx), vec![hit]);
1802
1803 assert!(set.remove(hit));
1804 assert!(set.matches(&ctx).is_empty());
1805 assert_eq!(set.len(), 1);
1806 assert!(set.iter().any(|(id, _)| id == miss));
1807 }
1808
1809 #[test]
1810 fn engine_error_carries_stable_code() {
1811 let err = EngineError::Aborted {
1812 at: NodeContext::at(NodeId(1), Path::root().push(NodeId(1))),
1813 reason: "user requested".into(),
1814 };
1815 use miette::Diagnostic;
1816 assert_eq!(
1817 err.code().map(|c| c.to_string()).as_deref(),
1818 Some("dsl_kit::eval::aborted")
1819 );
1820 }
1821
1822 #[test]
1823 fn engine_error_catalog_covers_every_variant() {
1824 let entries = engine_error_catalog();
1825 let codes: Vec<&str> = entries.iter().map(|e| e.code.as_str()).collect();
1826 assert!(codes.contains(&"dsl_kit::eval::aborted"));
1827 assert!(codes.contains(&"dsl_kit::eval::failed"));
1828 assert!(codes.contains(&"dsl_kit::ast::malformed"));
1829 assert!(codes.contains(&"dsl_kit::stepper::protocol"));
1830 assert!(codes.contains(&"dsl_kit::stepper::unknown_suspension"));
1831 assert!(codes.contains(&"dsl_kit::reducer::unknown"));
1832 for entry in &entries {
1833 assert!(!entry.help.is_empty(), "help empty for {}", entry.code);
1834 }
1835 }
1836
1837 #[test]
1838 fn reducer_id_from_str_and_string() {
1839 let a: ReducerId = "foo".into();
1840 let b: ReducerId = String::from("foo").into();
1841 assert_eq!(a, b);
1842 }
1843
1844 #[test]
1845 fn reducer_registry_resolves_fail_fast_and_collect_all_independently() {
1846 struct FirstNonNone;
1849 impl Reducer<i64, ()> for FirstNonNone {
1850 fn reduce(
1851 &self,
1852 slots: &[Option<i64>],
1853 _deltas: &[Option<()>],
1854 _winners: &[ChildIndex],
1855 ) -> Result<(i64, ()), EngineError> {
1856 let v = slots.iter().find_map(|s| *s).unwrap_or(0);
1857 Ok((v, ()))
1858 }
1859 }
1860
1861 struct CountOk;
1863 impl ReducerCollectAll<i64, (), std::io::Error> for CountOk {
1864 fn reduce(
1865 &self,
1866 slots: &[Option<Result<i64, std::io::Error>>],
1867 _deltas: &[Option<()>],
1868 _winners: &[ChildIndex],
1869 ) -> Result<(i64, ()), EngineError> {
1870 let count = slots.iter().filter(|s| matches!(s, Some(Ok(_)))).count();
1871 Ok((count as i64, ()))
1872 }
1873 }
1874
1875 let mut reg: ReducerRegistry<i64, (), std::io::Error> = ReducerRegistry::new();
1876 reg.register_fail_fast("first", Arc::new(FirstNonNone));
1877 reg.register_collect_all("count_ok", Arc::new(CountOk));
1878
1879 let ff = reg.resolve(&"first".into(), FailPolicy::FailFast).unwrap();
1880 assert!(matches!(ff, ReducerHandle::FailFast(_)));
1881 let ca = reg
1882 .resolve(&"count_ok".into(), FailPolicy::CollectAll)
1883 .unwrap();
1884 assert!(matches!(ca, ReducerHandle::CollectAll(_)));
1885
1886 let miss = reg.resolve(&"nope".into(), FailPolicy::FailFast);
1887 assert!(matches!(miss, Err(EngineError::UnknownReducer { .. })));
1888 }
1889
1890 struct FixedSuggester(&'static str);
1896 impl Suggester for FixedSuggester {
1897 fn suggest<'a>(&self, _q: &str, cands: &'a [&str]) -> Vec<Suggestion<'a>> {
1898 cands
1899 .iter()
1900 .find(|c| **c == self.0)
1901 .map(|c| Suggestion {
1902 candidate: c,
1903 score: 1.0,
1904 })
1905 .into_iter()
1906 .collect()
1907 }
1908 }
1909
1910 #[test]
1911 fn unknown_reducer_defaults_to_no_hint() {
1912 struct Noop;
1915 impl Reducer<i64, ()> for Noop {
1916 fn reduce(
1917 &self,
1918 _s: &[Option<i64>],
1919 _d: &[Option<()>],
1920 _w: &[ChildIndex],
1921 ) -> Result<(i64, ()), EngineError> {
1922 Ok((0, ()))
1923 }
1924 }
1925 let mut reg: ReducerRegistry<i64, (), std::io::Error> = ReducerRegistry::new();
1926 reg.register_fail_fast("first", Arc::new(Noop));
1927 let miss = reg.resolve(&"frst".into(), FailPolicy::FailFast);
1928 let err = match miss {
1929 Err(e) => e,
1930 Ok(_) => panic!("expected miss"),
1931 };
1932 assert_eq!(err.to_string(), "unknown reducer ReducerId(\"frst\")");
1936 }
1937
1938 #[test]
1939 fn unknown_reducer_with_suggester_appends_hint() {
1940 struct Noop;
1941 impl Reducer<i64, ()> for Noop {
1942 fn reduce(
1943 &self,
1944 _s: &[Option<i64>],
1945 _d: &[Option<()>],
1946 _w: &[ChildIndex],
1947 ) -> Result<(i64, ()), EngineError> {
1948 Ok((0, ()))
1949 }
1950 }
1951 let mut reg: ReducerRegistry<i64, (), std::io::Error> = ReducerRegistry::new();
1952 reg.register_fail_fast("first", Arc::new(Noop));
1953 let reg = reg.with_suggester(Arc::new(FixedSuggester("first")));
1954 let miss = reg.resolve(&"frst".into(), FailPolicy::FailFast);
1955 let err = match miss {
1956 Err(e) => e,
1957 Ok(_) => panic!("expected miss"),
1958 };
1959 let msg = err.to_string();
1960 assert!(
1961 msg.contains("did you mean") && msg.contains("first"),
1962 "expected hint, got: {msg}"
1963 );
1964 }
1965
1966 #[test]
1967 fn unknown_op_defaults_to_no_hint() {
1968 struct AddOp;
1969 impl Op<i64> for AddOp {
1970 fn apply(&self, _n: NodeId, args: &[i64]) -> Result<i64, EngineError> {
1971 Ok(args.iter().sum())
1972 }
1973 }
1974 let mut reg: OpRegistry<i64> = OpRegistry::new();
1975 reg.register("add", Arc::new(AddOp));
1976 let miss = reg.resolve(&"ad".into());
1977 let err = match miss {
1978 Err(e) => e,
1979 Ok(_) => panic!("expected miss"),
1980 };
1981 assert_eq!(err.to_string(), "unknown op OpId(\"ad\")");
1982 }
1983
1984 #[test]
1985 fn unknown_op_with_suggester_appends_hint() {
1986 struct AddOp;
1987 impl Op<i64> for AddOp {
1988 fn apply(&self, _n: NodeId, args: &[i64]) -> Result<i64, EngineError> {
1989 Ok(args.iter().sum())
1990 }
1991 }
1992 let mut reg: OpRegistry<i64> = OpRegistry::new();
1993 reg.register("add", Arc::new(AddOp));
1994 let reg = reg.with_suggester(Arc::new(FixedSuggester("add")));
1995 let miss = reg.resolve(&"ad".into());
1996 let err = match miss {
1997 Err(e) => e,
1998 Ok(_) => panic!("expected miss"),
1999 };
2000 let msg = err.to_string();
2001 assert!(
2002 msg.contains("did you mean") && msg.contains("add"),
2003 "expected hint, got: {msg}"
2004 );
2005 }
2006}