Skip to main content

xmachines_runtime/
lib.rs

1#![doc = include_str!("../README.md")]
2
3mod actor;
4pub mod core;
5mod delay;
6mod error;
7mod event;
8pub mod host;
9mod interp;
10mod load;
11mod machine;
12pub mod migrate;
13pub mod ops;
14mod registry;
15pub mod step;
16pub mod system;
17pub mod work;
18
19use serde::de::DeserializeOwned;
20use serde_json::Value;
21
22pub use actor::{Actor, RestoreOptions};
23pub use error::{LoadError, LoadErrorKind};
24pub use event::{js_numbers, Ev, EventType};
25pub use load::{Reference, References};
26pub use machine::{Machine, NodeId};
27pub use migrate::Migration;
28pub use registry::{
29    Code, CodeKind, ContextArgs, Enq, Evaluator, ExprArgs, GuardArgs, HostActions, HostEvaluator, Registry, Scope,
30    Slot, SpawnOptions,
31};
32pub use system::{
33    ActorRef, Effect, EffectKind, ExternalEffect, FixedState, InitOptions, Logic, Status, System, SystemError,
34    SystemLogic, TransitionCheck, TransitionRejection, DEFAULT_MAX_STEPS,
35};
36
37/// A JSON number, the type `xmachines-build` generates of a `number` schema:
38/// an integer or a float as JSON wrote it, so it writes back the same.
39pub use serde_json::Number;
40
41/// The runtime's hash map, of the [`FixedState`] hasher. The crate's `clippy.toml`
42/// disallows std's `HashMap` and `HashSet` by name, since the lint cannot see
43/// the `RandomState` of a defaulted parameter (`HashMap::from`, `collect()`,
44/// `Default::default()`); these two aliases are the one way in.
45#[allow(clippy::disallowed_types)]
46pub(crate) type FixedMap<K, V> = std::collections::HashMap<K, V, FixedState>;
47
48/// The runtime's hash set, of the [`FixedState`] hasher (see [`FixedMap`]).
49#[allow(clippy::disallowed_types)]
50pub(crate) type FixedSet<T> = std::collections::HashSet<T, FixedState>;
51
52/// What code generated by `xmachines-build` refers to. Not a stable API.
53#[doc(hidden)]
54pub mod __codegen {
55    pub use crate::{
56        Actor, Ev, Evaluator, EventType, ExprArgs, FixedState, GuardArgs, HostActions, LoadError, Logic, Machine,
57        Number, Registry, Status, SystemError,
58    };
59    pub use indexmap::IndexMap;
60    pub use serde;
61    pub use serde_json;
62}
63
64/// Includes the module `xmachines-build` generated for a machine bundle, by
65/// module name (the bundle's file name without `.machine.json`):
66///
67/// ```ignore
68/// pub mod checkout {
69///     xmachines_runtime::include_machine!("checkout");
70/// }
71/// ```
72#[macro_export]
73macro_rules! include_machine {
74    ($name:literal) => {
75        include!(concat!(env!("OUT_DIR"), "/xstate/", $name, ".rs"));
76    };
77}
78
79impl<C, E> Machine<C, E>
80where
81    C: DeserializeOwned + 'static,
82    E: EventType + 'static,
83{
84    /// Compiles a `MachineJSON` definition. Every referenced guard, action and
85    /// named delay must be in `registry` (or defined in the JSON itself). A
86    /// macrostep is unbounded unless the definition sets
87    /// `options.maxIterations`, as `machineToJSON` writes it.
88    pub fn from_json(json: &Value, registry: &Registry<C, E>) -> Result<Self, LoadError> {
89        load::load(json, registry)
90    }
91
92    /// Validates a definition and lists the guards, actions, delays and
93    /// actors it needs from the host (everything not defined in the JSON or
94    /// built in), with their JSON paths and params. Used by code generation.
95    pub fn references(json: &Value) -> Result<References, LoadError> {
96        load::references(json)
97    }
98
99    /// Parses and compiles a definition from a JSON string. Key order is
100    /// preserved, which transition priority depends on.
101    pub fn from_json_str(json: &str, registry: &Registry<C, E>) -> Result<Self, LoadError> {
102        let value: Value = serde_json::from_str(json)
103            .map_err(|e| LoadError::new(LoadErrorKind::Invalid, "$", format!("invalid JSON: {e}")))?;
104        Self::from_json(&value, registry)
105    }
106}