Skip to main content

xmachines_runtime/
machine.rs

1//! The compiled form of a JSON machine definition: the structural [`Tree`]
2//! shared with every host, plus the values the native host needs.
3
4use std::sync::Arc;
5
6use serde_json::{Map, Value};
7
8use crate::core::{Nid, Tid, Tree};
9use crate::event::{matches_descriptor, Ev};
10use crate::registry::{ActionFn, ContextFn, DelayFn, ExprFn, Factory, GuardFn};
11use crate::system::{EffectExec, Logic};
12use crate::FixedMap;
13
14/// Index of a state node, in document order.
15pub type NodeId = Nid;
16
17pub(crate) const ROOT: Nid = 0;
18
19/// Per-node values.
20pub(crate) struct NodeData {
21    pub key: String,
22    pub id: String,
23    pub entry: Vec<Action>,
24    pub exit: Vec<Action>,
25    /// Delayed transitions' timers, in XState's order: `after` entries,
26    /// the state `timeout`, then invoke timeouts.
27    pub delayed: Vec<DelayedDef>,
28    pub invokes: Vec<InvokeDef>,
29    pub output: Option<Template>,
30    pub tags: Vec<String>,
31    /// The static targets of a compound state's `initial`.
32    pub initial: Arc<[Nid]>,
33    /// The `input` of an object-form `initial` (`{ target, input }`), for
34    /// the states it enters (taken as it is: XState does not evaluate it).
35    pub initial_input: Option<Value>,
36    /// The default targets of a history state.
37    pub history_target: Arc<[Nid]>,
38    /// Whether the state declares `onError`, which recovers an actor from
39    /// an execution error (XState's `getExecutionErrorEvent`).
40    pub on_error: bool,
41}
42
43/// A timer a state schedules on entry and cancels on exit; its event is
44/// caught by the state's delayed transitions.
45pub(crate) struct DelayedDef {
46    pub kind: DelayedKind,
47    pub delay: DelaySpec,
48}
49
50pub(crate) enum DelayedKind {
51    /// `after`: raises `{ type: "xstate.after", delay, stateId }`, where
52    /// `delay` is a number for numeric keys and the key string otherwise.
53    After { event_delay: Value },
54    /// The state `timeout`: raises `{ type: "xstate.timeout.state", stateId }`.
55    StateTimeout,
56    /// An invoke `timeout`: raises `{ type: "xstate.timeout.actor", actorId, sessionId }`.
57    InvokeTimeout { invoke_id: String },
58}
59
60/// One `invoke` of a state.
61pub(crate) struct InvokeDef {
62    pub id: String,
63    pub logic: Arc<dyn Logic>,
64    pub input: Option<Template>,
65    pub registry_key: Option<String>,
66    /// Whether the invoke has `onSnapshot` (the child then reports snapshots).
67    pub sync_snapshot: bool,
68}
69
70/// A custom action reference: its name and params, and the bound Rust
71/// implementation (if the registry provides one).
72pub(crate) struct CustomAction {
73    pub name: String,
74    pub params: Option<Value>,
75    pub exec: EffectExec,
76}
77
78/// A custom action or guard whose `params` hold expressions: its
79/// implementation is bound to the params each time it runs.
80pub(crate) struct Dynamic<T> {
81    pub name: String,
82    pub factory: Factory<T>,
83    pub params: Template,
84}
85
86/// A JSON value with expressions in it (XState's resolvable values).
87#[derive(Debug, Clone)]
88pub(crate) enum Template {
89    Static(Value),
90    /// Index into `Machine::exprs` (or `Machine::context_exprs` in the root
91    /// `context`).
92    Expr(u32),
93    Object(Vec<(String, Template)>),
94    Array(Vec<Template>),
95}
96
97impl Template {
98    /// The value, with `expr` computing each expression.
99    pub fn eval(&self, expr: &mut dyn FnMut(u32) -> Value) -> Value {
100        match self {
101            Template::Static(v) => v.clone(),
102            Template::Expr(i) => expr(*i),
103            Template::Object(fields) => Value::Object(fields.iter().map(|(k, t)| (k.clone(), t.eval(expr))).collect()),
104            Template::Array(items) => Value::Array(items.iter().map(|t| t.eval(expr)).collect()),
105        }
106    }
107}
108
109#[derive(Debug, Clone, Copy)]
110pub(crate) enum DelaySpec {
111    Fixed(u64),
112    Named(u32),
113    /// An expression (index into `Machine::exprs`): milliseconds or a
114    /// duration string.
115    Expr(u32),
116}
117
118pub(crate) struct TransitionData {
119    /// `None` for a targetless transition.
120    pub targets: Option<Arc<[Nid]>>,
121    pub matches: Vec<(String, Value)>,
122    pub guard: Option<Guard>,
123    /// The transition's `context` patch.
124    pub context: Option<Map<String, Value>>,
125    /// Instead of `context`: a patch with expressions in it.
126    pub context_expr: Option<Template>,
127    pub actions: Vec<Action>,
128    pub reenter: bool,
129    /// For invoke completion transitions: the child's id, whose session must
130    /// match the event's `sessionId` (XState's `_eventMatcher`).
131    pub session: Option<String>,
132    /// For completion transitions of an invoke with a `timeout`: the timer
133    /// key the transition cancels after its own operations.
134    pub cancel_timeout: Option<crate::system::TimerKey>,
135    /// A transition function (an expression in the `transition` slot):
136    /// its result gives the targets, context and `reenter`.
137    pub function: Option<TransitionFn>,
138    /// The `input` the transition gives the states it enters.
139    pub input: Option<Template>,
140    /// [`TransitionData::evaluates`], computed once after loading.
141    pub selects: bool,
142}
143
144/// XState's error for rejection reasons that are not a nonempty array of
145/// objects with a string `type`.
146pub(crate) const REJECT_REASONS: &str =
147    "reject(...) requires a nonempty array of rejection objects with a string type.";
148
149/// A transition computed when it is selected, as XState's `to` functions
150/// (expression indices are into `Machine::exprs`).
151#[derive(Debug, Clone)]
152pub(crate) enum TransitionFn {
153    /// A transition expression, with `enq`.
154    Expr(u32),
155    /// A route function: its state is the target of every result (a falsy
156    /// result blocks the route, `true` takes it as it is).
157    Route { expr: u32, target: Arc<[Nid]> },
158    /// A choice state's expression, which must give a target.
159    ChoiceExpr { expr: u32, id: String },
160    /// A choice state's branches: the first whose `when` passes.
161    Choice { branches: Vec<ChoiceBranch>, path: String, id: String },
162    /// A JSON rejecting transition (`{ reject: [...] }`): its reasons, as
163    /// `machineFromJSON` compiles it to a transition function returning
164    /// `reject(reasons)`.
165    Reject(Template),
166}
167
168#[derive(Debug, Clone)]
169pub(crate) struct ChoiceBranch {
170    pub when: Option<Guard>,
171    pub targets: Option<Arc<[Nid]>>,
172    pub context: Option<Template>,
173    pub input: Option<Template>,
174    pub reenter: bool,
175}
176
177impl TransitionData {
178    /// Whether XState compiles this transition to a transition function
179    /// (`machineFromJSON` does so for any `context` or `actions`; invoke
180    /// timeouts wrap completion transitions in one).
181    pub fn is_dynamic(&self) -> bool {
182        self.context.is_some()
183            || self.context_expr.is_some()
184            || !self.actions.is_empty()
185            || self.cancel_timeout.is_some()
186            || self.function.is_some()
187    }
188
189    /// Whether the transition runs expressions, so its result is computed
190    /// when it is selected, as XState evaluates transition functions.
191    pub fn evaluates(&self) -> bool {
192        self.function.is_some() || self.context_expr.is_some() || self.actions.iter().any(Action::evaluates)
193    }
194}
195
196#[derive(Debug, Clone)]
197pub(crate) enum Guard {
198    Custom(u32),
199    Not(Box<Guard>),
200    StateIn(Nid),
201    /// A route's match: the event's `to` is this `#id`.
202    RouteTo(String),
203    /// Both, in order (a route's match, then its named guard).
204    And(Box<Guard>, Box<Guard>),
205    /// An inline expression, truthy as in JavaScript.
206    Expr(u32),
207    /// A custom guard with expressions in its params (index into
208    /// `Machine::dynamic_guards`).
209    Dynamic(u32),
210    /// A named JSON guard with params its expressions read: the params
211    /// (resolved in the outer scope), then the guard.
212    Scoped(Box<Template>, Box<Guard>),
213    /// `@xstate.stateIn` with expressions in its params (the state id is
214    /// resolved when the guard runs).
215    StateInExpr(Box<Template>),
216}
217
218#[derive(Debug, Clone)]
219pub(crate) enum Action {
220    /// Index into `Machine::raise_events`.
221    Raise {
222        event: u32,
223        id: Option<String>,
224        delay: Option<u64>,
225    },
226    Cancel(String),
227    Log(Vec<Value>),
228    Emit(Value),
229    Assign(Map<String, Value>),
230    Custom(u32),
231    /// `@xstate.raise` of an event with expressions in it.
232    RaiseExpr {
233        event: Template,
234        id: Option<String>,
235        delay: Option<u64>,
236    },
237    EmitExpr(Template),
238    AssignExpr(Template),
239    /// Index into `Machine::dynamic_actions`.
240    CustomExpr(u32),
241    /// An expression as an action: its result's `context` is merged.
242    Expr(u32),
243    /// The start of a named JSON action whose params its expressions read:
244    /// the params, resolved here, are their scope's until `EndParams`.
245    Params(Template),
246    EndParams,
247}
248
249impl Action {
250    /// Whether the action writes the context (and so needs the context it
251    /// starts from).
252    pub fn assigns(&self) -> bool {
253        matches!(self, Action::Assign(_) | Action::AssignExpr(_) | Action::Expr(_))
254    }
255
256    /// Whether the action evaluates expressions (which read the context).
257    pub fn evaluates(&self) -> bool {
258        matches!(
259            self,
260            Action::RaiseExpr { .. }
261                | Action::EmitExpr(_)
262                | Action::AssignExpr(_)
263                | Action::CustomExpr(_)
264                | Action::Expr(_)
265                | Action::Params(_)
266        )
267    }
268}
269
270pub(crate) enum InitialContext<C> {
271    Value(C),
272    Template(Template),
273}
274
275/// The options of a machine definition (XState's machine `options`).
276#[derive(Debug, Clone, Default)]
277pub(crate) struct MachineOptions {
278    /// The microstep bound for one macrostep (`options.maxIterations`):
279    /// more is an infinite loop. Unbounded when the definition sets none.
280    pub(crate) max_iterations: Option<usize>,
281}
282
283/// A compiled machine definition. Create actors from it with
284/// [`crate::Actor::start`]; one machine can be shared by many actors.
285pub struct Machine<C, E> {
286    pub(crate) id: Option<String>,
287    pub(crate) version: Option<String>,
288    pub(crate) tree: Tree,
289    pub(crate) nodes: Vec<NodeData>,
290    pub(crate) transitions: Vec<TransitionData>,
291    pub(crate) guards: Vec<GuardFn<C, E>>,
292    pub(crate) actions: Vec<CustomAction>,
293    pub(crate) actors: Vec<(String, Arc<dyn Logic>)>,
294    pub(crate) delays: Vec<DelayFn<C, E>>,
295    pub(crate) raise_events: Vec<Ev<E>>,
296    pub(crate) exprs: Vec<ExprFn<C, E>>,
297    pub(crate) context_exprs: Vec<ContextFn>,
298    pub(crate) dynamic_actions: Vec<Dynamic<ActionFn>>,
299    pub(crate) dynamic_guards: Vec<Dynamic<GuardFn<C, E>>>,
300    /// The registry's custom actions, for `enq.action` in expressions.
301    pub(crate) action_factories: FixedMap<String, Factory<ActionFn>>,
302    /// The custom actions left to the host, which run no implementation and
303    /// stay pending until the host says they are done.
304    pub(crate) host_actions: crate::registry::HostActions,
305    pub(crate) id_map: FixedMap<String, Nid>,
306    pub(crate) internal_events: Vec<String>,
307    /// The initial context: a value, or, when the root `context` has
308    /// expressions, computed from the actor's input at start.
309    pub(crate) initial_context: InitialContext<C>,
310    pub(crate) output: Option<Template>,
311    pub(crate) options: MachineOptions,
312    /// Why starting fails although the definition loads: a root `initial`
313    /// without child states, which XState accepts and fails on at start.
314    pub(crate) start_error: Option<String>,
315    /// Empty snapshot parts that new snapshots share until they first write
316    /// them (copy-on-write), so an actor allocates none it does not use.
317    pub(crate) empty: crate::interp::EmptyParts<E>,
318}
319
320/// The machine's `id`, `version` and size; its implementations are closures.
321impl<C, E> std::fmt::Debug for Machine<C, E> {
322    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
323        f.debug_struct("Machine")
324            .field("id", &self.id)
325            .field("version", &self.version)
326            .field("states", &self.nodes.len())
327            .field("transitions", &self.transitions.len())
328            .finish_non_exhaustive()
329    }
330}
331
332impl<C, E> Machine<C, E> {
333    /// Whether the custom action `name` is left to the host.
334    pub(crate) fn is_host_action(&self, name: &str) -> bool {
335        self.host_actions.includes(name, self.action_factories.contains_key(name))
336    }
337
338    /// The machine's `id`, if the definition declares one.
339    pub fn id(&self) -> Option<&str> {
340        self.id.as_deref()
341    }
342
343    /// The definition's `version`, if any.
344    pub fn version(&self) -> Option<&str> {
345        self.version.as_deref()
346    }
347
348    /// The id of every state node, in document order.
349    pub fn state_ids(&self) -> impl Iterator<Item = &str> {
350        self.nodes.iter().map(|n| n.id.as_str())
351    }
352
353    pub(crate) fn node_by_id(&self, id: &str) -> Option<Nid> {
354        self.id_map.get(id).copied()
355    }
356
357    /// XState's `resolveTarget` for one target of a transition from
358    /// `source`: `#id`, `.child.path` below the source, or a path below the
359    /// source's parent.
360    pub(crate) fn resolve_target(&self, source: Nid, target: &str) -> Result<Nid, String> {
361        if let Some(id) = target.strip_prefix('#') {
362            return self.node_by_id(id).ok_or_else(|| format!("no state has id \"{id}\""));
363        }
364        let (mut current, path) = match target.strip_prefix('.') {
365            Some(rest) => (source, rest),
366            None => match self.tree.node(source).parent {
367                Some(parent) => (parent, target),
368                None => return Err(format!("invalid target \"{target}\" on the root; use \".child\" or \"#id\"")),
369            },
370        };
371        for segment in crate::load::to_state_path(path) {
372            if segment.is_empty() {
373                break;
374            }
375            let node = self.tree.node(current);
376            current = node
377                .children
378                .iter()
379                .chain(&node.history_children)
380                .copied()
381                .find(|&c| self.data(c).key == segment)
382                .ok_or_else(|| format!("child state '{segment}' does not exist on '{}'", self.data(current).id))?;
383        }
384        Ok(current)
385    }
386
387    #[inline]
388    pub(crate) fn data(&self, n: Nid) -> &NodeData {
389        &self.nodes[n as usize]
390    }
391
392    pub(crate) fn transition(&self, t: Tid) -> &TransitionData {
393        &self.transitions[t as usize]
394    }
395
396    pub(crate) fn is_internal_event(&self, event_type: &str) -> bool {
397        self.internal_events.iter().any(|d| matches_descriptor(event_type, d))
398    }
399
400    /// XState's state value for a configuration.
401    pub(crate) fn state_value(&self, config: &[Nid]) -> Value {
402        let all = crate::core::all_state_nodes(&self.tree, config, |n| self.data(n).initial.clone());
403        let adj = self.tree.active_children(all.as_slice());
404        self.node_value(ROOT, &adj)
405    }
406
407    fn node_value(&self, node: Nid, adj: &[Vec<Nid>]) -> Value {
408        let children = &adj[node as usize];
409        if children.is_empty() {
410            return Value::Object(Map::new());
411        }
412        if self.tree.kind(node) == crate::core::Kind::Compound {
413            let child = children[0];
414            if self.tree.kind(child).is_atomic() {
415                return Value::String(self.data(child).key.clone());
416            }
417        }
418        let mut map = Map::new();
419        for &c in children {
420            map.insert(self.data(c).key.clone(), self.node_value(c, adj));
421        }
422        Value::Object(map)
423    }
424}