Skip to main content

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