1use 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
14pub type NodeId = Nid;
16
17pub(crate) const ROOT: Nid = 0;
18
19pub(crate) struct NodeData {
21 pub key: String,
22 pub id: String,
23 pub entry: Vec<Action>,
24 pub exit: Vec<Action>,
25 pub delayed: Vec<DelayedDef>,
28 pub invokes: Vec<InvokeDef>,
29 pub output: Option<Template>,
30 pub tags: Vec<String>,
31 pub initial: Arc<[Nid]>,
33 pub initial_input: Option<Value>,
36 pub history_target: Arc<[Nid]>,
38 pub on_error: bool,
41}
42
43pub(crate) struct DelayedDef {
46 pub kind: DelayedKind,
47 pub delay: DelaySpec,
48}
49
50pub(crate) enum DelayedKind {
51 After { event_delay: Value },
54 StateTimeout,
56 InvokeTimeout { invoke_id: String },
58}
59
60pub(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 pub sync_snapshot: bool,
68}
69
70pub(crate) struct CustomAction {
73 pub name: String,
74 pub params: Option<Value>,
75 pub exec: EffectExec,
76}
77
78pub(crate) struct Dynamic<T> {
81 pub name: String,
82 pub factory: Factory<T>,
83 pub params: Template,
84}
85
86#[derive(Debug, Clone)]
88pub(crate) enum Template {
89 Static(Value),
90 Expr(u32),
93 Object(Vec<(String, Template)>),
94 Array(Vec<Template>),
95}
96
97impl Template {
98 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 Expr(u32),
116}
117
118pub(crate) struct TransitionData {
119 pub targets: Option<Arc<[Nid]>>,
121 pub matches: Vec<(String, Value)>,
122 pub guard: Option<Guard>,
123 pub context: Option<Map<String, Value>>,
125 pub context_expr: Option<Template>,
127 pub actions: Vec<Action>,
128 pub reenter: bool,
129 pub session: Option<String>,
132 pub cancel_timeout: Option<crate::system::TimerKey>,
135 pub function: Option<TransitionFn>,
138 pub input: Option<Template>,
140 pub selects: bool,
142}
143
144pub(crate) const REJECT_REASONS: &str =
147 "reject(...) requires a nonempty array of rejection objects with a string type.";
148
149#[derive(Debug, Clone)]
152pub(crate) enum TransitionFn {
153 Expr(u32),
155 Route { expr: u32, target: Arc<[Nid]> },
158 ChoiceExpr { expr: u32, id: String },
160 Choice { branches: Vec<ChoiceBranch>, path: String, id: String },
162 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 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 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 RouteTo(String),
203 And(Box<Guard>, Box<Guard>),
205 Expr(u32),
207 Dynamic(u32),
210 Scoped(Box<Template>, Box<Guard>),
213 StateInExpr(Box<Template>),
216}
217
218#[derive(Debug, Clone)]
219pub(crate) enum Action {
220 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 RaiseExpr {
233 event: Template,
234 id: Option<String>,
235 delay: Option<u64>,
236 },
237 EmitExpr(Template),
238 AssignExpr(Template),
239 CustomExpr(u32),
241 Expr(u32),
243 Params(Template),
246 EndParams,
247}
248
249impl Action {
250 pub fn assigns(&self) -> bool {
253 matches!(self, Action::Assign(_) | Action::AssignExpr(_) | Action::Expr(_))
254 }
255
256 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#[derive(Debug, Clone, Default)]
277pub(crate) struct MachineOptions {
278 pub(crate) max_iterations: Option<usize>,
281}
282
283pub 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 pub(crate) action_factories: FixedMap<String, Factory<ActionFn>>,
302 pub(crate) host_actions: crate::registry::HostActions,
305 pub(crate) id_map: FixedMap<String, Nid>,
306 pub(crate) internal_events: Vec<String>,
307 pub(crate) initial_context: InitialContext<C>,
310 pub(crate) output: Option<Template>,
311 pub(crate) options: MachineOptions,
312 pub(crate) start_error: Option<String>,
315 pub(crate) empty: crate::interp::EmptyParts<E>,
318}
319
320impl<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 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 pub fn id(&self) -> Option<&str> {
340 self.id.as_deref()
341 }
342
343 pub fn version(&self) -> Option<&str> {
345 self.version.as_deref()
346 }
347
348 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 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 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}