Skip to main content

xmachines_runtime/
interp.rs

1//! The native host: JSON machines as pure actor logic on the shared
2//! [`crate::core`] algorithm, with XState's value semantics for
3//! `machineFromJSON` machines.
4//!
5//! - Transition results (`context`, `actions`) are computed against the
6//!   snapshot at the start of the microstep and merged after exits, as
7//!   XState's transition functions are.
8//! - Actions produce effects in XState's vocabulary. `@xstate.raise`
9//!   without a delay goes to the internal queue; delayed raises and cancels
10//!   update the snapshot's logical timers and return timer effects; emits,
11//!   logs and custom actions become external effects.
12//! - Invoked children are allocated through the system while the state is
13//!   entered and started after the macrostep, as in XState.
14//! - Eventless transitions are re-selected only after a microstep that
15//!   produced a new snapshot, mirroring XState's snapshot-identity check.
16
17use std::any::Any;
18use std::borrow::Cow;
19use std::cell::{Cell, RefCell};
20use std::collections::VecDeque;
21use std::sync::Arc;
22
23use indexmap::IndexMap;
24use serde::de::DeserializeOwned;
25use serde::Serialize;
26use serde_json::{json, Map, Value};
27
28use crate::core::{self, Host, MicrostepResult, Nid, RegionOutput, Resolved, Resolver, TRef, Tid};
29use crate::error::{xstate_error, CodeValue::Raw, CodeValue::Str};
30use crate::event::{Ev, EventType, AFTER, DONE_STATE};
31use crate::machine::*;
32use crate::registry::{
33    ActionFn, ChildIds, ContextArgs, Enq, EnqOp, ExprArgs, GuardArgs, SendTarget, Spawn, SpawnOptions,
34};
35use crate::system::{
36    has_builtin_timer_identity, ActorRef, AfterDelay, AllocateOptions, AnySnapshot, Context, Effect, EffectKind,
37    EffectType, ExternalSpec, FailedStart, FixedState, Logic, Status, SystemError, TimerKey, Transition,
38    TransitionCheck, TransitionRejection,
39};
40
41/// A logical timer in a machine snapshot (XState's `snapshot.timers` entry).
42#[derive(Clone)]
43pub(crate) struct LogicalTimer<E> {
44    /// XState's `occurrence`: the scheduling that set the timer (from the
45    /// snapshot's `nextTimerOccurrence`), so a notification of a replaced
46    /// scheduling matches no timer. Restored timers may have none.
47    pub occurrence: Option<u64>,
48    pub id: Option<String>,
49    pub seq: Option<u64>,
50    pub delay: u64,
51    pub event: TimerEv<E>,
52    pub target: TimerTarget,
53}
54
55/// Where a logical timer delivers its event: XState's timer `type` and
56/// `target`, the actor itself being `"self"`.
57#[derive(Clone, PartialEq)]
58pub(crate) enum TimerTarget {
59    /// A delayed raise (`@xstate.raise`): an internal event of the actor.
60    Raise,
61    /// A delayed `sendTo` the actor itself: a message to it, as XState sends
62    /// it (`@xstate.sendTo`, `target: "self"`).
63    SendToSelf,
64    /// A delayed `sendTo` another actor, by reference.
65    SendTo(Box<ActorRef>),
66}
67
68impl TimerTarget {
69    fn timer_type(&self) -> &'static str {
70        match self {
71            TimerTarget::Raise => "@xstate.raise",
72            TimerTarget::SendToSelf | TimerTarget::SendTo(_) => "@xstate.sendTo",
73        }
74    }
75
76    fn to_json(&self) -> Value {
77        match self {
78            TimerTarget::Raise | TimerTarget::SendToSelf => json!("self"),
79            TimerTarget::SendTo(target) => target.to_json(),
80        }
81    }
82
83    /// Reads a persisted timer's `type` and `target`, as XState's restore
84    /// validates them.
85    fn from_json(timer_type: Option<&Value>, target: Option<&Value>) -> Option<Self> {
86        match (timer_type?.as_str()?, target?) {
87            ("@xstate.raise", Value::String(s)) if s == "self" => Some(TimerTarget::Raise),
88            ("@xstate.sendTo", Value::String(s)) if s == "self" => Some(TimerTarget::SendToSelf),
89            ("@xstate.sendTo", target @ Value::Object(_)) => {
90                ActorRef::from_json(target).map(|r| TimerTarget::SendTo(Box::new(r)))
91            }
92            _ => None,
93        }
94    }
95}
96
97/// A logical timer's event. `after` events (most timers) are kept without
98/// their JSON object, which costs several allocations per pending timer.
99#[derive(Clone)]
100pub(crate) enum TimerEv<E> {
101    /// `{ type: "xstate.after", delay, stateId }`.
102    After { delay: AfterDelay, state_id: String },
103    /// Boxed: delayed raises are rarer than `after` timers, and an event is
104    /// large inline.
105    Ev(Box<Ev<E>>),
106}
107
108impl<E: EventType> TimerEv<E> {
109    fn new(event: Ev<E>) -> Self {
110        let after = |data: &Map<String, Value>| {
111            data.len() == 2
112                && data.keys().zip(["delay", "stateId"]).all(|(k, n)| k == n)
113                && data["stateId"].is_string()
114                && matches!(data["delay"], Value::Number(_) | Value::String(_))
115        };
116        let delay = |v: Option<Value>| v.and_then(AfterDelay::from_value).expect("checked");
117        match event {
118            Ev::Internal { event_type, mut data } if event_type == AFTER && after(&data) => {
119                let Some(Value::String(state_id)) = data.swap_remove("stateId") else { unreachable!() };
120                TimerEv::After { delay: delay(data.swap_remove("delay")), state_id }
121            }
122            // A restored untyped event.
123            Ev::User(e) if e.event_type() == AFTER => match e.to_json() {
124                Value::Object(mut data) if data.keys().next().map(String::as_str) == Some("type") => {
125                    data.shift_remove("type");
126                    if after(&data) {
127                        let Some(Value::String(state_id)) = data.swap_remove("stateId") else { unreachable!() };
128                        TimerEv::After { delay: delay(data.swap_remove("delay")), state_id }
129                    } else {
130                        TimerEv::Ev(Box::new(Ev::User(e)))
131                    }
132                }
133                _ => TimerEv::Ev(Box::new(Ev::User(e))),
134            },
135            other => TimerEv::Ev(Box::new(other)),
136        }
137    }
138
139    fn event_type(&self) -> &str {
140        match self {
141            TimerEv::After { .. } => AFTER,
142            TimerEv::Ev(e) => e.event_type(),
143        }
144    }
145
146    fn field(&self, key: &str) -> Option<Value> {
147        match (self, key) {
148            (TimerEv::After { delay, .. }, "delay") => Some(delay.to_value()),
149            (TimerEv::After { state_id, .. }, "stateId") => Some(Value::String(state_id.clone())),
150            (TimerEv::After { .. }, _) => None,
151            (TimerEv::Ev(e), _) => e.field(key),
152        }
153    }
154
155    fn to_json(&self) -> Value {
156        match self {
157            TimerEv::After { delay, state_id } => json!({ "type": AFTER, "delay": delay, "stateId": state_id }),
158            TimerEv::Ev(e) => e.to_json(),
159        }
160    }
161
162    fn into_ev(self) -> Ev<E> {
163        match self {
164            TimerEv::After { delay, state_id } => {
165                let mut data = Map::with_capacity(2);
166                data.insert("delay".into(), delay.to_value());
167                data.insert("stateId".into(), Value::String(state_id));
168                Ev::Internal { event_type: Cow::Borrowed(AFTER), data }
169            }
170            TimerEv::Ev(e) => *e,
171        }
172    }
173}
174
175impl<E: EventType> LogicalTimer<E> {
176    /// XState's `getTimerKey`.
177    fn key(&self) -> TimerKey {
178        if let Some(id) = &self.id {
179            return TimerKey::Id(id.clone());
180        }
181        if let Some(seq) = self.seq {
182            return TimerKey::Seq(seq);
183        }
184        let e = match &self.event {
185            TimerEv::After { delay, state_id } => {
186                return TimerKey::After { delay: delay.clone(), state_id: state_id.clone() }
187            }
188            TimerEv::Ev(e) => e,
189        };
190        let ty = e.event_type();
191        let fields: &[&str] = match ty {
192            "xstate.after" => &["delay", "stateId"],
193            "xstate.timeout.state" => &["stateId"],
194            "xstate.timeout.actor" => &["actorId"],
195            _ => return TimerKey::Event(Box::new(e.to_json())),
196        };
197        // `builtinTimerIdentity`, from the fields it keeps.
198        let mut identity = Map::with_capacity(fields.len() + 1);
199        identity.insert("type".into(), Value::String(ty.to_owned()));
200        for f in fields {
201            if let Some(v) = e.field(f) {
202                identity.insert((*f).to_owned(), v);
203            }
204        }
205        TimerKey::of_timer_event(&json!({ "event": identity })).expect("an event key")
206    }
207
208    /// XState's `matchesTimerKey`.
209    fn matches(&self, key: &TimerKey) -> bool {
210        if let TimerKey::Id(id) = key {
211            return self.id.as_deref() == Some(id.as_str());
212        }
213        if self.id.is_some() {
214            return false;
215        }
216        if let TimerKey::Seq(seq) = key {
217            return self.seq == Some(*seq);
218        }
219        if self.seq.is_some() {
220            return false;
221        }
222        let field_is = |name: &str, v: &Value| self.event.field(name).as_ref() == Some(v);
223        let str_field_is = |name: &str, s: &str| self.event.field(name).as_ref().and_then(Value::as_str) == Some(s);
224        match key {
225            TimerKey::After { delay, state_id } => match &self.event {
226                TimerEv::After { delay: d, state_id: s } => d == delay && s == state_id,
227                TimerEv::Ev(e) => {
228                    e.event_type() == AFTER
229                        && e.field("delay").is_some_and(|v| delay.is(&v))
230                        && str_field_is("stateId", state_id)
231                }
232            },
233            TimerKey::StateTimeout { state_id } => {
234                self.event.event_type() == "xstate.timeout.state" && str_field_is("stateId", state_id)
235            }
236            TimerKey::Event(pattern) => pattern.as_object().is_some_and(|pattern| {
237                pattern.iter().all(|(k, v)| match k.as_str() {
238                    "type" => v.as_str() == Some(self.event.event_type()),
239                    _ => field_is(k, v),
240                })
241            }),
242            TimerKey::Id(_) | TimerKey::Seq(_) => unreachable!("handled above"),
243        }
244    }
245
246    fn to_data(&self) -> Value {
247        let mut m = Map::new();
248        if let Some(occurrence) = self.occurrence {
249            m.insert("occurrence".into(), json!(occurrence));
250        }
251        if let Some(id) = &self.id {
252            m.insert("id".into(), Value::String(id.clone()));
253        }
254        if let Some(seq) = self.seq {
255            m.insert("seq".into(), json!(seq));
256        }
257        m.insert("delay".into(), json!(self.delay));
258        m.insert("type".into(), json!(self.target.timer_type()));
259        m.insert("event".into(), self.event.to_json());
260        m.insert("target".into(), self.target.to_json());
261        Value::Object(m)
262    }
263}
264
265/// Recorded history: each history state and its recorded states.
266pub(crate) type HistoryValues = Vec<(Nid, Vec<Nid>)>;
267
268/// A machine actor's snapshot.
269pub(crate) struct State<C, E> {
270    /// The configuration, in XState's order.
271    pub nodes: Vec<Nid>,
272    pub context: C,
273    pub status: Status,
274    /// Boxed, like `error`: rarely set, and a `Value` is large inline.
275    pub output: Option<Box<Value>>,
276    pub error: Option<Box<Value>>,
277    /// `historyValue`, in key order. Copy-on-write (`Arc::make_mut`) like
278    /// `children` and `timers`, so a macrostep's rollback copy is cheap.
279    pub history: Arc<HistoryValues>,
280    /// `snapshot.children`, in order.
281    pub children: Arc<IndexMap<String, ActorRef, FixedState>>,
282    /// `snapshot.timers`, in order.
283    pub timers: Arc<Vec<LogicalTimer<E>>>,
284    pub next_timer_id: u64,
285    /// `nextTimerOccurrence`: the occurrence of the next timer scheduled.
286    pub next_timer_occurrence: u64,
287    /// `stateInputs`: the input of each active state that has one, in
288    /// order. Boxed: 8 bytes per actor instead of a `Vec`'s 24, and most
289    /// machines have none.
290    #[allow(clippy::box_collection)]
291    pub inputs: Option<Box<Vec<(Nid, Value)>>>,
292    /// `nextActorIds`: the next free index of each generated child id
293    /// prefix (`<src>:<n>`), so freed ids are never handed out again.
294    #[allow(clippy::box_collection)]
295    pub actor_ids: Option<Box<Vec<(String, u64)>>>,
296    /// For an untyped context: known to need no number normalization
297    /// (`js_numbers`), so merges need not check it again. Not persisted.
298    pub context_normalized: bool,
299}
300
301impl<C: Clone, E: Clone> Clone for State<C, E> {
302    fn clone(&self) -> Self {
303        Self {
304            nodes: self.nodes.clone(),
305            context: self.context.clone(),
306            status: self.status,
307            output: self.output.clone(),
308            error: self.error.clone(),
309            history: self.history.clone(),
310            children: self.children.clone(),
311            timers: self.timers.clone(),
312            next_timer_id: self.next_timer_id,
313            next_timer_occurrence: self.next_timer_occurrence,
314            inputs: self.inputs.clone(),
315            actor_ids: self.actor_ids.clone(),
316            context_normalized: self.context_normalized,
317        }
318    }
319}
320
321/// Shared empty `history`, `children` and `timers` (see [`Machine`]).
322pub(crate) struct EmptyParts<E> {
323    history: Arc<HistoryValues>,
324    children: Arc<IndexMap<String, ActorRef, FixedState>>,
325    timers: Arc<Vec<LogicalTimer<E>>>,
326}
327
328impl<E> Default for EmptyParts<E> {
329    fn default() -> Self {
330        Self { history: Arc::default(), children: Arc::default(), timers: Arc::default() }
331    }
332}
333
334impl<C, E> State<C, E> {
335    pub fn new(context: C, empty: &EmptyParts<E>) -> Self {
336        Self {
337            nodes: vec![ROOT],
338            context,
339            status: Status::Active,
340            output: None,
341            error: None,
342            history: empty.history.clone(),
343            children: empty.children.clone(),
344            timers: empty.timers.clone(),
345            next_timer_id: 0,
346            next_timer_occurrence: 0,
347            inputs: None,
348            actor_ids: None,
349            context_normalized: false,
350        }
351    }
352}
353
354impl<C, E> AnySnapshot for State<C, E>
355where
356    C: Clone + Send + 'static,
357    E: EventType + Send + Sync,
358{
359    fn status(&self) -> Status {
360        self.status
361    }
362
363    fn output(&self) -> Option<Value> {
364        self.output.as_deref().cloned()
365    }
366
367    fn error(&self) -> Option<Value> {
368        self.error.as_deref().cloned()
369    }
370
371    fn fail(&mut self, error: Value) {
372        self.status = Status::Error;
373        self.error = Some(Box::new(error));
374    }
375
376    fn timer_pending(&self, key: &TimerKey) -> bool {
377        self.timers.iter().any(|t| t.matches(key))
378    }
379
380    fn as_any(&self) -> &dyn Any {
381        self
382    }
383
384    fn as_any_mut(&mut self) -> &mut dyn Any {
385        self
386    }
387
388    fn clone_box(&self) -> Option<Box<dyn AnySnapshot>> {
389        Some(Box::new(self.clone()))
390    }
391}
392
393/// `Object.is` over JSON values, except that numbers compare by value.
394fn js_eq(a: &Value, b: &Value) -> bool {
395    match (a, b) {
396        (Value::Number(x), Value::Number(y)) => x.as_f64() == y.as_f64(),
397        _ => a == b,
398    }
399}
400
401/// What an action list asks for, before resolution.
402enum Op<E> {
403    Raise {
404        event: Ev<E>,
405        id: Option<String>,
406        delay: u64,
407        target: TimerTarget,
408    },
409    SendTo(ActorRef, Value),
410    /// `enq.spawn`, applied (and, unless `committed`, allocated) in order.
411    /// Boxed, like the target above: rare, and large inline.
412    SpawnChild(Box<SpawnOp>),
413    /// An event whose target is missing (`@xstate.deadLetter`).
414    DeadLetter(Value),
415    Cancel(TimerKey),
416    Log(Vec<Value>),
417    Emit(Value),
418    Custom(u32),
419    /// A custom action bound to params computed when it ran.
420    CustomDyn {
421        name: String,
422        params: Value,
423        /// `None` for an action left to the host.
424        exec: Option<ActionFn>,
425    },
426    Spawn(ActorRef),
427    Stop(ActorRef),
428}
429
430/// The result of running an action list or a transition function: the
431/// context object XState would merge (`res.context`), the queued operations
432/// and the raised events.
433struct Outcome<E> {
434    context: Option<Map<String, Value>>,
435    /// Instead of `context`: the merge is this transition's static
436    /// `context` patch, read from the machine when merged (not copied).
437    static_patch: Option<Tid>,
438    ops: Vec<Op<E>>,
439    internal: Vec<Ev<E>>,
440    /// A transition's `input` for the states it enters (when truthy).
441    /// Boxed: rare, and a `Value` is large inline.
442    input: Option<Box<Value>>,
443}
444
445impl<E> Outcome<E> {
446    fn empty() -> Self {
447        Self { context: None, static_patch: None, ops: Vec::new(), internal: Vec::new(), input: None }
448    }
449}
450
451/// Restores the expression scope's state when dropped.
452struct ScopeGuard<'a>(&'a Cell<Option<Nid>>, Option<Nid>);
453
454impl Drop for ScopeGuard<'_> {
455    fn drop(&mut self) {
456        self.0.set(self.1);
457    }
458}
459
460/// A transition evaluated when it was selected (a transition function, or
461/// one whose content runs expressions), reused when it is taken.
462struct Selected<E> {
463    targets: Option<Arc<[Nid]>>,
464    reenter: bool,
465    /// The reasons of a transition that rejected the event (XState's
466    /// `reject(...)` result): it is selected, so its ancestors are not
467    /// searched, and then left out; the event counts as handled.
468    rejected: Option<Box<Value>>,
469    /// Taken by the microstep's `Current` resolver.
470    outcome: Option<Outcome<E>>,
471}
472
473/// XState's `isRejection`: a transition result with a `reject` key.
474fn is_rejection(result: &Value) -> bool {
475    result.as_object().is_some_and(|o| o.contains_key("reject"))
476}
477
478/// A transition function's rejection, checked as XState's
479/// `assertRejectionResult` and `evaluateTransitionFunction` check it: its
480/// reasons a nonempty array of objects with a string `type`, without a
481/// target, context, input or reenter, and nothing enqueued. (Rejection
482/// schemas, `schemas.rejections`, are not checked, as no event schema is.)
483fn rejection<E>(result: &Value, enq: &Enq) -> Result<Option<Selected<E>>, SystemError> {
484    let valid = result.get("reject").and_then(Value::as_array).is_some_and(|reasons| {
485        !reasons.is_empty() && reasons.iter().all(|r| r.get("type").is_some_and(Value::is_string))
486    });
487    if !valid {
488        return Err(SystemError::Failed(REJECT_REASONS.into()));
489    }
490    if ["target", "context", "input", "reenter"].iter().any(|k| result.get(*k).is_some()) {
491        return Err(SystemError::Failed("A rejection cannot include a target, context, input, or reenter.".into()));
492    }
493    if !enq.ops.borrow().is_empty() {
494        return Err(SystemError::Failed(
495            "A rejecting transition cannot enqueue effects. Check rejection conditions before calling enq.".into(),
496        ));
497    }
498    let reasons = result.get("reject").cloned().map(Box::new);
499    Ok(Some(Selected { targets: None, reenter: false, rejected: reasons, outcome: Some(Outcome::empty()) }))
500}
501
502/// The parts of a snapshot a failed macrostep restores. The context, the
503/// history, the children and the timers are saved separately, by the host,
504/// just before the macrostep first writes them (`SavedParts`).
505struct Saved {
506    nodes: core::Buf<Nid>,
507    status: Status,
508    output: Option<Box<Value>>,
509    error: Option<Box<Value>>,
510    next_timer_id: u64,
511    next_timer_occurrence: u64,
512    #[allow(clippy::box_collection)]
513    inputs: Option<Box<Vec<(Nid, Value)>>>,
514    #[allow(clippy::box_collection)]
515    actor_ids: Option<Box<Vec<(String, u64)>>>,
516}
517
518impl Saved {
519    fn of<C, E>(st: &State<C, E>) -> Self {
520        Saved {
521            nodes: core::Buf::from_slice(&st.nodes),
522            status: st.status,
523            output: st.output.clone(),
524            error: st.error.clone(),
525            next_timer_id: st.next_timer_id,
526            next_timer_occurrence: st.next_timer_occurrence,
527            inputs: st.inputs.clone(),
528            actor_ids: st.actor_ids.clone(),
529        }
530    }
531
532    fn restore<C, E>(self, st: &mut State<C, E>, parts: SavedParts<E>) {
533        st.nodes.clear();
534        st.nodes.extend_from_slice(&self.nodes);
535        st.status = self.status;
536        st.output = self.output;
537        st.error = self.error;
538        st.next_timer_id = self.next_timer_id;
539        st.next_timer_occurrence = self.next_timer_occurrence;
540        st.inputs = self.inputs;
541        st.actor_ids = self.actor_ids;
542        if let Some(history) = parts.history {
543            st.history = history;
544        }
545        if let Some(children) = parts.children {
546            st.children = children;
547        }
548        if let Some(timers) = parts.timers {
549            st.timers = timers;
550        }
551    }
552}
553
554/// The copy-on-write parts of a snapshot as they were before a macrostep
555/// first wrote them (`None`: not written).
556struct SavedParts<E> {
557    history: Option<Arc<HistoryValues>>,
558    children: Option<Arc<IndexMap<String, ActorRef, FixedState>>>,
559    timers: Option<Arc<Vec<LogicalTimer<E>>>>,
560}
561
562impl<E> Default for SavedParts<E> {
563    fn default() -> Self {
564        Self { history: None, children: None, timers: None }
565    }
566}
567
568/// A child `enq.spawn` created, waiting to join the children (XState's
569/// child update `add`).
570struct SpawnOp {
571    id: String,
572    child: ActorRef,
573    /// The next index of the id's prefix, for the snapshot's counters.
574    counter: Option<(String, u64)>,
575}
576
577/// XState's spawn allocation for one macrostep: generated-id counters by
578/// prefix, the explicit ids taken, and the ids of the children stopped
579/// (`stoppedIds`).
580#[derive(Default)]
581struct SpawnAlloc {
582    counters: Vec<(String, u64)>,
583    explicit: Vec<String>,
584    stopped: Vec<String>,
585}
586
587/// How `enq.spawn` behaves in an evaluation, as XState's `enq` does where
588/// the host evaluates.
589#[derive(Clone, Copy, PartialEq, Eq)]
590enum SpawnMode {
591    /// Actions, and transitions when taken (`createTransitionEnqueue` with
592    /// `createActors`): the id is allocated and the child created at once.
593    Create,
594    /// Transition selection (`createTransitionSelection`): a spawn throws,
595    /// which ends the evaluation and enables the transition, evaluated
596    /// again when it is taken.
597    Select,
598    /// Conflict resolution's evaluation of a transition that spawns
599    /// (`createActors: false`): only the id the spawn would get.
600    Predict,
601}
602
603/// `spawn` for a root context expression: XState's `createSpawner` in its
604/// context factory, which allocates each child at once (its id from the
605/// transaction's counters, as `allocateChildId`; an explicit id must be
606/// free, as `assertChildIdFree`).
607struct ContextSpawner<'a, 'c> {
608    actors: &'a [(String, Arc<dyn Logic>)],
609    cx: RefCell<&'a mut (dyn Context + 'c)>,
610    spawned: RefCell<Vec<(String, ActorRef)>>,
611    /// Generated ids' next index, by prefix (`nextActorIds`).
612    counters: RefCell<Vec<(String, u64)>>,
613    error: RefCell<Option<SystemError>>,
614}
615
616impl ContextSpawner<'_, '_> {
617    fn fail_spawn(&self, message: String) -> Option<ActorRef> {
618        self.error.borrow_mut().get_or_insert(SystemError::Failed(message));
619        None
620    }
621}
622
623impl crate::registry::Spawner for ContextSpawner<'_, '_> {
624    fn self_ref(&self) -> ActorRef {
625        self.cx.borrow().self_ref()
626    }
627
628    fn fail(&self, message: String) {
629        self.fail_spawn(message);
630    }
631
632    fn spawn(&self, src: &str, options: SpawnOptions) -> Option<ActorRef> {
633        if self.error.borrow().is_some() {
634            return None;
635        }
636        let Some(logic) = self.actors.iter().find(|(name, _)| name == src).map(|(_, l)| l.clone()) else {
637            return self.fail_spawn(xstate_error(66, &[Str(src)]));
638        };
639        let in_use = |id: &str| self.spawned.borrow().iter().any(|(taken, _)| taken == id);
640        let id = match &options.id {
641            Some(id) if in_use(id) => {
642                let parent = self.cx.borrow().self_id();
643                return self.fail_spawn(xstate_error(67, &[Str(id), Str(&parent)]));
644            }
645            Some(id) => id.clone(),
646            None => {
647                let mut counters = self.counters.borrow_mut();
648                let entry = match counters.iter().position(|(p, _)| p == src) {
649                    Some(i) => &mut counters[i],
650                    None => {
651                        counters.push((src.to_owned(), 0));
652                        counters.last_mut().expect("pushed")
653                    }
654                };
655                let mut n = entry.1;
656                while in_use(&format!("{src}:{n}")) {
657                    n += 1;
658                }
659                entry.1 = n + 1;
660                format!("{src}:{n}")
661            }
662        };
663        let mut cx = self.cx.borrow_mut();
664        let parent = Some(cx.self_ref());
665        let allocated = cx.allocate(
666            &logic,
667            AllocateOptions {
668                id: id.clone(),
669                input: options.input,
670                parent,
671                registry_key: options.system_id,
672                sync_snapshot: options.sync_snapshot,
673                defer_initialization: false,
674            },
675        );
676        drop(cx);
677        match allocated {
678            Ok(child) => {
679                self.spawned.borrow_mut().push((id, child.clone()));
680                Some(child)
681            }
682            Err(e) => {
683                self.error.borrow_mut().get_or_insert(e);
684                None
685            }
686        }
687    }
688}
689
690/// The prefix of a generated child id (`<prefix>:<n>`), as XState's
691/// `parseGeneratedActorId`.
692fn generated_prefix(id: &str) -> Option<&str> {
693    let (prefix, index) = id.rsplit_once(':')?;
694    (!prefix.is_empty()
695        && !index.is_empty()
696        && index.bytes().all(|b| b.is_ascii_digit())
697        && index.parse::<u64>().is_ok())
698    .then_some(prefix)
699}
700
701impl<C, E> ChildIds for NativeHost<'_, C, E>
702where
703    C: Serialize + DeserializeOwned + Clone + 'static,
704    E: EventType,
705{
706    /// XState's `enq.spawn`: in `Create`, `allocateChildId`, or
707    /// `assertChildIdFree` and `reserveChildId` for an explicit id, then the
708    /// system's `createActorRef`; in `Predict`, the id the spawn would get.
709    fn spawn(&self, src: &str, options: &SpawnOptions) -> Result<Spawn, SystemError> {
710        let mode = self.spawn_mode.get();
711        if mode == SpawnMode::Select {
712            return Ok(Spawn::Abort);
713        }
714        let Some(logic) = self.m.actors.iter().find(|(name, _)| name == src).map(|(_, l)| l) else {
715            return Err(SystemError::Failed(xstate_error(66, &[Str(src)])));
716        };
717        let start_children = self.start_children();
718        let next_index = |alloc: &SpawnAlloc, prefix: &str| {
719            let counter = alloc.counters.iter().find(|(p, _)| p == prefix).map_or(0, |(_, n)| *n);
720            let persisted =
721                self.st.actor_ids.iter().flat_map(|i| i.iter()).find(|(p, _)| p == prefix).map_or(0, |(_, n)| *n);
722            counter.max(persisted)
723        };
724        let set_counter = |alloc: &mut SpawnAlloc, prefix: &str, next: u64| match alloc
725            .counters
726            .iter_mut()
727            .find(|(p, _)| p == prefix)
728        {
729            Some(entry) => entry.1 = next,
730            None => alloc.counters.push((prefix.to_owned(), next)),
731        };
732        let (id, counter) = match &options.id {
733            None => {
734                let mut alloc = self.spawn_alloc.borrow_mut();
735                let mut next = next_index(&alloc, src);
736                while alloc.explicit.iter().any(|x| *x == format!("{src}:{next}"))
737                    || start_children.contains_key(&format!("{src}:{next}"))
738                {
739                    next += 1;
740                }
741                if mode == SpawnMode::Predict {
742                    return Ok(Spawn::Predicted(format!("{src}:{next}")));
743                }
744                set_counter(&mut alloc, src, next + 1);
745                (format!("{src}:{next}"), Some((src.to_owned(), next + 1)))
746            }
747            Some(id) if mode == SpawnMode::Predict => return Ok(Spawn::Predicted(id.clone())),
748            Some(id) => {
749                self.assert_child_id_free(id).map_err(SystemError::Failed)?;
750                // A generated-shaped explicit id moves its prefix's counter
751                // past it (never back).
752                let counter = generated_prefix(id).map(|prefix| {
753                    let mut alloc = self.spawn_alloc.borrow_mut();
754                    let index: u64 = id[prefix.len() + 1..].parse().expect("checked");
755                    let next = next_index(&alloc, prefix).max(index + 1);
756                    set_counter(&mut alloc, prefix, next);
757                    (prefix.to_owned(), next)
758                });
759                (id.clone(), counter)
760            }
761        };
762        let mut cx = self.cx.borrow_mut();
763        let parent = Some(cx.self_ref());
764        let child = cx.allocate(
765            logic,
766            AllocateOptions {
767                id: id.clone(),
768                input: options.input.clone(),
769                parent,
770                registry_key: options.system_id.clone(),
771                sync_snapshot: options.sync_snapshot,
772                defer_initialization: false,
773            },
774        )?;
775        Ok(Spawn::Created { id, child, counter })
776    }
777
778    fn stop_child(&self, id: &str) {
779        // The selection's `enq` only records the stop, for the microstep.
780        if self.spawn_mode.get() != SpawnMode::Select && self.st.children.contains_key(id) {
781            self.record_stopped_child(id);
782        }
783    }
784}
785
786impl<C, E> NativeHost<'_, C, E>
787where
788    C: Serialize + DeserializeOwned + Clone + 'static,
789    E: EventType,
790{
791    /// The children of the snapshot the macrostep started from (XState's
792    /// `getWorkingSnapshotOf`, the actor's snapshot before the transition).
793    fn start_children(&self) -> Arc<IndexMap<String, ActorRef, FixedState>> {
794        match &self.saved_parts.children {
795            Some(saved) => saved.clone(),
796            None if self.rollback => self.st.children.clone(),
797            None => self.m.empty.children.clone(),
798        }
799    }
800
801    /// XState's `assertChildIdFree`: an explicit id a spawn or an invoke
802    /// claims must be free, and is then taken for the rest of the
803    /// macrostep. It is in use when an active child of the snapshot the
804    /// macrostep started from holds it and the macrostep has not stopped
805    /// that child, or when a spawn or invoke of the macrostep took it.
806    fn assert_child_id_free(&self, id: &str) -> Result<(), String> {
807        let mut alloc = self.spawn_alloc.borrow_mut();
808        let occupied = self.start_children().get(id).is_some_and(|existing| {
809            !alloc.stopped.iter().any(|s| s == id) && self.cx.borrow().status_of(existing) == Status::Active
810        });
811        if occupied || alloc.explicit.iter().any(|x| x == id) {
812            return Err(xstate_error(67, &[Str(id), Str(&self.cx.borrow().self_id())]));
813        }
814        alloc.explicit.push(id.to_owned());
815        Ok(())
816    }
817
818    /// XState's `recordStoppedChild`: a child the macrostep stopped frees
819    /// its id for a later spawn or invoke of the same macrostep.
820    fn record_stopped_child(&self, id: &str) {
821        let mut alloc = self.spawn_alloc.borrow_mut();
822        alloc.explicit.retain(|x| x != id);
823        alloc.stopped.push(id.to_owned());
824    }
825
826    /// Whether the `enq` an expression ran with ended it, as XState's
827    /// `enq` throws. A failed call ends it with its failure, ahead of one
828    /// the expression reported after it. A spawn at selection ends it
829    /// without one (`true`): a failure the expression reported after the
830    /// spawn never happened, but a call that failed before it did.
831    fn enq_ended(&self, enq: &Enq<'_>) -> Result<bool, SystemError> {
832        if enq.failed.get() {
833            self.expr_error.take();
834            let failure = self.push_enq_ops(enq.take(), &mut Outcome::empty());
835            return Err(failure.expect_err("a failed enq call records its failure"));
836        }
837        if !enq.aborted.get() {
838            return Ok(false);
839        }
840        self.push_enq_ops(enq.take(), &mut Outcome::empty())?;
841        self.expr_error.take();
842        self.aborted.set(true);
843        Ok(true)
844    }
845}
846
847/// Sets a state's input, keeping its place if it had one.
848fn set_input(inputs: &mut Vec<(Nid, Value)>, node: Nid, input: Value) {
849    match inputs.iter_mut().find(|(n, _)| *n == node) {
850        Some(entry) => entry.1 = input,
851        None => inputs.push((node, input)),
852    }
853}
854
855/// A computed context patch, as XState's object spread reads it: an object,
856/// nothing for `null`, booleans and numbers, and index keys for a string's
857/// characters or an array's items.
858fn computed_patch(value: Value, _what: &str) -> Result<Option<Map<String, Value>>, SystemError> {
859    Ok(match value {
860        Value::Object(patch) => Some(patch),
861        Value::Null | Value::Bool(_) | Value::Number(_) => None,
862        // JavaScript spreads a string's characters and an array's items
863        // under their indices.
864        Value::String(s) => {
865            Some(s.chars().enumerate().map(|(i, c)| (i.to_string(), Value::String(c.into()))).collect())
866        }
867        Value::Array(items) => Some(items.into_iter().enumerate().map(|(i, v)| (i.to_string(), v)).collect()),
868    })
869}
870
871/// A computed event to raise or emit: an object with a string type, or
872/// nothing for the values XState drops (`null`, booleans, numbers).
873fn computed_event(value: Value, what: &str) -> Result<Option<Value>, SystemError> {
874    match value {
875        Value::Object(ref e) if e.get("type").is_some_and(Value::is_string) => Ok(Some(value)),
876        Value::Null | Value::Bool(_) | Value::Number(_) => Ok(None),
877        other => Err(SystemError::Failed(format!("{what} must be an object with a string type, not {other}"))),
878    }
879}
880
881/// A computed event to raise: XState rejects a string and raises anything
882/// else, but only an object with a string type can be taken by a transition,
883/// so the rest is dropped.
884fn computed_raise(value: Value) -> Result<Option<Value>, SystemError> {
885    match value {
886        Value::String(s) => Err(SystemError::Failed(xstate_error(68, &[Str(&s)]))),
887        Value::Object(ref e) if e.get("type").is_some_and(Value::is_string) => Ok(Some(value)),
888        _ => Ok(None),
889    }
890}
891
892/// JavaScript truthiness (`!!value`).
893fn js_truthy(value: &Value) -> bool {
894    match value {
895        Value::Null => false,
896        Value::Bool(b) => *b,
897        Value::Number(n) => n.as_f64().is_some_and(|f| f != 0.0 && !f.is_nan()),
898        Value::String(s) => !s.is_empty(),
899        Value::Array(_) | Value::Object(_) => true,
900    }
901}
902
903/// A context as JSON: a clone for untyped (`Value`) contexts, serde for
904/// typed ones (with numbers as JavaScript writes them).
905fn context_json<C: Serialize + 'static>(context: &C) -> Value {
906    if let Some(v) = (context as &dyn Any).downcast_ref::<Value>() {
907        let mut v = v.clone();
908        crate::event::js_numbers(&mut v);
909        return v;
910    }
911    let mut v = serde_json::to_value(context).unwrap_or(Value::Null);
912    crate::event::js_numbers(&mut v);
913    v
914}
915
916/// A JSON value that serializes with whole-number floats written as
917/// integers, as [`crate::event::js_numbers`] would leave it, without
918/// copying it.
919struct JsNumbers<'a>(&'a Value);
920
921impl Serialize for JsNumbers<'_> {
922    fn serialize<S: serde::Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
923        use serde::ser::{SerializeMap as _, SerializeSeq as _};
924        const MAX_SAFE: f64 = 9_007_199_254_740_991.0;
925        match self.0 {
926            Value::Number(n) if n.is_f64() => {
927                let f = n.as_f64().unwrap_or(f64::NAN);
928                if f.fract() == 0.0 && f.abs() <= MAX_SAFE {
929                    serializer.serialize_i64(f as i64)
930                } else {
931                    serializer.serialize_f64(f)
932                }
933            }
934            Value::Array(items) => {
935                let mut seq = serializer.serialize_seq(Some(items.len()))?;
936                for item in items {
937                    seq.serialize_element(&JsNumbers(item))?;
938                }
939                seq.end()
940            }
941            Value::Object(map) => {
942                let mut out = serializer.serialize_map(Some(map.len()))?;
943                for (k, v) in map {
944                    out.serialize_entry(k, &JsNumbers(v))?;
945                }
946                out.end()
947            }
948            other => other.serialize(serializer),
949        }
950    }
951}
952
953/// An event that serializes as [`Ev::to_json`] builds it.
954struct EvView<'a, E>(&'a Ev<E>);
955
956impl<E: EventType> Serialize for EvView<'_, E> {
957    fn serialize<S: serde::Serializer>(&self, s: S) -> Result<S::Ok, S::Error> {
958        use serde::ser::SerializeMap as _;
959        match self.0 {
960            Ev::Internal { event_type, data } if !data.contains_key("type") => {
961                let mut map = s.serialize_map(Some(data.len() + 1))?;
962                map.serialize_entry("type", &**event_type)?;
963                for (k, v) in data {
964                    map.serialize_entry(k, v)?;
965                }
966                map.end()
967            }
968            other => other.to_json().serialize(s),
969        }
970    }
971}
972
973/// `{ type: "xstate.after", delay, stateId }`.
974struct AfterView<'a>(&'a AfterDelay, &'a str);
975
976impl Serialize for AfterView<'_> {
977    fn serialize<S: serde::Serializer>(&self, s: S) -> Result<S::Ok, S::Error> {
978        use serde::ser::SerializeMap as _;
979        let mut map = s.serialize_map(Some(3))?;
980        map.serialize_entry("type", AFTER)?;
981        map.serialize_entry("delay", self.0)?;
982        map.serialize_entry("stateId", self.1)?;
983        map.end()
984    }
985}
986
987/// A logical timer that serializes as [`LogicalTimer::to_data`] builds it.
988struct TimerData<'a, E>(&'a LogicalTimer<E>);
989
990impl<E: EventType> Serialize for TimerData<'_, E> {
991    fn serialize<S: serde::Serializer>(&self, s: S) -> Result<S::Ok, S::Error> {
992        use serde::ser::SerializeMap as _;
993        let t = self.0;
994        let mut map = s.serialize_map(Some(
995            4 + usize::from(t.occurrence.is_some()) + usize::from(t.id.is_some()) + usize::from(t.seq.is_some()),
996        ))?;
997        if let Some(occurrence) = t.occurrence {
998            map.serialize_entry("occurrence", &occurrence)?;
999        }
1000        if let Some(id) = &t.id {
1001            map.serialize_entry("id", id)?;
1002        }
1003        if let Some(seq) = t.seq {
1004            map.serialize_entry("seq", &seq)?;
1005        }
1006        map.serialize_entry("delay", &t.delay)?;
1007        map.serialize_entry("type", t.target.timer_type())?;
1008        match &t.event {
1009            TimerEv::After { delay, state_id } => map.serialize_entry("event", &AfterView(delay, state_id))?,
1010            TimerEv::Ev(e) => map.serialize_entry("event", &EvView(e))?,
1011        }
1012        match &t.target {
1013            TimerTarget::SendTo(target) => map.serialize_entry("target", &target.to_json())?,
1014            TimerTarget::Raise | TimerTarget::SendToSelf => map.serialize_entry("target", "self")?,
1015        }
1016        map.end()
1017    }
1018}
1019
1020/// A machine snapshot that serializes as [`Machine::snapshot_data`] builds it.
1021struct SnapshotView<'a, C, E> {
1022    m: &'a Machine<C, E>,
1023    st: &'a State<C, E>,
1024    /// Leave out what restore rebuilds identically (`System::compact_view`).
1025    compact: bool,
1026}
1027
1028impl<C, E> Serialize for SnapshotView<'_, C, E>
1029where
1030    C: Serialize + DeserializeOwned + Clone + 'static,
1031    E: EventType,
1032{
1033    fn serialize<S: serde::Serializer>(&self, s: S) -> Result<S::Ok, S::Error> {
1034        use serde::ser::SerializeMap;
1035        struct Ids<'a, C, E>(&'a Machine<C, E>, &'a [Nid]);
1036        impl<C, E> Serialize for Ids<'_, C, E> {
1037            fn serialize<S: serde::Serializer>(&self, s: S) -> Result<S::Ok, S::Error> {
1038                s.collect_seq(self.1.iter().map(|&n| self.0.data(n).id.as_str()))
1039            }
1040        }
1041        struct StateNodes<'a, C, E>(&'a Machine<C, E>, &'a [Nid]);
1042        impl<C, E> Serialize for StateNodes<'_, C, E> {
1043            fn serialize<S: serde::Serializer>(&self, s: S) -> Result<S::Ok, S::Error> {
1044                s.collect_seq(self.1.iter().map(|&n| {
1045                    let mut one = std::collections::BTreeMap::new();
1046                    one.insert("@stateNode", self.0.data(n).id.as_str());
1047                    one
1048                }))
1049            }
1050        }
1051        struct History<'a, C, E>(&'a Machine<C, E>, &'a [(Nid, Vec<Nid>)]);
1052        impl<C, E> Serialize for History<'_, C, E> {
1053            fn serialize<S: serde::Serializer>(&self, s: S) -> Result<S::Ok, S::Error> {
1054                s.collect_map(self.1.iter().map(|(h, nodes)| (self.0.data(*h).id.as_str(), StateNodes(self.0, nodes))))
1055            }
1056        }
1057        struct Children<'a>(&'a IndexMap<String, ActorRef, FixedState>);
1058        impl Serialize for Children<'_> {
1059            fn serialize<S: serde::Serializer>(&self, s: S) -> Result<S::Ok, S::Error> {
1060                struct RefView<'a>(&'a ActorRef);
1061                impl Serialize for RefView<'_> {
1062                    fn serialize<S: serde::Serializer>(&self, s: S) -> Result<S::Ok, S::Error> {
1063                        use serde::ser::SerializeMap as _;
1064                        let mut m = s.serialize_map(Some(2))?;
1065                        m.serialize_entry("@actor", &*self.0.address)?;
1066                        m.serialize_entry("incarnation", &self.0.incarnation.to_string())?;
1067                        m.end()
1068                    }
1069                }
1070                s.collect_map(self.0.iter().map(|(k, r)| (k, RefView(r))))
1071            }
1072        }
1073        let (m, st, compact) = (self.m, self.st, self.compact);
1074        // Compact leaves out what restore rebuilds: the value (from
1075        // `nodeIds`), empty children, timers, history and `stateInputs`,
1076        // and a zero `nextTimerId`.
1077        let keep = |non_empty: bool| !compact || non_empty;
1078        let (keep_children, keep_timers, keep_history, keep_inputs, keep_next) = (
1079            keep(!st.children.is_empty()),
1080            keep(!st.timers.is_empty()),
1081            keep(!st.history.is_empty()),
1082            keep(st.inputs.is_some()),
1083            keep(st.next_timer_id != 0),
1084        );
1085        // Exact lengths let encoders such as MessagePack write maps directly
1086        // instead of buffering them.
1087        let len = 3
1088            + usize::from(st.output.is_some())
1089            + usize::from(st.error.is_some())
1090            + if compact { 0 } else { 1 }
1091            + usize::from(st.actor_ids.is_some())
1092            + usize::from(st.next_timer_occurrence > 0)
1093            + [keep_children, keep_timers, keep_history, keep_inputs, keep_next].iter().filter(|k| **k).count();
1094        let mut map = s.serialize_map(Some(len))?;
1095        map.serialize_entry("status", st.status.as_str())?;
1096        if let Some(o) = &st.output {
1097            map.serialize_entry("output", o)?;
1098        }
1099        if let Some(e) = &st.error {
1100            map.serialize_entry("error", e)?;
1101        }
1102        match (&st.context as &dyn Any).downcast_ref::<Value>() {
1103            Some(v) => map.serialize_entry("context", &JsNumbers(v))?,
1104            None => map.serialize_entry("context", &context_json(&st.context))?,
1105        }
1106        if !compact {
1107            map.serialize_entry("value", &m.state_value(&st.nodes))?;
1108        }
1109        if keep_children {
1110            map.serialize_entry("children", &Children(&st.children))?;
1111        }
1112        struct Timers<'a, E>(&'a [LogicalTimer<E>]);
1113        impl<E: EventType> Serialize for Timers<'_, E> {
1114            fn serialize<S: serde::Serializer>(&self, s: S) -> Result<S::Ok, S::Error> {
1115                s.collect_seq(self.0.iter().map(TimerData))
1116            }
1117        }
1118        if keep_timers {
1119            map.serialize_entry("timers", &Timers(&st.timers))?;
1120        }
1121        if keep_history {
1122            map.serialize_entry("historyValue", &History(m, &st.history))?;
1123        }
1124        if keep_inputs {
1125            struct Inputs<'a, C, E>(&'a Machine<C, E>, &'a [(Nid, Value)]);
1126            impl<C, E> Serialize for Inputs<'_, C, E> {
1127                fn serialize<S: serde::Serializer>(&self, s: S) -> Result<S::Ok, S::Error> {
1128                    s.collect_map(self.1.iter().map(|(n, v)| (&self.0.data(*n).id, JsNumbers(v))))
1129                }
1130            }
1131            map.serialize_entry("stateInputs", &Inputs(m, st.inputs.as_deref().map_or(&[], Vec::as_slice)))?;
1132        }
1133        if keep_next {
1134            map.serialize_entry("nextTimerId", &st.next_timer_id)?;
1135        }
1136        // Written only once a timer was scheduled, as XState writes it.
1137        if st.next_timer_occurrence > 0 {
1138            map.serialize_entry("nextTimerOccurrence", &st.next_timer_occurrence)?;
1139        }
1140        if let Some(ids) = &st.actor_ids {
1141            struct Ids<'a>(&'a [(String, u64)]);
1142            impl Serialize for Ids<'_> {
1143                fn serialize<S: serde::Serializer>(&self, s: S) -> Result<S::Ok, S::Error> {
1144                    s.collect_map(self.0.iter().map(|(p, n)| (p, n)))
1145                }
1146            }
1147            map.serialize_entry("nextActorIds", &Ids(ids))?;
1148        }
1149        map.serialize_entry("nodeIds", &Ids(m, &st.nodes))?;
1150        map.end()
1151    }
1152}
1153
1154/// Which macrostep is being run.
1155/// An event type copied to the stack (types longer than its buffer go to
1156/// the heap), so it can be read after its event has moved.
1157struct TypeName {
1158    buf: [u8; 64],
1159    len: usize,
1160    heap: Option<String>,
1161}
1162
1163impl TypeName {
1164    fn of(s: &str) -> Self {
1165        let mut buf = [0; 64];
1166        match buf.get_mut(..s.len()) {
1167            Some(head) => {
1168                head.copy_from_slice(s.as_bytes());
1169                Self { buf, len: s.len(), heap: None }
1170            }
1171            None => Self { buf, len: 0, heap: Some(s.to_owned()) },
1172        }
1173    }
1174
1175    fn as_str(&self) -> &str {
1176        match &self.heap {
1177            Some(s) => s,
1178            None => std::str::from_utf8(&self.buf[..self.len]).expect("copied from a str"),
1179        }
1180    }
1181}
1182
1183pub(crate) enum MacroEvent {
1184    Init,
1185    Event(Value),
1186    /// A fired timer, `{ type: "xstate.timer", ...key }`.
1187    /// A fired timer's key and the occurrence its notification carries.
1188    Timer(TimerKey, Option<u64>),
1189}
1190
1191struct NativeHost<'a, C, E> {
1192    m: &'a Machine<C, E>,
1193    st: &'a mut State<C, E>,
1194    /// The actor's system, borrowed briefly: `enq.spawn` creates children
1195    /// on it while an expression runs.
1196    cx: RefCell<&'a mut dyn Context>,
1197    event: Ev<E>,
1198    queue: VecDeque<Ev<E>>,
1199    effects: Vec<Effect>,
1200    /// The snapshot object's identity: bumped whenever XState would clone it.
1201    token: u64,
1202    /// Whether the current microstep has cloned the snapshot.
1203    cloned: bool,
1204    /// Transition results computed this microstep (`getCurrentTransitionResult`).
1205    outcomes: Vec<(Tid, Outcome<E>)>,
1206    /// Transitions evaluated by the last selection (XState's selection results).
1207    selected: Vec<(Tid, Selected<E>)>,
1208    /// The state whose input expressions see (`None`: no input), as XState
1209    /// passes a state's input to its own functions.
1210    scope: Cell<Option<Nid>>,
1211    /// The inputs of the transitions of this microstep, for `begin_entry`.
1212    pending_inputs: Vec<(Tid, Value)>,
1213    /// XState's spawn allocation for this macrostep: generated-id counters
1214    /// by prefix, the explicit ids taken and the children stopped.
1215    spawn_alloc: RefCell<SpawnAlloc>,
1216    /// How `enq.spawn` behaves in the evaluation running now.
1217    spawn_mode: Cell<SpawnMode>,
1218    /// Whether a spawn ended the evaluation running at selection.
1219    aborted: Cell<bool>,
1220    /// The last configurations, for the infinite-loop error.
1221    recent: VecDeque<Vec<Nid>>,
1222    /// The identity of the snapshot the last microstep returned.
1223    microstep_token_value: u64,
1224    /// The context before this macrostep's first write, to roll back to
1225    /// when the macrostep fails.
1226    context_backup: Option<C>,
1227    /// For an untyped context patched in place: whether the undo log, not
1228    /// `context_backup`, records this macrostep's writes, and the log (each
1229    /// written key and the value it replaced, `None` for a key it added).
1230    context_undo_active: bool,
1231    context_undo: Vec<(String, Option<Value>)>,
1232    /// Whether a transition selects by what decides it alone, as `can`
1233    /// asks: its guard, its match and its function, not what it does.
1234    selection_alone: bool,
1235    /// Whether a failure rolls the macrostep back (not for the initial one),
1236    /// and the parts saved for it.
1237    rollback: bool,
1238    saved_parts: SavedParts<E>,
1239    /// The failure an expression reported ([`ExprArgs::fail`]), taken
1240    /// after each evaluation.
1241    expr_error: RefCell<Option<String>>,
1242    /// The event the macrostep began with, once an internal event replaced
1243    /// it in `event`.
1244    macrostep_event: Option<Ev<E>>,
1245}
1246
1247impl<'a, C, E> NativeHost<'a, C, E>
1248where
1249    C: Serialize + DeserializeOwned + Clone + 'static,
1250    E: EventType,
1251{
1252    /// A host for one macrostep (or one check) of `st`; `rollback` when a
1253    /// failure rolls the macrostep back (not for the initial one).
1254    fn new(m: &'a Machine<C, E>, st: &'a mut State<C, E>, cx: &'a mut dyn Context, rollback: bool) -> Self {
1255        NativeHost {
1256            m,
1257            st,
1258            cx: RefCell::new(cx),
1259            event: Ev::Init,
1260            queue: VecDeque::new(),
1261            effects: Vec::new(),
1262            token: 0,
1263            cloned: false,
1264            outcomes: Vec::new(),
1265            selected: Vec::new(),
1266            scope: Cell::new(None),
1267            pending_inputs: Vec::new(),
1268            spawn_alloc: RefCell::new(SpawnAlloc::default()),
1269            spawn_mode: Cell::new(SpawnMode::Create),
1270            aborted: Cell::new(false),
1271            recent: VecDeque::new(),
1272            microstep_token_value: 0,
1273            context_backup: None,
1274            context_undo_active: false,
1275            context_undo: Vec::new(),
1276            selection_alone: false,
1277            rollback,
1278            saved_parts: SavedParts::default(),
1279            expr_error: RefCell::new(None),
1280            macrostep_event: None,
1281        }
1282    }
1283}
1284
1285impl<C, E> NativeHost<'_, C, E>
1286where
1287    C: Serialize + DeserializeOwned + Clone + 'static,
1288    E: EventType,
1289{
1290    fn context_object(&self) -> Result<Map<String, Value>, SystemError> {
1291        if let Some(v) = (&self.st.context as &dyn Any).downcast_ref::<Value>() {
1292            let mut map = v.as_object().cloned().unwrap_or_default();
1293            if crate::ops::enabled() {
1294                crate::ops::count_n(crate::ops::Op::ContextValue, map.values().map(crate::ops::json_size).sum());
1295            }
1296            map.values_mut().for_each(crate::event::js_numbers);
1297            return Ok(map);
1298        }
1299        match serde_json::to_value(&self.st.context) {
1300            Ok(Value::Object(mut map)) => {
1301                if crate::ops::enabled() {
1302                    crate::ops::count_n(crate::ops::Op::ContextValue, map.values().map(crate::ops::json_size).sum());
1303                }
1304                map.values_mut().for_each(crate::event::js_numbers);
1305                Ok(map)
1306            }
1307            Ok(_) => Ok(Map::new()),
1308            Err(e) => Err(SystemError::Failed(format!("invalid context: {e}"))),
1309        }
1310    }
1311
1312    /// The timers, to write (saving them first for a rollback).
1313    fn timers_mut(&mut self) -> &mut Vec<LogicalTimer<E>> {
1314        if self.rollback && self.saved_parts.timers.is_none() {
1315            self.saved_parts.timers = Some(self.st.timers.clone());
1316        }
1317        Arc::make_mut(&mut self.st.timers)
1318    }
1319
1320    /// The children, to write (saving them first for a rollback).
1321    fn children_mut(&mut self) -> &mut IndexMap<String, ActorRef, FixedState> {
1322        if self.rollback && self.saved_parts.children.is_none() {
1323            self.saved_parts.children = Some(self.st.children.clone());
1324        }
1325        Arc::make_mut(&mut self.st.children)
1326    }
1327
1328    /// The history, to write (saving it first for a rollback).
1329    fn history_mut(&mut self) -> &mut HistoryValues {
1330        if self.rollback && self.saved_parts.history.is_none() {
1331            self.saved_parts.history = Some(self.st.history.clone());
1332        }
1333        Arc::make_mut(&mut self.st.history)
1334    }
1335
1336    /// `mergeContextPatch`.
1337    fn merge_context(&mut self, patch: &Map<String, Value>) -> Result<(), SystemError> {
1338        crate::ops::count(crate::ops::Op::ContextMerge);
1339        let normalized = self.st.context_normalized;
1340        if let Some(v) = (&mut self.st.context as &mut dyn Any).downcast_mut::<Value>() {
1341            // An untyped context is patched in place. To roll back a failed
1342            // macrostep, an undo log keeps each overwritten value (no copy
1343            // of the context) while the context is an object whose numbers
1344            // are already normalized; otherwise the whole context is copied
1345            // on the macrostep's first write.
1346            let first_write = self.context_backup.is_none() && !self.context_undo_active;
1347            if first_write {
1348                if v.as_object().is_some_and(|m| normalized || !m.values().any(crate::event::needs_js_numbers)) {
1349                    self.context_undo_active = true;
1350                } else {
1351                    let copy = v.clone();
1352                    self.context_backup = Some(*(Box::new(copy) as Box<dyn Any>).downcast::<C>().expect("C is Value"));
1353                }
1354            }
1355            if !v.is_object() {
1356                *v = Value::Object(Map::new());
1357            }
1358            let map = v.as_object_mut().expect("an object");
1359            if !self.context_undo_active {
1360                map.values_mut().for_each(crate::event::js_numbers);
1361            }
1362            for (k, val) in patch {
1363                let mut val = val.clone();
1364                crate::event::js_numbers(&mut val);
1365                let old = match map.get_mut(k) {
1366                    Some(slot) => Some(std::mem::replace(slot, val)),
1367                    None => map.insert(k.clone(), val),
1368                };
1369                if self.context_undo_active {
1370                    self.context_undo.push((k.clone(), old));
1371                }
1372            }
1373            self.st.context_normalized = true;
1374            self.cloned = true;
1375            return Ok(());
1376        }
1377        let mut map = self.context_object()?;
1378        for (k, v) in patch {
1379            map.insert(k.clone(), v.clone());
1380        }
1381        let merged = Value::Object(map);
1382        let context = if std::any::TypeId::of::<C>() == std::any::TypeId::of::<Value>() {
1383            // An untyped context takes the object as it is.
1384            *(Box::new(merged) as Box<dyn Any>).downcast::<C>().expect("C is Value")
1385        } else {
1386            C::deserialize(&merged).map_err(|e| SystemError::Failed(format!("invalid context: {e}")))?
1387        };
1388        let previous = std::mem::replace(&mut self.st.context, context);
1389        self.context_backup.get_or_insert(previous);
1390        self.cloned = true;
1391        Ok(())
1392    }
1393
1394    /// The context an action list starts from, which only actions that
1395    /// assign read (and expressions after them or after a transition's
1396    /// `context` patch); `None` (not serialized) otherwise.
1397    fn action_base(&self, actions: &[Action], patched: bool) -> Result<Option<Map<String, Value>>, SystemError> {
1398        if actions.iter().any(Action::assigns) || (patched && actions.iter().any(Action::evaluates)) {
1399            self.context_object().map(Some)
1400        } else {
1401            Ok(None)
1402        }
1403    }
1404
1405    /// The context `base` with `assigned` merged in, as the context type.
1406    fn context_from(&self, base: &Map<String, Value>, assigned: Option<&Map<String, Value>>) -> Result<C, SystemError> {
1407        let mut map = base.clone();
1408        for (k, v) in assigned.into_iter().flatten() {
1409            map.insert(k.clone(), v.clone());
1410        }
1411        let merged = Value::Object(map);
1412        if std::any::TypeId::of::<C>() == std::any::TypeId::of::<Value>() {
1413            return Ok(*(Box::new(merged) as Box<dyn Any>).downcast::<C>().expect("C is Value"));
1414        }
1415        C::deserialize(&merged).map_err(|e| SystemError::Failed(format!("invalid context: {e}")))
1416    }
1417
1418    /// A template's value in the expression scope (the current event).
1419    fn eval(&self, t: &Template, context: &C, params: Option<&Value>) -> Result<Value, SystemError> {
1420        self.eval_for(t, context, &self.event, params)
1421    }
1422
1423    fn eval_for(&self, t: &Template, context: &C, event: &Ev<E>, params: Option<&Value>) -> Result<Value, SystemError> {
1424        if let Template::Static(v) = t {
1425            return Ok(v.clone());
1426        }
1427        let m = self.m;
1428        let args = ExprArgs {
1429            context,
1430            event,
1431            params,
1432            input: self.scope_input(),
1433            machine: m,
1434            config: &self.st.nodes,
1435            enq: None,
1436            children: &self.st.children,
1437            cx: &self.cx,
1438            error: &self.expr_error,
1439        };
1440        let value = t.eval(&mut |i| {
1441            crate::ops::count(crate::ops::Op::Expr);
1442            (m.exprs[i as usize])(&args)
1443        });
1444        self.expr_failed()?;
1445        Ok(value)
1446    }
1447
1448    /// The failure an expression reported, if any.
1449    fn expr_failed(&self) -> Result<(), SystemError> {
1450        match self.expr_error.borrow_mut().take() {
1451            Some(message) => Err(SystemError::Failed(message)),
1452            None => Ok(()),
1453        }
1454    }
1455
1456    /// The input of the state in scope.
1457    fn scope_input(&self) -> Option<&Value> {
1458        let node = self.scope.get()?;
1459        self.st.inputs.as_ref()?.iter().find(|(n, _)| *n == node).map(|(_, v)| v)
1460    }
1461
1462    /// Puts `node`'s input in the expression scope until the guard drops.
1463    fn scoped(&self, node: Option<Nid>) -> ScopeGuard<'_> {
1464        ScopeGuard(&self.scope, self.scope.replace(node))
1465    }
1466
1467    /// `executeActions` from `machineFromJSON`, against `base` as the
1468    /// context (`patched`: a transition's `context` patch is in `base`, so
1469    /// expressions see it).
1470    fn execute_actions(
1471        &self,
1472        actions: &[Action],
1473        base: &Map<String, Value>,
1474        patched: bool,
1475    ) -> Result<Outcome<E>, SystemError> {
1476        let mut assigned: Option<Map<String, Value>> = None;
1477        let mut out = Outcome::empty();
1478        // The context expressions see when it is not the snapshot's: the
1479        // base with what was assigned before them (built when one reads it).
1480        let mut scope: Option<C> = None;
1481        let mut stale = patched;
1482        let mut params: Vec<Value> = Vec::new();
1483        for action in actions {
1484            if crate::ops::enabled() && !matches!(action, Action::Params(_) | Action::EndParams) {
1485                crate::ops::count(crate::ops::Op::Action);
1486            }
1487            if stale && action.evaluates() {
1488                scope = Some(self.context_from(base, assigned.as_ref())?);
1489                stale = false;
1490            }
1491            let context = scope.as_ref().unwrap_or(&self.st.context);
1492            let p = params.last();
1493            match action {
1494                Action::Raise { event, id, delay } => {
1495                    let event = self.m.raise_events[*event as usize].clone();
1496                    match delay {
1497                        None => out.internal.push(event),
1498                        Some(delay) => {
1499                            out.ops.push(Op::Raise { event, id: id.clone(), delay: *delay, target: TimerTarget::Raise })
1500                        }
1501                    }
1502                }
1503                Action::RaiseExpr { event, id, delay } => {
1504                    let Some(value) = computed_raise(self.eval(event, context, p)?)? else {
1505                        continue;
1506                    };
1507                    let event = Ev::from_json(value).expect("an object with a string type");
1508                    match delay {
1509                        None => out.internal.push(event),
1510                        Some(delay) => {
1511                            out.ops.push(Op::Raise { event, id: id.clone(), delay: *delay, target: TimerTarget::Raise })
1512                        }
1513                    }
1514                }
1515                Action::Cancel(id) => out.ops.push(Op::Cancel(TimerKey::Id(id.clone()))),
1516                Action::Log(args) => out.ops.push(Op::Log(args.clone())),
1517                Action::Emit(event) => out.ops.push(Op::Emit(event.clone())),
1518                Action::EmitExpr(event) => {
1519                    if let Some(event) = computed_event(self.eval(event, context, p)?, "an emitted event")? {
1520                        out.ops.push(Op::Emit(event));
1521                    }
1522                }
1523                Action::Assign(patch) => {
1524                    let a = assigned.get_or_insert_with(Map::new);
1525                    for (k, v) in patch {
1526                        a.insert(k.clone(), v.clone());
1527                    }
1528                    stale = true;
1529                }
1530                Action::AssignExpr(patch) => {
1531                    let patch = computed_patch(self.eval(patch, context, p)?, "an assigned context")?;
1532                    assigned.get_or_insert_with(Map::new).extend(patch.into_iter().flatten());
1533                    stale = true;
1534                }
1535                Action::Custom(i) => out.ops.push(Op::Custom(*i)),
1536                Action::CustomExpr(i) => {
1537                    let d = &self.m.dynamic_actions[*i as usize];
1538                    let params = self.eval(&d.params, context, p)?;
1539                    let exec =
1540                        if self.m.is_host_action(&d.name) {
1541                            None
1542                        } else {
1543                            Some((d.factory)(&params).map_err(|m| {
1544                                SystemError::Failed(format!("invalid params for action '{}': {m}", d.name))
1545                            })?)
1546                        };
1547                    out.ops.push(Op::CustomDyn { name: d.name.clone(), params, exec });
1548                }
1549                Action::Expr(i) => {
1550                    let m = self.m;
1551                    let enq = Enq {
1552                        ops: RefCell::new(Vec::new()),
1553                        ids: Some(self),
1554                        aborted: Cell::new(false),
1555                        failed: Cell::new(false),
1556                    };
1557                    let args = ExprArgs {
1558                        context,
1559                        event: &self.event,
1560                        params: p,
1561                        input: self.scope_input(),
1562                        machine: m,
1563                        config: &self.st.nodes,
1564                        enq: Some(&enq),
1565                        children: &self.st.children,
1566                        cx: &self.cx,
1567                        error: &self.expr_error,
1568                    };
1569                    crate::ops::count(crate::ops::Op::Expr);
1570                    let mut result = (m.exprs[*i as usize])(&args);
1571                    if self.enq_ended(&enq)? {
1572                        return Ok(out);
1573                    }
1574                    self.expr_failed()?;
1575                    self.push_enq_ops(enq.take(), &mut out)?;
1576                    // XState merges a truthy `context` of the result.
1577                    if let Some(patch) = result.get_mut("context").map(Value::take) {
1578                        if js_truthy(&patch) {
1579                            let patch = computed_patch(patch, "an action's context")?;
1580                            assigned.get_or_insert_with(Map::new).extend(patch.into_iter().flatten());
1581                            stale = true;
1582                        }
1583                    }
1584                }
1585                Action::Params(t) => {
1586                    let value = self.eval(t, context, p)?;
1587                    params.push(value);
1588                }
1589                Action::EndParams => {
1590                    params.pop();
1591                }
1592            }
1593        }
1594        out.context = assigned.map(|patch| {
1595            let mut full = base.clone();
1596            for (k, v) in patch {
1597                full.insert(k, v);
1598            }
1599            full
1600        });
1601        Ok(out)
1602    }
1603
1604    /// The transition function `machineFromJSON` builds for a transition
1605    /// with `context` or `actions` (wrapped, for invoke completions with a
1606    /// timeout, by a function that then cancels the timeout).
1607    fn transition_outcome(&self, t: Tid) -> Result<Outcome<E>, SystemError> {
1608        let tr = self.m.transition(t);
1609        // XState evaluates a transition's `input` with only the context and
1610        // the event (no state input).
1611        let input = match &tr.input {
1612            Some(input) => {
1613                let _scope = self.scoped(None);
1614                Some(self.eval(input, &self.st.context, None)?).filter(js_truthy).map(Box::new)
1615            }
1616            None => None,
1617        };
1618        let mut out = self.transition_body(t)?;
1619        out.input = out.input.or(input);
1620        Ok(out)
1621    }
1622
1623    fn transition_body(&self, t: Tid) -> Result<Outcome<E>, SystemError> {
1624        let tr = self.m.transition(t);
1625        if !tr.is_dynamic() {
1626            return Ok(Outcome::empty());
1627        }
1628        let _scope = self.scoped(Some(self.m.tree.transitions[t as usize].source));
1629        if tr.function.is_some() {
1630            return Ok(self.eval_function(t)?.and_then(|s| s.outcome).unwrap_or_else(Outcome::empty));
1631        }
1632        let mut out = if tr.context.is_some() || tr.context_expr.is_some() || !tr.actions.is_empty() {
1633            let computed = match &tr.context_expr {
1634                Some(patch) => computed_patch(self.eval(patch, &self.st.context, None)?, "a transition's context")?,
1635                None => None,
1636            };
1637            let patch = computed.as_ref().or(tr.context.as_ref());
1638            // Only actions that assign, or expressions after the patch, read
1639            // the base (`None` otherwise), so only then does it need the patch.
1640            let mut base = self.action_base(&tr.actions, patch.is_some())?;
1641            if let (Some(base), Some(patch)) = (&mut base, patch) {
1642                for (k, v) in patch {
1643                    base.insert(k.clone(), v.clone());
1644                }
1645            }
1646            let mut out = if tr.actions.is_empty() {
1647                Outcome::empty()
1648            } else {
1649                self.execute_actions(&tr.actions, base.as_ref().unwrap_or(&Map::new()), patch.is_some())?
1650            };
1651            if out.context.is_none() {
1652                if computed.is_some() {
1653                    out.context = computed;
1654                } else if tr.context.is_some() {
1655                    out.static_patch = Some(t);
1656                }
1657            }
1658            out
1659        } else {
1660            Outcome::empty()
1661        };
1662        if let Some(key) = &tr.cancel_timeout {
1663            out.ops.push(Op::Cancel(key.clone()));
1664        }
1665        Ok(out)
1666    }
1667
1668    /// A candidate's evaluation at selection: `None` when it needs none
1669    /// (a plain transition), `Some(None)` when its function is not enabled.
1670    fn select(&self, t: Tid) -> Result<Option<Option<Selected<E>>>, SystemError> {
1671        let tr = self.m.transition(t);
1672        if tr.function.is_some() {
1673            Ok(Some(self.eval_function(t)?))
1674        } else if tr.evaluates() {
1675            let outcome = self.transition_outcome(t)?;
1676            Ok(Some(Some(Selected {
1677                targets: tr.targets.clone(),
1678                reenter: tr.reenter,
1679                rejected: None,
1680                outcome: Some(outcome),
1681            })))
1682        } else {
1683            Ok(None)
1684        }
1685    }
1686
1687    /// What an `enq` recorded, appended to an outcome in order.
1688    fn push_enq_ops(&self, ops: Vec<EnqOp>, out: &mut Outcome<E>) -> Result<(), SystemError> {
1689        for op in ops {
1690            match op {
1691                EnqOp::Raise { event, delay, id } => {
1692                    let Some(event) = computed_raise(event)? else { continue };
1693                    let event = Ev::from_json(event).expect("an object with a string type");
1694                    match delay {
1695                        None => out.internal.push(event),
1696                        Some(delay) => out.ops.push(Op::Raise { event, id, delay, target: TimerTarget::Raise }),
1697                    }
1698                }
1699                EnqOp::Emit(event) => {
1700                    if let Some(event) = computed_event(event, "an emitted event")? {
1701                        out.ops.push(Op::Emit(event));
1702                    }
1703                }
1704                EnqOp::Cancel(id) => out.ops.push(Op::Cancel(TimerKey::Id(id))),
1705                EnqOp::Log(args) => out.ops.push(Op::Log(args)),
1706                EnqOp::Action { name, params } => {
1707                    let exec = if self.m.is_host_action(&name) {
1708                        None
1709                    } else {
1710                        let factory = self.m.action_factories.get(&name).ok_or_else(|| {
1711                            SystemError::Failed(format!("enq.action: no custom action \"{name}\" is registered"))
1712                        })?;
1713                        Some(
1714                            factory(&params)
1715                                .map_err(|m| SystemError::Failed(format!("invalid params for action '{name}': {m}")))?,
1716                        )
1717                    };
1718                    out.ops.push(Op::CustomDyn { name, params, exec });
1719                }
1720                EnqOp::SendTo { to, event, delay, id } => {
1721                    if !event.is_object() {
1722                        let message = match &event {
1723                            Value::String(s) => xstate_error(70, &[Str(s)]),
1724                            other => xstate_error(70, &[Raw(&other.to_string())]),
1725                        };
1726                        return Err(SystemError::Failed(message));
1727                    }
1728                    let target = match &to {
1729                        SendTarget::Child(id) => self.st.children.get(id).cloned(),
1730                        SendTarget::Ref(r) => Some(r.clone()),
1731                        SendTarget::Parent => self.cx.borrow().parent_ref(),
1732                        SendTarget::Nowhere => None,
1733                    };
1734                    match (target, delay) {
1735                        (None, _) => out.ops.push(Op::DeadLetter(event)),
1736                        (Some(target), None) => out.ops.push(Op::SendTo(target, event)),
1737                        (Some(target), Some(delay)) => {
1738                            let event = Ev::from_json(event.clone()).unwrap_or_else(|| Ev::Internal {
1739                                event_type: Cow::Owned(String::new()),
1740                                data: event.as_object().cloned().unwrap_or_default(),
1741                            });
1742                            // XState writes a delayed send to the actor itself as `"self"`.
1743                            let target = if target == self.cx.borrow().self_ref() {
1744                                TimerTarget::SendToSelf
1745                            } else {
1746                                TimerTarget::SendTo(Box::new(target))
1747                            };
1748                            out.ops.push(Op::Raise { event, id, delay, target });
1749                        }
1750                    }
1751                }
1752                EnqOp::Stop(id) => {
1753                    if let Some(child) = self.st.children.get(&id) {
1754                        out.ops.push(Op::Stop(child.clone()));
1755                    }
1756                }
1757                EnqOp::Spawn { id, child, counter } => {
1758                    out.ops.push(Op::SpawnChild(Box::new(SpawnOp { id, child, counter })))
1759                }
1760                EnqOp::Fail(e) => return Err(e),
1761            }
1762        }
1763        Ok(())
1764    }
1765
1766    /// Evaluates a transition function (XState's `evaluateTransitionFunction`
1767    /// and `getTransitionResult`): `None` when it is not enabled (it
1768    /// returned nothing and enqueued nothing; for a route, a falsy result).
1769    fn eval_function(&self, t: Tid) -> Result<Option<Selected<E>>, SystemError> {
1770        let m = self.m;
1771        let tr = m.transition(t);
1772        let source = m.tree.transitions[t as usize].source;
1773        let enq =
1774            Enq { ops: RefCell::new(Vec::new()), ids: Some(self), aborted: Cell::new(false), failed: Cell::new(false) };
1775        // Only a transition expression's scope has `enq`.
1776        let _scope = self.scoped(Some(source));
1777        let call = |expr: u32, enq: Option<&Enq>| {
1778            let args = ExprArgs {
1779                context: &self.st.context,
1780                event: &self.event,
1781                params: None,
1782                input: self.scope_input(),
1783                machine: m,
1784                config: &self.st.nodes,
1785                enq,
1786                children: &self.st.children,
1787                cx: &self.cx,
1788                error: &self.expr_error,
1789            };
1790            crate::ops::count(crate::ops::Op::Expr);
1791            let value = (m.exprs[expr as usize])(&args);
1792            if let Some(enq) = enq {
1793                if self.enq_ended(enq)? {
1794                    return Ok(Value::Null);
1795                }
1796            }
1797            self.expr_failed().map(|()| value)
1798        };
1799        let targets_of = |result: &Value| -> Result<Option<Arc<[Nid]>>, SystemError> {
1800            let list: Vec<&str> = match result.get("target") {
1801                Some(Value::String(s)) if !s.is_empty() => vec![s.as_str()],
1802                Some(Value::Array(items)) => items.iter().filter_map(Value::as_str).collect(),
1803                _ => return Ok(None),
1804            };
1805            list.into_iter()
1806                .map(|s| m.resolve_target(source, s))
1807                .collect::<Result<Vec<Nid>, String>>()
1808                .map(|v| Some(v.into()))
1809                .map_err(SystemError::Failed)
1810        };
1811        let (result, targets) = match tr.function.as_ref().expect("a transition function") {
1812            TransitionFn::Expr(expr) => {
1813                let result = call(*expr, Some(&enq))?;
1814                if self.aborted.get() {
1815                    // Enabled, with no result: evaluated again when taken.
1816                    return Ok(Some(Selected {
1817                        targets: None,
1818                        reenter: false,
1819                        rejected: None,
1820                        outcome: Some(Outcome::empty()),
1821                    }));
1822                }
1823                if result.is_null() && enq.ops.borrow().is_empty() {
1824                    return Ok(None);
1825                }
1826                if is_rejection(&result) {
1827                    return rejection(&result, &enq);
1828                }
1829                let targets = targets_of(&result)?;
1830                (result, targets)
1831            }
1832            TransitionFn::Reject(reasons) => {
1833                let result = json!({ "reject": self.eval(reasons, &self.st.context, None)? });
1834                return rejection(&result, &enq);
1835            }
1836            TransitionFn::Route { expr, target } => {
1837                let result = call(*expr, None)?;
1838                if !js_truthy(&result) {
1839                    return Ok(None);
1840                }
1841                (if result == Value::Bool(true) { Value::Object(Map::new()) } else { result }, Some(target.clone()))
1842            }
1843            TransitionFn::ChoiceExpr { expr, id } => {
1844                let result = call(*expr, None)?;
1845                if !js_truthy(&result) || result.get("target").is_none() {
1846                    return Err(SystemError::Failed(xstate_error(62, &[Str(id)])));
1847                }
1848                let targets = targets_of(&result)?;
1849                (result, targets)
1850            }
1851            TransitionFn::Choice { branches, path, id } => {
1852                let mut taken = None;
1853                for branch in branches {
1854                    if match &branch.when {
1855                        Some(g) => self.eval_guard(g, None)?,
1856                        None => true,
1857                    } {
1858                        taken = Some(branch);
1859                        break;
1860                    }
1861                }
1862                let branch = taken
1863                    .ok_or_else(|| SystemError::Failed(format!("Choice state at {path} did not match any branch.")))?;
1864                if branch.targets.is_none() {
1865                    return Err(SystemError::Failed(xstate_error(62, &[Str(id)])));
1866                }
1867                let mut result = Map::new();
1868                if let Some(context) = &branch.context {
1869                    result.insert("context".into(), self.eval(context, &self.st.context, None)?);
1870                }
1871                if let Some(input) = &branch.input {
1872                    result.insert("input".into(), self.eval(input, &self.st.context, None)?);
1873                }
1874                result.insert("reenter".into(), Value::Bool(branch.reenter));
1875                (Value::Object(result), branch.targets.clone())
1876            }
1877        };
1878        let ops = enq.take();
1879        let mut outcome = Outcome::empty();
1880        outcome.context = match result.get("context") {
1881            Some(patch) if js_truthy(patch) => computed_patch(patch.clone(), "a transition's context")?,
1882            _ => None,
1883        };
1884        self.push_enq_ops(ops, &mut outcome)?;
1885        if let Some(key) = &tr.cancel_timeout {
1886            outcome.ops.push(Op::Cancel(key.clone()));
1887        }
1888        outcome.input = result.get("input").filter(|i| js_truthy(i)).cloned().map(Box::new);
1889        let reenter = result.get("reenter").is_some_and(js_truthy);
1890        Ok(Some(Selected { targets, reenter, rejected: None, outcome: Some(outcome) }))
1891    }
1892
1893    /// `resolveActionsWithContext`: logical timers update the snapshot now;
1894    /// everything becomes an effect.
1895    fn resolve_ops(&mut self, ops: Vec<Op<E>>) -> Result<(), SystemError> {
1896        for op in ops {
1897            // Messages are counted by the system, which delivers them.
1898            if crate::ops::enabled() {
1899                let kind = match &op {
1900                    Op::Raise { .. } => Some(crate::ops::Op::TimerSchedule),
1901                    Op::Cancel(_) => Some(crate::ops::Op::TimerCancel),
1902                    Op::Spawn(_) | Op::SpawnChild(_) => Some(crate::ops::Op::ActorStart),
1903                    Op::Stop(_) => Some(crate::ops::Op::ActorStop),
1904                    Op::SendTo(..) => None,
1905                    Op::Log(_) | Op::Emit(_) | Op::Custom(_) | Op::CustomDyn { .. } | Op::DeadLetter(_) => {
1906                        Some(crate::ops::Op::Effect)
1907                    }
1908                };
1909                if let Some(kind) = kind {
1910                    crate::ops::count(kind);
1911                }
1912            }
1913            match op {
1914                Op::Raise { event, id, delay, target } => {
1915                    let seq = if id.is_none() && !has_builtin_timer_identity(event.event_type()) {
1916                        let seq = self.st.next_timer_id;
1917                        self.st.next_timer_id += 1;
1918                        Some(seq)
1919                    } else {
1920                        None
1921                    };
1922                    let occurrence = self.st.next_timer_occurrence;
1923                    self.st.next_timer_occurrence += 1;
1924                    let timer = LogicalTimer {
1925                        occurrence: Some(occurrence),
1926                        id,
1927                        seq,
1928                        delay,
1929                        event: TimerEv::new(event),
1930                        target,
1931                    };
1932                    let key = timer.key();
1933                    let timers = self.timers_mut();
1934                    match timers.iter_mut().find(|t| t.matches(&key)) {
1935                        Some(existing) => *existing = timer,
1936                        None => {
1937                            // Snapshots hold few timers: no spare capacity.
1938                            timers.reserve_exact(1);
1939                            timers.push(timer);
1940                        }
1941                    }
1942                    self.cloned = true;
1943                    self.effects.push(Effect::DelayedRaise { key, delay, occurrence });
1944                }
1945                Op::Cancel(key) => {
1946                    if self.st.timers.iter().any(|t| t.matches(&key)) {
1947                        self.timers_mut().retain(|t| !t.matches(&key));
1948                        self.cloned = true;
1949                    }
1950                    self.effects.push(Effect::Cancel(key));
1951                }
1952                Op::Log(args) => self.effects.push(Effect::External(ExternalSpec {
1953                    kind: EffectKind::Action,
1954                    ty: EffectType::Fixed("@xstate.log".into()),
1955                    params: Some(json!({})),
1956                    args,
1957                    event: None,
1958                    reason: None,
1959                    exec: None,
1960                })),
1961                Op::Emit(event) => {
1962                    let ty = event.get("type").and_then(Value::as_str).unwrap_or("").to_owned();
1963                    self.effects.push(Effect::External(ExternalSpec {
1964                        kind: EffectKind::Emit,
1965                        ty: EffectType::Fixed(ty),
1966                        // The system derives the params (the event without
1967                        // `type`) when it keeps the effect.
1968                        params: None,
1969                        args: Vec::new(),
1970                        event: Some(event),
1971                        reason: None,
1972                        exec: None,
1973                    }));
1974                }
1975                Op::CustomDyn { name, params, exec } => self.effects.push(Effect::External(ExternalSpec {
1976                    kind: EffectKind::Action,
1977                    ty: EffectType::Action(name),
1978                    params: Some(json!({})),
1979                    args: vec![params],
1980                    event: None,
1981                    reason: None,
1982                    exec,
1983                })),
1984                Op::Custom(i) => {
1985                    let action = &self.m.actions[i as usize];
1986                    self.effects.push(Effect::External(ExternalSpec {
1987                        kind: EffectKind::Action,
1988                        ty: EffectType::Action(action.name.clone()),
1989                        params: Some(json!({})),
1990                        args: vec![action.params.clone().unwrap_or(Value::Null)],
1991                        event: None,
1992                        reason: None,
1993                        exec: (!self.m.is_host_action(&action.name)).then(|| action.exec.clone()),
1994                    }));
1995                }
1996                Op::SendTo(target, event) => self.effects.push(Effect::SendTo { target, event }),
1997                Op::DeadLetter(event) => self.effects.push(Effect::External(ExternalSpec {
1998                    kind: EffectKind::Builtin,
1999                    ty: EffectType::Fixed("@xstate.deadLetter".into()),
2000                    params: None,
2001                    args: Vec::new(),
2002                    event: Some(event),
2003                    reason: Some("missingTarget".into()),
2004                    exec: None,
2005                })),
2006                Op::Spawn(r) => self.effects.push(Effect::Spawn(r)),
2007                Op::Stop(r) => {
2008                    // XState's `applyChildUpdate`: the child leaves `children`
2009                    // and the registry at once, and counts as stopping.
2010                    if self.st.children.values().any(|c| *c == r) {
2011                        self.children_mut().retain(|_, c| *c != r);
2012                    }
2013                    self.cx.get_mut().unregister(&r);
2014                    self.cloned = true;
2015                    self.effects.push(Effect::Stop(r));
2016                }
2017                Op::SpawnChild(spawn) => {
2018                    // XState's `applyChildUpdate` of an `add`: the child
2019                    // `enq.spawn` created joins `children`, and its id's
2020                    // counter the snapshot's (`mergeActorIdCounters`).
2021                    let SpawnOp { id, child, counter } = *spawn;
2022                    self.children_mut().insert(id, child.clone());
2023                    if let Some((prefix, next)) = counter {
2024                        let ids = self.st.actor_ids.get_or_insert_with(Default::default);
2025                        match ids.iter_mut().find(|(p, _)| *p == prefix) {
2026                            Some(entry) => entry.1 = entry.1.max(next),
2027                            None => ids.push((prefix, next)),
2028                        }
2029                    }
2030                    self.cloned = true;
2031                    self.effects.push(Effect::Spawn(child));
2032                }
2033            }
2034        }
2035        Ok(())
2036    }
2037
2038    /// A state's exit function: its timers are cancelled (the wrappers
2039    /// nest, so the last first), then the exit actions run.
2040    fn exit_outcome(&self, node: Nid) -> Result<Outcome<E>, SystemError> {
2041        let _scope = self.scoped(Some(node));
2042        let data = self.m.data(node);
2043        let base = self.action_base(&data.exit, false)?.unwrap_or_default();
2044        let mut out = self.execute_actions(&data.exit, &base, false)?;
2045        let mut ops: Vec<Op<E>> = data.delayed.iter().rev().map(|d| Op::Cancel(self.delayed_key(node, d))).collect();
2046        ops.append(&mut out.ops);
2047        out.ops = ops;
2048        Ok(out)
2049    }
2050
2051    /// The key of a state's delayed event (its built-in identity).
2052    fn delayed_key(&self, node: Nid, d: &DelayedDef) -> TimerKey {
2053        let id = &self.m.data(node).id;
2054        match &d.kind {
2055            DelayedKind::After { event_delay } => match AfterDelay::from_value(event_delay.clone()) {
2056                Some(delay) => TimerKey::After { delay, state_id: id.clone() },
2057                None => TimerKey::Event(Box::new(json!({ "type": AFTER, "delay": event_delay, "stateId": id }))),
2058            },
2059            DelayedKind::StateTimeout => TimerKey::StateTimeout { state_id: id.clone() },
2060            DelayedKind::InvokeTimeout { invoke_id } => {
2061                TimerKey::Event(Box::new(json!({ "type": "xstate.timeout.actor", "actorId": invoke_id })))
2062            }
2063        }
2064    }
2065
2066    fn delayed_event(&self, node: Nid, d: &DelayedDef) -> Ev<E> {
2067        let id = Value::String(self.m.data(node).id.clone());
2068        let mut data = Map::new();
2069        let ty: &'static str = match &d.kind {
2070            DelayedKind::After { event_delay } => {
2071                data.insert("delay".into(), event_delay.clone());
2072                data.insert("stateId".into(), id);
2073                AFTER
2074            }
2075            DelayedKind::StateTimeout => {
2076                data.insert("stateId".into(), id);
2077                "xstate.timeout.state"
2078            }
2079            DelayedKind::InvokeTimeout { invoke_id } => {
2080                data.insert("actorId".into(), Value::String(invoke_id.clone()));
2081                if let Some(child) = self.st.children.get(invoke_id) {
2082                    data.insert("sessionId".into(), Value::String(child.incarnation.to_string()));
2083                }
2084                "xstate.timeout.actor"
2085            }
2086        };
2087        Ev::Internal { event_type: Cow::Borrowed(ty), data }
2088    }
2089
2090    fn resolve_delay(&self, spec: DelaySpec) -> Result<u64, SystemError> {
2091        Ok(match spec {
2092            DelaySpec::Fixed(ms) => ms,
2093            DelaySpec::Named(i) => {
2094                (self.m.delays[i as usize])(&self.st.context, &self.event).map_err(SystemError::Failed)?
2095            }
2096            DelaySpec::Expr(i) => {
2097                let value = self.eval(&Template::Expr(i), &self.st.context, None)?;
2098                match &value {
2099                    Value::Number(n) => n.as_f64().and_then(crate::delay::ms_to_u64),
2100                    Value::String(s) => crate::delay::parse_duration_ms(s).and_then(crate::delay::ms_to_u64),
2101                    _ => None,
2102                }
2103                .ok_or_else(|| {
2104                    SystemError::Failed(format!("a delay must be milliseconds or a duration string, not {value}"))
2105                })?
2106            }
2107        })
2108    }
2109
2110    /// Entering a state, with its input in scope: invokes, entry actions,
2111    /// then its delayed transitions' timers.
2112    fn enter_state_scoped(&mut self, node: Nid) -> Result<(), SystemError> {
2113        let data = self.m.data(node);
2114        let mut ops: Vec<Op<E>> = Vec::new();
2115        // Final states are inert: their invocations never start. An invoke's
2116        // child is reserved before the entry actions, which can address it,
2117        // and initialized after them, with an input computed against the
2118        // context they produced (XState's `_deferInitialization`).
2119        let mut pending: Vec<(ActorRef, &Option<Template>)> = Vec::new();
2120        if self.m.tree.kind(node) != core::Kind::Final {
2121            for inv in &data.invokes {
2122                self.assert_child_id_free(&inv.id).map_err(SystemError::Failed)?;
2123                let cx = self.cx.get_mut();
2124                let parent = Some(cx.self_ref());
2125                let child = cx.allocate(
2126                    &inv.logic,
2127                    AllocateOptions {
2128                        id: inv.id.clone(),
2129                        input: None,
2130                        parent,
2131                        registry_key: inv.registry_key.clone(),
2132                        sync_snapshot: Some(inv.sync_snapshot),
2133                        defer_initialization: true,
2134                    },
2135                )?;
2136                ops.push(Op::Spawn(child.clone()));
2137                self.children_mut().insert(inv.id.clone(), child.clone());
2138                self.cloned = true;
2139                pending.push((child, &inv.input));
2140            }
2141        }
2142        let base = self.action_base(&data.entry, false)?.unwrap_or_default();
2143        let mut out = self.execute_actions(&data.entry, &base, false)?;
2144        // Delayed transitions' timers are scheduled by entry wrappers, after
2145        // the entry actions and against the context they produced.
2146        if let Some(ctx) = &out.context {
2147            self.merge_context(ctx)?;
2148        }
2149        for (child, input) in pending {
2150            let input = input.as_ref().map(|t| self.eval(t, &self.st.context, None)).transpose()?;
2151            self.cx.get_mut().initialize(&child, input)?;
2152        }
2153        for d in &data.delayed {
2154            let delay = self.resolve_delay(d.delay)?;
2155            out.ops.push(Op::Raise { event: self.delayed_event(node, d), id: None, delay, target: TimerTarget::Raise });
2156        }
2157        self.queue.extend(out.internal);
2158        ops.append(&mut out.ops);
2159        self.resolve_ops(ops)?;
2160        // The `initial` and history default transitions of JSON machines
2161        // carry no context or actions.
2162        Ok(())
2163    }
2164
2165    /// A final state's output, computed against the current context and event.
2166    fn output_of(&self, node: Nid) -> Result<Option<Value>, SystemError> {
2167        let _scope = self.scoped(Some(node));
2168        self.m.data(node).output.as_ref().map(|t| self.eval(t, &self.st.context, None)).transpose()
2169    }
2170
2171    fn done_event(&self, node: Nid, output: Option<Value>) -> Ev<E> {
2172        let mut data = Map::new();
2173        data.insert("stateId".into(), Value::String(self.m.data(node).id.clone()));
2174        if let Some(output) = output {
2175            data.insert("output".into(), output);
2176        }
2177        Ev::Internal { event_type: Cow::Borrowed(DONE_STATE), data }
2178    }
2179
2180    fn queued_done_output(&self, node: Nid) -> Option<Value> {
2181        let id = &self.m.data(node).id;
2182        self.queue.iter().find_map(|e| match e {
2183            Ev::Internal { event_type, data }
2184                if event_type == DONE_STATE && data.get("stateId").and_then(Value::as_str) == Some(id) =>
2185            {
2186                data.get("output").cloned()
2187            }
2188            _ => None,
2189        })
2190    }
2191
2192    /// A guard, with `params` the scope of its expressions.
2193    fn eval_guard(&self, guard: &Guard, params: Option<&Value>) -> Result<bool, SystemError> {
2194        crate::ops::count(crate::ops::Op::Guard);
2195        // XState's guard arguments have no state input.
2196        let _scope = self.scoped(None);
2197        let args =
2198            || GuardArgs { context: &self.st.context, event: &self.event, machine: self.m, config: &self.st.nodes };
2199        Ok(match guard {
2200            Guard::Custom(i) => (self.m.guards[*i as usize])(&args()).map_err(SystemError::Failed)?,
2201            Guard::Not(inner) => !self.eval_guard(inner, params)?,
2202            Guard::StateIn(node) => self.st.nodes.contains(node),
2203            Guard::RouteTo(to) => self.event.field("to").as_ref().and_then(Value::as_str) == Some(to.as_str()),
2204            Guard::And(a, b) => self.eval_guard(a, params)? && self.eval_guard(b, params)?,
2205            Guard::Expr(i) => js_truthy(&self.eval(&Template::Expr(*i), &self.st.context, params)?),
2206            Guard::Dynamic(i) => {
2207                let d = &self.m.dynamic_guards[*i as usize];
2208                let value = self.eval(&d.params, &self.st.context, params)?;
2209                let f = (d.factory)(&value)
2210                    .map_err(|m| SystemError::Failed(format!("invalid params for guard '{}': {m}", d.name)))?;
2211                f(&args()).map_err(SystemError::Failed)?
2212            }
2213            Guard::StateInExpr(params_template) => {
2214                let resolved = self.eval(params_template, &self.st.context, params)?;
2215                match resolved.get("stateId").and_then(Value::as_str) {
2216                    Some(id) => {
2217                        let id = id.strip_prefix('#').unwrap_or(id);
2218                        let node =
2219                            self.m.node_by_id(id).ok_or_else(|| SystemError::Failed(xstate_error(20, &[Str(id)])))?;
2220                        self.st.nodes.contains(&node)
2221                    }
2222                    None => false,
2223                }
2224            }
2225            Guard::Scoped(scope, inner) => {
2226                let value = self.eval(scope, &self.st.context, params)?;
2227                self.eval_guard(inner, Some(&value))?
2228            }
2229        })
2230    }
2231
2232    /// XState's `matchesActorSession`.
2233    fn matches_session(&self, actor_id: &str) -> bool {
2234        let Some(child) = self.st.children.get(actor_id) else { return true };
2235        match self.event.field("sessionId") {
2236            None => true,
2237            Some(session) => session.as_str() == Some(child.incarnation.to_string().as_str()),
2238        }
2239    }
2240
2241    /// XState's `removeTerminatedChild`.
2242    fn remove_terminated_child(&mut self) {
2243        let ty = self.event.event_type();
2244        if ty != "xstate.done.actor" && ty != "xstate.error.actor" {
2245            return;
2246        }
2247        let Some(actor_id) = self.event.field("actorId").and_then(|v| v.as_str().map(str::to_owned)) else { return };
2248        let Some(child) = self.st.children.get(&actor_id).cloned() else { return };
2249        if self.event.field("sessionId").as_ref().and_then(Value::as_str)
2250            != Some(child.incarnation.to_string().as_str())
2251        {
2252            return;
2253        }
2254        self.children_mut().shift_remove(&actor_id);
2255        self.cx.get_mut().unregister(&child);
2256        self.token += 1;
2257    }
2258
2259    fn stop_children_ops(&self) -> Vec<Op<E>> {
2260        self.st.children.values().map(|c| Op::Stop(c.clone())).collect()
2261    }
2262
2263    /// A fired timer: its event is queued as internal. False when no
2264    /// pending timer has the key.
2265    ///
2266    /// `occurrence` is the notification's (`None` when it has none, which
2267    /// matches any; `Some(None)` when it is not a whole number, which
2268    /// matches none): a notification of a replaced scheduling matches no
2269    /// timer.
2270    fn fire_timer(&mut self, key: Option<TimerKey>, occurrence: Option<Option<u64>>) -> bool {
2271        let index = key.as_ref().and_then(|k| {
2272            self.st
2273                .timers
2274                .iter()
2275                .position(|t| t.matches(k) && occurrence.is_none_or(|o| o.is_some() && o == t.occurrence))
2276        });
2277        let Some(index) = index else { return false };
2278        let timer = self.timers_mut().remove(index);
2279        self.token += 1;
2280        match timer.target {
2281            // A delayed `sendTo` relays its event (dropped if the target
2282            // has stopped), to the actor itself too.
2283            TimerTarget::SendTo(target) => {
2284                self.effects.push(Effect::SendTo { target: *target, event: timer.event.into_ev().to_json() })
2285            }
2286            TimerTarget::SendToSelf => {
2287                let target = self.cx.borrow().self_ref();
2288                self.effects.push(Effect::SendTo { target, event: timer.event.into_ev().to_json() })
2289            }
2290            TimerTarget::Raise => self.queue.push_back(timer.event.into_ev()),
2291        }
2292        self.event = Ev::Internal { event_type: Cow::Borrowed("xstate.timer"), data: Map::new() };
2293        true
2294    }
2295
2296    fn cancel_timer_ops(&self) -> Vec<Op<E>> {
2297        self.st.timers.iter().map(|t| Op::Cancel(t.key())).collect()
2298    }
2299}
2300
2301impl<C, E> Host for NativeHost<'_, C, E>
2302where
2303    C: Serialize + DeserializeOwned + Clone + 'static,
2304    E: EventType,
2305{
2306    type Error = SystemError;
2307
2308    fn config(&self, out: &mut Vec<Nid>) {
2309        out.extend_from_slice(&self.st.nodes);
2310    }
2311
2312    fn history(&self, history: Nid) -> Option<Vec<Nid>> {
2313        self.st.history.iter().find(|(h, _)| *h == history).map(|(_, v)| v.clone())
2314    }
2315
2316    fn static_initial(&self, node: Nid) -> Arc<[Nid]> {
2317        self.m.data(node).initial.clone()
2318    }
2319
2320    fn begin_selection(&mut self) -> Result<(), SystemError> {
2321        crate::ops::count_n(crate::ops::Op::ActiveState, self.st.nodes.len() as u64);
2322        self.selected.clear();
2323        Ok(())
2324    }
2325
2326    fn eval_candidate(&mut self, t: Tid, _node: Nid, _eventless: bool) -> Result<bool, SystemError> {
2327        crate::ops::count(crate::ops::Op::Candidate);
2328        let tr = self.m.transition(t);
2329        for (key, expected) in &tr.matches {
2330            match self.event.field(key) {
2331                Some(actual) if js_eq(&actual, expected) => {}
2332                _ => return Ok(false),
2333            }
2334        }
2335        if let Some(actor_id) = &tr.session {
2336            if !self.matches_session(actor_id) {
2337                return Ok(false);
2338            }
2339        }
2340        if let Some(g) = &tr.guard {
2341            if !self.eval_guard(g, None)? {
2342                return Ok(false);
2343            }
2344        }
2345        // XState evaluates transition functions (and `machineFromJSON`'s
2346        // functions for transitions with `context` or `actions`) here and
2347        // reuses the result when the transition is taken. (The others give
2348        // the same results whenever they are computed.)
2349        // `can` selects a transition of JSON by its guard alone, as
2350        // kit-workflow does: its context, actions and input never decide
2351        // whether it is taken, so a throw of them is the step's, not the
2352        // selection's. A transition function decides as it runs.
2353        if !tr.selects || (self.selection_alone && tr.function.is_none()) {
2354            return Ok(true);
2355        }
2356        // A shared ancestor's `always` is visited once per active leaf: the
2357        // first evaluation stands (XState's cached selection result).
2358        if self.selected.iter().any(|(x, _)| *x == t) {
2359            return Ok(true);
2360        }
2361        // XState's selection `enq` records what the transition enqueues,
2362        // and throws from a spawn (`createTransitionSelection`): the
2363        // transition is then enabled, with a result that cannot be reused,
2364        // and is evaluated again when it is taken.
2365        self.spawn_mode.set(SpawnMode::Select);
2366        let selected = self.select(t);
2367        self.spawn_mode.set(SpawnMode::Create);
2368        if self.aborted.replace(false) {
2369            selected?;
2370            self.selected.retain(|(x, _)| *x != t);
2371            return Ok(true);
2372        }
2373        let Some(selected) = selected? else { return Ok(true) };
2374        let Some(selected) = selected else { return Ok(false) };
2375        match self.selected.iter_mut().find(|(x, _)| *x == t) {
2376            Some(entry) => entry.1 = selected,
2377            None => self.selected.push((t, selected)),
2378        }
2379        Ok(true)
2380    }
2381
2382    fn rejected(&self, t: Tid) -> bool {
2383        self.selected.iter().any(|(x, s)| *x == t && s.rejected.is_some())
2384    }
2385
2386    fn resolve(&mut self, resolver: Resolver, t: TRef) -> Result<Resolved, SystemError> {
2387        match t {
2388            TRef::T(t) => {
2389                // Every resolver reuses the selection's results
2390                // (`selectEventlessTransitions` too, since beta.4).
2391                let found = self.selected.iter_mut().find(|(x, _)| *x == t);
2392                if let Some((_, selected)) = found {
2393                    let resolved = Resolved { targets: selected.targets.clone(), reenter: selected.reenter };
2394                    if resolver == Resolver::Current && !self.outcomes.iter().any(|(x, _)| *x == t) {
2395                        if let Some(outcome) = selected.outcome.take() {
2396                            // XState replays what the selection recorded into
2397                            // the microstep's `enq`, which records its stops.
2398                            for op in &outcome.ops {
2399                                if let Op::Stop(r) = op {
2400                                    if let Some((id, _)) = self.st.children.iter().find(|(_, c)| *c == r) {
2401                                        self.record_stopped_child(id);
2402                                    }
2403                                }
2404                            }
2405                            self.outcomes.push((t, outcome));
2406                        }
2407                    }
2408                    return Ok(resolved);
2409                }
2410                let tr = self.m.transition(t);
2411                if tr.function.is_some() {
2412                    // Not selected in this microstep, or its spawn ended the
2413                    // selection: evaluated again, creating its children when
2414                    // taken (`resolveActions`) and only predicting their ids
2415                    // otherwise (`createActors: false`).
2416                    let current = resolver == Resolver::Current;
2417                    if !current {
2418                        self.spawn_mode.set(SpawnMode::Predict);
2419                    }
2420                    let selected = self.eval_function(t);
2421                    self.spawn_mode.set(SpawnMode::Create);
2422                    let selected = selected?;
2423                    let resolved = selected.as_ref().map_or_else(Resolved::default, |s| Resolved {
2424                        targets: s.targets.clone(),
2425                        reenter: s.reenter,
2426                    });
2427                    if current {
2428                        // The microstep's resolver keeps its result.
2429                        let outcome = selected.and_then(|s| s.outcome).unwrap_or_else(Outcome::empty);
2430                        self.outcomes.push((t, outcome));
2431                        let Resolved { targets, reenter } = resolved.clone();
2432                        self.selected.push((t, Selected { targets, reenter, rejected: None, outcome: None }));
2433                    }
2434                    return Ok(resolved);
2435                }
2436                if resolver == Resolver::Current
2437                    && (tr.is_dynamic() || tr.input.is_some())
2438                    && !self.outcomes.iter().any(|(x, _)| *x == t)
2439                {
2440                    let outcome = self.transition_outcome(t)?;
2441                    self.outcomes.push((t, outcome));
2442                }
2443                Ok(Resolved { targets: tr.targets.clone(), reenter: tr.reenter })
2444            }
2445            TRef::Initial(n) => Ok(Resolved { targets: Some(self.m.data(n).initial.clone()), reenter: false }),
2446            TRef::HistoryDefault(h) => {
2447                Ok(Resolved { targets: Some(self.m.data(h).history_target.clone()), reenter: false })
2448            }
2449            TRef::InitialMicrostep => unreachable!("resolved by the core"),
2450        }
2451    }
2452
2453    fn begin_microstep(&mut self) -> Result<(), SystemError> {
2454        crate::ops::count(crate::ops::Op::Microstep);
2455        self.outcomes.clear();
2456        self.cloned = false;
2457        Ok(())
2458    }
2459
2460    fn exit_state(&mut self, node: Nid) -> Result<(), SystemError> {
2461        crate::ops::count(crate::ops::Op::Exit);
2462        let out = self.exit_outcome(node)?;
2463        self.queue.extend(out.internal);
2464        if let Some(ctx) = &out.context {
2465            self.merge_context(ctx)?;
2466        }
2467        self.resolve_ops(out.ops)?;
2468        let stops: Vec<Op<E>> = self
2469            .m
2470            .data(node)
2471            .invokes
2472            .iter()
2473            .filter_map(|inv| self.st.children.get(&inv.id).cloned())
2474            .map(Op::Stop)
2475            .collect();
2476        for op in &stops {
2477            if let Op::Stop(c) = op {
2478                if let Some((id, _)) = self.st.children.iter().find(|(_, r)| *r == c) {
2479                    self.record_stopped_child(id);
2480                }
2481            }
2482        }
2483        self.resolve_ops(stops)?;
2484        Ok(())
2485    }
2486
2487    fn transition_content(&mut self, filtered: &[TRef], _active: &[Nid]) -> Result<(), SystemError> {
2488        let mut ops = Vec::new();
2489        let mut internal = Vec::new();
2490        for &t in filtered {
2491            let TRef::T(t) = t else { continue };
2492            let outcome = match self.outcomes.iter().position(|(x, _)| *x == t) {
2493                Some(i) => self.outcomes.remove(i).1,
2494                None => self.transition_outcome(t)?,
2495            };
2496            if let Some(ctx) = &outcome.context {
2497                self.merge_context(ctx)?;
2498            } else if let Some(t) = outcome.static_patch {
2499                let m = self.m;
2500                self.merge_context(m.transition(t).context.as_ref().expect("a static patch"))?;
2501            }
2502            ops.extend(outcome.ops);
2503            internal.extend(outcome.internal);
2504            if let Some(input) = outcome.input {
2505                self.pending_inputs.push((t, *input));
2506            }
2507        }
2508        self.queue.extend(internal);
2509        self.resolve_ops(ops)?;
2510        Ok(())
2511    }
2512
2513    /// XState's `stateInputMap`: the inputs of states still active, then
2514    /// each transition's input for the targets it enters.
2515    fn begin_entry(&mut self, active: &[Nid], entered: &[(TRef, core::Buf<Nid>)]) -> Result<(), SystemError> {
2516        let pending = std::mem::take(&mut self.pending_inputs);
2517        if self.st.inputs.is_none() && pending.is_empty() {
2518            return Ok(());
2519        }
2520        let mut inputs = self.st.inputs.take().map(|b| *b).unwrap_or_default();
2521        let before = inputs.len();
2522        inputs.retain(|(n, _)| active.contains(n));
2523        let mut changed = inputs.len() != before;
2524        for (t, input) in pending {
2525            let Some((_, targets)) = entered.iter().find(|(r, _)| *r == TRef::T(t)) else { continue };
2526            for &n in targets.iter() {
2527                set_input(&mut inputs, n, input.clone());
2528                changed = true;
2529            }
2530        }
2531        if changed {
2532            self.cloned = true;
2533        }
2534        self.st.inputs = (!inputs.is_empty()).then(|| Box::new(inputs));
2535        Ok(())
2536    }
2537
2538    fn enter_state(&mut self, node: Nid, default_entry: bool, _history_defaults: &[Nid]) -> Result<(), SystemError> {
2539        crate::ops::count(crate::ops::Op::Enter);
2540        self.scope.set(Some(node));
2541        let result = self.enter_state_scoped(node);
2542        self.scope.set(None);
2543        result?;
2544        // The `input` of an object-form `initial`, for the states it enters.
2545        let data = self.m.data(node);
2546        if let Some(input) = data.initial_input.as_ref().filter(|i| default_entry && js_truthy(i)) {
2547            let mut inputs = self.st.inputs.take().map(|b| *b).unwrap_or_default();
2548            for &n in data.initial.iter() {
2549                set_input(&mut inputs, n, input.clone());
2550            }
2551            self.st.inputs = Some(Box::new(inputs));
2552            self.cloned = true;
2553        }
2554        Ok(())
2555    }
2556
2557    fn done_compound(&mut self, parent: Nid, final_child: Nid) -> Result<(), SystemError> {
2558        let output = self.output_of(final_child)?;
2559        let event = self.done_event(parent, output);
2560        self.queue.push_back(event);
2561        Ok(())
2562    }
2563
2564    fn done_parallel(&mut self, parallel: Nid, regions: &[RegionOutput]) -> Result<(), SystemError> {
2565        let mut output = Map::new();
2566        for region in regions {
2567            let (node, value) = match *region {
2568                RegionOutput::Final(r) => (r, self.output_of(r)?),
2569                RegionOutput::Parallel(r) => (r, self.queued_done_output(r)),
2570                RegionOutput::Compound(r, child) => (r, child.map(|c| self.output_of(c)).transpose()?.flatten()),
2571            };
2572            if let Some(value) = value {
2573                output.insert(self.m.data(node).key.clone(), value);
2574            }
2575        }
2576        let event = self.done_event(parallel, Some(Value::Object(output)));
2577        self.queue.push_back(event);
2578        Ok(())
2579    }
2580
2581    fn machine_done(&mut self, completion: Nid) -> Result<(), SystemError> {
2582        let tree = &self.m.tree;
2583        let completion_output = if self.m.data(completion).output.is_some() && tree.node(completion).parent.is_some() {
2584            let root_done =
2585                if tree.node(completion).parent == Some(ROOT) { self.queued_done_output(ROOT) } else { None };
2586            match root_done {
2587                Some(done) => Some(done),
2588                None => self.output_of(completion)?,
2589            }
2590        } else if tree.kind(completion) == core::Kind::Parallel {
2591            self.queued_done_output(completion)
2592        } else {
2593            None
2594        };
2595        self.st.status = Status::Done;
2596        self.st.output = match &self.m.output {
2597            Some(Template::Static(output)) => Some(Box::new(output.clone())),
2598            // Computed with the completing state's done event.
2599            Some(output) => {
2600                let event = self.done_event(completion, completion_output);
2601                Some(Box::new(self.eval_for(output, &self.st.context, &event, None)?))
2602            }
2603            None if tree.node(completion).parent == Some(ROOT) => completion_output.map(Box::new),
2604            None => None,
2605        };
2606        self.cloned = true;
2607        Ok(())
2608    }
2609
2610    fn end_entry(&mut self) -> Result<(), SystemError> {
2611        Ok(())
2612    }
2613
2614    fn is_done(&self) -> bool {
2615        self.st.status == Status::Done
2616    }
2617
2618    fn exit_on_done(&mut self, nodes_desc: &[Nid]) -> Result<(), SystemError> {
2619        let mut ops = Vec::new();
2620        for &node in nodes_desc {
2621            crate::ops::count(crate::ops::Op::Exit);
2622            let out = self.exit_outcome(node)?;
2623            if let Some(ctx) = &out.context {
2624                self.merge_context(ctx)?;
2625            }
2626            ops.extend(out.ops);
2627            self.queue.extend(out.internal);
2628        }
2629        self.resolve_ops(ops)?;
2630        let stops = self.stop_children_ops();
2631        self.resolve_ops(stops)?;
2632        let cancels = self.cancel_timer_ops();
2633        self.resolve_ops(cancels)?;
2634        Ok(())
2635    }
2636
2637    fn apply_microstep(&mut self, result: Option<MicrostepResult>, _enabled: &[TRef]) -> Result<(), SystemError> {
2638        if let Some(r) = result {
2639            if r.structure_changed {
2640                self.st.nodes.clear();
2641                self.st.nodes.extend_from_slice(&r.nodes);
2642                for (h, nodes) in r.history_updates {
2643                    let history = self.history_mut();
2644                    match history.iter_mut().find(|(x, _)| *x == h) {
2645                        Some(entry) => entry.1 = nodes,
2646                        None => history.push((h, nodes)),
2647                    }
2648                }
2649                self.cloned = true;
2650            }
2651        }
2652        if self.cloned {
2653            self.token += 1;
2654        }
2655        let token = self.token;
2656        self.remove_terminated_child();
2657        // The identity the loop compares is the microstep's own result.
2658        self.microstep_token_value = token;
2659        Ok(())
2660    }
2661
2662    fn is_active(&self) -> bool {
2663        self.st.status == Status::Active
2664    }
2665
2666    fn check_iteration(&mut self, iteration: usize) -> Result<(), SystemError> {
2667        // Unbounded without `options.maxIterations`, as in XState.
2668        let Some(max_iterations) = self.m.options.max_iterations else {
2669            return Ok(());
2670        };
2671        if iteration > max_iterations {
2672            return Err(SystemError::InfiniteLoop {
2673                actor_id: self.cx.borrow().self_id(),
2674                event_type: self.macrostep_event.as_ref().unwrap_or(&self.event).event_type().to_owned(),
2675                max_iterations,
2676                states: self.recent.iter().map(|c| self.m.state_value(c)).collect(),
2677            });
2678        }
2679        // The error reports the configurations of the last five iterations
2680        // before the bound, so only those are recorded.
2681        if iteration + 5 <= max_iterations {
2682            return Ok(());
2683        }
2684        if self.recent.len() == 5 {
2685            let mut oldest = self.recent.pop_front().unwrap_or_default();
2686            oldest.clone_from(&self.st.nodes);
2687            self.recent.push_back(oldest);
2688        } else {
2689            self.recent.push_back(self.st.nodes.clone());
2690        }
2691        Ok(())
2692    }
2693
2694    fn snapshot_token(&self) -> u64 {
2695        self.token
2696    }
2697
2698    fn microstep_token(&self) -> u64 {
2699        self.microstep_token_value
2700    }
2701
2702    fn drain_raised(&mut self) -> Result<(), SystemError> {
2703        Ok(())
2704    }
2705
2706    fn queue_is_empty(&self) -> bool {
2707        self.queue.is_empty()
2708    }
2709
2710    fn dequeue(&mut self) -> Result<Option<String>, SystemError> {
2711        Ok(self.queue.pop_front().map(|e| {
2712            crate::ops::count(crate::ops::Op::InternalEvent);
2713            let ty = e.event_type().to_owned();
2714            let previous = std::mem::replace(&mut self.event, e);
2715            // The macrostep's own event, which XState's infinite-loop error
2716            // names, outlives the internal events after it.
2717            if self.macrostep_event.is_none() {
2718                self.macrostep_event = Some(previous);
2719            }
2720            ty
2721        }))
2722    }
2723}
2724
2725impl<C, E> Machine<C, E>
2726where
2727    C: Serialize + DeserializeOwned + Clone + 'static,
2728    E: EventType,
2729{
2730    /// One macrostep of XState's machine logic (`initialTransition` or
2731    /// `transition`): the effects it produces, in order, including deferred
2732    /// child starts and the termination effect.
2733    pub(crate) fn run_macrostep(
2734        &self,
2735        st: &mut State<C, E>,
2736        cx: &mut dyn Context,
2737        event: MacroEvent,
2738    ) -> Result<Vec<Effect>, SystemError> {
2739        crate::ops::count(crate::ops::Op::Macrostep);
2740        let initial = matches!(event, MacroEvent::Init);
2741        let previous_status = st.status;
2742        // A macrostep that throws leaves the previous snapshot in the error
2743        // status, as XState's actor does (`_setErrorSnapshot`); the failed
2744        // step's state and effects are discarded. The context is saved on
2745        // its first write.
2746        let saved = (!initial).then(|| Saved::of(st));
2747        let live = cx.live_errors();
2748        let mut h = NativeHost::new(self, st, cx, !initial);
2749        if let Err(e) = self.macrostep_body(&mut h, event) {
2750            let context = h.context_backup.take();
2751            let undo = std::mem::take(&mut h.context_undo);
2752            let parts = std::mem::take(&mut h.saved_parts);
2753            if let Some(saved) = saved {
2754                saved.restore(st, parts);
2755                st.context_normalized = false;
2756                if let Some(context) = context {
2757                    st.context = context;
2758                }
2759                if let Some(Value::Object(map)) = (&mut st.context as &mut dyn Any).downcast_mut::<Value>() {
2760                    // In reverse: a replaced value goes back to its place,
2761                    // and an added key (the last one at that point) leaves.
2762                    for (key, old) in undo.into_iter().rev() {
2763                        match old {
2764                            Some(old) => {
2765                                map.insert(key, old);
2766                            }
2767                            None => {
2768                                map.shift_remove(&key);
2769                            }
2770                        }
2771                    }
2772                }
2773            }
2774            // The pure system API fails the actor here; a live one recovers
2775            // or fails from the restored snapshot (`System::recover_or_fail`).
2776            if !live || initial {
2777                st.status = Status::Error;
2778                st.error = Some(Box::new(e.to_value()));
2779            }
2780            return Err(e);
2781        }
2782        let mut effects = std::mem::take(&mut h.effects);
2783        let status = h.st.status;
2784        // `completeMacrostep`: children start after the snapshot is committed.
2785        let starts: Vec<Effect> = effects
2786            .iter()
2787            .filter_map(|e| match e {
2788                Effect::Spawn(r) => Some(Effect::Start(r.clone())),
2789                _ => None,
2790            })
2791            .collect();
2792        effects.extend(starts);
2793        if (previous_status == Status::Active || initial) && matches!(status, Status::Done | Status::Error) {
2794            effects.push(Effect::Terminate);
2795        }
2796        Ok(effects)
2797    }
2798
2799    /// XState's `snapshot.check(event)` (`StateMachine._checkTransition`):
2800    /// the event's transitions selected as a macrostep selects them (guards
2801    /// and transition functions run, an `enq` only records), on a copy of
2802    /// the snapshot, and none taken. A transition that rejects the event
2803    /// gives its rejection; one that has a target, a transition function
2804    /// (enabled, whatever it returns), `context` or `actions` accepts it; a
2805    /// selected transition with none of them (`{}`, a guard alone) neither
2806    /// accepts nor rejects it, but still keeps its ancestors from being
2807    /// searched. Conflicts between the selected transitions are not
2808    /// resolved, as only targeted transitions conflict, and each of them
2809    /// accepts the event.
2810    pub(crate) fn check_event(
2811        &self,
2812        st: &State<C, E>,
2813        cx: &mut dyn Context,
2814        event: &Value,
2815    ) -> Result<TransitionCheck, SystemError> {
2816        if st.status != Status::Active {
2817            return Ok(TransitionCheck::Unhandled);
2818        }
2819        let ty = event
2820            .get("type")
2821            .and_then(Value::as_str)
2822            .ok_or_else(|| SystemError::Rejected("an event must have a string \"type\"".into()))?;
2823        let mut st = st.clone();
2824        let mut h = NativeHost::new(self, &mut st, cx, true);
2825        h.event = Ev::from_json(event.clone()).expect("an object with a string type");
2826        let transitions = core::select_event_transitions(&self.tree, &mut h, ty)?;
2827        let mut rejections = Vec::new();
2828        let mut accepted = false;
2829        for &t in transitions.iter() {
2830            let reasons = h.selected.iter().find(|(x, _)| *x == t).and_then(|(_, s)| s.rejected.as_deref());
2831            if let Some(reasons) = reasons {
2832                let source = self.data(self.tree.transitions[t as usize].source).id.clone();
2833                rejections
2834                    .push(TransitionRejection { source, reasons: reasons.as_array().cloned().unwrap_or_default() });
2835                continue;
2836            }
2837            let tr = self.transition(t);
2838            accepted |= tr.targets.is_some()
2839                || tr.function.is_some()
2840                || tr.context.is_some()
2841                || tr.context_expr.is_some()
2842                || !tr.actions.is_empty();
2843        }
2844        Ok(match (accepted, rejections.is_empty()) {
2845            (true, true) => TransitionCheck::Accepted,
2846            (false, true) => TransitionCheck::Unhandled,
2847            (true, false) => TransitionCheck::Partial(rejections),
2848            (false, false) => TransitionCheck::Rejected(rejections),
2849        })
2850    }
2851
2852    /// Whether `st` selects a transition of `event`, as [`Self::check_event`]
2853    /// selects them: any transition, also one that neither accepts nor
2854    /// rejects it, or one that rejects it (XState's
2855    /// `!isUnhandled(transition(...))`). None of a snapshot that is not
2856    /// active.
2857    pub(crate) fn handles_event(
2858        &self,
2859        st: &State<C, E>,
2860        cx: &mut dyn Context,
2861        event: &Value,
2862    ) -> Result<bool, SystemError> {
2863        if st.status != Status::Active {
2864            return Ok(false);
2865        }
2866        let ty = event
2867            .get("type")
2868            .and_then(Value::as_str)
2869            .ok_or_else(|| SystemError::Rejected("an event must have a string \"type\"".into()))?;
2870        let mut st = st.clone();
2871        let mut h = NativeHost::new(self, &mut st, cx, true);
2872        h.selection_alone = true;
2873        h.event = Ev::from_json(event.clone()).expect("an object with a string type");
2874        Ok(!core::select_event_transitions(&self.tree, &mut h, ty)?.is_empty())
2875    }
2876
2877    fn macrostep_body(&self, h: &mut NativeHost<'_, C, E>, event: MacroEvent) -> Result<(), SystemError> {
2878        let tree = &self.tree;
2879        let event = match event {
2880            MacroEvent::Init => {
2881                h.event = Ev::Init;
2882                core::initial_microstep(tree, h)?;
2883                return core::run_to_completion(tree, h);
2884            }
2885            MacroEvent::Event(event) => event,
2886            MacroEvent::Timer(key, occurrence) => {
2887                if h.st.status != Status::Active || !h.fire_timer(Some(key), occurrence.map(Some)) {
2888                    return Ok(());
2889                }
2890                return core::run_after_timer(tree, h);
2891            }
2892        };
2893        if h.st.status != Status::Active {
2894            return Ok(());
2895        }
2896        // The type outlives the event (moved into the host below).
2897        let ty = TypeName::of(event.get("type").and_then(Value::as_str).unwrap_or(""));
2898        let ty = ty.as_str();
2899        match ty {
2900            "xstate.stop" => {
2901                let stops = h.stop_children_ops();
2902                h.resolve_ops(stops)?;
2903                let cancels = h.cancel_timer_ops();
2904                h.resolve_ops(cancels)?;
2905                h.st.status = Status::Stopped;
2906                return Ok(());
2907            }
2908            "xstate.timer" => {
2909                let occurrence = event.get("occurrence").map(Value::as_u64);
2910                if !h.fire_timer(TimerKey::of_timer_event(&event), occurrence) {
2911                    return Ok(());
2912                }
2913                return core::run_after_timer(tree, h);
2914            }
2915            _ => {
2916                h.event = Ev::from_json(event)
2917                    .ok_or_else(|| SystemError::Rejected("an event must have a string \"type\"".into()))?;
2918                let mut transitions = core::select_event_transitions(tree, h, ty)?;
2919                // A transition that rejected the event handles it, but is
2920                // not taken.
2921                let rejected = transitions.iter().any(|&t| h.rejected(t));
2922                transitions.retain(|&t| !h.rejected(t));
2923                if ty.starts_with("xstate.error.") && transitions.is_empty() && !rejected {
2924                    if ty == "xstate.error.actor" {
2925                        let actor_id = h.event.field("actorId").and_then(|v| v.as_str().map(str::to_owned));
2926                        if let Some(actor_id) = actor_id {
2927                            if !h.matches_session(&actor_id) {
2928                                return Ok(());
2929                            }
2930                        }
2931                    }
2932                    h.st.status = Status::Error;
2933                    h.st.error = h.event.field("error").map(Box::new);
2934                    h.remove_terminated_child();
2935                    return Ok(());
2936                }
2937                let enabled: core::Buf<TRef> = transitions.iter().map(|&t| TRef::T(t)).collect();
2938                core::microstep(tree, h, &enabled, None)?;
2939            }
2940        }
2941        core::run_to_completion(tree, h)
2942    }
2943
2944    /// XState's snapshot data for a machine snapshot (`snapshotData`).
2945    pub(crate) fn snapshot_data(&self, st: &State<C, E>) -> Value {
2946        let mut m = Map::new();
2947        m.insert("status".into(), json!(st.status.as_str()));
2948        if let Some(o) = &st.output {
2949            m.insert("output".into(), (**o).clone());
2950        }
2951        if let Some(e) = &st.error {
2952            m.insert("error".into(), (**e).clone());
2953        }
2954        m.insert("context".into(), context_json(&st.context));
2955        m.insert("value".into(), self.state_value(&st.nodes));
2956        m.insert("children".into(), Value::Object(st.children.iter().map(|(k, r)| (k.clone(), r.to_json())).collect()));
2957        m.insert("timers".into(), Value::Array(st.timers.iter().map(LogicalTimer::to_data).collect()));
2958        m.insert(
2959            "historyValue".into(),
2960            Value::Object(
2961                st.history
2962                    .iter()
2963                    .map(|(h, nodes)| {
2964                        let refs = nodes.iter().map(|&n| json!({ "@stateNode": self.data(n).id })).collect();
2965                        (self.data(*h).id.clone(), Value::Array(refs))
2966                    })
2967                    .collect(),
2968            ),
2969        );
2970        m.insert("stateInputs".into(), self.inputs_json(st));
2971        m.insert("nextTimerId".into(), json!(st.next_timer_id));
2972        if st.next_timer_occurrence > 0 {
2973            m.insert("nextTimerOccurrence".into(), json!(st.next_timer_occurrence));
2974        }
2975        if let Some(ids) = &st.actor_ids {
2976            m.insert("nextActorIds".into(), Value::Object(ids.iter().map(|(p, n)| (p.clone(), json!(n))).collect()));
2977        }
2978        m.insert("nodeIds".into(), Value::Array(st.nodes.iter().map(|&n| json!(self.data(n).id)).collect()));
2979        Value::Object(m)
2980    }
2981
2982    /// `stateInputs`: inputs by state id.
2983    fn inputs_json(&self, st: &State<C, E>) -> Value {
2984        Value::Object(
2985            st.inputs.iter().flat_map(|i| i.iter()).map(|(n, v)| (self.data(*n).id.clone(), v.clone())).collect(),
2986        )
2987    }
2988
2989    /// Rebuilds a machine snapshot from [`Machine::snapshot_data`].
2990    pub(crate) fn restore_state(&self, data: &Value) -> Result<State<C, E>, SystemError> {
2991        let bad = |what: &str| SystemError::Rejected(format!("invalid machine snapshot: {what}"));
2992        let lookup = |id: &str| {
2993            self.node_by_id(id).ok_or_else(|| {
2994                SystemError::Rejected(format!("state \"{id}\" does not exist in this machine definition"))
2995            })
2996        };
2997        let context = C::deserialize(data.get("context").unwrap_or(&Value::Null))
2998            .map_err(|e| SystemError::Rejected(format!("context does not fit the context type: {e}")))?;
2999        let mut st = State::new(context, &self.empty);
3000        st.status = crate::system::parse_status(data)?;
3001        st.output = data.get("output").cloned().map(Box::new);
3002        st.error = data.get("error").cloned().map(Box::new);
3003        st.nodes = data
3004            .get("nodeIds")
3005            .and_then(Value::as_array)
3006            .ok_or_else(|| bad("nodeIds"))?
3007            .iter()
3008            .map(|v| lookup(v.as_str().unwrap_or("")))
3009            .collect::<Result<_, _>>()?;
3010        self.check_configuration(&st.nodes)?;
3011        for (h, recorded) in data.get("historyValue").and_then(Value::as_object).into_iter().flatten() {
3012            let h = lookup(h)?;
3013            let nodes = recorded
3014                .as_array()
3015                .ok_or_else(|| bad("historyValue"))?
3016                .iter()
3017                .map(|r| lookup(r.get("@stateNode").and_then(Value::as_str).unwrap_or("")))
3018                .collect::<Result<_, _>>()?;
3019            Arc::make_mut(&mut st.history).push((h, nodes));
3020        }
3021        for (k, r) in data.get("children").and_then(Value::as_object).into_iter().flatten() {
3022            Arc::make_mut(&mut st.children).insert(k.clone(), ActorRef::from_json(r).ok_or_else(|| bad("children"))?);
3023        }
3024        for t in data.get("timers").and_then(Value::as_array).into_iter().flatten() {
3025            let event =
3026                Ev::from_json(t.get("event").cloned().unwrap_or(Value::Null)).ok_or_else(|| bad("timer event"))?;
3027            Arc::make_mut(&mut st.timers).push(LogicalTimer {
3028                occurrence: t.get("occurrence").and_then(Value::as_u64),
3029                id: t.get("id").and_then(Value::as_str).map(str::to_owned),
3030                seq: t.get("seq").and_then(Value::as_u64),
3031                delay: t.get("delay").and_then(Value::as_u64).unwrap_or(0),
3032                event: TimerEv::new(event),
3033                target: TimerTarget::from_json(t.get("type"), t.get("target")).ok_or_else(|| bad("timer target"))?,
3034            });
3035        }
3036        st.next_timer_id = data.get("nextTimerId").and_then(Value::as_u64).unwrap_or(0);
3037        // As XState's pure system decodes it: past every pending timer's
3038        // occurrence.
3039        st.next_timer_occurrence = st
3040            .timers
3041            .iter()
3042            .filter_map(|t| t.occurrence)
3043            .map(|o| o + 1)
3044            .fold(data.get("nextTimerOccurrence").and_then(Value::as_u64).unwrap_or(0), u64::max);
3045        let mut inputs = Vec::new();
3046        for (id, input) in data.get("stateInputs").and_then(Value::as_object).into_iter().flatten() {
3047            inputs.push((lookup(id)?, input.clone()));
3048        }
3049        st.inputs = (!inputs.is_empty()).then(|| Box::new(inputs));
3050        // `nextActorIds` as persisted (XState's pure system decodes it
3051        // without folding in the children's ids).
3052        let ids: Vec<(String, u64)> = data
3053            .get("nextActorIds")
3054            .and_then(Value::as_object)
3055            .into_iter()
3056            .flatten()
3057            .map(|(p, n)| (p.clone(), n.as_u64().unwrap_or(0)))
3058            .collect();
3059        st.actor_ids = (!ids.is_empty()).then(|| Box::new(ids));
3060        Ok(st)
3061    }
3062
3063    /// Checks that a configuration is legal.
3064    /// What restore checks: every state at most once, and no history state.
3065    /// The configuration need not be legal: XState can produce illegal ones
3066    /// (fixture `conflicting_regions`) and restores whatever ids it is given.
3067    fn check_configuration(&self, nodes: &[Nid]) -> Result<(), SystemError> {
3068        let mut active = vec![false; self.nodes.len()];
3069        for &n in nodes {
3070            let id = &self.data(n).id;
3071            if std::mem::replace(&mut active[n as usize], true) {
3072                return Err(SystemError::Rejected(format!("state \"{id}\" appears twice")));
3073            }
3074            if matches!(self.tree.kind(n), core::Kind::History { .. }) {
3075                return Err(SystemError::Rejected(format!("history state \"{id}\" cannot be active")));
3076            }
3077        }
3078        Ok(())
3079    }
3080}
3081
3082/// The type of XState's execution error event (`createErrorPlatformEvent`).
3083const ERROR_EXECUTION: &str = "xstate.error.execution";
3084
3085impl<C, E> Machine<C, E>
3086where
3087    C: Serialize + DeserializeOwned + Clone + Send + Sync + 'static,
3088    E: EventType + Send + Sync,
3089{
3090    /// XState's `getExecutionErrorEvent`: `{ type: "xstate.error.execution",
3091    /// error }` when an active state of `st` declares `onError`.
3092    fn error_event(&self, st: &State<C, E>, error: &Value) -> Option<Value> {
3093        (st.status == Status::Active && st.nodes.iter().any(|&n| self.data(n).on_error))
3094            .then(|| json!({ "type": ERROR_EXECUTION, "error": error }))
3095    }
3096
3097    /// The snapshot of an actor whose context factory threw `error`
3098    /// (XState's error snapshot of `initialTransition`): the root
3099    /// configuration, an empty context (a computed context is `{}`), no
3100    /// children, in the `error` status. A context type that cannot be empty
3101    /// leaves only the error ([`FailedStart`]), as a start that throws
3102    /// elsewhere does.
3103    fn error_state(&self, error: Value) -> Box<dyn AnySnapshot> {
3104        match C::deserialize(&json!({})) {
3105            Ok(context) => {
3106                let mut st = State::new(context, &self.empty);
3107                st.status = Status::Error;
3108                st.error = Some(Box::new(error));
3109                Box::new(st)
3110            }
3111            Err(_) => Box::new(FailedStart { error }),
3112        }
3113    }
3114}
3115
3116impl<C, E> Logic for Machine<C, E>
3117where
3118    C: Serialize + DeserializeOwned + Clone + Send + Sync + 'static,
3119    E: EventType + Send + Sync,
3120{
3121    fn version(&self) -> Option<&str> {
3122        self.version.as_deref()
3123    }
3124
3125    fn logic_id(&self) -> Option<String> {
3126        Some(self.id.clone().unwrap_or_else(|| "(machine)".into()))
3127    }
3128
3129    fn initial_transition(&self, input: Option<&Value>, cx: &mut dyn Context) -> Result<Transition, SystemError> {
3130        if let Some(e) = &self.start_error {
3131            return Err(SystemError::Failed(e.clone()));
3132        }
3133        let mut spawned = Vec::new();
3134        let mut actor_ids = Vec::new();
3135        let context = match &self.initial_context {
3136            InitialContext::Value(c) => c.clone(),
3137            InitialContext::Template(t) => {
3138                let spawner = ContextSpawner {
3139                    actors: &self.actors,
3140                    cx: RefCell::new(&mut *cx),
3141                    spawned: RefCell::new(Vec::new()),
3142                    counters: RefCell::new(Vec::new()),
3143                    error: RefCell::new(None),
3144                };
3145                let args = ContextArgs { input, spawner: Some(&spawner) };
3146                let value = t.eval(&mut |i| (self.context_exprs[i as usize])(&args));
3147                if let Some(e) = spawner.error.into_inner() {
3148                    // A context factory that throws starts the actor in
3149                    // `error`, in XState's pure and live APIs alike.
3150                    return Ok(Transition { snapshot: self.error_state(e.to_value()), effects: Vec::new() });
3151                }
3152                spawned = spawner.spawned.into_inner();
3153                actor_ids = spawner.counters.into_inner();
3154                C::deserialize(&value).map_err(|e| {
3155                    SystemError::Failed(format!("the computed context does not fit the context type: {e}"))
3156                })?
3157            }
3158        };
3159        let mut st = State::new(context, &self.empty);
3160        // Children the context factory spawned: allocated already, started
3161        // with the actor, before anything its initial states invoke.
3162        let mut effects = Vec::with_capacity(spawned.len());
3163        if !spawned.is_empty() {
3164            let children = Arc::make_mut(&mut st.children);
3165            for (id, child) in spawned {
3166                children.insert(id, child.clone());
3167                effects.push(Effect::Spawn(child));
3168            }
3169        }
3170        if !actor_ids.is_empty() {
3171            st.actor_ids = Some(Box::new(actor_ids));
3172        }
3173        // A root with `onError` recovers from an initial macrostep that
3174        // throws by a macrostep for the execution error from the state
3175        // before it (XState's `initialTransition`).
3176        let pre_initial = self.data(ROOT).on_error.then(|| st.clone());
3177        let rest = match (self.run_macrostep(&mut st, cx, MacroEvent::Init), pre_initial) {
3178            (Ok(rest), _) => rest,
3179            (Err(e), Some(pre)) if e.is_execution_error() => {
3180                st = pre;
3181                let event = json!({ "type": ERROR_EXECUTION, "error": e.to_value() });
3182                self.run_macrostep(&mut st, cx, MacroEvent::Event(event))?
3183            }
3184            (Err(e), _) => return Err(e),
3185        };
3186        // They start first too, in the order of `children`.
3187        let starts: Vec<Effect> = effects
3188            .iter()
3189            .filter_map(|e| match e {
3190                Effect::Spawn(r) => Some(Effect::Start(r.clone())),
3191                _ => None,
3192            })
3193            .collect();
3194        let at = rest.iter().position(|e| matches!(e, Effect::Start(_))).unwrap_or(rest.len());
3195        let mut rest = rest.into_iter();
3196        effects.extend(rest.by_ref().take(at));
3197        effects.extend(starts);
3198        effects.extend(rest);
3199        Ok(Transition { snapshot: Box::new(st), effects })
3200    }
3201
3202    fn transition(
3203        &self,
3204        snapshot: &mut Box<dyn AnySnapshot>,
3205        event: Value,
3206        cx: &mut dyn Context,
3207    ) -> Result<Vec<Effect>, SystemError> {
3208        let st = snapshot
3209            .as_any_mut()
3210            .downcast_mut::<State<C, E>>()
3211            .ok_or_else(|| SystemError::Failed("machine received a foreign snapshot".into()))?;
3212        self.run_macrostep(st, cx, MacroEvent::Event(event))
3213    }
3214
3215    fn check(
3216        &self,
3217        snapshot: &dyn AnySnapshot,
3218        event: &Value,
3219        cx: &mut dyn Context,
3220    ) -> Result<TransitionCheck, SystemError> {
3221        // A root whose start threw has only its error, in the `error` status.
3222        if snapshot.status() != Status::Active {
3223            return Ok(TransitionCheck::Unhandled);
3224        }
3225        let st = snapshot
3226            .as_any()
3227            .downcast_ref::<State<C, E>>()
3228            .ok_or_else(|| SystemError::Failed("machine received a foreign snapshot".into()))?;
3229        self.check_event(st, cx, event)
3230    }
3231
3232    fn handles(&self, snapshot: &dyn AnySnapshot, event: &Value, cx: &mut dyn Context) -> Result<bool, SystemError> {
3233        if snapshot.status() != Status::Active {
3234            return Ok(false);
3235        }
3236        let st = snapshot
3237            .as_any()
3238            .downcast_ref::<State<C, E>>()
3239            .ok_or_else(|| SystemError::Failed("machine received a foreign snapshot".into()))?;
3240        self.handles_event(st, cx, event)
3241    }
3242
3243    fn timer_transition(
3244        &self,
3245        snapshot: &mut Box<dyn AnySnapshot>,
3246        key: TimerKey,
3247        occurrence: Option<u64>,
3248        cx: &mut dyn Context,
3249    ) -> Result<Vec<Effect>, SystemError> {
3250        let st = snapshot
3251            .as_any_mut()
3252            .downcast_mut::<State<C, E>>()
3253            .ok_or_else(|| SystemError::Failed("machine received a foreign snapshot".into()))?;
3254        self.run_macrostep(st, cx, MacroEvent::Timer(key, occurrence))
3255    }
3256
3257    fn snapshot_data(&self, snapshot: &dyn AnySnapshot) -> Value {
3258        match snapshot.as_any().downcast_ref::<State<C, E>>() {
3259            Some(st) => Machine::snapshot_data(self, st),
3260            None => Value::Null,
3261        }
3262    }
3263
3264    fn snapshot_serialize<'a>(
3265        &'a self,
3266        snapshot: &'a dyn AnySnapshot,
3267        compact: bool,
3268    ) -> Box<dyn erased_serde::Serialize + 'a> {
3269        match snapshot.as_any().downcast_ref::<State<C, E>>() {
3270            Some(st) => Box::new(SnapshotView { m: self, st, compact }),
3271            None => Box::new(Value::Null),
3272        }
3273    }
3274
3275    fn restore(&self, data: &Value) -> Result<Box<dyn AnySnapshot>, SystemError> {
3276        Ok(Box::new(self.restore_state(data)?))
3277    }
3278
3279    fn is_internal_event_type(&self, event_type: &str) -> bool {
3280        event_type == "xstate.timer" || self.is_internal_event(event_type)
3281    }
3282
3283    fn actor_sources(&self) -> Vec<(String, Arc<dyn Logic>)> {
3284        self.actors.clone()
3285    }
3286
3287    fn execution_error_event(&self, snapshot: &dyn AnySnapshot, error: &Value) -> Option<Value> {
3288        self.error_event(snapshot.as_any().downcast_ref::<State<C, E>>()?, error)
3289    }
3290}