dsl_kit_core/lib.rs
1//! Engine primitives for `dsl-kit` (v3 engine shape).
2//!
3//! This crate defines the observable primitives every DSL built with the
4//! kit carries: stable node identifiers, call frame identifiers with
5//! depth, iteration counters, root-to-node paths, an event stream, the
6//! `Stepper` trait modelling evaluation as an externally-driven state
7//! machine, an AST traversal contract, and structured errors that always
8//! carry the location at which the error happened.
9//!
10//! ## v3 shape (Round 13)
11//!
12//! - `Stepper` is a sync trait; async is a host concern. Interpretation is
13//! observable, steppable, and supports first-class fan-out with structured
14//! join through `Par` frames.
15//! - Suspensions are identified by `SuspensionId` and can be N-in-flight;
16//! the host resolves each with `Ok(Value)` or `Err(EffectError)`.
17//! - Fan-out is expressed by a `Par` frame with a `JoinPolicy` (shape +
18//! fail); reducers fold the collected slots into the parent value.
19//! - Cancellation is cooperative; the host drains cancelled ids via
20//! `take_cancellations()` and looks them up in its own runtime-handle
21//! map.
22//!
23//! The full behavioural specification lives in the rustdoc of
24//! [`Engine`], [`Stepper`], and the item-level contracts they link.
25
26#![warn(missing_docs)]
27
28// Re-exported for `#[derive(DslExec)]`-generated code (`Call` payload
29// construction); not part of the public API surface.
30#[doc(hidden)]
31pub use serde_json;
32
33use std::borrow::Cow;
34use std::collections::{BTreeMap, HashMap};
35use std::fmt;
36use std::sync::atomic::{AtomicU64, Ordering};
37use std::sync::{Arc, Mutex};
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// ---------- Observation primitives --------------------------------------
50
51/// Stable identifier assigned to every AST node when the tree is built.
52///
53/// A `NodeId` is orthogonal to source location: two nodes at the same
54/// source span but in different expansions carry different IDs, and the
55/// same node retains its ID across evaluation runs.
56///
57/// Ordered by the allocation counter behind it, so an ordered map keyed
58/// on `NodeId` (e.g. [`AllowTable`]) iterates in allocation order.
59#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
60pub struct NodeId(pub u64);
61
62impl fmt::Display for NodeId {
63 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
64 write!(f, "n{}", self.0)
65 }
66}
67
68/// Identifier for a single activation of a function-like node.
69#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
70pub struct CallFrameId(pub u64);
71
72impl fmt::Display for CallFrameId {
73 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
74 write!(f, "f{}", self.0)
75 }
76}
77
78/// Position within the current iteration of a loop-shaped node.
79#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
80pub struct Iteration(pub u64);
81
82/// Root-to-node identifier chain, usable for path-shaped breakpoint
83/// conditions.
84#[derive(Debug, Clone, PartialEq, Eq, Hash, Default)]
85pub struct Path(pub Vec<NodeId>);
86
87impl Path {
88 /// Returns an empty path (i.e. the root).
89 #[inline]
90 pub fn root() -> Self {
91 Path(Vec::new())
92 }
93
94 /// Returns a new path with `node` pushed onto the end.
95 pub fn push(&self, node: NodeId) -> Self {
96 let mut next = self.0.clone();
97 next.push(node);
98 Path(next)
99 }
100
101 /// Depth of the path (number of node IDs).
102 #[inline]
103 pub fn depth(&self) -> usize {
104 self.0.len()
105 }
106
107 /// Returns the node ID at the tip of the path, if any.
108 pub fn tip(&self) -> Option<NodeId> {
109 self.0.last().copied()
110 }
111}
112
113impl fmt::Display for Path {
114 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
115 if self.0.is_empty() {
116 return write!(f, "/");
117 }
118 for id in &self.0 {
119 write!(f, "/{id}")?;
120 }
121 Ok(())
122 }
123}
124
125/// Lint rules a document allowed at specific nodes, keyed by the
126/// [`NodeId`] the build minted for the annotated node.
127///
128/// A document annotates a node with the rule names it wants suppressed
129/// there; the build carries those names across to the typed AST, where
130/// the node's identity is a `NodeId` rather than a source position.
131/// [`IdGen::take_allows`] produces the table and a linter consumes it —
132/// the two halves never have to agree on anything but the id.
133///
134/// The backing map is ordered, so iteration is deterministic and two
135/// runs over the same document produce byte-identical reports.
136#[derive(Debug, Clone, Default, PartialEq, Eq)]
137pub struct AllowTable(BTreeMap<NodeId, Vec<String>>);
138
139impl AllowTable {
140 /// Records the rule names allowed at `id`, replacing any names
141 /// previously recorded for it.
142 pub fn insert(&mut self, id: NodeId, allows: Vec<String>) {
143 self.0.insert(id, allows);
144 }
145
146 /// Rule names allowed at `id`, or `None` when the node carries no
147 /// annotation.
148 pub fn get(&self, id: &NodeId) -> Option<&Vec<String>> {
149 self.0.get(id)
150 }
151
152 /// Iterates the annotated nodes in ascending [`NodeId`] order.
153 pub fn iter(&self) -> impl Iterator<Item = (&NodeId, &Vec<String>)> {
154 self.0.iter()
155 }
156
157 /// True when no node carries an annotation.
158 pub fn is_empty(&self) -> bool {
159 self.0.is_empty()
160 }
161
162 /// Number of annotated nodes.
163 pub fn len(&self) -> usize {
164 self.0.len()
165 }
166}
167
168/// Monotonic ID generator for nodes and call frames.
169///
170/// Also the collection point for per-node annotations a front-end
171/// carried through the parse trunk: the build records them against the
172/// id it just minted ([`Self::record_allows`]) and the host drains them
173/// once the tree is built ([`Self::take_allows`]).
174#[derive(Debug, Default)]
175pub struct IdGen {
176 next: AtomicU64,
177 /// Pending `(node, allowed rule names)` pairs, in the order the
178 /// build recorded them. A `Mutex` (rather than the lock-free
179 /// counter next to it) because the payload is not a scalar; the
180 /// lock is held only for a push / take.
181 allows: Mutex<Vec<(NodeId, Vec<String>)>>,
182}
183
184impl IdGen {
185 /// Creates a fresh generator initialised at zero.
186 pub const fn new() -> Self {
187 Self {
188 next: AtomicU64::new(0),
189 allows: Mutex::new(Vec::new()),
190 }
191 }
192
193 /// Allocates a fresh `NodeId`.
194 pub fn node(&self) -> NodeId {
195 NodeId(self.next.fetch_add(1, Ordering::Relaxed))
196 }
197
198 /// Allocates a fresh `CallFrameId`.
199 pub fn frame(&self) -> CallFrameId {
200 CallFrameId(self.next.fetch_add(1, Ordering::Relaxed))
201 }
202
203 /// Records the rule names a document allowed at `id`.
204 ///
205 /// Called by `#[derive(DslBuild)]`-generated code for every node
206 /// whose parse tree carried an annotation; hand-written builds may
207 /// call it too. Recording nothing is the normal case, so an
208 /// un-annotated document leaves the generator untouched.
209 pub fn record_allows(&self, id: NodeId, allows: Vec<String>) {
210 self.lock_allows().push((id, allows));
211 }
212
213 /// Drains every recorded annotation into an [`AllowTable`].
214 ///
215 /// The host's order is `from_parse_tree` first, `take_allows`
216 /// second: the build mints the ids and records against them, then
217 /// this hands the accumulated table over to whoever consumes it
218 /// (the linter). Draining leaves the generator empty, so a second
219 /// call returns an empty table — take once and keep the result.
220 pub fn take_allows(&self) -> AllowTable {
221 let mut table = AllowTable::default();
222 for (id, allows) in std::mem::take(&mut *self.lock_allows()) {
223 table.insert(id, allows);
224 }
225 table
226 }
227
228 /// Locks the annotation buffer, recovering from poisoning.
229 ///
230 /// The only code under the lock is a `push` / `mem::take`, neither
231 /// of which can leave the `Vec` in a torn state, so a poisoned
232 /// mutex (some other thread panicked while holding it) carries no
233 /// broken invariant worth propagating.
234 fn lock_allows(&self) -> std::sync::MutexGuard<'_, Vec<(NodeId, Vec<String>)>> {
235 self.allows.lock().unwrap_or_else(|e| e.into_inner())
236 }
237}
238
239/// Location context attached to every emitted event and to every error.
240#[derive(Debug, Clone, PartialEq, Eq)]
241pub struct NodeContext {
242 /// The node currently being evaluated.
243 pub node: NodeId,
244 /// The root-to-node path leading to `node`.
245 pub path: Path,
246 /// The active call frame, if any.
247 pub frame: Option<CallFrameId>,
248 /// Depth of the current call / evaluation stack.
249 pub depth: u32,
250 /// Iteration counter when the surrounding node is loop-shaped.
251 pub iteration: Option<Iteration>,
252}
253
254impl NodeContext {
255 /// Builds a context for a node visited without any active frame.
256 pub fn at(node: NodeId, path: Path) -> Self {
257 Self {
258 node,
259 path,
260 frame: None,
261 depth: 0,
262 iteration: None,
263 }
264 }
265}
266
267impl fmt::Display for NodeContext {
268 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
269 write!(f, "{}", self.node)?;
270 if let Some(frame) = self.frame {
271 write!(f, " (frame {}, depth {})", frame, self.depth)?;
272 }
273 if let Some(it) = self.iteration {
274 write!(f, " iter {}", it.0)?;
275 }
276 write!(f, " at {}", self.path)
277 }
278}
279
280// ---------- Suspension identity ----------------------------------------
281
282/// Stable identifier for one in-flight suspension.
283///
284/// Allocated by the engine when a `Frame::PendingEffect` leaf is created.
285/// The host uses it as the key on [`Stepper::resolve`] and as the map key
286/// for its own `SuspensionId -> runtime handle` bookkeeping when
287/// cooperative cancellation is required. Monotonic within one `Stepper`
288/// instance; never reused, even after cancellation.
289#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
290pub struct SuspensionId(pub u64);
291
292impl fmt::Display for SuspensionId {
293 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
294 write!(f, "s{}", self.0)
295 }
296}
297
298/// One live suspension.
299#[derive(Debug, Clone)]
300pub struct Pending {
301 /// Stable identifier.
302 pub id: SuspensionId,
303 /// Why the engine yielded.
304 pub reason: SuspendReason,
305 /// Where the suspension happened.
306 pub at: NodeContext,
307}
308
309// ---------- Suspend reason ---------------------------------------------
310
311/// Why the engine yielded control.
312///
313/// Cancellation runtime handles are NOT stored here — the host maintains
314/// its own `SuspensionId -> handle` map.
315#[derive(Debug, Clone)]
316#[non_exhaustive]
317pub enum SuspendReason {
318 /// A first-class external effect (LLM call, tool invocation, …).
319 Call {
320 /// Host-defined effect descriptor.
321 spec: CallSpec,
322 },
323 /// A registered breakpoint fired.
324 Breakpoint,
325 /// The scheduler chose to yield cooperatively.
326 Cooperative,
327 /// Host-defined effect the DSL wants to model beyond `Call`.
328 User {
329 /// Short tag identifying the effect kind.
330 tag: Cow<'static, str>,
331 },
332}
333
334impl fmt::Display for SuspendReason {
335 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
336 match self {
337 SuspendReason::Call { spec } => write!(f, "call({})", spec.label),
338 SuspendReason::Breakpoint => write!(f, "breakpoint"),
339 SuspendReason::Cooperative => write!(f, "cooperative"),
340 SuspendReason::User { tag } => write!(f, "user({tag})"),
341 }
342 }
343}
344
345/// Host-defined effect descriptor. Opaque to the engine.
346#[derive(Debug, Clone)]
347pub struct CallSpec {
348 /// Short human-readable label (also fed into the DSL's canned
349 /// responses when applicable).
350 pub label: String,
351 /// Effect payload; the engine stores it verbatim and the host
352 /// interprets it per the DSL's semantics.
353 pub payload: serde_json::Value,
354}
355
356// ---------- Event stream -----------------------------------------------
357
358/// One observation from the evaluator.
359#[derive(Debug, Clone)]
360#[non_exhaustive]
361pub enum Event {
362 /// Emitted before a node's semantics run.
363 VisitPre {
364 /// Where the observation happened.
365 at: NodeContext,
366 },
367 /// Emitted after a node's semantics complete.
368 VisitPost {
369 /// Where the observation happened.
370 at: NodeContext,
371 },
372 /// A function-like node started a new call frame.
373 FrameEnter {
374 /// Where the observation happened.
375 at: NodeContext,
376 },
377 /// A function-like node's frame ended.
378 FrameLeave {
379 /// Where the observation happened.
380 at: NodeContext,
381 },
382 /// A loop node advanced to a new iteration.
383 IterationTick {
384 /// Where the observation happened.
385 at: NodeContext,
386 },
387 /// The stepper is about to yield to the outside world.
388 Suspend {
389 /// Where the observation happened.
390 at: NodeContext,
391 /// Why the stepper is yielding.
392 reason: SuspendReason,
393 },
394 /// The stepper resumed after a yield.
395 Resume {
396 /// Where the observation happened.
397 at: NodeContext,
398 },
399 /// A suspension was cancelled (tracer convenience; the authoritative
400 /// channel is [`Stepper::take_cancellations`]).
401 Cancel {
402 /// The cancelled suspension.
403 id: SuspensionId,
404 },
405}
406
407/// Sink for the event stream.
408pub trait EventSink {
409 /// Consumes one event.
410 fn emit(&mut self, event: &Event);
411}
412
413/// A no-op sink useful for tests and for evaluators that do not need
414/// observation.
415#[derive(Debug, Default)]
416pub struct NullSink;
417
418impl EventSink for NullSink {
419 #[inline]
420 fn emit(&mut self, _event: &Event) {}
421}
422
423/// Silent event sink that counts each event kind.
424///
425/// Used by the engine as its default observation channel so hosts
426/// can inspect basic activity without wiring a custom sink.
427#[derive(Debug, Default, Clone, Copy)]
428pub struct CountingSink {
429 /// Number of `VisitPre` events observed.
430 pub visit_pre: u32,
431 /// Number of `VisitPost` events observed.
432 pub visit_post: u32,
433 /// Number of `FrameEnter` events observed.
434 pub frame_enter: u32,
435 /// Number of `FrameLeave` events observed.
436 pub frame_leave: u32,
437 /// Number of `IterationTick` events observed.
438 pub iteration_tick: u32,
439 /// Number of `Suspend` events observed.
440 pub suspend: u32,
441 /// Number of `Resume` events observed.
442 pub resume: u32,
443}
444
445impl EventSink for CountingSink {
446 fn emit(&mut self, event: &Event) {
447 match event {
448 Event::VisitPre { .. } => self.visit_pre += 1,
449 Event::VisitPost { .. } => self.visit_post += 1,
450 Event::FrameEnter { .. } => self.frame_enter += 1,
451 Event::FrameLeave { .. } => self.frame_leave += 1,
452 Event::IterationTick { .. } => self.iteration_tick += 1,
453 Event::Suspend { .. } => self.suspend += 1,
454 Event::Resume { .. } => self.resume += 1,
455 _ => {}
456 }
457 }
458}
459
460impl CountingSink {
461 /// Returns a single-line human-readable event histogram.
462 pub fn summarise(&self) -> String {
463 format!(
464 "pre={} post={} frame_enter={} frame_leave={} iter={} suspend={} resume={}",
465 self.visit_pre,
466 self.visit_post,
467 self.frame_enter,
468 self.frame_leave,
469 self.iteration_tick,
470 self.suspend,
471 self.resume,
472 )
473 }
474}
475
476/// Recording event sink that keeps every observed [`Event`] in order.
477///
478/// Complements [`CountingSink`] (built-in on `Engine`) by preserving the
479/// full event history for downstream inspection — debuggers, tracers,
480/// test assertions, etc. Attach one to an engine via
481/// `Engine::attach_sink` and drain / snapshot it between mutations.
482#[derive(Debug, Default, Clone)]
483pub struct BufferingSink {
484 events: Vec<Event>,
485}
486
487impl BufferingSink {
488 /// Creates an empty, unbounded buffer.
489 pub fn new() -> Self {
490 Self { events: Vec::new() }
491 }
492
493 /// Creates an empty buffer with pre-allocated capacity `cap`.
494 ///
495 /// The buffer is still logically unbounded; `cap` is only a
496 /// hint to avoid early re-allocations.
497 pub fn with_capacity(cap: usize) -> Self {
498 Self {
499 events: Vec::with_capacity(cap),
500 }
501 }
502
503 /// Returns a slice view of the recorded events without draining.
504 pub fn snapshot(&self) -> &[Event] {
505 &self.events
506 }
507
508 /// Takes every recorded event and clears the buffer.
509 pub fn drain(&mut self) -> Vec<Event> {
510 std::mem::take(&mut self.events)
511 }
512
513 /// Discards every recorded event without returning them.
514 pub fn clear(&mut self) {
515 self.events.clear();
516 }
517
518 /// Number of recorded events currently held.
519 pub fn len(&self) -> usize {
520 self.events.len()
521 }
522
523 /// True when no events are held.
524 pub fn is_empty(&self) -> bool {
525 self.events.is_empty()
526 }
527}
528
529impl EventSink for BufferingSink {
530 fn emit(&mut self, event: &Event) {
531 self.events.push(event.clone());
532 }
533}
534
535// ---------- Errors ------------------------------------------------------
536
537/// Structured error type for engine and evaluator failures.
538///
539/// Every applicable variant carries a [`NodeContext`] or a
540/// [`SuspensionId`] / [`ReducerId`] so that error messages, MCP tool
541/// responses, and log lines can always answer "at which node / for
542/// which id did this happen?". Diagnostic codes are stable,
543/// machine-readable identifiers under the `dsl_kit::` namespace.
544#[derive(Debug, thiserror::Error, miette::Diagnostic)]
545#[non_exhaustive]
546pub enum EngineError {
547 /// The evaluator explicitly aborted the current step.
548 #[error("evaluation aborted at {at}: {reason}")]
549 #[diagnostic(
550 code(dsl_kit::eval::aborted),
551 help(
552 "The interpreter returned an `Aborted` outcome. Inspect the reason and the node context to locate the abort site."
553 )
554 )]
555 Aborted {
556 /// Where the abort happened.
557 at: NodeContext,
558 /// Why the evaluator aborted.
559 reason: String,
560 },
561
562 /// A node's semantics returned an error.
563 #[error("evaluator failed at {at}")]
564 #[diagnostic(
565 code(dsl_kit::eval::failed),
566 help(
567 "The interpreter returned an error while evaluating this node. The `#[source]` chain points at the underlying failure."
568 )
569 )]
570 EvalFailed {
571 /// Where the failure happened.
572 at: NodeContext,
573 /// The underlying error returned by the interpreter.
574 #[source]
575 source: Box<dyn std::error::Error + Send + Sync>,
576 },
577
578 /// A traversal or stepper reached a node that was expected to have a
579 /// specific shape but did not.
580 #[error("malformed AST at {at}: {detail}")]
581 #[diagnostic(
582 code(dsl_kit::ast::malformed),
583 help(
584 "An AST invariant was violated. This usually means a hand-constructed tree omitted a required child."
585 )
586 )]
587 Malformed {
588 /// Where the invariant violation was detected.
589 at: NodeContext,
590 /// Human-readable description of the invariant that failed.
591 detail: String,
592 },
593
594 /// The host tried to resume a suspended stepper before it had suspended,
595 /// or resumed twice for a single suspension.
596 #[error("stepper protocol violation at {at}: {detail}")]
597 #[diagnostic(
598 code(dsl_kit::stepper::protocol),
599 help(
600 "The stepper's suspend/resume contract was broken. Each `PendingEffect` leaf must be resolved exactly once before further steps observe its value."
601 )
602 )]
603 StepperProtocol {
604 /// Where the protocol violation was detected.
605 at: NodeContext,
606 /// Human-readable description of the misuse.
607 detail: String,
608 },
609
610 /// The host called `resolve` with a `SuspensionId` the engine does
611 /// not know about (never created, already resolved, or belonging to
612 /// a cancelled leg). Hosts treat this as a benign no-op — it
613 /// happens routinely for cancelled effects whose external work
614 /// completes after abort.
615 #[error("unknown suspension {id}")]
616 #[diagnostic(
617 code(dsl_kit::stepper::unknown_suspension),
618 help(
619 "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."
620 )
621 )]
622 UnknownSuspension {
623 /// The unknown suspension id.
624 id: SuspensionId,
625 },
626
627 /// A `ParFrame` referenced a `ReducerId` that is not registered in
628 /// the active [`ReducerRegistry`].
629 #[error("unknown reducer {id:?}{hint}")]
630 #[diagnostic(
631 code(dsl_kit::reducer::unknown),
632 help(
633 "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."
634 )
635 )]
636 UnknownReducer {
637 /// The unknown reducer id.
638 id: ReducerId,
639 /// Optional `did you mean` hint produced by the registry's
640 /// injected [`Suggester`]. Empty when no suggester is wired
641 /// or no candidate scored above threshold, so the historical
642 /// `unknown reducer "X"` wording is preserved as the base
643 /// case.
644 hint: String,
645 },
646
647 /// An `Apply` node referenced an [`OpId`] that is not registered in
648 /// the active [`OpRegistry`].
649 #[error("unknown op {id:?}{hint}")]
650 #[diagnostic(
651 code(dsl_kit::op::unknown),
652 help(
653 "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."
654 )
655 )]
656 UnknownOp {
657 /// The unknown op id.
658 id: OpId,
659 /// Optional `did you mean` hint produced by the registry's
660 /// injected [`Suggester`]. Same semantics as
661 /// [`Self::UnknownReducer::hint`].
662 hint: String,
663 },
664}
665
666/// Result alias for engine and evaluator operations.
667pub type EngineResult<T> = Result<T, EngineError>;
668
669/// One entry in an error catalogue: a stable machine-readable code paired
670/// with the human-readable help text explaining how to react to it.
671#[derive(Debug, Clone, PartialEq, Eq)]
672pub struct ErrorCatalogEntry {
673 /// Stable diagnostic code, e.g. `"dsl_kit::eval::aborted"`.
674 pub code: String,
675 /// Help text mirroring the miette `help(..)` attribute on the variant.
676 pub help: String,
677}
678
679/// Returns the built-in [`EngineError`] catalogue.
680pub fn engine_error_catalog() -> Vec<ErrorCatalogEntry> {
681 use miette::Diagnostic;
682
683 fn ctx() -> NodeContext {
684 NodeContext::at(NodeId(0), Path::root())
685 }
686
687 let samples: Vec<EngineError> = vec![
688 EngineError::Aborted {
689 at: ctx(),
690 reason: String::new(),
691 },
692 EngineError::EvalFailed {
693 at: ctx(),
694 source: Box::new(std::io::Error::other("")),
695 },
696 EngineError::Malformed {
697 at: ctx(),
698 detail: String::new(),
699 },
700 EngineError::StepperProtocol {
701 at: ctx(),
702 detail: String::new(),
703 },
704 EngineError::UnknownSuspension {
705 id: SuspensionId(0),
706 },
707 EngineError::UnknownReducer {
708 id: ReducerId(String::new()),
709 hint: String::new(),
710 },
711 EngineError::UnknownOp {
712 id: OpId(String::new()),
713 hint: String::new(),
714 },
715 ];
716
717 samples
718 .into_iter()
719 .filter_map(|e| {
720 let code = e.code()?.to_string();
721 let help = e.help()?.to_string();
722 Some(ErrorCatalogEntry { code, help })
723 })
724 .collect()
725}
726
727// ---------- Step outcome & Stepper -------------------------------------
728
729/// Result of one [`Stepper::step`] call.
730///
731/// The three states name the driver's next action verbatim:
732///
733/// - `Ready` — the engine made progress and can make more without host
734/// input. Call `step()` again immediately.
735/// - `Blocked { newly_pending }` — the engine did everything it can
736/// without host input. Do NOT call `step()` again until at least one
737/// `resolve` has been fed back, or a cancellation observed via
738/// `take_cancellations()`.
739/// - `Done(v)` — the root frame produced a value; interpretation is
740/// complete.
741///
742/// Terminal failure is returned as `Err(Stepper::Error)` from `step()`;
743/// there is no `Failed` variant. Cancellations queued during the failing
744/// step are still drainable via `take_cancellations()` after the `Err`.
745#[derive(Debug, Clone)]
746pub enum StepOutcome<V> {
747 /// Engine advanced; keep looping.
748 Ready,
749 /// Engine is blocked awaiting host input. `newly_pending` names
750 /// suspensions created this call (may be empty when the block is
751 /// on already-live pending).
752 Blocked {
753 /// Suspensions newly created during this `step` call.
754 newly_pending: smallvec::SmallVec<[Pending; 1]>,
755 },
756 /// Interpretation completed with a value.
757 Done(V),
758}
759
760/// Something that can be driven one step at a time from the outside.
761///
762/// v3 shape: sync trait, generic in `V` / `C` / `D` / `EffectError` /
763/// `Error`. Async is a host concern — a host wrapping the stepper in
764/// `FuturesUnordered<ResolverFuture>` is the canonical async story.
765pub trait Stepper {
766 /// Value the stepper produces on completion.
767 type Value;
768 /// DSL-specific node cursor state stored inside `Frame::Node`.
769 type Cursor;
770 /// DSL-specific state delta / write log stored inside `Env` and
771 /// merged by reducers at join.
772 type Delta;
773 /// DSL-specific effect-side failure surfaced via `resolve`.
774 type EffectError: std::error::Error + Send + Sync + 'static;
775 /// DSL / engine-level error surfaced from `step` and `resolve`.
776 type Error: From<Self::EffectError> + std::error::Error + Send + Sync + 'static;
777
778 /// Advance the interpretation as far as possible without host input.
779 fn step(&mut self) -> Result<StepOutcome<Self::Value>, Self::Error>;
780
781 /// Feed a response back for one pending suspension.
782 ///
783 /// Order-independent; the host may resolve pending IDs in any
784 /// order. Unknown IDs return an error the host may treat as a
785 /// benign no-op (see [`EngineError::UnknownSuspension`]).
786 fn resolve(
787 &mut self,
788 id: SuspensionId,
789 result: Result<Self::Value, Self::EffectError>,
790 ) -> Result<(), Self::Error>;
791
792 /// Snapshot of every suspension currently blocking the tree.
793 /// Excludes ids under `Frame::Cancelled` sub-trees. Order matches
794 /// DFS pre-order over the frame tree.
795 fn pending(&self) -> &[Pending];
796
797 /// Drain the set of suspensions the engine has just cancelled.
798 /// Must be called after every `Ok(Ready)` AND every `Err(_)`
799 /// return from `step()`.
800 fn take_cancellations(&mut self) -> Vec<SuspensionId>;
801
802 /// Root of the live frame tree. Debugger read.
803 fn frame_tree(&self) -> &FrameTree<Self::Value, Self::Cursor, Self::Delta, Self::EffectError>;
804
805 /// True when the root has produced a value.
806 fn is_done(&self) -> bool;
807}
808
809// ---------- Frame tree --------------------------------------------------
810
811/// Which child slot in a `ParFrame` a value corresponds to.
812pub type ChildIndex = usize;
813
814/// Why a sub-tree was cancelled.
815#[derive(Debug, Clone)]
816pub enum CancelReason {
817 /// Cancelled because the enclosing `Par` policy fired
818 /// (`Any` / `FirstK` winner selected).
819 ParPolicyFired,
820 /// Cancelled because a sibling failed (FailFast).
821 SiblingFailed,
822}
823
824/// One node in the live frame tree.
825#[derive(Debug)]
826pub enum Frame<V, C, D, EE> {
827 /// An interior interpretation node currently executing.
828 Node {
829 /// AST node this frame is interpreting.
830 node: NodeId,
831 /// Shared environment snapshot.
832 env: EnvRef<D>,
833 /// DSL-specific cursor (opaque to the engine).
834 cursor: C,
835 },
836 /// A fan-out root. Children live on the enclosing `FrameTree.kids`.
837 Par(ParFrame<V, D, EE>),
838 /// A labelled section wrapper (no fan-out semantics).
839 Scope {
840 /// Section label.
841 label: String,
842 /// Shared environment snapshot.
843 env: EnvRef<D>,
844 },
845 /// A leaf blocked on an external effect.
846 PendingEffect {
847 /// Stable id (also present in `Stepper::pending`).
848 id: SuspensionId,
849 },
850 /// A leaf whose value is ready and waiting to be consumed by its
851 /// parent frame's continuation.
852 Value(V),
853 /// A sub-tree the engine has cancelled. Never selected for `step()`
854 /// progress; kept so the debugger can render it.
855 Cancelled {
856 /// Why the sub-tree was cancelled.
857 reason: CancelReason,
858 },
859}
860
861/// Tree of frames. `kids[i]` under a `Par` root is the `i`-th sibling
862/// child, matched positionally with `ParFrame.slots[i]` and
863/// `ParFrame.deltas[i]`.
864#[derive(Debug)]
865pub struct FrameTree<V, C, D, EE> {
866 /// The frame at this node.
867 pub root: Frame<V, C, D, EE>,
868 /// Child sub-trees.
869 pub kids: Vec<FrameTree<V, C, D, EE>>,
870}
871
872/// Fan-out metadata.
873///
874/// `children` are stored on the enclosing `FrameTree.kids`; `slots`,
875/// `deltas`, and `completion_order` are indexed against that same
876/// positional list.
877#[derive(Debug)]
878pub struct ParFrame<V, D, EE> {
879 /// Policy (shape + fail).
880 pub policy: JoinPolicy,
881 /// `slots[i]` is `Some(v)` once child i completed successfully;
882 /// `None` while still running, pending, or cancelled without a
883 /// value. FailFast: reroutes failure to `Err` before reducer.
884 /// CollectAll: per-child failures live in `failures[i]`; combine
885 /// slot + failure at reducer-invocation time.
886 pub slots: Vec<Option<V>>,
887 /// Per-child effect-side failures (CollectAll only). `Some(e)`
888 /// once the child resolved with `Err(e)`; always `None` under
889 /// FailFast (failures reroute to `Err` before the reducer runs).
890 pub failures: Vec<Option<EE>>,
891 /// Per-child accumulated delta.
892 pub deltas: Vec<Option<D>>,
893 /// Order in which children completed successfully.
894 pub completion_order: Vec<ChildIndex>,
895 /// Registry key for the reducer.
896 pub reducer_id: ReducerId,
897 /// Resolved reducer handle (FailFast or CollectAll, matching
898 /// `policy.fail`).
899 pub reducer: ReducerHandle<V, D, EE>,
900 /// True once the shape has fired.
901 pub joined: bool,
902}
903
904// ---------- Join policy -------------------------------------------------
905
906/// Full policy for a `ParFrame`: success-side `shape` + failure-side
907/// `fail`.
908#[derive(Debug, Clone, Copy)]
909pub struct JoinPolicy {
910 /// Success completion condition.
911 pub shape: JoinShape,
912 /// Failure handling.
913 pub fail: FailPolicy,
914}
915
916/// Success-side completion condition.
917#[derive(Debug, Clone, Copy)]
918pub enum JoinShape {
919 /// Every child must complete successfully.
920 All,
921 /// The first successful child wins; remaining children are cancelled.
922 Any,
923 /// The first `k` successful children win; remaining children are
924 /// cancelled.
925 FirstK(usize),
926}
927
928/// Failure-side policy.
929#[derive(Debug, Clone, Copy)]
930pub enum FailPolicy {
931 /// A single child failure aborts the `Par` immediately.
932 FailFast,
933 /// Failures are collected into slots; shape completion still decides
934 /// based on the count of successes.
935 CollectAll,
936}
937
938// ---------- Reducer trait + registry -----------------------------------
939
940/// Serialisable name for a registered reducer.
941#[derive(Debug, Clone, PartialEq, Eq, Hash)]
942pub struct ReducerId(pub String);
943
944impl fmt::Display for ReducerId {
945 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
946 write!(f, "{}", self.0)
947 }
948}
949
950impl From<&str> for ReducerId {
951 fn from(s: &str) -> Self {
952 ReducerId(s.to_string())
953 }
954}
955
956impl From<String> for ReducerId {
957 fn from(s: String) -> Self {
958 ReducerId(s)
959 }
960}
961
962/// FailFast reducer. Sees successful joins only.
963pub trait Reducer<V, D>: Send + Sync {
964 /// Fold slots + deltas + completion order into a joined `(V, D)`.
965 fn reduce(
966 &self,
967 slots: &[Option<V>],
968 deltas: &[Option<D>],
969 winners: &[ChildIndex],
970 ) -> Result<(V, D), EngineError>;
971}
972
973/// CollectAll reducer. Sees the full success/failure slot vector.
974pub trait ReducerCollectAll<V, D, EffectError>: Send + Sync {
975 /// Fold slots (each `Some(Ok)` / `Some(Err)` / `None`) + deltas +
976 /// completion order into a joined `(V, D)`.
977 fn reduce(
978 &self,
979 slots: &[Option<Result<V, EffectError>>],
980 deltas: &[Option<D>],
981 winners: &[ChildIndex],
982 ) -> Result<(V, D), EngineError>;
983}
984
985/// Runtime handle for the resolved reducer of a `ParFrame`.
986///
987/// Which variant is present is dictated by `JoinPolicy.fail`. The
988/// `CollectAll` variant is typed directly in the effect-error `EE`
989/// so the engine can invoke `reduce` on a `&[Option<Result<V, EE>>]`
990/// slot vector at fold time without any downcast.
991pub enum ReducerHandle<V, D, EE> {
992 /// FailFast-typed reducer.
993 FailFast(Arc<dyn Reducer<V, D>>),
994 /// CollectAll-typed reducer, typed in the effect-error `EE`.
995 CollectAll(Arc<dyn ReducerCollectAll<V, D, EE>>),
996}
997
998impl<V, D, EE> fmt::Debug for ReducerHandle<V, D, EE> {
999 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1000 match self {
1001 ReducerHandle::FailFast(_) => f.write_str("ReducerHandle::FailFast(..)"),
1002 ReducerHandle::CollectAll(_) => f.write_str("ReducerHandle::CollectAll(..)"),
1003 }
1004 }
1005}
1006
1007impl<V, D, EE> Clone for ReducerHandle<V, D, EE> {
1008 fn clone(&self) -> Self {
1009 match self {
1010 ReducerHandle::FailFast(a) => ReducerHandle::FailFast(a.clone()),
1011 ReducerHandle::CollectAll(a) => ReducerHandle::CollectAll(a.clone()),
1012 }
1013 }
1014}
1015
1016/// Runtime lookup table.
1017///
1018/// Constructed by the host at Stepper build time; a DSL typically ships
1019/// a helper `default_registry()` that registers its standard reducers
1020/// under the canonical ids (`"reduce_all_ordered"` etc.).
1021pub struct ReducerRegistry<V, D, EffectError> {
1022 fail_fast: HashMap<ReducerId, Arc<dyn Reducer<V, D>>>,
1023 collect_all: HashMap<ReducerId, Arc<dyn ReducerCollectAll<V, D, EffectError>>>,
1024 suggester: crate::suggest::SuggesterHandle,
1025}
1026
1027impl<V, D, EE> Default for ReducerRegistry<V, D, EE> {
1028 fn default() -> Self {
1029 Self::new()
1030 }
1031}
1032
1033impl<V, D, EE> ReducerRegistry<V, D, EE> {
1034 /// Creates an empty registry.
1035 pub fn new() -> Self {
1036 Self {
1037 fail_fast: HashMap::new(),
1038 collect_all: HashMap::new(),
1039 suggester: crate::suggest::noop_handle(),
1040 }
1041 }
1042
1043 /// Injects a fuzzy-match [`Suggester`](crate::Suggester) used to
1044 /// enrich [`EngineError::UnknownReducer`] with a `did you mean X?`
1045 /// hint at [`Self::resolve`] time.
1046 ///
1047 /// The default is a no-op suggester, so the crate stays free of a
1048 /// similarity algorithm on its own. Pass
1049 /// `Arc::new(dsl_kit_fuzzy::FuzzySuggester::default())` (or any
1050 /// other [`Suggester`](crate::Suggester) impl) at the composition
1051 /// root to enable hints.
1052 pub fn with_suggester(mut self, suggester: crate::suggest::SuggesterHandle) -> Self {
1053 self.suggester = suggester;
1054 self
1055 }
1056
1057 /// Registers a FailFast-typed reducer under `id`.
1058 pub fn register_fail_fast(
1059 &mut self,
1060 id: impl Into<ReducerId>,
1061 reducer: Arc<dyn Reducer<V, D>>,
1062 ) {
1063 self.fail_fast.insert(id.into(), reducer);
1064 }
1065
1066 /// Registers a CollectAll-typed reducer under `id`.
1067 pub fn register_collect_all(
1068 &mut self,
1069 id: impl Into<ReducerId>,
1070 reducer: Arc<dyn ReducerCollectAll<V, D, EE>>,
1071 ) {
1072 self.collect_all.insert(id.into(), reducer);
1073 }
1074
1075 /// Resolves the reducer for a `ParFrame` at construction time.
1076 ///
1077 /// The `fail` argument disambiguates when the same id has been
1078 /// registered under both traits. Returns
1079 /// `EngineError::UnknownReducer` on miss.
1080 pub fn resolve(
1081 &self,
1082 id: &ReducerId,
1083 fail: FailPolicy,
1084 ) -> Result<ReducerHandle<V, D, EE>, EngineError> {
1085 let miss = || {
1086 // Candidates are drawn from the branch the caller asked
1087 // for so the hint never suggests an id that would still
1088 // miss under the same `fail` policy.
1089 let names: Vec<&str> = match fail {
1090 FailPolicy::FailFast => self.fail_fast.keys().map(|k| k.0.as_str()).collect(),
1091 FailPolicy::CollectAll => self.collect_all.keys().map(|k| k.0.as_str()).collect(),
1092 };
1093 let hint = self
1094 .suggester
1095 .enrich_unknown(&id.0, &names)
1096 .map(|h| format!(" ({h})"))
1097 .unwrap_or_default();
1098 EngineError::UnknownReducer {
1099 id: id.clone(),
1100 hint,
1101 }
1102 };
1103 match fail {
1104 FailPolicy::FailFast => self
1105 .fail_fast
1106 .get(id)
1107 .cloned()
1108 .map(ReducerHandle::FailFast)
1109 .ok_or_else(miss),
1110 FailPolicy::CollectAll => self
1111 .collect_all
1112 .get(id)
1113 .cloned()
1114 .map(ReducerHandle::CollectAll)
1115 .ok_or_else(miss),
1116 }
1117 }
1118}
1119
1120// ---------- Op trait + registry -----------------------------------------
1121
1122/// Serialisable name for a registered op.
1123#[derive(Debug, Clone, PartialEq, Eq, Hash)]
1124pub struct OpId(pub String);
1125
1126impl fmt::Display for OpId {
1127 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1128 write!(f, "{}", self.0)
1129 }
1130}
1131
1132impl From<&str> for OpId {
1133 fn from(s: &str) -> Self {
1134 OpId(s.to_string())
1135 }
1136}
1137
1138impl From<String> for OpId {
1139 fn from(s: String) -> Self {
1140 OpId(s)
1141 }
1142}
1143
1144/// A pure value fold applied by an `Apply` node once every child
1145/// argument has produced a value.
1146///
1147/// Ops never suspend: effects belong in `Call` children, whose values
1148/// arrive here as ordinary `args` entries. Domain failures (division by
1149/// zero, type mismatch on a dynamic value) are reported as
1150/// [`EngineError::EvalFailed`] with the node context supplied by the
1151/// engine at the call site.
1152pub trait Op<V>: Send + Sync {
1153 /// Fold the evaluated child values into the node's value.
1154 ///
1155 /// `args` holds one entry per `Apply` child, in declaration order.
1156 /// Zero-child `Apply` nodes invoke the op with an empty slice.
1157 fn apply(&self, node: NodeId, args: &[V]) -> Result<V, EngineError>;
1158}
1159
1160/// Runtime handle for the resolved op of an `Apply` frame.
1161pub type OpHandle<V> = Arc<dyn Op<V>>;
1162
1163/// Runtime lookup table for [`Op`]s, the `Apply` counterpart of
1164/// [`ReducerRegistry`].
1165///
1166/// Constructed by the host at Stepper build time; a DSL typically ships
1167/// a helper that registers its standard ops under canonical ids
1168/// (`"add"`, `"mul"`, ...). Passed to [`Engine::new_with_ops`]; DSLs
1169/// with no `Apply` nodes can stay on [`Engine::new`], which uses an
1170/// empty registry.
1171///
1172/// [`Engine::new`]: crate::Engine::new
1173/// [`Engine::new_with_ops`]: crate::Engine::new_with_ops
1174pub struct OpRegistry<V> {
1175 ops: HashMap<OpId, OpHandle<V>>,
1176 suggester: crate::suggest::SuggesterHandle,
1177}
1178
1179impl<V> Default for OpRegistry<V> {
1180 fn default() -> Self {
1181 Self::new()
1182 }
1183}
1184
1185impl<V> OpRegistry<V> {
1186 /// Creates an empty registry.
1187 pub fn new() -> Self {
1188 Self {
1189 ops: HashMap::new(),
1190 suggester: crate::suggest::noop_handle(),
1191 }
1192 }
1193
1194 /// Injects a fuzzy-match [`Suggester`](crate::Suggester) used to
1195 /// enrich [`EngineError::UnknownOp`] with a `did you mean X?`
1196 /// hint at [`Self::resolve`] time.
1197 ///
1198 /// The default is a no-op suggester, so the crate stays free of a
1199 /// similarity algorithm on its own. Pass
1200 /// `Arc::new(dsl_kit_fuzzy::FuzzySuggester::default())` at the
1201 /// composition root to enable hints.
1202 pub fn with_suggester(mut self, suggester: crate::suggest::SuggesterHandle) -> Self {
1203 self.suggester = suggester;
1204 self
1205 }
1206
1207 /// Registers an op under `id`.
1208 pub fn register(&mut self, id: impl Into<OpId>, op: OpHandle<V>) {
1209 self.ops.insert(id.into(), op);
1210 }
1211
1212 /// Resolves the op for an `Apply` frame at spawn / validation time.
1213 /// Returns [`EngineError::UnknownOp`] on miss.
1214 pub fn resolve(&self, id: &OpId) -> Result<OpHandle<V>, EngineError> {
1215 self.ops.get(id).cloned().ok_or_else(|| {
1216 let names: Vec<&str> = self.ops.keys().map(|k| k.0.as_str()).collect();
1217 let hint = self
1218 .suggester
1219 .enrich_unknown(&id.0, &names)
1220 .map(|h| format!(" ({h})"))
1221 .unwrap_or_default();
1222 EngineError::UnknownOp {
1223 id: id.clone(),
1224 hint,
1225 }
1226 })
1227 }
1228}
1229
1230// ---------- Derived execution (DslExec / DslSemantics / DerivedAst) ----
1231
1232/// Mechanical node classification, normally supplied by
1233/// `#[derive(DslExec)]` from `dsl-kit-macros`.
1234///
1235/// This is the derivable half of an [`Ast`]: which engine [`NodeKind`]
1236/// each variant maps to, and the payload of `value`-marked literal
1237/// variants. The semantic half (value type, truthiness, bindings)
1238/// lives in [`DslSemantics`]; [`DerivedAst`] zips the two into an
1239/// engine-ready [`Ast`].
1240pub trait DslExec: Walk {
1241 /// Payload type of `#[dsl_exec(value)]` variants. `()` when the
1242 /// enum has no value variants.
1243 type LitValue: Clone + fmt::Debug;
1244
1245 /// Engine classification of this node.
1246 fn exec_kind(&self) -> NodeKind;
1247
1248 /// Payload of a value variant; `None` for every other variant.
1249 fn exec_literal(&self) -> Option<Self::LitValue>;
1250}
1251
1252/// The semantic half an author writes next to `#[derive(DslExec)]`:
1253/// the runtime value type and the hooks whose meaning the kit cannot
1254/// derive. Every hook mirrors its [`Ast`] counterpart and keeps the
1255/// same default, so a DSL only implements what its node kinds use.
1256pub trait DslSemantics {
1257 /// Runtime value type produced by the DSL.
1258 type Value: Clone + fmt::Debug;
1259 /// Per-child state delta accumulated across a `Par` and extended
1260 /// by `Bind`.
1261 type Delta: Clone + Default + fmt::Debug;
1262 /// Effect-side failure the host reports through `resolve`.
1263 type EffectError: std::error::Error + Clone + Send + Sync + 'static;
1264 /// Per-frame cursor surfaced through the projected frame tree.
1265 type Cursor: Clone + fmt::Debug + Default;
1266
1267 /// See [`Ast::unit_value`].
1268 fn unit_value(&self) -> Self::Value;
1269
1270 /// See [`Ast::truthy`].
1271 fn truthy(&self, _value: &Self::Value) -> Option<bool> {
1272 None
1273 }
1274
1275 /// See [`Ast::continue_loop`].
1276 fn continue_loop(&self, _node: NodeId, _last: &Self::Value, _iteration: usize) -> LoopDecision {
1277 LoopDecision::Break
1278 }
1279
1280 /// See [`Ast::bind_delta`].
1281 fn bind_delta(&self, _name: &str, _value: &Self::Value) -> Option<Self::Delta> {
1282 None
1283 }
1284
1285 /// See [`Ast::lookup`].
1286 fn lookup(&self, _delta: &Self::Delta, _name: &str) -> Option<Self::Value> {
1287 None
1288 }
1289}
1290
1291/// Engine-ready [`Ast`] assembled from a `#[derive(DslExec)]` node
1292/// type plus a [`DslSemantics`] implementation.
1293///
1294/// Construction walks the tree once to build the `NodeId -> node`
1295/// lookup; `node_kind` / `literal` then delegate to the derived
1296/// classification and every semantic hook to `S`.
1297///
1298/// This form borrows the tree (`&'a N`), so an [`Engine`] built from it
1299/// cannot outlive the program it walks — the right choice for a
1300/// transient engine. See [`OwnedDerivedAst`] for a variant that projects
1301/// the tree into owned storage and carries no lifetime; reach for it
1302/// when embedding an engine in a long-lived host that would otherwise
1303/// need `Box::leak` to keep program and engine together.
1304pub struct DerivedAst<'a, N, S> {
1305 root: &'a N,
1306 by_id: HashMap<NodeId, &'a N>,
1307 sem: S,
1308}
1309
1310impl<'a, N: DslExec, S> DerivedAst<'a, N, S> {
1311 /// Builds the lookup for `root` and attaches the semantics.
1312 pub fn new(root: &'a N, sem: S) -> Self {
1313 fn collect<'a, N: Walk>(node: &'a N, map: &mut HashMap<NodeId, &'a N>) {
1314 map.insert(node.node_id(), node);
1315 for child in node.children() {
1316 collect(child, map);
1317 }
1318 }
1319 let mut by_id = HashMap::new();
1320 collect(root, &mut by_id);
1321 Self { root, by_id, sem }
1322 }
1323
1324 fn node(&self, id: NodeId) -> &'a N {
1325 self.by_id.get(&id).copied().expect("unknown NodeId")
1326 }
1327}
1328
1329impl<N, S> Ast for DerivedAst<'_, N, S>
1330where
1331 N: DslExec,
1332 S: DslSemantics,
1333 S::Value: From<N::LitValue>,
1334{
1335 type Value = S::Value;
1336 type Delta = S::Delta;
1337 type EffectError = S::EffectError;
1338 type Cursor = S::Cursor;
1339
1340 fn root(&self) -> NodeId {
1341 self.root.node_id()
1342 }
1343
1344 fn node_kind(&self, id: NodeId) -> NodeKind {
1345 self.node(id).exec_kind()
1346 }
1347
1348 fn unit_value(&self) -> Self::Value {
1349 self.sem.unit_value()
1350 }
1351
1352 fn truthy(&self, value: &Self::Value) -> Option<bool> {
1353 self.sem.truthy(value)
1354 }
1355
1356 fn continue_loop(&self, node: NodeId, last: &Self::Value, iteration: usize) -> LoopDecision {
1357 self.sem.continue_loop(node, last, iteration)
1358 }
1359
1360 fn bind_delta(&self, name: &str, value: &Self::Value) -> Option<Self::Delta> {
1361 self.sem.bind_delta(name, value)
1362 }
1363
1364 fn lookup(&self, delta: &Self::Delta, name: &str) -> Option<Self::Value> {
1365 self.sem.lookup(delta, name)
1366 }
1367
1368 fn literal(&self, node: NodeId) -> Option<Self::Value> {
1369 self.node(node).exec_literal().map(S::Value::from)
1370 }
1371}
1372
1373/// Owned counterpart of [`DerivedAst`]: an engine-ready [`Ast`] that
1374/// carries no borrow of the source tree.
1375///
1376/// [`DerivedAst`] keeps `&'a N` references into a live tree, so an
1377/// [`Engine`] built from it cannot outlive that tree. A long-lived host
1378/// that wants to hold its program and engine together in one struct
1379/// therefore had to synthesise a `&'static` borrow with `Box::leak`.
1380/// `OwnedDerivedAst` removes that need: its constructor walks `root`
1381/// once, projecting each node's classification ([`NodeKind`]) and
1382/// literal payload into an owned side table. The borrow ends when the
1383/// constructor returns, so the result carries no lifetime — a host can
1384/// own `program: N` alongside `engine: Engine<OwnedDerivedAst<L, S>>` in
1385/// the same struct with no leak and no `unsafe` (and no `Arc`).
1386///
1387/// Use [`DerivedAst`] when a borrow of the tree is acceptable — a
1388/// transient engine that lives no longer than the program it walks. Use
1389/// `OwnedDerivedAst` when the engine is embedded in a long-lived host.
1390///
1391/// When `L` and `S` are both [`Clone`], `OwnedDerivedAst` is `Clone`,
1392/// so a host can keep a pristine copy of the projection to rebuild the
1393/// engine from on reset.
1394pub struct OwnedDerivedAst<L, S> {
1395 root: NodeId,
1396 nodes: HashMap<NodeId, OwnedNode<L>>,
1397 sem: S,
1398}
1399
1400/// Owned per-node projection captured by [`OwnedDerivedAst::new`]: the
1401/// node's engine classification plus its literal payload, both stored
1402/// by value so the projection outlives the source tree.
1403#[derive(Clone)]
1404struct OwnedNode<L> {
1405 kind: NodeKind,
1406 literal: Option<L>,
1407}
1408
1409impl<L, S> OwnedDerivedAst<L, S> {
1410 /// Walks `root` once, projecting each node's classification and
1411 /// literal payload into owned storage. The borrow ends when this
1412 /// constructor returns — the result carries no lifetime.
1413 pub fn new<N>(root: &N, sem: S) -> Self
1414 where
1415 N: DslExec<LitValue = L>,
1416 {
1417 fn collect<N: DslExec>(node: &N, map: &mut HashMap<NodeId, OwnedNode<N::LitValue>>) {
1418 map.insert(
1419 node.node_id(),
1420 OwnedNode {
1421 kind: node.exec_kind(),
1422 literal: node.exec_literal(),
1423 },
1424 );
1425 for child in node.children() {
1426 collect(child, map);
1427 }
1428 }
1429 let mut nodes = HashMap::new();
1430 collect(root, &mut nodes);
1431 Self {
1432 root: root.node_id(),
1433 nodes,
1434 sem,
1435 }
1436 }
1437
1438 fn node(&self, id: NodeId) -> &OwnedNode<L> {
1439 self.nodes.get(&id).expect("unknown NodeId")
1440 }
1441}
1442
1443impl<L, S> Clone for OwnedDerivedAst<L, S>
1444where
1445 L: Clone,
1446 S: Clone,
1447{
1448 fn clone(&self) -> Self {
1449 Self {
1450 root: self.root,
1451 nodes: self.nodes.clone(),
1452 sem: self.sem.clone(),
1453 }
1454 }
1455}
1456
1457impl<L, S> Ast for OwnedDerivedAst<L, S>
1458where
1459 L: Clone + fmt::Debug,
1460 S: DslSemantics,
1461 S::Value: From<L>,
1462{
1463 type Value = S::Value;
1464 type Delta = S::Delta;
1465 type EffectError = S::EffectError;
1466 type Cursor = S::Cursor;
1467
1468 fn root(&self) -> NodeId {
1469 self.root
1470 }
1471
1472 fn node_kind(&self, id: NodeId) -> NodeKind {
1473 self.node(id).kind.clone()
1474 }
1475
1476 fn unit_value(&self) -> Self::Value {
1477 self.sem.unit_value()
1478 }
1479
1480 fn truthy(&self, value: &Self::Value) -> Option<bool> {
1481 self.sem.truthy(value)
1482 }
1483
1484 fn continue_loop(&self, node: NodeId, last: &Self::Value, iteration: usize) -> LoopDecision {
1485 self.sem.continue_loop(node, last, iteration)
1486 }
1487
1488 fn bind_delta(&self, name: &str, value: &Self::Value) -> Option<Self::Delta> {
1489 self.sem.bind_delta(name, value)
1490 }
1491
1492 fn lookup(&self, delta: &Self::Delta, name: &str) -> Option<Self::Value> {
1493 self.sem.lookup(delta, name)
1494 }
1495
1496 fn literal(&self, node: NodeId) -> Option<Self::Value> {
1497 self.node(node).literal.clone().map(S::Value::from)
1498 }
1499}
1500
1501// ---------- Environment sharing ----------------------------------------
1502
1503/// Shared environment handle.
1504///
1505/// Reads are cheap `Arc` clones. Writes accumulate in a per-child `D`
1506/// (state delta) inside a `Par` and are merged by the reducer at join.
1507#[derive(Debug)]
1508pub struct EnvRef<D>(pub Arc<Env<D>>);
1509
1510impl<D> Clone for EnvRef<D> {
1511 fn clone(&self) -> Self {
1512 EnvRef(self.0.clone())
1513 }
1514}
1515
1516/// The `Env` a `Frame::Node` or `Frame::Scope` holds. Generic over the
1517/// DSL-owned `D` (state delta); the engine does not interpret `D`.
1518#[derive(Debug)]
1519pub struct Env<D> {
1520 /// The DSL's own state delta / bindings snapshot.
1521 pub delta: D,
1522 /// Optional parent for lexical lookup.
1523 pub parent: Option<Arc<Env<D>>>,
1524}
1525
1526// ---------- Marker traits + traversal ----------------------------------
1527
1528/// Marker trait for AST enums recognised by the kit.
1529pub trait DslNode {
1530 /// Returns the stable ID assigned to this node.
1531 fn node_id(&self) -> NodeId;
1532
1533 /// Returns the enum variant name of this node as a static string
1534 /// (e.g. `"Seq"`, `"Par"`, `"Call"`).
1535 ///
1536 /// The name matches the variant's Rust source ident and lines up
1537 /// with `dsl_kit_schema::VariantSchema::name` when the type also
1538 /// derives `DslSchema`. Consumers use this to correlate a runtime
1539 /// node with its type-level schema entry — schema-aware lint
1540 /// rules, editor tooling, and any other component that needs to
1541 /// go from an AST value to "which variant is this" without
1542 /// downcasting.
1543 fn variant_name(&self) -> &'static str;
1544}
1545
1546// ---------- Breakpoints -------------------------------------------------
1547
1548/// Identifier assigned by a [`BreakpointSet`] to each added condition.
1549#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
1550pub struct BreakpointId(pub u64);
1551
1552impl fmt::Display for BreakpointId {
1553 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1554 write!(f, "bp{}", self.0)
1555 }
1556}
1557
1558/// A boolean predicate over [`NodeContext`] used to describe conditional
1559/// breakpoints.
1560#[derive(Debug, Clone, PartialEq, Eq)]
1561pub enum BreakCondition {
1562 /// Matches when the node ID is exactly `id`.
1563 Node(NodeId),
1564 /// Matches when the current path has the given prefix.
1565 PathPrefix(Path),
1566 /// Matches when the current path equals the given path exactly.
1567 PathExact(Path),
1568 /// Matches when the current call-frame depth is at least `n`.
1569 DepthAtLeast(u32),
1570 /// Matches when the current call-frame depth is at most `n`.
1571 DepthAtMost(u32),
1572 /// Matches when the current call-frame depth equals `n` exactly.
1573 DepthEquals(u32),
1574 /// Matches when the iteration counter equals `n`.
1575 Iteration(u64),
1576 /// Matches when the current call frame equals `frame`.
1577 CallFrame(CallFrameId),
1578 /// Matches when any child matches.
1579 Any(Vec<BreakCondition>),
1580 /// Matches when every child matches.
1581 All(Vec<BreakCondition>),
1582 /// Matches when the inner does not match.
1583 Not(Box<BreakCondition>),
1584 /// Always matches (useful as a debugger's "break on every node" mode).
1585 Always,
1586 /// Never matches (useful as a disabled placeholder).
1587 Never,
1588}
1589
1590impl BreakCondition {
1591 /// Convenience constructor.
1592 pub fn at_node(id: NodeId) -> Self {
1593 Self::Node(id)
1594 }
1595
1596 /// Convenience constructor.
1597 pub fn under_path(path: Path) -> Self {
1598 Self::PathPrefix(path)
1599 }
1600
1601 /// Convenience constructor.
1602 pub fn at_path(path: Path) -> Self {
1603 Self::PathExact(path)
1604 }
1605
1606 /// Convenience constructor.
1607 pub fn at_depth_at_least(n: u32) -> Self {
1608 Self::DepthAtLeast(n)
1609 }
1610
1611 /// Convenience constructor.
1612 pub fn at_depth_at_most(n: u32) -> Self {
1613 Self::DepthAtMost(n)
1614 }
1615
1616 /// Convenience constructor.
1617 pub fn at_depth(n: u32) -> Self {
1618 Self::DepthEquals(n)
1619 }
1620
1621 /// Convenience constructor.
1622 pub fn at_iteration(n: u64) -> Self {
1623 Self::Iteration(n)
1624 }
1625
1626 /// Convenience constructor.
1627 pub fn in_call_frame(frame: CallFrameId) -> Self {
1628 Self::CallFrame(frame)
1629 }
1630
1631 /// Logical AND.
1632 pub fn and(self, other: Self) -> Self {
1633 match (self, other) {
1634 (Self::All(mut xs), Self::All(ys)) => {
1635 xs.extend(ys);
1636 Self::All(xs)
1637 }
1638 (Self::All(mut xs), other) => {
1639 xs.push(other);
1640 Self::All(xs)
1641 }
1642 (this, Self::All(mut ys)) => {
1643 ys.insert(0, this);
1644 Self::All(ys)
1645 }
1646 (this, other) => Self::All(vec![this, other]),
1647 }
1648 }
1649
1650 /// Logical OR.
1651 pub fn or(self, other: Self) -> Self {
1652 match (self, other) {
1653 (Self::Any(mut xs), Self::Any(ys)) => {
1654 xs.extend(ys);
1655 Self::Any(xs)
1656 }
1657 (Self::Any(mut xs), other) => {
1658 xs.push(other);
1659 Self::Any(xs)
1660 }
1661 (this, Self::Any(mut ys)) => {
1662 ys.insert(0, this);
1663 Self::Any(ys)
1664 }
1665 (this, other) => Self::Any(vec![this, other]),
1666 }
1667 }
1668
1669 /// Evaluates the condition against a context.
1670 pub fn matches(&self, ctx: &NodeContext) -> bool {
1671 match self {
1672 Self::Node(id) => ctx.node == *id,
1673 Self::PathPrefix(prefix) => {
1674 ctx.path.0.len() >= prefix.0.len() && ctx.path.0[..prefix.0.len()] == prefix.0[..]
1675 }
1676 Self::PathExact(path) => ctx.path == *path,
1677 Self::DepthAtLeast(n) => ctx.depth >= *n,
1678 Self::DepthAtMost(n) => ctx.depth <= *n,
1679 Self::DepthEquals(n) => ctx.depth == *n,
1680 Self::Iteration(n) => ctx.iteration.map(|i| i.0 == *n).unwrap_or(false),
1681 Self::CallFrame(frame) => ctx.frame == Some(*frame),
1682 Self::Any(children) => children.iter().any(|c| c.matches(ctx)),
1683 Self::All(children) => children.iter().all(|c| c.matches(ctx)),
1684 Self::Not(inner) => !inner.matches(ctx),
1685 Self::Always => true,
1686 Self::Never => false,
1687 }
1688 }
1689}
1690
1691impl std::ops::Not for BreakCondition {
1692 type Output = Self;
1693
1694 /// Logical NOT: `!cond` matches exactly when `cond` does not.
1695 fn not(self) -> Self {
1696 Self::Not(Box::new(self))
1697 }
1698}
1699
1700/// A registry of breakpoint conditions and their assigned IDs.
1701#[derive(Debug, Default)]
1702pub struct BreakpointSet {
1703 next: u64,
1704 entries: Vec<(BreakpointId, BreakCondition)>,
1705}
1706
1707impl BreakpointSet {
1708 /// Creates an empty set.
1709 pub fn new() -> Self {
1710 Self {
1711 next: 1,
1712 entries: Vec::new(),
1713 }
1714 }
1715
1716 /// Adds a condition and returns its assigned id.
1717 pub fn add(&mut self, condition: BreakCondition) -> BreakpointId {
1718 let id = BreakpointId(self.next);
1719 self.next += 1;
1720 self.entries.push((id, condition));
1721 id
1722 }
1723
1724 /// Removes an entry by id. Returns whether an entry was found.
1725 pub fn remove(&mut self, id: BreakpointId) -> bool {
1726 let before = self.entries.len();
1727 self.entries.retain(|(entry_id, _)| *entry_id != id);
1728 self.entries.len() != before
1729 }
1730
1731 /// Returns the ids of all entries whose condition matches `ctx`.
1732 pub fn matches(&self, ctx: &NodeContext) -> Vec<BreakpointId> {
1733 self.entries
1734 .iter()
1735 .filter(|(_, cond)| cond.matches(ctx))
1736 .map(|(id, _)| *id)
1737 .collect()
1738 }
1739
1740 /// Returns whether the set has no entries.
1741 pub fn is_empty(&self) -> bool {
1742 self.entries.is_empty()
1743 }
1744
1745 /// Number of entries currently registered.
1746 pub fn len(&self) -> usize {
1747 self.entries.len()
1748 }
1749
1750 /// Iterates over the registered `(id, condition)` pairs.
1751 pub fn iter(&self) -> impl Iterator<Item = (BreakpointId, &BreakCondition)> {
1752 self.entries.iter().map(|(id, c)| (*id, c))
1753 }
1754}
1755
1756// ---------- Traversal ---------------------------------------------------
1757
1758/// Which side of a node's traversal the visitor is currently on.
1759#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1760pub enum Phase {
1761 /// Before descending into the node's children.
1762 Pre,
1763 /// After all children have been visited.
1764 Post,
1765}
1766
1767/// AST traversal contract.
1768pub trait Walk: DslNode + Sized {
1769 /// Direct children of this node, in traversal order.
1770 fn children(&self) -> Vec<&Self>;
1771
1772 /// Depth-first pre / post traversal.
1773 fn walk<F>(&self, visitor: &mut F)
1774 where
1775 F: FnMut(&Self, Phase),
1776 {
1777 visitor(self, Phase::Pre);
1778 for child in self.children() {
1779 child.walk(visitor);
1780 }
1781 visitor(self, Phase::Post);
1782 }
1783
1784 /// Depth-first traversal with early exit.
1785 fn walk_until<F, T>(&self, visitor: &mut F) -> Option<T>
1786 where
1787 F: FnMut(&Self, Phase) -> Option<T>,
1788 {
1789 if let Some(t) = visitor(self, Phase::Pre) {
1790 return Some(t);
1791 }
1792 for child in self.children() {
1793 if let Some(t) = child.walk_until(visitor) {
1794 return Some(t);
1795 }
1796 }
1797 visitor(self, Phase::Post)
1798 }
1799
1800 /// Locates a node by its stable ID.
1801 fn find_by_id(&self, target: NodeId) -> Option<&Self> {
1802 self.walk_until(&mut |node, phase| {
1803 if phase == Phase::Pre && node.node_id() == target {
1804 Some(node as *const Self)
1805 } else {
1806 None
1807 }
1808 })
1809 .map(|ptr| unsafe { &*ptr })
1810 }
1811}
1812
1813/// Mutable counterpart of [`Walk`].
1814pub trait WalkMut: DslNode + Sized {
1815 /// Direct children of this node, mutably, in traversal order.
1816 fn children_mut(&mut self) -> Vec<&mut Self>;
1817
1818 /// Depth-first pre / post traversal with mutable access.
1819 fn walk_mut<F>(&mut self, visitor: &mut F)
1820 where
1821 F: FnMut(&mut Self, Phase),
1822 {
1823 visitor(self, Phase::Pre);
1824 for child in self.children_mut() {
1825 child.walk_mut(visitor);
1826 }
1827 visitor(self, Phase::Post);
1828 }
1829}
1830
1831#[cfg(test)]
1832mod tests {
1833 use super::*;
1834
1835 #[test]
1836 fn path_push_extends_depth() {
1837 let ids = IdGen::new();
1838 let a = ids.node();
1839 let b = ids.node();
1840
1841 let root = Path::root();
1842 assert_eq!(root.depth(), 0);
1843
1844 let one = root.push(a);
1845 assert_eq!(one.depth(), 1);
1846
1847 let two = one.push(b);
1848 assert_eq!(two.depth(), 2);
1849 assert_eq!(two.tip(), Some(b));
1850 }
1851
1852 #[test]
1853 fn id_generator_yields_distinct_ids() {
1854 let ids = IdGen::new();
1855 let a = ids.node();
1856 let b = ids.node();
1857 assert_ne!(a, b);
1858 }
1859
1860 #[test]
1861 fn null_sink_accepts_events() {
1862 let mut sink = NullSink;
1863 let event = Event::VisitPre {
1864 at: NodeContext::at(NodeId(0), Path::root()),
1865 };
1866 sink.emit(&event);
1867 }
1868
1869 fn ctx_at(node: NodeId, path: Path, depth: u32) -> NodeContext {
1870 NodeContext {
1871 node,
1872 path,
1873 frame: None,
1874 depth,
1875 iteration: None,
1876 }
1877 }
1878
1879 #[test]
1880 fn breakpoint_node_matches_exact_id() {
1881 let cond = BreakCondition::at_node(NodeId(7));
1882 assert!(cond.matches(&ctx_at(NodeId(7), Path::root().push(NodeId(7)), 1)));
1883 assert!(!cond.matches(&ctx_at(NodeId(8), Path::root().push(NodeId(8)), 1)));
1884 }
1885
1886 #[test]
1887 fn breakpoint_set_add_matches_remove() {
1888 let mut set = BreakpointSet::new();
1889 let hit = set.add(BreakCondition::at_node(NodeId(4)));
1890 let miss = set.add(BreakCondition::at_node(NodeId(99)));
1891
1892 let ctx = ctx_at(NodeId(4), Path::root().push(NodeId(4)), 1);
1893 assert_eq!(set.matches(&ctx), vec![hit]);
1894
1895 assert!(set.remove(hit));
1896 assert!(set.matches(&ctx).is_empty());
1897 assert_eq!(set.len(), 1);
1898 assert!(set.iter().any(|(id, _)| id == miss));
1899 }
1900
1901 #[test]
1902 fn engine_error_carries_stable_code() {
1903 let err = EngineError::Aborted {
1904 at: NodeContext::at(NodeId(1), Path::root().push(NodeId(1))),
1905 reason: "user requested".into(),
1906 };
1907 use miette::Diagnostic;
1908 assert_eq!(
1909 err.code().map(|c| c.to_string()).as_deref(),
1910 Some("dsl_kit::eval::aborted")
1911 );
1912 }
1913
1914 #[test]
1915 fn engine_error_catalog_covers_every_variant() {
1916 let entries = engine_error_catalog();
1917 let codes: Vec<&str> = entries.iter().map(|e| e.code.as_str()).collect();
1918 assert!(codes.contains(&"dsl_kit::eval::aborted"));
1919 assert!(codes.contains(&"dsl_kit::eval::failed"));
1920 assert!(codes.contains(&"dsl_kit::ast::malformed"));
1921 assert!(codes.contains(&"dsl_kit::stepper::protocol"));
1922 assert!(codes.contains(&"dsl_kit::stepper::unknown_suspension"));
1923 assert!(codes.contains(&"dsl_kit::reducer::unknown"));
1924 for entry in &entries {
1925 assert!(!entry.help.is_empty(), "help empty for {}", entry.code);
1926 }
1927 }
1928
1929 #[test]
1930 fn reducer_id_from_str_and_string() {
1931 let a: ReducerId = "foo".into();
1932 let b: ReducerId = String::from("foo").into();
1933 assert_eq!(a, b);
1934 }
1935
1936 #[test]
1937 fn reducer_registry_resolves_fail_fast_and_collect_all_independently() {
1938 // A trivial FailFast reducer that returns the first non-None
1939 // slot verbatim.
1940 struct FirstNonNone;
1941 impl Reducer<i64, ()> for FirstNonNone {
1942 fn reduce(
1943 &self,
1944 slots: &[Option<i64>],
1945 _deltas: &[Option<()>],
1946 _winners: &[ChildIndex],
1947 ) -> Result<(i64, ()), EngineError> {
1948 let v = slots.iter().find_map(|s| *s).unwrap_or(0);
1949 Ok((v, ()))
1950 }
1951 }
1952
1953 // A trivial CollectAll reducer.
1954 struct CountOk;
1955 impl ReducerCollectAll<i64, (), std::io::Error> for CountOk {
1956 fn reduce(
1957 &self,
1958 slots: &[Option<Result<i64, std::io::Error>>],
1959 _deltas: &[Option<()>],
1960 _winners: &[ChildIndex],
1961 ) -> Result<(i64, ()), EngineError> {
1962 let count = slots.iter().filter(|s| matches!(s, Some(Ok(_)))).count();
1963 Ok((count as i64, ()))
1964 }
1965 }
1966
1967 let mut reg: ReducerRegistry<i64, (), std::io::Error> = ReducerRegistry::new();
1968 reg.register_fail_fast("first", Arc::new(FirstNonNone));
1969 reg.register_collect_all("count_ok", Arc::new(CountOk));
1970
1971 let ff = reg.resolve(&"first".into(), FailPolicy::FailFast).unwrap();
1972 assert!(matches!(ff, ReducerHandle::FailFast(_)));
1973 let ca = reg
1974 .resolve(&"count_ok".into(), FailPolicy::CollectAll)
1975 .unwrap();
1976 assert!(matches!(ca, ReducerHandle::CollectAll(_)));
1977
1978 let miss = reg.resolve(&"nope".into(), FailPolicy::FailFast);
1979 assert!(matches!(miss, Err(EngineError::UnknownReducer { .. })));
1980 }
1981
1982 /// Fixed-output suggester used to prove the with_suggester wiring
1983 /// without depending on `dsl-kit-fuzzy` — a real dev-dep on that
1984 /// crate would create a cycle since fuzzy already depends on
1985 /// dsl-kit-core, and cargo cannot unify the `Suggester` trait
1986 /// across the two versions of core that would result.
1987 struct FixedSuggester(&'static str);
1988 impl Suggester for FixedSuggester {
1989 fn suggest<'a>(&self, _q: &str, cands: &'a [&str]) -> Vec<Suggestion<'a>> {
1990 cands
1991 .iter()
1992 .find(|c| **c == self.0)
1993 .map(|c| Suggestion {
1994 candidate: c,
1995 score: 1.0,
1996 })
1997 .into_iter()
1998 .collect()
1999 }
2000 }
2001
2002 #[test]
2003 fn unknown_reducer_defaults_to_no_hint() {
2004 // Without an injected suggester the historical `unknown
2005 // reducer "X"` wording is preserved verbatim.
2006 struct Noop;
2007 impl Reducer<i64, ()> for Noop {
2008 fn reduce(
2009 &self,
2010 _s: &[Option<i64>],
2011 _d: &[Option<()>],
2012 _w: &[ChildIndex],
2013 ) -> Result<(i64, ()), EngineError> {
2014 Ok((0, ()))
2015 }
2016 }
2017 let mut reg: ReducerRegistry<i64, (), std::io::Error> = ReducerRegistry::new();
2018 reg.register_fail_fast("first", Arc::new(Noop));
2019 let miss = reg.resolve(&"frst".into(), FailPolicy::FailFast);
2020 let err = match miss {
2021 Err(e) => e,
2022 Ok(_) => panic!("expected miss"),
2023 };
2024 // Base wording matches the historical `{id:?}` Debug shape;
2025 // the trailing `hint` is empty so no parenthesised clause
2026 // appears.
2027 assert_eq!(err.to_string(), "unknown reducer ReducerId(\"frst\")");
2028 }
2029
2030 #[test]
2031 fn unknown_reducer_with_suggester_appends_hint() {
2032 struct Noop;
2033 impl Reducer<i64, ()> for Noop {
2034 fn reduce(
2035 &self,
2036 _s: &[Option<i64>],
2037 _d: &[Option<()>],
2038 _w: &[ChildIndex],
2039 ) -> Result<(i64, ()), EngineError> {
2040 Ok((0, ()))
2041 }
2042 }
2043 let mut reg: ReducerRegistry<i64, (), std::io::Error> = ReducerRegistry::new();
2044 reg.register_fail_fast("first", Arc::new(Noop));
2045 let reg = reg.with_suggester(Arc::new(FixedSuggester("first")));
2046 let miss = reg.resolve(&"frst".into(), FailPolicy::FailFast);
2047 let err = match miss {
2048 Err(e) => e,
2049 Ok(_) => panic!("expected miss"),
2050 };
2051 let msg = err.to_string();
2052 assert!(
2053 msg.contains("did you mean") && msg.contains("first"),
2054 "expected hint, got: {msg}"
2055 );
2056 }
2057
2058 #[test]
2059 fn unknown_op_defaults_to_no_hint() {
2060 struct AddOp;
2061 impl Op<i64> for AddOp {
2062 fn apply(&self, _n: NodeId, args: &[i64]) -> Result<i64, EngineError> {
2063 Ok(args.iter().sum())
2064 }
2065 }
2066 let mut reg: OpRegistry<i64> = OpRegistry::new();
2067 reg.register("add", Arc::new(AddOp));
2068 let miss = reg.resolve(&"ad".into());
2069 let err = match miss {
2070 Err(e) => e,
2071 Ok(_) => panic!("expected miss"),
2072 };
2073 assert_eq!(err.to_string(), "unknown op OpId(\"ad\")");
2074 }
2075
2076 #[test]
2077 fn unknown_op_with_suggester_appends_hint() {
2078 struct AddOp;
2079 impl Op<i64> for AddOp {
2080 fn apply(&self, _n: NodeId, args: &[i64]) -> Result<i64, EngineError> {
2081 Ok(args.iter().sum())
2082 }
2083 }
2084 let mut reg: OpRegistry<i64> = OpRegistry::new();
2085 reg.register("add", Arc::new(AddOp));
2086 let reg = reg.with_suggester(Arc::new(FixedSuggester("add")));
2087 let miss = reg.resolve(&"ad".into());
2088 let err = match miss {
2089 Err(e) => e,
2090 Ok(_) => panic!("expected miss"),
2091 };
2092 let msg = err.to_string();
2093 assert!(
2094 msg.contains("did you mean") && msg.contains("add"),
2095 "expected hint, got: {msg}"
2096 );
2097 }
2098}