Skip to main content

xmachines_runtime/
core.rs

1//! The structural statechart algorithm, shared by every host.
2//!
3//! This is a port of the structural half of XState v6's `stateUtils.ts`
4//! (`selectEventTransitions`, `selectEventlessTransitions`, `removeConflictingTransitions`,
5//! `getTransitionDomain`, `computeExitSet`, `microstep`, `initialMicrostep` and
6//! the loop in `macrostep`). Everything that touches values (guards,
7//! transition functions, entry and exit functions, effects, snapshots) is
8//! delegated to a [`Host`], called in exactly the order XState performs the
9//! same work. The native interpreter is one host; the patched XState package
10//! used to run XState's own test suite (through `xstate-suite-bridge`) is another.
11//!
12//! The configuration is an insertion-ordered set, like XState's `nodes`
13//! array: state values, parallel region order and selection order all follow
14//! it, and it can differ from document order after a region is re-entered.
15
16use std::cell::RefCell;
17use std::ops::{Deref, DerefMut};
18use std::sync::Arc;
19
20/// A state node, by document order (XState's `StateNode.order`).
21pub type Nid = u32;
22/// A transition definition registered with the tree.
23pub type Tid = u32;
24
25#[derive(Debug, Clone, Copy, PartialEq, Eq)]
26pub enum Kind {
27    Atomic,
28    Compound,
29    Parallel,
30    Final,
31    History {
32        deep: bool,
33    },
34    /// Choice states are atomic for the algorithm; their branches are `always` transitions.
35    Choice,
36}
37
38impl Kind {
39    /// XState's `isAtomicStateNode`.
40    pub fn is_atomic(self) -> bool {
41        matches!(self, Kind::Atomic | Kind::Final | Kind::Choice)
42    }
43}
44
45/// XState's internal `_transitionDomain` override.
46#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
47pub enum DomainHint {
48    #[default]
49    None,
50    Internal,
51    External,
52}
53
54#[derive(Debug, Clone)]
55pub struct TreeNode {
56    pub parent: Option<Nid>,
57    pub kind: Kind,
58    /// Child states except history states, in `states` order.
59    pub children: Vec<Nid>,
60    /// History states declared in `states`, in order.
61    pub history_children: Vec<Nid>,
62    /// The node's transition map in insertion order: descriptor and the
63    /// transitions registered under it.
64    pub on: Vec<(String, Vec<Tid>)>,
65    pub always: Vec<Tid>,
66    /// One past the last descendant.
67    end: Nid,
68}
69
70impl TreeNode {
71    pub fn new(parent: Option<Nid>, kind: Kind) -> Self {
72        Self {
73            parent,
74            kind,
75            children: Vec::new(),
76            history_children: Vec::new(),
77            on: Vec::new(),
78            always: Vec::new(),
79            end: 0,
80        }
81    }
82}
83
84#[derive(Debug, Clone, Copy)]
85pub struct TreeTransition {
86    pub source: Nid,
87    pub domain: DomainHint,
88}
89
90/// The structure of a machine: nodes in document order and the source of
91/// every transition.
92#[derive(Debug, Clone)]
93pub struct Tree {
94    pub nodes: Vec<TreeNode>,
95    pub transitions: Vec<TreeTransition>,
96    pub has_eventless: bool,
97}
98
99impl Tree {
100    /// Finishes a tree whose nodes are in pre-order with parents set.
101    /// Fills in `end` and `has_eventless`.
102    pub fn new(mut nodes: Vec<TreeNode>, transitions: Vec<TreeTransition>) -> Self {
103        let n = nodes.len() as Nid;
104        for i in 0..n {
105            nodes[i as usize].end = i + 1;
106        }
107        for i in (1..n).rev() {
108            if let Some(p) = nodes[i as usize].parent {
109                let end = nodes[i as usize].end;
110                if end > nodes[p as usize].end {
111                    nodes[p as usize].end = end;
112                }
113            }
114        }
115        let has_eventless = nodes.iter().any(|n| !n.always.is_empty());
116        Self { nodes, transitions, has_eventless }
117    }
118
119    #[inline]
120    pub fn node(&self, n: Nid) -> &TreeNode {
121        &self.nodes[n as usize]
122    }
123
124    #[inline]
125    pub fn kind(&self, n: Nid) -> Kind {
126        self.nodes[n as usize].kind
127    }
128
129    #[inline]
130    fn is_history(&self, n: Nid) -> bool {
131        matches!(self.kind(n), Kind::History { .. })
132    }
133
134    /// XState's `isDescendant(child, parent)`: strict; `None` (no domain)
135    /// contains every node, the root included.
136    #[inline]
137    pub fn is_descendant(&self, node: Nid, ancestor: Option<Nid>) -> bool {
138        match ancestor {
139            None => true,
140            Some(a) => node > a && node < self.node(a).end,
141        }
142    }
143
144    /// XState's `getProperAncestors(node, to)`, without collecting.
145    pub fn ancestors(&self, node: Nid, to: Option<Nid>) -> impl Iterator<Item = Nid> + '_ {
146        let start = if Some(node) == to { None } else { self.node(node).parent };
147        std::iter::successors(start, move |&a| self.node(a).parent).take_while(move |&a| Some(a) != to)
148    }
149
150    /// XState's `getProperAncestors(node, to)`.
151    pub fn proper_ancestors(&self, node: Nid, to: Option<Nid>) -> Vec<Nid> {
152        let mut out = Vec::new();
153        if Some(node) == to {
154            return out;
155        }
156        let mut m = self.node(node).parent;
157        while let Some(a) = m {
158            if Some(a) == to {
159                break;
160            }
161            out.push(a);
162            m = self.node(a).parent;
163        }
164        out
165    }
166
167    /// XState's `getCandidates`: exact descriptor first, then the other
168    /// matching descriptors, longest first.
169    pub fn candidates(&self, node: Nid, event_type: &str) -> Buf<Tid> {
170        self.candidates_with_warnings(node, event_type, &mut |_| {})
171    }
172
173    /// [`Tree::candidates`], reporting the development warnings XState's
174    /// `matchesEventDescriptor` logs for misplaced wildcards, in order.
175    pub fn candidates_with_warnings(&self, node: Nid, event_type: &str, warn: &mut dyn FnMut(String)) -> Buf<Tid> {
176        let on = &self.node(node).on;
177        let mut out: Buf<Tid> = Buf::new();
178        if let Some((_, ts)) = on.iter().find(|(d, _)| d == event_type) {
179            out.extend_from_slice(ts);
180        }
181        let mut wild =
182            on.iter().filter(|(d, _)| d != event_type && matches_event_descriptor_warn(event_type, d, &mut *warn));
183        // Usually there is no wildcard; only sort when there are several.
184        if let Some(first) = wild.next() {
185            match wild.next() {
186                None => out.extend_from_slice(&first.1),
187                Some(second) => {
188                    let mut all: Vec<&(String, Vec<Tid>)> = vec![first, second];
189                    all.extend(wild);
190                    all.sort_by_key(|(d, _)| std::cmp::Reverse(d.len()));
191                    for (_, ts) in all {
192                        out.extend_from_slice(ts);
193                    }
194                }
195            }
196        }
197        out
198    }
199
200    /// XState's `isInFinalState`, over a configuration membership test.
201    pub fn is_in_final_state(&self, set: &OrderedSet, node: Nid) -> bool {
202        let n = self.node(node);
203        match n.kind {
204            Kind::Compound => n.children.iter().any(|&c| self.kind(c) == Kind::Final && set.contains(c)),
205            Kind::Parallel => n.children.iter().all(|&c| self.is_in_final_state(set, c)),
206            kind => kind == Kind::Final,
207        }
208    }
209
210    /// XState's `getStateValue` structure: for each active node, its active
211    /// children in configuration order. Returns, per node, the ordered list.
212    pub fn active_children(&self, config: &[Nid]) -> Vec<Vec<Nid>> {
213        let mut adj = vec![Vec::new(); self.nodes.len()];
214        for &s in config {
215            if let Some(p) = self.node(s).parent {
216                adj[p as usize].push(s);
217            }
218        }
219        adj
220    }
221}
222
223/// XState's `getAllStateNodes`: the configuration, initial descendants of
224/// compound and parallel states with no active child, and every ancestor, in
225/// XState's insertion order. `snapshot.value`, and therefore selection, is
226/// built from it. For a legal configuration it is the configuration itself;
227/// XState can produce illegal ones (fixture `conflicting_regions`), and both
228/// follow from it then. `initial` gives a compound state's static initial
229/// targets.
230pub fn all_state_nodes(tree: &Tree, config: &[Nid], initial: impl Fn(Nid) -> Arc<[Nid]>) -> OrderedSet {
231    let size = tree.nodes.len();
232    // `getInitialStateNodes`.
233    let initial_state_nodes = |node: Nid| -> OrderedSet {
234        let mut set = OrderedSet::new(size);
235        let mut stack: Buf<Nid> = Buf::new();
236        stack.push(node);
237        // Depth first in document order, as the recursive `iter`.
238        while let Some(n) = stack.pop() {
239            if !set.insert(n) {
240                continue;
241            }
242            match tree.kind(n) {
243                Kind::Compound => stack.extend(initial(n).iter().rev()),
244                Kind::Parallel => stack.extend(tree.node(n).children.iter().rev()),
245                _ => {}
246            }
247        }
248        let mut i = 0;
249        while i < set.order.len() {
250            let mut a = tree.node(set.order[i]).parent;
251            i += 1;
252            while let Some(p) = a.filter(|&p| p != node) {
253                set.insert(p);
254                a = tree.node(p).parent;
255            }
256        }
257        set
258    };
259    let mut set = OrderedSet::new(size);
260    let mut active_parent: Buf<bool> = Buf::filled(false, size);
261    for &s in config {
262        set.insert(s);
263        if let Some(p) = tree.node(s).parent {
264            active_parent[p as usize] = true;
265        }
266    }
267    let mut i = 0;
268    while i < set.order.len() {
269        let s = set.order[i];
270        i += 1;
271        match tree.kind(s) {
272            Kind::Compound if !active_parent[s as usize] => {
273                for &n in initial_state_nodes(s).as_slice() {
274                    set.insert(n);
275                }
276            }
277            Kind::Parallel => {
278                for &child in &tree.node(s).children {
279                    if !set.contains(child) {
280                        for &n in initial_state_nodes(child).as_slice() {
281                            set.insert(n);
282                        }
283                    }
284                }
285            }
286            _ => {}
287        }
288    }
289    let mut i = 0;
290    while i < set.order.len() {
291        let mut m = tree.node(set.order[i]).parent;
292        i += 1;
293        while let Some(p) = m {
294            if !set.insert(p) {
295                break;
296            }
297            m = tree.node(p).parent;
298        }
299    }
300    set
301}
302
303/// Element types with a pool of reusable vectors (see [`Buf`]).
304pub trait Pooled: Copy + 'static {
305    #[doc(hidden)]
306    fn with_pool<R>(f: impl FnOnce(&mut Vec<Vec<Self>>) -> R) -> Option<R>;
307}
308
309macro_rules! pooled {
310    ($t:ty, $pool:ident) => {
311        thread_local! {
312            static $pool: RefCell<Vec<Vec<$t>>> = const { RefCell::new(Vec::new()) };
313        }
314        impl Pooled for $t {
315            fn with_pool<R>(f: impl FnOnce(&mut Vec<Vec<Self>>) -> R) -> Option<R> {
316                $pool.try_with(|p| p.try_borrow_mut().ok().map(|mut p| f(&mut p))).ok().flatten()
317            }
318        }
319    };
320}
321
322pooled!(u32, NID_POOL);
323pooled!(bool, BOOL_POOL);
324pooled!(TRef, TREF_POOL);
325
326/// "No domain" in a plan of transition domains.
327const NO_DOMAIN: Nid = Nid::MAX;
328
329/// A scratch vector taken from a per-thread pool and returned to it on drop,
330/// so the algorithm's temporaries do not allocate once the pool is warm.
331/// Re-entrant calls (a guard running another actor) simply take other
332/// vectors.
333pub struct Buf<T: Pooled>(Vec<T>);
334
335impl<T: Pooled> Buf<T> {
336    pub fn new() -> Self {
337        Buf(T::with_pool(|p| p.pop()).flatten().unwrap_or_default())
338    }
339
340    /// A buffer holding `len` copies of `value`.
341    pub fn filled(value: T, len: usize) -> Self {
342        let mut b = Self::new();
343        b.0.resize(len, value);
344        b
345    }
346
347    pub fn from_slice(items: &[T]) -> Self {
348        let mut b = Self::new();
349        b.0.extend_from_slice(items);
350        b
351    }
352}
353
354impl<T: Pooled> Default for Buf<T> {
355    fn default() -> Self {
356        Self::new()
357    }
358}
359
360impl<T: Pooled> Drop for Buf<T> {
361    fn drop(&mut self) {
362        let mut v = std::mem::take(&mut self.0);
363        if v.capacity() == 0 || v.capacity() > 4096 {
364            return;
365        }
366        v.clear();
367        T::with_pool(|p| {
368            if p.len() < 64 {
369                p.push(v);
370            }
371        });
372    }
373}
374
375impl<T: Pooled> Deref for Buf<T> {
376    type Target = Vec<T>;
377    fn deref(&self) -> &Vec<T> {
378        &self.0
379    }
380}
381
382impl<T: Pooled> DerefMut for Buf<T> {
383    fn deref_mut(&mut self) -> &mut Vec<T> {
384        &mut self.0
385    }
386}
387
388impl<T: Pooled> Clone for Buf<T> {
389    fn clone(&self) -> Self {
390        Self::from_slice(&self.0)
391    }
392}
393
394impl<T: Pooled + std::fmt::Debug> std::fmt::Debug for Buf<T> {
395    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
396        self.0.fmt(f)
397    }
398}
399
400impl<T: Pooled + PartialEq> PartialEq for Buf<T> {
401    fn eq(&self, other: &Self) -> bool {
402        self.0 == other.0
403    }
404}
405
406impl<T: Pooled> FromIterator<T> for Buf<T> {
407    fn from_iter<I: IntoIterator<Item = T>>(iter: I) -> Self {
408        let mut b = Self::new();
409        b.0.extend(iter);
410        b
411    }
412}
413
414impl<'a, T: Pooled> IntoIterator for &'a Buf<T> {
415    type Item = &'a T;
416    type IntoIter = std::slice::Iter<'a, T>;
417    fn into_iter(self) -> Self::IntoIter {
418        self.0.iter()
419    }
420}
421
422/// XState's `matchesEventDescriptor`.
423pub fn matches_event_descriptor(event_type: &str, descriptor: &str) -> bool {
424    matches_event_descriptor_warn(event_type, descriptor, &mut |_| {})
425}
426
427/// XState's `matchesEventDescriptor`, including its development warnings.
428pub fn matches_event_descriptor_warn(event_type: &str, descriptor: &str, warn: &mut dyn FnMut(String)) -> bool {
429    if descriptor == event_type || descriptor == "*" {
430        return true;
431    }
432    if !descriptor.ends_with(".*") {
433        return false;
434    }
435    // `/.*\*.+/`: a `*` followed by anything.
436    if descriptor.find('*').is_some_and(|i| i + 1 < descriptor.len()) {
437        warn(format!(
438            "Wildcards can only be the last token of an event descriptor (e.g., \"event.*\") or the entire event descriptor (\"*\"). Check the \"{descriptor}\" event."
439        ));
440    }
441    let mut event_tokens = event_type.split('.');
442    let mut partial_tokens = descriptor.split('.').peekable();
443    while let Some(partial) = partial_tokens.next() {
444        let event_token = event_tokens.next();
445        if partial == "*" {
446            let is_last = partial_tokens.peek().is_none();
447            if !is_last {
448                warn(format!(
449                    "Infix wildcards in transition events are not allowed. Check the \"{descriptor}\" transition."
450                ));
451            }
452            return is_last;
453        }
454        if Some(partial) != event_token {
455            return false;
456        }
457    }
458    true
459}
460
461/// An insertion-ordered set of nodes with O(1) membership, like a JS `Set`.
462#[derive(Debug, Clone)]
463pub struct OrderedSet {
464    order: Buf<Nid>,
465    member: Buf<bool>,
466}
467
468impl OrderedSet {
469    pub fn new(size: usize) -> Self {
470        Self { order: Buf::new(), member: Buf::filled(false, size) }
471    }
472
473    pub fn from_slice(size: usize, items: &[Nid]) -> Self {
474        let mut s = Self::new(size);
475        for &i in items {
476            s.insert(i);
477        }
478        s
479    }
480
481    #[inline]
482    pub fn contains(&self, n: Nid) -> bool {
483        self.member[n as usize]
484    }
485
486    pub fn insert(&mut self, n: Nid) -> bool {
487        if self.member[n as usize] {
488            return false;
489        }
490        self.member[n as usize] = true;
491        self.order.push(n);
492        true
493    }
494
495    pub fn remove(&mut self, n: Nid) -> bool {
496        if !self.member[n as usize] {
497            return false;
498        }
499        self.member[n as usize] = false;
500        if let Some(i) = self.order.iter().position(|&x| x == n) {
501            self.order.remove(i);
502        }
503        true
504    }
505
506    pub fn as_slice(&self) -> &[Nid] {
507        &self.order
508    }
509
510    pub fn len(&self) -> usize {
511        self.order.len()
512    }
513
514    pub fn is_empty(&self) -> bool {
515        self.order.is_empty()
516    }
517
518    fn intersects(&self, other: &OrderedSet) -> bool {
519        let (small, big) = if self.len() <= other.len() { (self, other) } else { (other, self) };
520        small.order.iter().any(|&n| big.contains(n))
521    }
522}
523
524/// A transition as the algorithm sees it.
525#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
526pub enum TRef {
527    /// A registered transition definition.
528    T(Tid),
529    /// The `initial` transition of a compound state.
530    Initial(Nid),
531    /// The default transition of a history state (`resolveHistoryDefaultTransition`).
532    HistoryDefault(Nid),
533    /// The synthetic transition of the initial microstep.
534    InitialMicrostep,
535}
536
537/// Which of XState's transition-result resolvers a lookup goes through.
538/// Each has its own cache in XState; hosts must keep them apart.
539#[derive(Debug, Clone, Copy, PartialEq, Eq)]
540pub enum Resolver {
541    /// `selectEventlessTransitions`' conflict resolution
542    /// (`resolveActions: false`, with the selection's results since
543    /// XState 6.0.0-beta.4).
544    EventlessSelection,
545    /// The microstep's conflict resolution (`resolveActions: false`).
546    Conflicts,
547    /// The microstep's `getCurrentTransitionResult` (`resolveActions: true`).
548    Current,
549}
550
551/// The structural part of a transition result.
552#[derive(Debug, Clone, Default, PartialEq, Eq)]
553pub struct Resolved {
554    pub targets: Option<Arc<[Nid]>>,
555    pub reenter: bool,
556}
557
558/// How a region contributes to a parallel state's done output.
559#[derive(Debug, Clone, Copy, PartialEq, Eq)]
560pub enum RegionOutput {
561    /// The region is itself a final state.
562    Final(Nid),
563    /// The region is parallel: its output is its queued done event's output.
564    Parallel(Nid),
565    /// A compound region and its active final child, if any.
566    Compound(Nid, Option<Nid>),
567}
568
569/// The value-level half of the algorithm. Every method corresponds to a
570/// point in XState's `stateUtils.ts` where it reads or writes values.
571pub trait Host {
572    type Error;
573
574    /// Appends the current configuration (`snapshot.nodes`), in order, to `out`.
575    fn config(&self, out: &mut Vec<Nid>);
576    /// The recorded history of a history state in the current snapshot.
577    fn history(&self, history: Nid) -> Option<Vec<Nid>>;
578    /// The static targets of a compound state's `initial` (`initial.target`).
579    fn static_initial(&self, node: Nid) -> Arc<[Nid]>;
580
581    /// `machine._microstepHooks?.begin(self)`, at the start of selection.
582    fn begin_selection(&mut self) -> Result<(), Self::Error>;
583    /// Whether this is the first candidate lookup for `node` and
584    /// `event_type` (XState caches candidates per node and event type, so
585    /// its descriptor warnings appear only then). Hosts that do not report
586    /// warnings can return `false`.
587    fn first_candidates(&mut self, _node: Nid, _event_type: &str) -> bool {
588        false
589    }
590    /// A development warning, as XState logs with `console.warn`.
591    fn warn(&mut self, _message: &str) {}
592    /// `evaluateCandidate`: `matches`, guard, and transition function selection.
593    /// `eventless` tells whether the candidate is an `always` transition.
594    fn eval_candidate(&mut self, t: Tid, node: Nid, eventless: bool) -> Result<bool, Self::Error>;
595    /// Whether a candidate [`Host::eval_candidate`] enabled in this
596    /// selection rejected the event (its transition function returned
597    /// `reject(...)`): it is selected, so its ancestors are not searched,
598    /// then left out of the transitions taken.
599    fn rejected(&self, _t: Tid) -> bool {
600        false
601    }
602    /// A transition result through one of the resolvers.
603    fn resolve(&mut self, resolver: Resolver, t: TRef) -> Result<Resolved, Self::Error>;
604
605    /// Start of a microstep (`_microstepHooks?.drain`), before anything else.
606    fn begin_microstep(&mut self) -> Result<(), Self::Error>;
607    /// Exits one state: exit function, its actions, stopping its invokes.
608    fn exit_state(&mut self, node: Nid) -> Result<(), Self::Error>;
609    /// Executes the content of the filtered transitions, in order. `active`
610    /// is the configuration after exits, in the order of the snapshot's
611    /// (XState's `mutStateNodeSet`, which `_microstepHooks.transitionContent` gets).
612    fn transition_content(&mut self, filtered: &[TRef], active: &[Nid]) -> Result<(), Self::Error>;
613    /// Before entering: the configuration after exits, and the targets each
614    /// transition enters explicitly (for state inputs).
615    fn begin_entry(&mut self, active: &[Nid], entered: &[(TRef, Buf<Nid>)]) -> Result<(), Self::Error>;
616    /// Enters one state: invokes, entry function, and, for default entry, its
617    /// `initial` transition and the default transitions of `history_defaults`.
618    fn enter_state(&mut self, node: Nid, default_entry: bool, history_defaults: &[Nid]) -> Result<(), Self::Error>;
619    /// A final child was entered: queue `xstate.done.state` for its compound parent.
620    fn done_compound(&mut self, parent: Nid, final_child: Nid) -> Result<(), Self::Error>;
621    /// A parallel state completed: queue its done event with the region outputs.
622    fn done_parallel(&mut self, parallel: Nid, regions: &[RegionOutput]) -> Result<(), Self::Error>;
623    /// The machine completed through `completion`.
624    fn machine_done(&mut self, completion: Nid) -> Result<(), Self::Error>;
625    /// After all states were entered.
626    fn end_entry(&mut self) -> Result<(), Self::Error>;
627    /// Whether the machine completed in this microstep.
628    fn is_done(&self) -> bool;
629    /// The machine completed: exit every active state (deepest-last order
630    /// reversed: descending document order), stop children, cancel timers.
631    fn exit_on_done(&mut self, nodes_desc: &[Nid]) -> Result<(), Self::Error>;
632    /// Applies the microstep's structural result to the snapshot. `None`
633    /// means no transition was taken.
634    fn apply_microstep(&mut self, result: Option<MicrostepResult>, enabled: &[TRef]) -> Result<(), Self::Error>;
635
636    // The macrostep loop.
637
638    /// Whether the snapshot is active.
639    fn is_active(&self) -> bool;
640    /// Called at the top of each loop iteration with the iteration count;
641    /// fails when the microstep bound is exceeded.
642    fn check_iteration(&mut self, iteration: usize) -> Result<(), Self::Error>;
643    /// An identity for the current snapshot object.
644    fn snapshot_token(&self) -> u64;
645    /// The identity of the snapshot the last microstep returned (before any
646    /// post-microstep bookkeeping, such as removing a terminated child).
647    fn microstep_token(&self) -> u64;
648    /// `_microstepHooks?.drain`: raised events from failed eventless guards.
649    fn drain_raised(&mut self) -> Result<(), Self::Error>;
650    fn queue_is_empty(&self) -> bool;
651    /// Takes the next internal event, making it the current event. Returns
652    /// its type, or `None` when the queue is empty.
653    fn dequeue(&mut self) -> Result<Option<String>, Self::Error>;
654}
655
656/// The structural outcome of a microstep.
657#[derive(Debug, Clone)]
658pub struct MicrostepResult {
659    /// The transitions taken, after conflict removal.
660    pub filtered: Buf<TRef>,
661    /// The new configuration. Equal to the old one, order included, unless
662    /// `structure_changed`.
663    pub nodes: Buf<Nid>,
664    /// Whether membership or history changed (XState then builds a new
665    /// node list and history value).
666    pub structure_changed: bool,
667    /// History values recorded by this microstep, in recording order.
668    pub history_updates: Vec<(Nid, Vec<Nid>)>,
669}
670
671/// The synthetic transition of the initial microstep.
672#[derive(Debug, Clone)]
673pub struct InitialPlan {
674    pub targets: Arc<[Nid]>,
675    pub default_entry: Vec<Nid>,
676}
677
678// ---- selection ----------------------------------------------------------------
679
680fn config_of<H: Host>(h: &H) -> Buf<Nid> {
681    let mut config = Buf::new();
682    h.config(&mut config);
683    config
684}
685
686/// `StateNode.next`: the first enabled candidate of one node.
687fn node_next<H: Host>(tree: &Tree, h: &mut H, node: Nid, event_type: &str) -> Result<Option<Tid>, H::Error> {
688    if tree.kind(node) == Kind::Final {
689        return Ok(None);
690    }
691    let candidates = if h.first_candidates(node, event_type) {
692        let mut warnings = Vec::new();
693        let candidates = tree.candidates_with_warnings(node, event_type, &mut |w| warnings.push(w));
694        for w in &warnings {
695            h.warn(w);
696        }
697        candidates
698    } else {
699        tree.candidates(node, event_type)
700    };
701    for &t in &candidates {
702        if h.eval_candidate(t, node, false)? {
703            return Ok(Some(t));
704        }
705    }
706    Ok(None)
707}
708
709/// XState's `selectEventTransitions`, over the value structure of `all` (the
710/// configuration completed by [`all_state_nodes`]): a node's children in the
711/// value are its children in `all`. Each active leaf, in document order where
712/// a node has several active children, selects at the first node from it up
713/// to the root with an enabled candidate, as `always` does; once a node has
714/// several active children, a node a previous leaf already searched is not
715/// searched again (`checked`).
716struct EventSelection<'a> {
717    all: &'a [Nid],
718    event_type: &'a str,
719    checked: Option<Vec<bool>>,
720}
721
722impl EventSelection<'_> {
723    fn select_from_leaf<H: Host>(
724        &mut self,
725        tree: &Tree,
726        h: &mut H,
727        leaf: Nid,
728        out: &mut Vec<Tid>,
729    ) -> Result<(), H::Error> {
730        let mut m = Some(leaf);
731        while let Some(node) = m {
732            if let Some(checked) = &mut self.checked {
733                if checked[node as usize] {
734                    break;
735                }
736                checked[node as usize] = true;
737            }
738            if let Some(t) = node_next(tree, h, node, self.event_type)? {
739                out.push(t);
740                break;
741            }
742            m = tree.node(node).parent;
743        }
744        Ok(())
745    }
746
747    fn visit<H: Host>(&mut self, tree: &Tree, h: &mut H, node: Nid, out: &mut Vec<Tid>) -> Result<(), H::Error> {
748        let mut children: Buf<Nid> = self.all.iter().copied().filter(|&c| tree.node(c).parent == Some(node)).collect();
749        // A compound state whose active child is atomic has a string value.
750        if let Some(&child) =
751            children.first().filter(|&&c| tree.kind(node) == Kind::Compound && tree.kind(c).is_atomic())
752        {
753            return self.select_from_leaf(tree, h, child, out);
754        }
755        // An empty object value: a parallel region or a compound state
756        // without an active child.
757        if children.is_empty() {
758            return self.select_from_leaf(tree, h, node, out);
759        }
760        // Several entries: a parallel state's regions, or the several active
761        // children of an illegal configuration, in document order.
762        if children.len() > 1 {
763            self.checked.get_or_insert_with(|| vec![false; tree.nodes.len()]);
764            children.sort_unstable();
765        }
766        for &child in children.iter() {
767            self.visit(tree, h, child, out)?;
768        }
769        Ok(())
770    }
771}
772
773/// `machine.getTransitionData`: the transitions an event enables, without
774/// those that rejected it.
775pub fn select_transitions<H: Host>(tree: &Tree, h: &mut H, event_type: &str) -> Result<Buf<Tid>, H::Error> {
776    let mut selected = select_event_transitions(tree, h, event_type)?;
777    selected.retain(|&t| !h.rejected(t));
778    Ok(selected)
779}
780
781/// `selectEventTransitions` (`getTransitionData` with `includeRejections`):
782/// the transitions an event selects, those that rejected it included.
783pub fn select_event_transitions<H: Host>(tree: &Tree, h: &mut H, event_type: &str) -> Result<Buf<Tid>, H::Error> {
784    h.begin_selection()?;
785    let config = config_of(h);
786    let all = all_state_nodes(tree, &config, |n| h.static_initial(n));
787    let mut out = Buf::new();
788    if !config.is_empty() {
789        EventSelection { all: all.as_slice(), event_type, checked: None }.visit(tree, h, 0, &mut out)?;
790    }
791    Ok(out)
792}
793
794/// `selectEventlessTransitions`.
795pub fn select_eventless<H: Host>(tree: &Tree, h: &mut H) -> Result<Buf<TRef>, H::Error> {
796    h.begin_selection()?;
797    let config = config_of(h);
798    let mut enabled: Buf<TRef> = Buf::new();
799    // Active leaves in document order, as XState sorts them by `order`.
800    let mut atomics: Buf<Nid> = config.iter().copied().filter(|&n| tree.kind(n).is_atomic()).collect();
801    atomics.sort_unstable();
802    for &atomic in atomics.iter() {
803        let mut m = Some(atomic);
804        'ancestors: while let Some(node) = m {
805            for &t in &tree.node(node).always {
806                if h.eval_candidate(t, node, true)? {
807                    if !h.rejected(t) && !enabled.contains(&TRef::T(t)) {
808                        enabled.push(TRef::T(t));
809                    }
810                    break 'ancestors;
811                }
812            }
813            m = tree.node(node).parent;
814        }
815    }
816    let set = OrderedSet::from_slice(tree.nodes.len(), &config);
817    let mut ctx = Ctx { tree, h, resolver: Resolver::EventlessSelection, initial: None };
818    ctx.remove_conflicting(&enabled, &set)
819}
820
821// ---- domains and sets -------------------------------------------------------------
822
823/// The head and the rest of `[...effective, source]` (XState's
824/// `[...targetStates, transition.source]` in `getTransitionDomain`).
825fn split_with_source(effective: &[Nid], source: Nid) -> (Nid, TailWithSource<'_>) {
826    match effective.split_first() {
827        Some((&head, rest)) => (head, TailWithSource { rest, source: Some(source) }),
828        None => (source, TailWithSource { rest: &[], source: None }),
829    }
830}
831
832struct TailWithSource<'a> {
833    rest: &'a [Nid],
834    source: Option<Nid>,
835}
836
837impl TailWithSource<'_> {
838    fn all(&self, f: impl Fn(Nid) -> bool) -> bool {
839        self.rest.iter().all(|&x| f(x)) && self.source.is_none_or(&f)
840    }
841}
842
843struct Ctx<'a, H> {
844    tree: &'a Tree,
845    h: &'a mut H,
846    resolver: Resolver,
847    initial: Option<&'a InitialPlan>,
848}
849
850impl<H: Host> Ctx<'_, H> {
851    fn source(&self, t: TRef) -> Nid {
852        match t {
853            TRef::T(t) => self.tree.transitions[t as usize].source,
854            TRef::Initial(n) | TRef::HistoryDefault(n) => n,
855            TRef::InitialMicrostep => 0,
856        }
857    }
858
859    fn domain_hint(&self, t: TRef) -> DomainHint {
860        match t {
861            TRef::T(t) => self.tree.transitions[t as usize].domain,
862            _ => DomainHint::None,
863        }
864    }
865
866    fn resolve_with(&mut self, resolver: Resolver, t: TRef) -> Result<Resolved, H::Error> {
867        if let (TRef::InitialMicrostep, Some(plan)) = (t, self.initial) {
868            return Ok(Resolved { targets: Some(plan.targets.clone()), reenter: true });
869        }
870        self.h.resolve(resolver, t)
871    }
872
873    fn resolve(&mut self, t: TRef) -> Result<Resolved, H::Error> {
874        self.resolve_with(self.resolver, t)
875    }
876
877    /// `getEffectiveTargetStates`, against the snapshot's (old) history.
878    fn effective_targets(&mut self, t: TRef) -> Result<Buf<Nid>, H::Error> {
879        self.effective_targets_in(t, None)
880    }
881
882    /// `getEffectiveTargetStates`, against the snapshot's history with the
883    /// microstep's recorded `history` over it, when given.
884    fn effective_targets_in(&mut self, t: TRef, history: Option<&HistoryView>) -> Result<Buf<Nid>, H::Error> {
885        let mut set: Buf<Nid> = Buf::new();
886        let Some(targets) = self.resolve(t)?.targets else { return Ok(set) };
887        let add = |set: &mut Buf<Nid>, n: Nid| {
888            if !set.contains(&n) {
889                set.push(n);
890            }
891        };
892        for &target in targets.iter() {
893            if self.tree.is_history(target) {
894                let recorded = match history {
895                    Some(view) => view.get(&*self.h, target),
896                    None => self.h.history(target),
897                };
898                match recorded {
899                    Some(recorded) => recorded.into_iter().for_each(|n| add(&mut set, n)),
900                    None => {
901                        for &n in self.effective_targets_in(TRef::HistoryDefault(target), history)?.iter() {
902                            add(&mut set, n);
903                        }
904                    }
905                }
906            } else {
907                add(&mut set, target);
908            }
909        }
910        Ok(set)
911    }
912
913    fn narrow_parallel(&self, mut domain: Nid, targets: &[Nid]) -> Nid {
914        let tree = self.tree;
915        while tree.kind(domain) == Kind::Parallel {
916            let region = tree
917                .node(domain)
918                .children
919                .iter()
920                .copied()
921                .find(|&child| targets.iter().all(|&t| t == child || tree.is_descendant(t, Some(child))));
922            match region {
923                Some(r) => domain = r,
924                None => break,
925            }
926        }
927        domain
928    }
929
930    /// [`Ctx::narrow_parallel`] over `[...effective, source]`.
931    fn narrow_parallel_with_source(&self, mut domain: Nid, effective: &[Nid], source: Nid) -> Nid {
932        let tree = self.tree;
933        let within = |t: Nid, child: Nid| t == child || tree.is_descendant(t, Some(child));
934        while tree.kind(domain) == Kind::Parallel {
935            let region = tree
936                .node(domain)
937                .children
938                .iter()
939                .copied()
940                .find(|&child| within(source, child) && effective.iter().all(|&t| within(t, child)));
941            match region {
942                Some(r) => domain = r,
943                None => break,
944            }
945        }
946        domain
947    }
948
949    /// `getTransitionDomain`. `None` is "no domain": the whole machine.
950    fn domain(&mut self, t: TRef) -> Result<Option<Nid>, H::Error> {
951        let effective = self.effective_targets(t)?;
952        self.domain_with(t, &effective)
953    }
954
955    /// [`Ctx::domain`] with the transition's effective target states known.
956    fn domain_with(&mut self, t: TRef, effective: &[Nid]) -> Result<Option<Nid>, H::Error> {
957        let tree = self.tree;
958        let Resolved { targets, reenter } = self.resolve(t)?;
959        let source = self.source(t);
960
961        let hint = self.domain_hint(t);
962        if hint != DomainHint::None {
963            if hint == DomainHint::Internal
964                && tree.kind(source) == Kind::Compound
965                && effective.iter().all(|&x| tree.is_descendant(x, Some(source)))
966            {
967                return Ok(Some(source));
968            }
969            let (head, tail) = split_with_source(effective, source);
970            for ancestor in tree.ancestors(head, None) {
971                if tree.kind(ancestor) == Kind::Compound && tail.all(|x| tree.is_descendant(x, Some(ancestor))) {
972                    return Ok(Some(ancestor));
973                }
974            }
975            return Ok(None);
976        }
977
978        let restores_source_via_history =
979            targets.as_ref().is_some_and(|ts| ts.iter().any(|&x| tree.is_history(x))) && effective.contains(&source);
980        if !restores_source_via_history && effective.iter().all(|&x| x == source || tree.is_descendant(x, Some(source)))
981        {
982            return Ok(Some(if reenter { source } else { self.narrow_parallel(source, effective) }));
983        }
984        let (head, tail) = split_with_source(effective, source);
985        for ancestor in tree.ancestors(head, None) {
986            if tail.all(|x| tree.is_descendant(x, Some(ancestor))) {
987                // A transition across the regions of a parallel state exits
988                // the parallel state too, as in SCXML: the domain is its
989                // nearest compound ancestor (none: the whole machine).
990                if tree.kind(ancestor) == Kind::Parallel
991                    && self.narrow_parallel_with_source(ancestor, effective, source) == ancestor
992                {
993                    return Ok(tree.ancestors(ancestor, None).find(|&a| tree.kind(a) == Kind::Compound));
994                }
995                return Ok(Some(if reenter { ancestor } else { self.narrow_parallel(ancestor, effective) }));
996            }
997        }
998        if reenter {
999            return Ok(None);
1000        }
1001        Ok(Some(self.narrow_parallel(0, effective)))
1002    }
1003
1004    /// `computeExitSet`.
1005    fn exit_set(&mut self, transitions: &[TRef], config: &OrderedSet) -> Result<OrderedSet, H::Error> {
1006        let mut out = OrderedSet::new(self.tree.nodes.len());
1007        for &t in transitions {
1008            let Resolved { targets, reenter } = self.resolve(t)?;
1009            if targets.is_some_and(|ts| !ts.is_empty()) {
1010                let domain = self.domain(t)?;
1011                self.add_exits(&mut out, t, reenter, domain, config);
1012            }
1013        }
1014        Ok(out)
1015    }
1016
1017    /// [`Ctx::exit_set`] with the transitions' domains known.
1018    fn exit_set_with(
1019        &mut self,
1020        transitions: &[TRef],
1021        domain_of: impl Fn(usize) -> Option<Nid>,
1022        config: &OrderedSet,
1023    ) -> Result<OrderedSet, H::Error> {
1024        let mut out = OrderedSet::new(self.tree.nodes.len());
1025        for (i, &t) in transitions.iter().enumerate() {
1026            let Resolved { targets, reenter } = self.resolve(t)?;
1027            if targets.is_some_and(|ts| !ts.is_empty()) {
1028                self.add_exits(&mut out, t, reenter, domain_of(i), config);
1029            }
1030        }
1031        Ok(out)
1032    }
1033
1034    fn add_exits(&self, out: &mut OrderedSet, t: TRef, reenter: bool, domain: Option<Nid>, config: &OrderedSet) {
1035        let source = self.source(t);
1036        if reenter && Some(source) == domain {
1037            out.insert(source);
1038        }
1039        for &s in config.as_slice() {
1040            if self.tree.is_descendant(s, domain) {
1041                out.insert(s);
1042            }
1043        }
1044    }
1045
1046    /// `removeConflictingTransitions`.
1047    fn remove_conflicting(&mut self, enabled: &[TRef], config: &OrderedSet) -> Result<Buf<TRef>, H::Error> {
1048        let mut filtered: Buf<TRef> = Buf::new();
1049        let mut exit_sets: Vec<(TRef, OrderedSet)> = Vec::new();
1050        for &t1 in enabled {
1051            let mut preempted = false;
1052            let mut remove: Vec<TRef> = Vec::new();
1053            let e1 = self.cached_exit_set(&mut exit_sets, t1, config)?;
1054            for &t2 in &filtered {
1055                let e2 = self.cached_exit_set(&mut exit_sets, t2, config)?;
1056                if exit_sets[e1].1.intersects(&exit_sets[e2].1) {
1057                    if self.tree.is_descendant(self.source(t1), Some(self.source(t2))) {
1058                        remove.push(t2);
1059                    } else {
1060                        preempted = true;
1061                        break;
1062                    }
1063                }
1064            }
1065            if !preempted {
1066                filtered.retain(|t| !remove.contains(t));
1067                filtered.push(t1);
1068            }
1069        }
1070        Ok(filtered)
1071    }
1072
1073    fn cached_exit_set(
1074        &mut self,
1075        cache: &mut Vec<(TRef, OrderedSet)>,
1076        t: TRef,
1077        config: &OrderedSet,
1078    ) -> Result<usize, H::Error> {
1079        if let Some(i) = cache.iter().position(|(x, _)| *x == t) {
1080            return Ok(i);
1081        }
1082        let set = self.exit_set(&[t], config)?;
1083        cache.push((t, set));
1084        Ok(cache.len() - 1)
1085    }
1086}
1087
1088// ---- microstep ----------------------------------------------------------------------
1089
1090/// Entry-set state, as the closures in XState's `enterStates`.
1091struct Entry {
1092    to_enter: OrderedSet,
1093    default_entry: Buf<bool>,
1094    /// History states whose default transition a parent takes on entry.
1095    history_defaults: Vec<(Nid, Vec<Nid>)>,
1096}
1097
1098impl<H: Host> Ctx<'_, H> {
1099    fn has_descendant_state(&self, set: &OrderedSet, parent: Nid) -> bool {
1100        set.as_slice().iter().any(|&s| self.tree.is_descendant(s, Some(parent)))
1101    }
1102
1103    fn add_ancestors(
1104        &mut self,
1105        e: &mut Entry,
1106        history: &HistoryView,
1107        ancestors: &[Nid],
1108        reentrancy_domain: Option<Nid>,
1109    ) -> Result<(), H::Error> {
1110        for &anc in ancestors {
1111            if reentrancy_domain.is_none() || self.tree.is_descendant(anc, reentrancy_domain) {
1112                e.to_enter.insert(anc);
1113            }
1114            if self.tree.kind(anc) == Kind::Parallel {
1115                let tree = self.tree;
1116                for &child in &tree.node(anc).children {
1117                    if !self.has_descendant_state(&e.to_enter, child) {
1118                        e.to_enter.insert(child);
1119                        self.add_descendants(e, history, child)?;
1120                    }
1121                }
1122            }
1123        }
1124        Ok(())
1125    }
1126
1127    fn add_descendants(&mut self, e: &mut Entry, history: &HistoryView, node: Nid) -> Result<(), H::Error> {
1128        let tree = self.tree;
1129        match tree.kind(node) {
1130            Kind::History { .. } => {
1131                let parent = tree.node(node).parent.expect("history states have a parent");
1132                if let Some(recorded) = history.get(self.h, node) {
1133                    for &s in &recorded {
1134                        e.to_enter.insert(s);
1135                        self.add_descendants(e, history, s)?;
1136                    }
1137                    for &s in &recorded {
1138                        let ancestors: Buf<Nid> = tree.ancestors(s, Some(parent)).collect();
1139                        self.add_ancestors(e, history, &ancestors, None)?;
1140                    }
1141                } else {
1142                    e.default_entry[parent as usize] = true;
1143                    match e.history_defaults.iter_mut().find(|(p, _)| *p == parent) {
1144                        Some((_, list)) => list.push(node),
1145                        None => e.history_defaults.push((parent, vec![node])),
1146                    }
1147                    let targets = self.resolve(TRef::HistoryDefault(node))?.targets.unwrap_or_else(|| Arc::from([]));
1148                    for &s in targets.iter() {
1149                        e.to_enter.insert(s);
1150                        // `historyDefaultTransition === stateNode.parent.initial`
1151                        // only adds `parent` again, which is already marked.
1152                        self.add_descendants(e, history, s)?;
1153                    }
1154                    for &s in targets.iter() {
1155                        let ancestors: Buf<Nid> = tree.ancestors(s, Some(parent)).collect();
1156                        self.add_ancestors(e, history, &ancestors, None)?;
1157                    }
1158                }
1159            }
1160            Kind::Compound => {
1161                let initial = self.resolve(TRef::Initial(node))?.targets.unwrap_or_else(|| Arc::from([]));
1162                for &s in initial.iter() {
1163                    if !tree.is_history(s) {
1164                        e.to_enter.insert(s);
1165                    }
1166                }
1167                e.default_entry[node as usize] = true;
1168                for &s in initial.iter() {
1169                    self.add_descendants(e, history, s)?;
1170                }
1171                for &s in initial.iter() {
1172                    let ancestors: Buf<Nid> = tree.ancestors(s, Some(node)).collect();
1173                    self.add_ancestors(e, history, &ancestors, None)?;
1174                }
1175            }
1176            Kind::Parallel => {
1177                for &child in &tree.node(node).children {
1178                    if !self.has_descendant_state(&e.to_enter, child) {
1179                        e.to_enter.insert(child);
1180                        e.default_entry[child as usize] = true;
1181                        self.add_descendants(e, history, child)?;
1182                    }
1183                }
1184            }
1185            Kind::Atomic | Kind::Final | Kind::Choice => {}
1186        }
1187        Ok(())
1188    }
1189}
1190
1191/// The history visible to entry: the snapshot's, overlaid with what this
1192/// microstep recorded.
1193struct HistoryView {
1194    updates: Option<Vec<(Nid, Vec<Nid>)>>,
1195}
1196
1197impl HistoryView {
1198    fn get<H: Host>(&self, h: &H, node: Nid) -> Option<Vec<Nid>> {
1199        if let Some(updates) = &self.updates {
1200            if let Some((_, v)) = updates.iter().find(|(n, _)| *n == node) {
1201                return Some(v.clone());
1202            }
1203        }
1204        h.history(node)
1205    }
1206}
1207
1208/// XState's `getInitialStateNodes(root)` and `collectDefaultEntryStates`,
1209/// from the static `initial.target` of each compound state.
1210pub fn initial_plan<H: Host>(tree: &Tree, h: &H) -> InitialPlan {
1211    let size = tree.nodes.len();
1212    let mut set = OrderedSet::new(size);
1213    fn iter<H: Host>(tree: &Tree, h: &H, set: &mut OrderedSet, n: Nid) {
1214        if !set.insert(n) {
1215            return;
1216        }
1217        match tree.kind(n) {
1218            Kind::Compound => {
1219                for &t in h.static_initial(n).iter() {
1220                    iter(tree, h, set, t);
1221                }
1222            }
1223            Kind::Parallel => {
1224                for &c in &tree.node(n).children {
1225                    iter(tree, h, set, c);
1226                }
1227            }
1228            _ => {}
1229        }
1230    }
1231    iter(tree, h, &mut set, 0);
1232    for s in set.as_slice().to_vec() {
1233        for a in tree.proper_ancestors(s, Some(0)) {
1234            set.insert(a);
1235        }
1236    }
1237    let nodes = set.as_slice();
1238    let targets: Vec<Nid> =
1239        nodes.iter().copied().filter(|&s| !nodes.iter().any(|&o| o != s && tree.is_descendant(o, Some(s)))).collect();
1240
1241    let mut default_entry = Vec::new();
1242    fn collect<H: Host>(tree: &Tree, h: &H, out: &mut Vec<Nid>, n: Nid) {
1243        match tree.kind(n) {
1244            Kind::Compound => {
1245                if !out.contains(&n) {
1246                    out.push(n);
1247                }
1248                for &t in h.static_initial(n).iter() {
1249                    collect(tree, h, out, t);
1250                }
1251            }
1252            Kind::Parallel => {
1253                for &c in &tree.node(n).children {
1254                    collect(tree, h, out, c);
1255                }
1256            }
1257            _ => {}
1258        }
1259    }
1260    collect(tree, h, &mut default_entry, 0);
1261    InitialPlan { targets: targets.into(), default_entry }
1262}
1263
1264/// XState's `microstep`. `initial` is set for the initial microstep, whose
1265/// only transition is [`TRef::InitialMicrostep`].
1266pub fn microstep<H: Host>(
1267    tree: &Tree,
1268    h: &mut H,
1269    transitions: &[TRef],
1270    initial: Option<&InitialPlan>,
1271) -> Result<(), H::Error> {
1272    h.begin_microstep()?;
1273    if transitions.is_empty() {
1274        return h.apply_microstep(None, transitions);
1275    }
1276    let is_initial = initial.is_some();
1277    let size = tree.nodes.len();
1278    let original = config_of(h);
1279    let mut set = OrderedSet::from_slice(size, &original);
1280
1281    let filtered = if transitions.len() == 1 {
1282        Buf::from_slice(transitions)
1283    } else {
1284        let mut ctx = Ctx { tree, h: &mut *h, resolver: Resolver::Conflicts, initial };
1285        ctx.remove_conflicting(transitions, &set)?
1286    };
1287
1288    let mut ctx = Ctx { tree, h: &mut *h, resolver: Resolver::Current, initial };
1289    let mut changes_state = false;
1290    for &t in &filtered {
1291        let r = ctx.resolve(t)?;
1292        if r.targets.is_some_and(|ts| !ts.is_empty()) || r.reenter {
1293            changes_state = true;
1294        }
1295    }
1296
1297    // Each transition's domain and effective target states. XState computes
1298    // them for the exit set and again for the entry set, from inputs fixed
1299    // for the whole microstep (the current resolver's result, which it
1300    // caches, and the snapshot's history, which changes only when the
1301    // microstep is applied), so computing them once here is the same; only
1302    // the entry set's ancestors take the effective targets against the
1303    // history the exits recorded (since beta.4).
1304    // `plan` holds (domain or NO_DOMAIN, end of its targets in `effective`)
1305    // per transition.
1306    let mut plan: Buf<Nid> = Buf::new();
1307    let mut effective: Option<Buf<Nid>> = None;
1308    if is_initial || changes_state {
1309        for &t in &filtered {
1310            let targets = ctx.effective_targets(t)?;
1311            let domain = ctx.domain_with(t, &targets)?;
1312            let end = match &mut effective {
1313                Some(all) => {
1314                    all.extend_from_slice(&targets);
1315                    all.len()
1316                }
1317                None => {
1318                    let end = targets.len();
1319                    effective = Some(targets);
1320                    end
1321                }
1322            };
1323            plan.push(domain.unwrap_or(NO_DOMAIN));
1324            plan.push(end as Nid);
1325        }
1326    }
1327    let domain_of = |i: usize| Some(plan[2 * i]).filter(|&d| d != NO_DOMAIN);
1328    let targets_of = |i: usize| {
1329        let start = if i == 0 { 0 } else { plan[2 * i - 1] as usize };
1330        &effective.as_deref().expect("planned")[start..plan[2 * i + 1] as usize]
1331    };
1332
1333    // Exit states.
1334    let mut history_updates: Option<Vec<(Nid, Vec<Nid>)>> = None;
1335    if !is_initial && changes_state {
1336        let exit = ctx.exit_set_with(&filtered, domain_of, &set)?;
1337        let mut to_exit = Buf::from_slice(exit.as_slice());
1338        to_exit.sort_by(|a, b| b.cmp(a));
1339        let current = Buf::from_slice(set.as_slice());
1340        for &s in &to_exit {
1341            for &hn in &tree.node(s).history_children {
1342                let deep = matches!(tree.kind(hn), Kind::History { deep: true });
1343                let recorded: Vec<Nid> = current
1344                    .iter()
1345                    .copied()
1346                    .filter(|&n| {
1347                        if deep {
1348                            tree.kind(n).is_atomic() && tree.is_descendant(n, Some(s))
1349                        } else {
1350                            tree.node(n).parent == Some(s)
1351                        }
1352                    })
1353                    .collect();
1354                let updates = history_updates.get_or_insert_with(Vec::new);
1355                match updates.iter_mut().find(|(n, _)| *n == hn) {
1356                    Some(entry) => entry.1 = recorded,
1357                    None => updates.push((hn, recorded)),
1358                }
1359            }
1360        }
1361        for &s in &to_exit {
1362            ctx.h.exit_state(s)?;
1363            set.remove(s);
1364        }
1365    }
1366
1367    // Transition content.
1368    ctx.h.transition_content(&filtered, set.as_slice())?;
1369
1370    // Enter states.
1371    if is_initial || changes_state {
1372        let history = HistoryView { updates: history_updates.clone() };
1373        let mut e = Entry {
1374            to_enter: OrderedSet::new(size),
1375            default_entry: Buf::filled(false, size),
1376            history_defaults: Vec::new(),
1377        };
1378        let mut entered: Vec<(TRef, Buf<Nid>)> = Vec::with_capacity(filtered.len());
1379        for (i, &t) in filtered.iter().enumerate() {
1380            let domain = domain_of(i);
1381            let Resolved { targets, reenter } = ctx.resolve(t)?;
1382            let source = ctx.source(t);
1383            let mut entered_targets = Buf::new();
1384            for &target in targets.as_deref().unwrap_or(&[]) {
1385                if !tree.is_history(target) && (source != target || Some(source) != domain || reenter) {
1386                    if !entered_targets.contains(&target) {
1387                        entered_targets.push(target);
1388                    }
1389                    e.to_enter.insert(target);
1390                    e.default_entry[target as usize] = true;
1391                }
1392                ctx.add_descendants(&mut e, &history, target)?;
1393            }
1394            entered.push((t, entered_targets));
1395            let recorded;
1396            let effective_now = match &history.updates {
1397                Some(_) => {
1398                    recorded = ctx.effective_targets_in(t, Some(&history))?;
1399                    &recorded[..]
1400                }
1401                None => targets_of(i),
1402            };
1403            for &s in effective_now {
1404                let mut ancestors: Buf<Nid> = tree.ancestors(s, domain).collect();
1405                if let Some(d) = domain {
1406                    if tree.kind(d) == Kind::Parallel {
1407                        ancestors.push(d);
1408                    }
1409                }
1410                let reentrancy = if tree.node(source).parent.is_none() && reenter { None } else { domain };
1411                ctx.add_ancestors(&mut e, &history, &ancestors, reentrancy)?;
1412            }
1413            // A targetless transition keeps the active states, `reenter`
1414            // or not: only a reentering transition with targets reenters
1415            // its source.
1416            if reenter && domain == Some(source) && targets.as_deref().is_some_and(|ts| !ts.is_empty()) {
1417                e.to_enter.insert(source);
1418            }
1419        }
1420        if let Some(plan) = initial {
1421            for &n in &plan.default_entry {
1422                e.default_entry[n as usize] = true;
1423            }
1424        }
1425
1426        ctx.h.begin_entry(set.as_slice(), &entered)?;
1427        let mut order = Buf::from_slice(e.to_enter.as_slice());
1428        order.sort_unstable();
1429        let mut completed: Buf<bool> = Buf::filled(false, size);
1430        for &s in &order {
1431            set.insert(s);
1432            let defaults = match e.history_defaults.iter().position(|(p, _)| *p == s) {
1433                Some(i) => e.history_defaults.swap_remove(i).1,
1434                None => Vec::new(),
1435            };
1436            ctx.h.enter_state(s, e.default_entry[s as usize], &defaults)?;
1437            if tree.kind(s) != Kind::Final {
1438                continue;
1439            }
1440            let parent = tree.node(s).parent;
1441            let mut marker = match parent {
1442                Some(p) if tree.kind(p) == Kind::Parallel => Some(p),
1443                Some(p) => tree.node(p).parent,
1444                None => None,
1445            };
1446            let mut completion = marker.unwrap_or(s);
1447            if let Some(p) = parent {
1448                if tree.kind(p) == Kind::Compound {
1449                    ctx.h.done_compound(p, s)?;
1450                }
1451            }
1452            while let Some(m) = marker {
1453                if tree.kind(m) != Kind::Parallel || completed[m as usize] || !tree.is_in_final_state(&set, m) {
1454                    break;
1455                }
1456                completed[m as usize] = true;
1457                let regions: Vec<RegionOutput> = tree
1458                    .node(m)
1459                    .children
1460                    .iter()
1461                    .map(|&r| match tree.kind(r) {
1462                        Kind::Final => RegionOutput::Final(r),
1463                        Kind::Parallel => RegionOutput::Parallel(r),
1464                        _ => RegionOutput::Compound(
1465                            r,
1466                            tree.node(r)
1467                                .children
1468                                .iter()
1469                                .copied()
1470                                .find(|&c| tree.kind(c) == Kind::Final && set.contains(c)),
1471                        ),
1472                    })
1473                    .collect();
1474                ctx.h.done_parallel(m, &regions)?;
1475                completion = m;
1476                marker = tree.node(m).parent;
1477            }
1478            if marker.is_some() {
1479                continue;
1480            }
1481            ctx.h.machine_done(completion)?;
1482        }
1483        ctx.h.end_entry()?;
1484    }
1485
1486    let mut nodes = Buf::from_slice(set.as_slice());
1487    if ctx.h.is_done() {
1488        // XState sorts its node list in place here, so a completed machine's
1489        // configuration is in descending document order.
1490        nodes.sort_by(|a, b| b.cmp(a));
1491        ctx.h.exit_on_done(&nodes)?;
1492    }
1493
1494    let same_membership = original.len() == set.len() && original.iter().all(|&n| set.contains(n));
1495    let structure_changed = history_updates.is_some() || !same_membership;
1496    let result = MicrostepResult {
1497        filtered,
1498        nodes: if structure_changed { nodes } else { original },
1499        structure_changed,
1500        history_updates: history_updates.unwrap_or_default(),
1501    };
1502    h.apply_microstep(Some(result), transitions)
1503}
1504
1505/// XState's `initialMicrostep`.
1506pub fn initial_microstep<H: Host>(tree: &Tree, h: &mut H) -> Result<(), H::Error> {
1507    let plan = initial_plan(tree, h);
1508    microstep(tree, h, &[TRef::InitialMicrostep], Some(&plan))
1509}
1510
1511/// The loop at the end of XState's `macrostep`: eventless transitions and
1512/// internal events until the machine is stable.
1513pub fn run_to_completion<H: Host>(tree: &Tree, h: &mut H) -> Result<(), H::Error> {
1514    run_loop(tree, h, true)
1515}
1516
1517/// The loop at the end of XState's `macrostep` for a timer notification
1518/// (`xstate.timer`): the fired timer's event, queued as internal, is handled
1519/// before eventless transitions are selected, and a timer that relays its
1520/// event to another actor selects none.
1521pub fn run_after_timer<H: Host>(tree: &Tree, h: &mut H) -> Result<(), H::Error> {
1522    run_loop(tree, h, false)
1523}
1524
1525fn run_loop<H: Host>(tree: &Tree, h: &mut H, select_eventless_first: bool) -> Result<(), H::Error> {
1526    if h.queue_is_empty() && !tree.has_eventless {
1527        return Ok(());
1528    }
1529    let mut should_select_eventless = select_eventless_first;
1530    let mut iteration = 0;
1531    while h.is_active() {
1532        iteration += 1;
1533        h.check_iteration(iteration)?;
1534        let mut enabled = if should_select_eventless { select_eventless(tree, h)? } else { Buf::new() };
1535        let previous = if enabled.is_empty() { None } else { Some(h.snapshot_token()) };
1536        h.drain_raised()?;
1537        if enabled.is_empty() {
1538            let Some(event_type) = h.dequeue()? else { break };
1539            enabled = select_transitions(tree, h, &event_type)?.iter().map(|&t| TRef::T(t)).collect();
1540        }
1541        microstep(tree, h, &enabled, None)?;
1542        should_select_eventless = Some(h.microstep_token()) != previous;
1543    }
1544    Ok(())
1545}
1546
1547#[cfg(test)]
1548mod tests {
1549    use super::*;
1550
1551    #[test]
1552    fn descriptors() {
1553        assert!(matches_event_descriptor("a.b", "a.*"));
1554        assert!(matches_event_descriptor("a", "a.*"));
1555        assert!(!matches_event_descriptor("ab", "a.*"));
1556        assert!(!matches_event_descriptor("a.b.c", "a.*.c"));
1557        assert!(matches_event_descriptor("x", "*"));
1558    }
1559
1560    #[test]
1561    fn ordered_set() {
1562        let mut s = OrderedSet::from_slice(5, &[0, 1, 2]);
1563        s.remove(1);
1564        s.insert(1);
1565        assert_eq!(s.as_slice(), &[0, 2, 1]);
1566        assert!(!s.insert(2));
1567    }
1568}