Skip to main content

statifier/driver/
position.rs

1//! A chart's position in the string-id vocabulary the reference migrates a
2//! position in: [`State::export_position`] writes one and
3//! [`Machine::import_position`] reads one back, onto the chart that wrote it
4//! or onto another that holds every state it names.
5//!
6//! The reference is `Statifier.Position.export/1` and `import/2` in
7//! statifier-ex. The export translates every state index to the id the
8//! document wrote and drops the root, which has none; it refuses a position
9//! whose internal queue holds an event and one that holds a state, the root
10//! apart, with no written id. The import resolves every id against the
11//! chart, refusing with every unknown id at once, sorted; it re-adds the
12//! root, starts the internal queue empty and reads no identity.
13//!
14//! A position holds the interpreter's state and nothing of the driver's:
15//! no session id beyond the datamodel's `_sessionid`, no virtual clock, no
16//! pending timer, no queued external event and no budget halt. The import
17//! starts each of those as a fresh session does: the clock at 0, nothing
18//! pending, nothing queued, not halted, the session id read from
19//! `_sessionid`, and the registered send types read from the entries of
20//! `_ioprocessors` other than the SCXML Event I/O Processor's.
21
22use super::{Done, RoundBudget, State, ids, is_built_in, leaf_count, leaf_ids};
23use crate::interpreter::{self, Counters, MachineState, Routes, Sends};
24use crate::machine::{Chart, Machine};
25use predicator_rs::{Key, Map, Value};
26use std::collections::{BTreeMap, BTreeSet, VecDeque};
27use std::fmt;
28
29#[cfg(test)]
30mod tests;
31
32/// The datamodel root the session id is read from.
33const SESSION_ID: &str = "_sessionid";
34
35/// The datamodel root the registered send types are read from.
36const IOPROCESSORS: &str = "_ioprocessors";
37
38/// Whether a chart has finished stopping: the reference's `status`.
39#[non_exhaustive]
40#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
41pub enum Status {
42    /// The chart runs, or is stopping.
43    Running,
44    /// Every state has exited: the chart has stopped.
45    Done,
46}
47
48/// A live invocation, as a position names it: the state whose `<invoke>`
49/// started it, which of that state's `<invoke>` elements, in document
50/// order from 0, and the invoke id.
51#[non_exhaustive]
52#[derive(Debug, Clone, PartialEq, Eq, Hash, PartialOrd, Ord)]
53pub struct ActiveInvocation {
54    /// The id of the state holding the `<invoke>`.
55    pub state: String,
56    /// Which of the state's `<invoke>` elements.
57    pub invoke_index: u64,
58    /// The invoke id.
59    pub invoke_id: String,
60}
61
62impl ActiveInvocation {
63    /// The live invocation of the `<invoke>` at `invoke_index` among the
64    /// `<invoke>` elements of the state `state`, with the invoke id
65    /// `invoke_id`: what a host that keeps a position in its own storage
66    /// builds each entry of [`Position::active_invocations`] from.
67    ///
68    /// ```
69    /// let invocation = statifier::ActiveInvocation::new("s1", 0, "s1.inv_1");
70    /// assert_eq!(invocation.state, "s1");
71    /// assert_eq!(invocation.invoke_index, 0);
72    /// assert_eq!(invocation.invoke_id, "s1.inv_1");
73    /// ```
74    pub fn new(state: impl Into<String>, invoke_index: u64, invoke_id: impl Into<String>) -> Self {
75        Self {
76            state: state.into(),
77            invoke_index,
78            invoke_id: invoke_id.into(),
79        }
80    }
81}
82
83/// A chart's position in the string-id vocabulary: every field of the
84/// reference's export, a state named by the id the document wrote and the
85/// root never named.
86///
87/// [`State::export_position`] answers one; [`Machine::import_position`]
88/// reads one, which a host may have kept anywhere and edited, or built from
89/// [`Position::default`] and its own storage. With the
90/// `serde` feature its serialized keys are the TypeScript sibling's, in
91/// camel case, and each datamodel root is the predicator crate's tagged
92/// text of its value, so a position one sibling writes reads in the other.
93///
94/// ```
95/// use statifier::{Options, Value};
96///
97/// let machine = statifier::compile(
98///     r#"<scxml xmlns="http://www.w3.org/2005/07/scxml" version="1.0" initial="a">
99///          <state id="a"><transition event="e.go" target="b"/></state>
100///          <state id="b"><transition event="e.go" target="c"/></state>
101///          <final id="c"/>
102///        </scxml>"#,
103/// )
104/// .map_err(|refusals| format!("{refusals:?}"))?;
105/// let moved = machine.start(Options::new("s-1"))?.state.step("e.go", Value::Undefined)?;
106/// let position = moved.state.export_position()?;
107/// assert!(position.configuration.contains("b"));
108///
109/// let resumed = machine.import_position(&position)?;
110/// assert_eq!(resumed.configuration(), ["b"]);
111/// let stopped = resumed.step("e.go", Value::Undefined)?;
112/// assert!(stopped.state.done().is_some());
113/// # Ok::<(), Box<dyn std::error::Error>>(())
114/// ```
115#[non_exhaustive]
116#[derive(Debug, Clone, PartialEq)]
117pub struct Position {
118    /// Provenance only: [`Machine::import_position`] never reads it. This
119    /// crate computes no chart identity, so an export writes
120    /// [`Value::Null`]; a position another sibling wrote keeps the identity
121    /// it carried.
122    pub identity: Value,
123    /// The active states' ids, the root left out.
124    pub configuration: BTreeSet<String>,
125    /// Every state ever entered, the root left out: a state's own `<data>`
126    /// binds on its first entry under late binding.
127    pub entered_states: BTreeSet<String>,
128    /// The states whose `<invoke>` elements have yet to start.
129    pub states_to_invoke: BTreeSet<String>,
130    /// Each history state that has recorded a value, by id, to the ids of
131    /// the states it restores.
132    pub history_values: BTreeMap<String, BTreeSet<String>>,
133    /// The live invocations.
134    pub active_invocations: Vec<ActiveInvocation>,
135    /// The last invoke id's number.
136    pub invoke_counter: u64,
137    /// The last generated send id's number.
138    pub send_counter: u64,
139    /// The last ordinal a delayed send, a cancel or a registered type's send
140    /// minted.
141    pub timer_counter: u64,
142    /// The datamodel, the system variables included.
143    pub datamodel: Map,
144    /// The specification's `running`: false once a top-level final state is
145    /// entered or the chart is cancelled.
146    pub running: bool,
147    /// Whether the chart has finished stopping.
148    pub status: Status,
149    /// The macrostep counter.
150    pub macrostep: u64,
151    /// The microstep counter.
152    pub microstep: u64,
153    /// The round counter.
154    pub round: u64,
155    /// The `trace` option the chart was started with.
156    pub trace: bool,
157    /// The round budget of each macrostep.
158    pub max_macrostep_rounds: RoundBudget,
159}
160
161/// The empty position: no identity ([`Value::Null`]), no state, no
162/// datamodel, every counter at 0, running and not stopped, no trace and the
163/// default round budget. A host that keeps a position in its own storage
164/// starts from it and sets each field it kept:
165///
166/// ```
167/// use statifier::{Key, Map, Position, Value};
168///
169/// let machine = statifier::compile(
170///     r#"<scxml xmlns="http://www.w3.org/2005/07/scxml" version="1.0" initial="a">
171///          <state id="a"><transition event="e.go" target="b"/></state>
172///          <final id="b"/>
173///        </scxml>"#,
174/// )
175/// .map_err(|refusals| format!("{refusals:?}"))?;
176///
177/// let mut datamodel = Map::new();
178/// datamodel.insert(Key::from("_sessionid"), Value::from("s-1"));
179/// let mut position = Position::default();
180/// position.configuration.insert("a".to_owned());
181/// position.entered_states.insert("a".to_owned());
182/// position.datamodel = datamodel;
183///
184/// let state = machine.import_position(&position)?;
185/// assert_eq!(state.configuration(), ["a"]);
186/// let stepped = state.step("e.go", Value::Undefined);
187/// assert!(stepped.is_ok_and(|moved| moved.state.done().is_some()));
188/// # Ok::<(), Box<dyn std::error::Error>>(())
189/// ```
190impl Default for Position {
191    fn default() -> Self {
192        Self {
193            identity: Value::Null,
194            configuration: BTreeSet::new(),
195            entered_states: BTreeSet::new(),
196            states_to_invoke: BTreeSet::new(),
197            history_values: BTreeMap::new(),
198            active_invocations: Vec::new(),
199            invoke_counter: 0,
200            send_counter: 0,
201            timer_counter: 0,
202            datamodel: Map::new(),
203            running: true,
204            status: Status::Running,
205            macrostep: 0,
206            microstep: 0,
207            round: 0,
208            trace: false,
209            max_macrostep_rounds: RoundBudget::default(),
210        }
211    }
212}
213
214/// Why [`State::export_position`] refused.
215#[non_exhaustive]
216#[derive(Debug, Clone, PartialEq, Eq)]
217pub enum ExportError {
218    /// The internal queue holds an event, selected against this chart's
219    /// transitions: the state is inside a macrostep, which a spent round
220    /// budget leaves it in.
221    InternalQueueNotEmpty,
222    /// The position holds states, the root apart, that the document gave no
223    /// id.
224    #[non_exhaustive]
225    UnnameableStates {
226        /// Every such state's index in document order, ascending.
227        indexes: Vec<usize>,
228    },
229}
230
231impl fmt::Display for ExportError {
232    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
233        match self {
234            ExportError::InternalQueueNotEmpty => {
235                formatter.write_str("the internal queue holds an event")
236            }
237            ExportError::UnnameableStates { indexes } => {
238                let indexes: Vec<String> = indexes.iter().map(usize::to_string).collect();
239                write!(
240                    formatter,
241                    "states with no id are in the position: {}",
242                    indexes.join(", ")
243                )
244            }
245        }
246    }
247}
248
249impl std::error::Error for ExportError {}
250
251/// Why [`Machine::import_position`] refused.
252#[non_exhaustive]
253#[derive(Debug, Clone, PartialEq, Eq)]
254pub enum ImportError {
255    /// The datamodel's `_sessionid` is missing or not a string, so the state
256    /// has no session to run as.
257    NoSessionId,
258    /// The position names states the chart does not hold.
259    #[non_exhaustive]
260    UnknownStateIds {
261        /// Every such id, sorted.
262        ids: Vec<String>,
263    },
264    /// A recorded history value the chart cannot restore: its key is not a
265    /// `<history>`, or it holds a state that is a history or is not inside
266    /// the history's parent.
267    #[non_exhaustive]
268    InvalidHistoryValue {
269        /// The history's id, the first such in id order.
270        history: String,
271    },
272    /// Two live invocations name the same `<invoke>` of the same state.
273    #[non_exhaustive]
274    DuplicateInvocation {
275        /// The state's id.
276        state: String,
277        /// Which of its `<invoke>` elements.
278        invoke_index: u64,
279    },
280    /// A live invocation names an `<invoke>` its state does not hold: its
281    /// index is not below the state's count of `<invoke>` elements.
282    #[non_exhaustive]
283    UnknownInvoke {
284        /// The state's id.
285        state: String,
286        /// The index named.
287        invoke_index: u64,
288    },
289}
290
291impl fmt::Display for ImportError {
292    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
293        match self {
294            ImportError::NoSessionId => {
295                formatter.write_str("the datamodel's _sessionid is not a string")
296            }
297            ImportError::UnknownStateIds { ids } => {
298                write!(
299                    formatter,
300                    "the chart holds no state with these ids: {}",
301                    ids.join(", ")
302                )
303            }
304            ImportError::InvalidHistoryValue { history } => {
305                write!(
306                    formatter,
307                    "the history value recorded for {history:?} cannot be restored"
308                )
309            }
310            ImportError::DuplicateInvocation {
311                state,
312                invoke_index,
313            } => write!(
314                formatter,
315                "two invocations name invoke {invoke_index} of {state:?}"
316            ),
317            ImportError::UnknownInvoke {
318                state,
319                invoke_index,
320            } => write!(formatter, "{state:?} holds no invoke {invoke_index}"),
321        }
322    }
323}
324
325impl std::error::Error for ImportError {}
326
327impl State {
328    /// The chart's position, in the string-id vocabulary.
329    ///
330    /// Only the interpreter's state travels: the virtual clock, the pending
331    /// timers, the queued external events and a budget halt are the
332    /// driver's, and a position carries none of them.
333    ///
334    /// Refused with [`ExportError::InternalQueueNotEmpty`] when the internal
335    /// queue holds an event, and with [`ExportError::UnnameableStates`],
336    /// naming every one, when the position holds a state other than the
337    /// root that the document gave no id.
338    pub fn export_position(&self) -> Result<Position, ExportError> {
339        let core = &self.core;
340        if !core.internal_queue.is_empty() {
341            return Err(ExportError::InternalQueueNotEmpty);
342        }
343        let chart = core.chart();
344        let unnameable: Vec<usize> = referenced(core)
345            .into_iter()
346            .filter(|&index| index != 0 && id_of(chart, index).is_none())
347            .collect();
348        if !unnameable.is_empty() {
349            return Err(ExportError::UnnameableStates {
350                indexes: unnameable,
351            });
352        }
353        let names = |indexes: &BTreeSet<usize>| -> BTreeSet<String> {
354            indexes
355                .iter()
356                .filter_map(|&index| id_of(chart, index))
357                .collect()
358        };
359        let history_values = core
360            .history
361            .iter()
362            .filter_map(|(&history, recorded)| {
363                id_of(chart, history).map(|history| (history, names(recorded)))
364            })
365            .collect();
366        let active_invocations = core
367            .active_invocations
368            .iter()
369            .filter_map(|(&(state, invoke_index), invoke_id)| {
370                id_of(chart, state).map(|state| ActiveInvocation {
371                    state,
372                    invoke_index,
373                    invoke_id: invoke_id.clone(),
374                })
375            })
376            .collect();
377        Ok(Position {
378            identity: Value::Null,
379            configuration: names(&core.configuration),
380            entered_states: names(&core.entered_states),
381            states_to_invoke: names(&core.states_to_invoke),
382            history_values,
383            active_invocations,
384            invoke_counter: core.invoke_counter,
385            send_counter: core.sends.send_counter,
386            timer_counter: core.sends.timer_counter,
387            datamodel: core.datamodel.clone(),
388            running: core.running,
389            status: match core.status {
390                interpreter::Status::Running => Status::Running,
391                interpreter::Status::Done => Status::Done,
392            },
393            macrostep: core.counters.macrostep,
394            microstep: core.counters.microstep,
395            round: core.counters.round,
396            trace: self.trace,
397            max_macrostep_rounds: self.round_budget,
398        })
399    }
400}
401
402impl Machine {
403    /// A chart in execution over this machine, at `position`: the reverse
404    /// of [`State::export_position`]. The position's identity is not read,
405    /// so a position may be imported into any chart that holds every state
406    /// it names.
407    ///
408    /// The root is re-added to the configuration and to the entered states,
409    /// and the internal queue starts empty. The driver's own fields start
410    /// as a fresh session's do: the virtual clock at 0, no pending timer,
411    /// no queued external event, not halted. The session id is the
412    /// datamodel's `_sessionid`, and the registered send types are the
413    /// entries of `_ioprocessors` other than the SCXML Event I/O
414    /// Processor's, as [`Machine::start`] writes them. A position carries
415    /// no child session, so a live invocation it names has none: it is
416    /// sent nothing, forwarded nothing and returns nothing, and its state's
417    /// exit cancels it.
418    ///
419    /// A stopped position imports stopped: [`State::done`] answers, and
420    /// [`State::step`] refuses. A position carries no donedata and a stopped
421    /// chart's configuration is empty, so [`Done::donedata`] is
422    /// [`Value::Undefined`] and [`Done::configuration`] the position's own.
423    ///
424    /// Refused, in this order, with [`ImportError::NoSessionId`] when
425    /// `_sessionid` is not a string; with [`ImportError::UnknownStateIds`],
426    /// naming every one, when the position names a state the chart does not
427    /// hold; with [`ImportError::InvalidHistoryValue`] when a recorded
428    /// history value is not one the chart can restore; and, live invocation
429    /// by live invocation, with [`ImportError::UnknownInvoke`] when one names
430    /// an `<invoke>` its state does not hold and with
431    /// [`ImportError::DuplicateInvocation`] when two name one `<invoke>`. Every state the position names is checked against
432    /// the chart before any of it is read.
433    pub fn import_position(&self, position: &Position) -> Result<State, ImportError> {
434        let session_id = match position.datamodel.get(&Key::from(SESSION_ID)) {
435            Some(Value::String(session_id)) => session_id.clone(),
436            _ => return Err(ImportError::NoSessionId),
437        };
438        let chart = self.chart();
439        let unknown: BTreeSet<&str> = named(position)
440            .filter(|id| !chart.id_to_index.contains_key(*id))
441            .collect();
442        if !unknown.is_empty() {
443            return Err(ImportError::UnknownStateIds {
444                ids: unknown.into_iter().map(str::to_owned).collect(),
445            });
446        }
447        let index = |id: &str| chart.id_to_index.get(id).copied().unwrap_or(0);
448        let indexes = |ids: &BTreeSet<String>| -> BTreeSet<usize> {
449            ids.iter().map(|id| index(id)).collect()
450        };
451        let mut history = BTreeMap::new();
452        for (key, recorded) in &position.history_values {
453            let restored = indexes(recorded);
454            if !restorable(chart, index(key), &restored) {
455                return Err(ImportError::InvalidHistoryValue {
456                    history: key.clone(),
457                });
458            }
459            history.insert(index(key), restored);
460        }
461        let mut active_invocations = BTreeMap::new();
462        for invocation in &position.active_invocations {
463            let key = (index(&invocation.state), invocation.invoke_index);
464            let held = chart
465                .states
466                .get(key.0)
467                .map_or(0, |state| state.invoke.len());
468            if usize::try_from(invocation.invoke_index).map_or(true, |at| at >= held) {
469                return Err(ImportError::UnknownInvoke {
470                    state: invocation.state.clone(),
471                    invoke_index: invocation.invoke_index,
472                });
473            }
474            if active_invocations
475                .insert(key, invocation.invoke_id.clone())
476                .is_some()
477            {
478                return Err(ImportError::DuplicateInvocation {
479                    state: invocation.state.clone(),
480                    invoke_index: invocation.invoke_index,
481                });
482            }
483        }
484        let mut configuration = indexes(&position.configuration);
485        configuration.insert(0);
486        let mut entered_states = indexes(&position.entered_states);
487        entered_states.insert(0);
488        let core = MachineState {
489            machine: self.clone(),
490            configuration,
491            history,
492            datamodel: position.datamodel.clone(),
493            internal_queue: VecDeque::new(),
494            entered_states,
495            sends: Sends {
496                send_counter: position.send_counter,
497                timer_counter: position.timer_counter,
498            },
499            states_to_invoke: indexes(&position.states_to_invoke),
500            active_invocations,
501            invoke_counter: position.invoke_counter,
502            send_types: send_types(&position.datamodel),
503            routes: Some(Routes {
504                sessions: BTreeSet::from([session_id.clone()]),
505                ..Routes::default()
506            }),
507            last_selection: None,
508            running: position.running,
509            status: match position.status {
510                Status::Running => interpreter::Status::Running,
511                Status::Done => interpreter::Status::Done,
512            },
513            counters: Counters {
514                macrostep: position.macrostep,
515                microstep: position.microstep,
516                round: position.round,
517            },
518            max_macrostep_rounds: position.max_macrostep_rounds.interpreter(),
519        };
520        let done = (position.status == Status::Done).then(|| Done {
521            donedata: Value::Undefined,
522            configuration: ids(&core, core.configuration.iter().copied()),
523            active_leaf_states: leaf_ids(&core, core.configuration.iter().copied()),
524            active_leaf_count: leaf_count(&core, core.configuration.iter().copied()),
525        });
526        let mut state = State::fresh(
527            core,
528            session_id,
529            BTreeMap::new(),
530            BTreeSet::new(),
531            position.max_macrostep_rounds,
532            position.trace,
533        );
534        state.done = done;
535        Ok(state)
536    }
537}
538
539/// The id the document gave the state at `index`, `None` for none.
540fn id_of(chart: &Chart, index: usize) -> Option<String> {
541    chart.states.get(index).and_then(|state| state.id.clone())
542}
543
544/// Every state index a position's fields hold, ascending.
545fn referenced(core: &MachineState) -> BTreeSet<usize> {
546    let mut indexes: BTreeSet<usize> = core
547        .configuration
548        .iter()
549        .chain(&core.entered_states)
550        .chain(&core.states_to_invoke)
551        .copied()
552        .collect();
553    for (&history, recorded) in &core.history {
554        indexes.insert(history);
555        indexes.extend(recorded);
556    }
557    indexes.extend(core.active_invocations.keys().map(|&(state, _)| state));
558    indexes
559}
560
561/// Every state id a position names, in no particular order.
562fn named(position: &Position) -> impl Iterator<Item = &str> {
563    position
564        .configuration
565        .iter()
566        .chain(&position.entered_states)
567        .chain(&position.states_to_invoke)
568        .chain(
569            position
570                .history_values
571                .iter()
572                .flat_map(|(history, recorded)| std::iter::once(history).chain(recorded)),
573        )
574        .chain(position.active_invocations.iter().map(|item| &item.state))
575        .map(String::as_str)
576}
577
578/// Whether the history state at `history` can restore `recorded`: it is a
579/// `<history>`, and each recorded state is a state other than a history
580/// inside the history's parent. Every restore then enters states deeper in
581/// the chart than the history's parent, so entering one always ends.
582fn restorable(chart: &Chart, history: usize, recorded: &BTreeSet<usize>) -> bool {
583    let Some(parent) = chart
584        .states
585        .get(history)
586        .filter(|_| chart.is_history(history))
587        .and_then(|state| state.parent)
588    else {
589        return false;
590    };
591    recorded
592        .iter()
593        .all(|&state| !chart.is_history(state) && chart.is_descendant(state, parent))
594}
595
596/// The send types a position's chart registered: the keys of
597/// `_ioprocessors` other than a built-in spelling of the SCXML Event I/O
598/// Processor.
599fn send_types(datamodel: &Map) -> BTreeSet<String> {
600    let Some(Value::Map(entries)) = datamodel.get(&Key::from(IOPROCESSORS)) else {
601        return BTreeSet::new();
602    };
603    entries
604        .keys()
605        .filter_map(|key| match key {
606            Key::String(send_type) if !is_built_in(send_type) => Some(send_type.clone()),
607            _ => None,
608        })
609        .collect()
610}