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.
1152///
1153/// `apply` sees the child *values*, not the node's own fields — an op
1154/// that needs data attached to its node reads it from an argument, or
1155/// the effect moves to a `Call` child and carries its arguments in
1156/// [`CallSpec::payload`].
1157pub trait Op<V>: Send + Sync {
1158 /// Fold the evaluated child values into the node's value.
1159 ///
1160 /// `args` holds one entry per `Apply` child, in declaration order.
1161 /// Zero-child `Apply` nodes invoke the op with an empty slice.
1162 fn apply(&self, node: NodeId, args: &[V]) -> Result<V, EngineError>;
1163}
1164
1165/// Runtime handle for the resolved op of an `Apply` frame.
1166pub type OpHandle<V> = Arc<dyn Op<V>>;
1167
1168/// Runtime lookup table for [`Op`]s, the `Apply` counterpart of
1169/// [`ReducerRegistry`].
1170///
1171/// Constructed by the host at Stepper build time; a DSL typically ships
1172/// a helper that registers its standard ops under canonical ids
1173/// (`"add"`, `"mul"`, ...). Passed to [`Engine::new_with_ops`]; DSLs
1174/// with no `Apply` nodes can stay on [`Engine::new`], which uses an
1175/// empty registry.
1176///
1177/// [`Engine::new`]: crate::Engine::new
1178/// [`Engine::new_with_ops`]: crate::Engine::new_with_ops
1179pub struct OpRegistry<V> {
1180 ops: HashMap<OpId, OpHandle<V>>,
1181 suggester: crate::suggest::SuggesterHandle,
1182}
1183
1184impl<V> Default for OpRegistry<V> {
1185 fn default() -> Self {
1186 Self::new()
1187 }
1188}
1189
1190impl<V> OpRegistry<V> {
1191 /// Creates an empty registry.
1192 pub fn new() -> Self {
1193 Self {
1194 ops: HashMap::new(),
1195 suggester: crate::suggest::noop_handle(),
1196 }
1197 }
1198
1199 /// Injects a fuzzy-match [`Suggester`](crate::Suggester) used to
1200 /// enrich [`EngineError::UnknownOp`] with a `did you mean X?`
1201 /// hint at [`Self::resolve`] time.
1202 ///
1203 /// The default is a no-op suggester, so the crate stays free of a
1204 /// similarity algorithm on its own. Pass
1205 /// `Arc::new(dsl_kit_fuzzy::FuzzySuggester::default())` at the
1206 /// composition root to enable hints.
1207 pub fn with_suggester(mut self, suggester: crate::suggest::SuggesterHandle) -> Self {
1208 self.suggester = suggester;
1209 self
1210 }
1211
1212 /// Registers an op under `id`.
1213 pub fn register(&mut self, id: impl Into<OpId>, op: OpHandle<V>) {
1214 self.ops.insert(id.into(), op);
1215 }
1216
1217 /// Resolves the op for an `Apply` frame at spawn / validation time.
1218 /// Returns [`EngineError::UnknownOp`] on miss.
1219 pub fn resolve(&self, id: &OpId) -> Result<OpHandle<V>, EngineError> {
1220 self.ops.get(id).cloned().ok_or_else(|| {
1221 let names: Vec<&str> = self.ops.keys().map(|k| k.0.as_str()).collect();
1222 let hint = self
1223 .suggester
1224 .enrich_unknown(&id.0, &names)
1225 .map(|h| format!(" ({h})"))
1226 .unwrap_or_default();
1227 EngineError::UnknownOp {
1228 id: id.clone(),
1229 hint,
1230 }
1231 })
1232 }
1233}
1234
1235// ---------- Derived execution (DslExec / DslSemantics / DerivedAst) ----
1236
1237/// Mechanical node classification, normally supplied by
1238/// `#[derive(DslExec)]` from `dsl-kit-macros`.
1239///
1240/// This is the derivable half of an [`Ast`]: which engine [`NodeKind`]
1241/// each variant maps to, and the payload of `value`-marked literal
1242/// variants. The semantic half (value type, truthiness, bindings)
1243/// lives in [`DslSemantics`]; [`DerivedAst`] zips the two into an
1244/// engine-ready [`Ast`].
1245pub trait DslExec: Walk {
1246 /// Payload type of `#[dsl_exec(value)]` variants. `()` when the
1247 /// enum has no value variants.
1248 type LitValue: Clone + fmt::Debug;
1249
1250 /// Engine classification of this node.
1251 fn exec_kind(&self) -> NodeKind;
1252
1253 /// Payload of a value variant; `None` for every other variant.
1254 fn exec_literal(&self) -> Option<Self::LitValue>;
1255}
1256
1257/// The semantic half an author writes next to `#[derive(DslExec)]`:
1258/// the runtime value type and the hooks whose meaning the kit cannot
1259/// derive. Every hook mirrors its [`Ast`] counterpart and keeps the
1260/// same default, so a DSL only implements what its node kinds use.
1261pub trait DslSemantics {
1262 /// Runtime value type produced by the DSL.
1263 type Value: Clone + fmt::Debug;
1264 /// Per-child state delta accumulated across a `Par` and extended
1265 /// by `Bind`.
1266 type Delta: Clone + Default + fmt::Debug;
1267 /// Effect-side failure the host reports through `resolve`.
1268 type EffectError: std::error::Error + Clone + Send + Sync + 'static;
1269 /// Per-frame cursor surfaced through the projected frame tree.
1270 type Cursor: Clone + fmt::Debug + Default;
1271
1272 /// See [`Ast::unit_value`].
1273 fn unit_value(&self) -> Self::Value;
1274
1275 /// See [`Ast::truthy`].
1276 fn truthy(&self, _value: &Self::Value) -> Option<bool> {
1277 None
1278 }
1279
1280 /// See [`Ast::continue_loop`].
1281 fn continue_loop(&self, _node: NodeId, _last: &Self::Value, _iteration: usize) -> LoopDecision {
1282 LoopDecision::Break
1283 }
1284
1285 /// See [`Ast::bind_delta`].
1286 fn bind_delta(&self, _name: &str, _value: &Self::Value) -> Option<Self::Delta> {
1287 None
1288 }
1289
1290 /// See [`Ast::lookup`].
1291 fn lookup(&self, _delta: &Self::Delta, _name: &str) -> Option<Self::Value> {
1292 None
1293 }
1294}
1295
1296/// Engine-ready [`Ast`] assembled from a `#[derive(DslExec)]` node
1297/// type plus a [`DslSemantics`] implementation.
1298///
1299/// Construction walks the tree once to build the `NodeId -> node`
1300/// lookup; `node_kind` / `literal` then delegate to the derived
1301/// classification and every semantic hook to `S`.
1302///
1303/// This form borrows the tree (`&'a N`), so an [`Engine`] built from it
1304/// cannot outlive the program it walks — the right choice for a
1305/// transient engine. See [`OwnedDerivedAst`] for a variant that projects
1306/// the tree into owned storage and carries no lifetime; reach for it
1307/// when embedding an engine in a long-lived host that would otherwise
1308/// need `Box::leak` to keep program and engine together.
1309pub struct DerivedAst<'a, N, S> {
1310 root: &'a N,
1311 by_id: HashMap<NodeId, &'a N>,
1312 sem: S,
1313}
1314
1315impl<'a, N: DslExec, S> DerivedAst<'a, N, S> {
1316 /// Builds the lookup for `root` and attaches the semantics.
1317 pub fn new(root: &'a N, sem: S) -> Self {
1318 fn collect<'a, N: Walk>(node: &'a N, map: &mut HashMap<NodeId, &'a N>) {
1319 map.insert(node.node_id(), node);
1320 for child in node.children() {
1321 collect(child, map);
1322 }
1323 }
1324 let mut by_id = HashMap::new();
1325 collect(root, &mut by_id);
1326 Self { root, by_id, sem }
1327 }
1328
1329 fn node(&self, id: NodeId) -> &'a N {
1330 self.by_id.get(&id).copied().expect("unknown NodeId")
1331 }
1332}
1333
1334impl<N, S> Ast for DerivedAst<'_, N, S>
1335where
1336 N: DslExec,
1337 S: DslSemantics,
1338 S::Value: From<N::LitValue>,
1339{
1340 type Value = S::Value;
1341 type Delta = S::Delta;
1342 type EffectError = S::EffectError;
1343 type Cursor = S::Cursor;
1344
1345 fn root(&self) -> NodeId {
1346 self.root.node_id()
1347 }
1348
1349 fn node_kind(&self, id: NodeId) -> NodeKind {
1350 self.node(id).exec_kind()
1351 }
1352
1353 fn unit_value(&self) -> Self::Value {
1354 self.sem.unit_value()
1355 }
1356
1357 fn truthy(&self, value: &Self::Value) -> Option<bool> {
1358 self.sem.truthy(value)
1359 }
1360
1361 fn continue_loop(&self, node: NodeId, last: &Self::Value, iteration: usize) -> LoopDecision {
1362 self.sem.continue_loop(node, last, iteration)
1363 }
1364
1365 fn bind_delta(&self, name: &str, value: &Self::Value) -> Option<Self::Delta> {
1366 self.sem.bind_delta(name, value)
1367 }
1368
1369 fn lookup(&self, delta: &Self::Delta, name: &str) -> Option<Self::Value> {
1370 self.sem.lookup(delta, name)
1371 }
1372
1373 fn literal(&self, node: NodeId) -> Option<Self::Value> {
1374 self.node(node).exec_literal().map(S::Value::from)
1375 }
1376}
1377
1378/// Owned counterpart of [`DerivedAst`]: an engine-ready [`Ast`] that
1379/// carries no borrow of the source tree.
1380///
1381/// [`DerivedAst`] keeps `&'a N` references into a live tree, so an
1382/// [`Engine`] built from it cannot outlive that tree. A long-lived host
1383/// that wants to hold its program and engine together in one struct
1384/// therefore had to synthesise a `&'static` borrow with `Box::leak`.
1385/// `OwnedDerivedAst` removes that need: its constructor walks `root`
1386/// once, projecting each node's classification ([`NodeKind`]) and
1387/// literal payload into an owned side table. The borrow ends when the
1388/// constructor returns, so the result carries no lifetime — a host can
1389/// own `program: N` alongside `engine: Engine<OwnedDerivedAst<L, S>>` in
1390/// the same struct with no leak and no `unsafe` (and no `Arc`).
1391///
1392/// Use [`DerivedAst`] when a borrow of the tree is acceptable — a
1393/// transient engine that lives no longer than the program it walks. Use
1394/// `OwnedDerivedAst` when the engine is embedded in a long-lived host.
1395///
1396/// When `L` and `S` are both [`Clone`], `OwnedDerivedAst` is `Clone`,
1397/// so a host can keep a pristine copy of the projection to rebuild the
1398/// engine from on reset.
1399pub struct OwnedDerivedAst<L, S> {
1400 root: NodeId,
1401 nodes: HashMap<NodeId, OwnedNode<L>>,
1402 sem: S,
1403}
1404
1405/// Owned per-node projection captured by [`OwnedDerivedAst::new`]: the
1406/// node's engine classification plus its literal payload, both stored
1407/// by value so the projection outlives the source tree.
1408#[derive(Clone)]
1409struct OwnedNode<L> {
1410 kind: NodeKind,
1411 literal: Option<L>,
1412}
1413
1414impl<L, S> OwnedDerivedAst<L, S> {
1415 /// Walks `root` once, projecting each node's classification and
1416 /// literal payload into owned storage. The borrow ends when this
1417 /// constructor returns — the result carries no lifetime.
1418 pub fn new<N>(root: &N, sem: S) -> Self
1419 where
1420 N: DslExec<LitValue = L>,
1421 {
1422 fn collect<N: DslExec>(node: &N, map: &mut HashMap<NodeId, OwnedNode<N::LitValue>>) {
1423 map.insert(
1424 node.node_id(),
1425 OwnedNode {
1426 kind: node.exec_kind(),
1427 literal: node.exec_literal(),
1428 },
1429 );
1430 for child in node.children() {
1431 collect(child, map);
1432 }
1433 }
1434 let mut nodes = HashMap::new();
1435 collect(root, &mut nodes);
1436 Self {
1437 root: root.node_id(),
1438 nodes,
1439 sem,
1440 }
1441 }
1442
1443 fn node(&self, id: NodeId) -> &OwnedNode<L> {
1444 self.nodes.get(&id).expect("unknown NodeId")
1445 }
1446}
1447
1448impl<L, S> Clone for OwnedDerivedAst<L, S>
1449where
1450 L: Clone,
1451 S: Clone,
1452{
1453 fn clone(&self) -> Self {
1454 Self {
1455 root: self.root,
1456 nodes: self.nodes.clone(),
1457 sem: self.sem.clone(),
1458 }
1459 }
1460}
1461
1462impl<L, S> Ast for OwnedDerivedAst<L, S>
1463where
1464 L: Clone + fmt::Debug,
1465 S: DslSemantics,
1466 S::Value: From<L>,
1467{
1468 type Value = S::Value;
1469 type Delta = S::Delta;
1470 type EffectError = S::EffectError;
1471 type Cursor = S::Cursor;
1472
1473 fn root(&self) -> NodeId {
1474 self.root
1475 }
1476
1477 fn node_kind(&self, id: NodeId) -> NodeKind {
1478 self.node(id).kind.clone()
1479 }
1480
1481 fn unit_value(&self) -> Self::Value {
1482 self.sem.unit_value()
1483 }
1484
1485 fn truthy(&self, value: &Self::Value) -> Option<bool> {
1486 self.sem.truthy(value)
1487 }
1488
1489 fn continue_loop(&self, node: NodeId, last: &Self::Value, iteration: usize) -> LoopDecision {
1490 self.sem.continue_loop(node, last, iteration)
1491 }
1492
1493 fn bind_delta(&self, name: &str, value: &Self::Value) -> Option<Self::Delta> {
1494 self.sem.bind_delta(name, value)
1495 }
1496
1497 fn lookup(&self, delta: &Self::Delta, name: &str) -> Option<Self::Value> {
1498 self.sem.lookup(delta, name)
1499 }
1500
1501 fn literal(&self, node: NodeId) -> Option<Self::Value> {
1502 self.node(node).literal.clone().map(S::Value::from)
1503 }
1504}
1505
1506// ---------- Environment sharing ----------------------------------------
1507
1508/// Shared environment handle.
1509///
1510/// Reads are cheap `Arc` clones. Writes accumulate in a per-child `D`
1511/// (state delta) inside a `Par` and are merged by the reducer at join.
1512#[derive(Debug)]
1513pub struct EnvRef<D>(pub Arc<Env<D>>);
1514
1515impl<D> Clone for EnvRef<D> {
1516 fn clone(&self) -> Self {
1517 EnvRef(self.0.clone())
1518 }
1519}
1520
1521/// The `Env` a `Frame::Node` or `Frame::Scope` holds. Generic over the
1522/// DSL-owned `D` (state delta); the engine does not interpret `D`.
1523#[derive(Debug)]
1524pub struct Env<D> {
1525 /// The DSL's own state delta / bindings snapshot.
1526 pub delta: D,
1527 /// Optional parent for lexical lookup.
1528 pub parent: Option<Arc<Env<D>>>,
1529}
1530
1531// ---------- Marker traits + traversal ----------------------------------
1532
1533/// Marker trait for AST enums recognised by the kit.
1534pub trait DslNode {
1535 /// Returns the stable ID assigned to this node.
1536 fn node_id(&self) -> NodeId;
1537
1538 /// Returns the enum variant name of this node as a static string
1539 /// (e.g. `"Seq"`, `"Par"`, `"Call"`).
1540 ///
1541 /// The name matches the variant's Rust source ident and lines up
1542 /// with `dsl_kit_schema::VariantSchema::name` when the type also
1543 /// derives `DslSchema`. Consumers use this to correlate a runtime
1544 /// node with its type-level schema entry — schema-aware lint
1545 /// rules, editor tooling, and any other component that needs to
1546 /// go from an AST value to "which variant is this" without
1547 /// downcasting.
1548 fn variant_name(&self) -> &'static str;
1549}
1550
1551// ---------- Breakpoints -------------------------------------------------
1552
1553/// Identifier assigned by a [`BreakpointSet`] to each added condition.
1554#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
1555pub struct BreakpointId(pub u64);
1556
1557impl fmt::Display for BreakpointId {
1558 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1559 write!(f, "bp{}", self.0)
1560 }
1561}
1562
1563/// A boolean predicate over [`NodeContext`] used to describe conditional
1564/// breakpoints.
1565#[derive(Debug, Clone, PartialEq, Eq)]
1566pub enum BreakCondition {
1567 /// Matches when the node ID is exactly `id`.
1568 Node(NodeId),
1569 /// Matches when the current path has the given prefix.
1570 PathPrefix(Path),
1571 /// Matches when the current path equals the given path exactly.
1572 PathExact(Path),
1573 /// Matches when the current call-frame depth is at least `n`.
1574 DepthAtLeast(u32),
1575 /// Matches when the current call-frame depth is at most `n`.
1576 DepthAtMost(u32),
1577 /// Matches when the current call-frame depth equals `n` exactly.
1578 DepthEquals(u32),
1579 /// Matches when the iteration counter equals `n`.
1580 Iteration(u64),
1581 /// Matches when the current call frame equals `frame`.
1582 CallFrame(CallFrameId),
1583 /// Matches when any child matches.
1584 Any(Vec<BreakCondition>),
1585 /// Matches when every child matches.
1586 All(Vec<BreakCondition>),
1587 /// Matches when the inner does not match.
1588 Not(Box<BreakCondition>),
1589 /// Always matches (useful as a debugger's "break on every node" mode).
1590 Always,
1591 /// Never matches (useful as a disabled placeholder).
1592 Never,
1593}
1594
1595impl BreakCondition {
1596 /// Convenience constructor.
1597 pub fn at_node(id: NodeId) -> Self {
1598 Self::Node(id)
1599 }
1600
1601 /// Convenience constructor.
1602 pub fn under_path(path: Path) -> Self {
1603 Self::PathPrefix(path)
1604 }
1605
1606 /// Convenience constructor.
1607 pub fn at_path(path: Path) -> Self {
1608 Self::PathExact(path)
1609 }
1610
1611 /// Convenience constructor.
1612 pub fn at_depth_at_least(n: u32) -> Self {
1613 Self::DepthAtLeast(n)
1614 }
1615
1616 /// Convenience constructor.
1617 pub fn at_depth_at_most(n: u32) -> Self {
1618 Self::DepthAtMost(n)
1619 }
1620
1621 /// Convenience constructor.
1622 pub fn at_depth(n: u32) -> Self {
1623 Self::DepthEquals(n)
1624 }
1625
1626 /// Convenience constructor.
1627 pub fn at_iteration(n: u64) -> Self {
1628 Self::Iteration(n)
1629 }
1630
1631 /// Convenience constructor.
1632 pub fn in_call_frame(frame: CallFrameId) -> Self {
1633 Self::CallFrame(frame)
1634 }
1635
1636 /// Logical AND.
1637 pub fn and(self, other: Self) -> Self {
1638 match (self, other) {
1639 (Self::All(mut xs), Self::All(ys)) => {
1640 xs.extend(ys);
1641 Self::All(xs)
1642 }
1643 (Self::All(mut xs), other) => {
1644 xs.push(other);
1645 Self::All(xs)
1646 }
1647 (this, Self::All(mut ys)) => {
1648 ys.insert(0, this);
1649 Self::All(ys)
1650 }
1651 (this, other) => Self::All(vec![this, other]),
1652 }
1653 }
1654
1655 /// Logical OR.
1656 pub fn or(self, other: Self) -> Self {
1657 match (self, other) {
1658 (Self::Any(mut xs), Self::Any(ys)) => {
1659 xs.extend(ys);
1660 Self::Any(xs)
1661 }
1662 (Self::Any(mut xs), other) => {
1663 xs.push(other);
1664 Self::Any(xs)
1665 }
1666 (this, Self::Any(mut ys)) => {
1667 ys.insert(0, this);
1668 Self::Any(ys)
1669 }
1670 (this, other) => Self::Any(vec![this, other]),
1671 }
1672 }
1673
1674 /// Evaluates the condition against a context.
1675 pub fn matches(&self, ctx: &NodeContext) -> bool {
1676 match self {
1677 Self::Node(id) => ctx.node == *id,
1678 Self::PathPrefix(prefix) => {
1679 ctx.path.0.len() >= prefix.0.len() && ctx.path.0[..prefix.0.len()] == prefix.0[..]
1680 }
1681 Self::PathExact(path) => ctx.path == *path,
1682 Self::DepthAtLeast(n) => ctx.depth >= *n,
1683 Self::DepthAtMost(n) => ctx.depth <= *n,
1684 Self::DepthEquals(n) => ctx.depth == *n,
1685 Self::Iteration(n) => ctx.iteration.map(|i| i.0 == *n).unwrap_or(false),
1686 Self::CallFrame(frame) => ctx.frame == Some(*frame),
1687 Self::Any(children) => children.iter().any(|c| c.matches(ctx)),
1688 Self::All(children) => children.iter().all(|c| c.matches(ctx)),
1689 Self::Not(inner) => !inner.matches(ctx),
1690 Self::Always => true,
1691 Self::Never => false,
1692 }
1693 }
1694}
1695
1696impl std::ops::Not for BreakCondition {
1697 type Output = Self;
1698
1699 /// Logical NOT: `!cond` matches exactly when `cond` does not.
1700 fn not(self) -> Self {
1701 Self::Not(Box::new(self))
1702 }
1703}
1704
1705/// A registry of breakpoint conditions and their assigned IDs.
1706#[derive(Debug, Default)]
1707pub struct BreakpointSet {
1708 next: u64,
1709 entries: Vec<(BreakpointId, BreakCondition)>,
1710}
1711
1712impl BreakpointSet {
1713 /// Creates an empty set.
1714 pub fn new() -> Self {
1715 Self {
1716 next: 1,
1717 entries: Vec::new(),
1718 }
1719 }
1720
1721 /// Adds a condition and returns its assigned id.
1722 pub fn add(&mut self, condition: BreakCondition) -> BreakpointId {
1723 let id = BreakpointId(self.next);
1724 self.next += 1;
1725 self.entries.push((id, condition));
1726 id
1727 }
1728
1729 /// Removes an entry by id. Returns whether an entry was found.
1730 pub fn remove(&mut self, id: BreakpointId) -> bool {
1731 let before = self.entries.len();
1732 self.entries.retain(|(entry_id, _)| *entry_id != id);
1733 self.entries.len() != before
1734 }
1735
1736 /// Returns the ids of all entries whose condition matches `ctx`.
1737 pub fn matches(&self, ctx: &NodeContext) -> Vec<BreakpointId> {
1738 self.entries
1739 .iter()
1740 .filter(|(_, cond)| cond.matches(ctx))
1741 .map(|(id, _)| *id)
1742 .collect()
1743 }
1744
1745 /// Returns whether the set has no entries.
1746 pub fn is_empty(&self) -> bool {
1747 self.entries.is_empty()
1748 }
1749
1750 /// Number of entries currently registered.
1751 pub fn len(&self) -> usize {
1752 self.entries.len()
1753 }
1754
1755 /// Iterates over the registered `(id, condition)` pairs.
1756 pub fn iter(&self) -> impl Iterator<Item = (BreakpointId, &BreakCondition)> {
1757 self.entries.iter().map(|(id, c)| (*id, c))
1758 }
1759}
1760
1761// ---------- Traversal ---------------------------------------------------
1762
1763/// Which side of a node's traversal the visitor is currently on.
1764#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1765pub enum Phase {
1766 /// Before descending into the node's children.
1767 Pre,
1768 /// After all children have been visited.
1769 Post,
1770}
1771
1772/// AST traversal contract.
1773pub trait Walk: DslNode + Sized {
1774 /// Direct children of this node, in traversal order.
1775 fn children(&self) -> Vec<&Self>;
1776
1777 /// Depth-first pre / post traversal.
1778 fn walk<F>(&self, visitor: &mut F)
1779 where
1780 F: FnMut(&Self, Phase),
1781 {
1782 visitor(self, Phase::Pre);
1783 for child in self.children() {
1784 child.walk(visitor);
1785 }
1786 visitor(self, Phase::Post);
1787 }
1788
1789 /// Depth-first traversal with early exit.
1790 fn walk_until<F, T>(&self, visitor: &mut F) -> Option<T>
1791 where
1792 F: FnMut(&Self, Phase) -> Option<T>,
1793 {
1794 if let Some(t) = visitor(self, Phase::Pre) {
1795 return Some(t);
1796 }
1797 for child in self.children() {
1798 if let Some(t) = child.walk_until(visitor) {
1799 return Some(t);
1800 }
1801 }
1802 visitor(self, Phase::Post)
1803 }
1804
1805 /// Locates a node by its stable ID.
1806 fn find_by_id(&self, target: NodeId) -> Option<&Self> {
1807 self.walk_until(&mut |node, phase| {
1808 if phase == Phase::Pre && node.node_id() == target {
1809 Some(node as *const Self)
1810 } else {
1811 None
1812 }
1813 })
1814 .map(|ptr| unsafe { &*ptr })
1815 }
1816}
1817
1818/// Mutable counterpart of [`Walk`].
1819pub trait WalkMut: DslNode + Sized {
1820 /// Direct children of this node, mutably, in traversal order.
1821 fn children_mut(&mut self) -> Vec<&mut Self>;
1822
1823 /// Depth-first pre / post traversal with mutable access.
1824 fn walk_mut<F>(&mut self, visitor: &mut F)
1825 where
1826 F: FnMut(&mut Self, Phase),
1827 {
1828 visitor(self, Phase::Pre);
1829 for child in self.children_mut() {
1830 child.walk_mut(visitor);
1831 }
1832 visitor(self, Phase::Post);
1833 }
1834}
1835
1836#[cfg(test)]
1837mod tests {
1838 use super::*;
1839
1840 #[test]
1841 fn path_push_extends_depth() {
1842 let ids = IdGen::new();
1843 let a = ids.node();
1844 let b = ids.node();
1845
1846 let root = Path::root();
1847 assert_eq!(root.depth(), 0);
1848
1849 let one = root.push(a);
1850 assert_eq!(one.depth(), 1);
1851
1852 let two = one.push(b);
1853 assert_eq!(two.depth(), 2);
1854 assert_eq!(two.tip(), Some(b));
1855 }
1856
1857 #[test]
1858 fn id_generator_yields_distinct_ids() {
1859 let ids = IdGen::new();
1860 let a = ids.node();
1861 let b = ids.node();
1862 assert_ne!(a, b);
1863 }
1864
1865 #[test]
1866 fn null_sink_accepts_events() {
1867 let mut sink = NullSink;
1868 let event = Event::VisitPre {
1869 at: NodeContext::at(NodeId(0), Path::root()),
1870 };
1871 sink.emit(&event);
1872 }
1873
1874 fn ctx_at(node: NodeId, path: Path, depth: u32) -> NodeContext {
1875 NodeContext {
1876 node,
1877 path,
1878 frame: None,
1879 depth,
1880 iteration: None,
1881 }
1882 }
1883
1884 #[test]
1885 fn breakpoint_node_matches_exact_id() {
1886 let cond = BreakCondition::at_node(NodeId(7));
1887 assert!(cond.matches(&ctx_at(NodeId(7), Path::root().push(NodeId(7)), 1)));
1888 assert!(!cond.matches(&ctx_at(NodeId(8), Path::root().push(NodeId(8)), 1)));
1889 }
1890
1891 #[test]
1892 fn breakpoint_set_add_matches_remove() {
1893 let mut set = BreakpointSet::new();
1894 let hit = set.add(BreakCondition::at_node(NodeId(4)));
1895 let miss = set.add(BreakCondition::at_node(NodeId(99)));
1896
1897 let ctx = ctx_at(NodeId(4), Path::root().push(NodeId(4)), 1);
1898 assert_eq!(set.matches(&ctx), vec![hit]);
1899
1900 assert!(set.remove(hit));
1901 assert!(set.matches(&ctx).is_empty());
1902 assert_eq!(set.len(), 1);
1903 assert!(set.iter().any(|(id, _)| id == miss));
1904 }
1905
1906 #[test]
1907 fn engine_error_carries_stable_code() {
1908 let err = EngineError::Aborted {
1909 at: NodeContext::at(NodeId(1), Path::root().push(NodeId(1))),
1910 reason: "user requested".into(),
1911 };
1912 use miette::Diagnostic;
1913 assert_eq!(
1914 err.code().map(|c| c.to_string()).as_deref(),
1915 Some("dsl_kit::eval::aborted")
1916 );
1917 }
1918
1919 #[test]
1920 fn engine_error_catalog_covers_every_variant() {
1921 let entries = engine_error_catalog();
1922 let codes: Vec<&str> = entries.iter().map(|e| e.code.as_str()).collect();
1923 assert!(codes.contains(&"dsl_kit::eval::aborted"));
1924 assert!(codes.contains(&"dsl_kit::eval::failed"));
1925 assert!(codes.contains(&"dsl_kit::ast::malformed"));
1926 assert!(codes.contains(&"dsl_kit::stepper::protocol"));
1927 assert!(codes.contains(&"dsl_kit::stepper::unknown_suspension"));
1928 assert!(codes.contains(&"dsl_kit::reducer::unknown"));
1929 for entry in &entries {
1930 assert!(!entry.help.is_empty(), "help empty for {}", entry.code);
1931 }
1932 }
1933
1934 #[test]
1935 fn reducer_id_from_str_and_string() {
1936 let a: ReducerId = "foo".into();
1937 let b: ReducerId = String::from("foo").into();
1938 assert_eq!(a, b);
1939 }
1940
1941 #[test]
1942 fn reducer_registry_resolves_fail_fast_and_collect_all_independently() {
1943 // A trivial FailFast reducer that returns the first non-None
1944 // slot verbatim.
1945 struct FirstNonNone;
1946 impl Reducer<i64, ()> for FirstNonNone {
1947 fn reduce(
1948 &self,
1949 slots: &[Option<i64>],
1950 _deltas: &[Option<()>],
1951 _winners: &[ChildIndex],
1952 ) -> Result<(i64, ()), EngineError> {
1953 let v = slots.iter().find_map(|s| *s).unwrap_or(0);
1954 Ok((v, ()))
1955 }
1956 }
1957
1958 // A trivial CollectAll reducer.
1959 struct CountOk;
1960 impl ReducerCollectAll<i64, (), std::io::Error> for CountOk {
1961 fn reduce(
1962 &self,
1963 slots: &[Option<Result<i64, std::io::Error>>],
1964 _deltas: &[Option<()>],
1965 _winners: &[ChildIndex],
1966 ) -> Result<(i64, ()), EngineError> {
1967 let count = slots.iter().filter(|s| matches!(s, Some(Ok(_)))).count();
1968 Ok((count as i64, ()))
1969 }
1970 }
1971
1972 let mut reg: ReducerRegistry<i64, (), std::io::Error> = ReducerRegistry::new();
1973 reg.register_fail_fast("first", Arc::new(FirstNonNone));
1974 reg.register_collect_all("count_ok", Arc::new(CountOk));
1975
1976 let ff = reg.resolve(&"first".into(), FailPolicy::FailFast).unwrap();
1977 assert!(matches!(ff, ReducerHandle::FailFast(_)));
1978 let ca = reg
1979 .resolve(&"count_ok".into(), FailPolicy::CollectAll)
1980 .unwrap();
1981 assert!(matches!(ca, ReducerHandle::CollectAll(_)));
1982
1983 let miss = reg.resolve(&"nope".into(), FailPolicy::FailFast);
1984 assert!(matches!(miss, Err(EngineError::UnknownReducer { .. })));
1985 }
1986
1987 /// Fixed-output suggester used to prove the with_suggester wiring
1988 /// without depending on `dsl-kit-fuzzy` — a real dev-dep on that
1989 /// crate would create a cycle since fuzzy already depends on
1990 /// dsl-kit-core, and cargo cannot unify the `Suggester` trait
1991 /// across the two versions of core that would result.
1992 struct FixedSuggester(&'static str);
1993 impl Suggester for FixedSuggester {
1994 fn suggest<'a>(&self, _q: &str, cands: &'a [&str]) -> Vec<Suggestion<'a>> {
1995 cands
1996 .iter()
1997 .find(|c| **c == self.0)
1998 .map(|c| Suggestion {
1999 candidate: c,
2000 score: 1.0,
2001 })
2002 .into_iter()
2003 .collect()
2004 }
2005 }
2006
2007 #[test]
2008 fn unknown_reducer_defaults_to_no_hint() {
2009 // Without an injected suggester the historical `unknown
2010 // reducer "X"` wording is preserved verbatim.
2011 struct Noop;
2012 impl Reducer<i64, ()> for Noop {
2013 fn reduce(
2014 &self,
2015 _s: &[Option<i64>],
2016 _d: &[Option<()>],
2017 _w: &[ChildIndex],
2018 ) -> Result<(i64, ()), EngineError> {
2019 Ok((0, ()))
2020 }
2021 }
2022 let mut reg: ReducerRegistry<i64, (), std::io::Error> = ReducerRegistry::new();
2023 reg.register_fail_fast("first", Arc::new(Noop));
2024 let miss = reg.resolve(&"frst".into(), FailPolicy::FailFast);
2025 let err = match miss {
2026 Err(e) => e,
2027 Ok(_) => panic!("expected miss"),
2028 };
2029 // Base wording matches the historical `{id:?}` Debug shape;
2030 // the trailing `hint` is empty so no parenthesised clause
2031 // appears.
2032 assert_eq!(err.to_string(), "unknown reducer ReducerId(\"frst\")");
2033 }
2034
2035 #[test]
2036 fn unknown_reducer_with_suggester_appends_hint() {
2037 struct Noop;
2038 impl Reducer<i64, ()> for Noop {
2039 fn reduce(
2040 &self,
2041 _s: &[Option<i64>],
2042 _d: &[Option<()>],
2043 _w: &[ChildIndex],
2044 ) -> Result<(i64, ()), EngineError> {
2045 Ok((0, ()))
2046 }
2047 }
2048 let mut reg: ReducerRegistry<i64, (), std::io::Error> = ReducerRegistry::new();
2049 reg.register_fail_fast("first", Arc::new(Noop));
2050 let reg = reg.with_suggester(Arc::new(FixedSuggester("first")));
2051 let miss = reg.resolve(&"frst".into(), FailPolicy::FailFast);
2052 let err = match miss {
2053 Err(e) => e,
2054 Ok(_) => panic!("expected miss"),
2055 };
2056 let msg = err.to_string();
2057 assert!(
2058 msg.contains("did you mean") && msg.contains("first"),
2059 "expected hint, got: {msg}"
2060 );
2061 }
2062
2063 #[test]
2064 fn unknown_op_defaults_to_no_hint() {
2065 struct AddOp;
2066 impl Op<i64> for AddOp {
2067 fn apply(&self, _n: NodeId, args: &[i64]) -> Result<i64, EngineError> {
2068 Ok(args.iter().sum())
2069 }
2070 }
2071 let mut reg: OpRegistry<i64> = OpRegistry::new();
2072 reg.register("add", Arc::new(AddOp));
2073 let miss = reg.resolve(&"ad".into());
2074 let err = match miss {
2075 Err(e) => e,
2076 Ok(_) => panic!("expected miss"),
2077 };
2078 assert_eq!(err.to_string(), "unknown op OpId(\"ad\")");
2079 }
2080
2081 #[test]
2082 fn unknown_op_with_suggester_appends_hint() {
2083 struct AddOp;
2084 impl Op<i64> for AddOp {
2085 fn apply(&self, _n: NodeId, args: &[i64]) -> Result<i64, EngineError> {
2086 Ok(args.iter().sum())
2087 }
2088 }
2089 let mut reg: OpRegistry<i64> = OpRegistry::new();
2090 reg.register("add", Arc::new(AddOp));
2091 let reg = reg.with_suggester(Arc::new(FixedSuggester("add")));
2092 let miss = reg.resolve(&"ad".into());
2093 let err = match miss {
2094 Err(e) => e,
2095 Ok(_) => panic!("expected miss"),
2096 };
2097 let msg = err.to_string();
2098 assert!(
2099 msg.contains("did you mean") && msg.contains("add"),
2100 "expected hint, got: {msg}"
2101 );
2102 }
2103}