statifier 0.1.0

An SCXML statechart interpreter core, a conformant sibling of the Elixir statifier package.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
//! The datamodel binding: how a chart's expressions reach the predicator
//! crate, the one expression language, as they reach it in the reference.
//!
//! The datamodel is a [`Map`] of root names to predicator values. Every
//! evaluation runs through [`predicator_rs::evaluate`] (a condition, a value)
//! or [`predicator_rs::execute`] (a `<script>` program) with the options one
//! evaluation site builds ([`Scope::options`]): `In()` as a host function over
//! the configuration the site was given, and the unbound policy that fails a
//! load of a root the datamodel does not hold. A site's options are built per
//! call and never kept: `In()` reads a configuration that moves at every
//! microstep, and `_event` is rewritten for every event.
//!
//! Nothing here panics or raises on a failed evaluation. A failure is a
//! [`Failure`] carrying its reason, and the interpreter turns it into the
//! `error.execution` platform event the reference raises
//! ([`Failure::event`]).

pub(crate) mod delay;
pub(crate) mod event_data;
pub(crate) mod location;
pub(crate) mod system_variables;

#[cfg(test)]
mod tests;

use location::LocationReason;
#[cfg(test)]
use system_variables::{EventFields, EventType};

use crate::machine::{Chart, Deferred, Expr, Program};
use crate::refusal::Refusal;
use predicator_rs::{Context, Error, Key, Map, OnUnbound, Options, Value};
use std::collections::BTreeSet;

/// The name of the platform event every failure here raises.
pub(crate) const ERROR_EXECUTION: &str = "error.execution";

/// The name of the platform event a `<send>` whose target cannot be reached
/// raises.
pub(crate) const ERROR_COMMUNICATION: &str = "error.communication";

/// The unbound policy every evaluation passes: a load of a root the
/// datamodel does not hold fails at the load, as the reference evaluates. A
/// declared root with no value holds [`Value::Undefined`] instead, and reads
/// as undefined.
pub(crate) const UNBOUND: OnUnbound = OnUnbound::Error;

/// One evaluation site's view: the datamodel, and the chart and the
/// configuration (the indexes of the active states) `In()` reads.
#[derive(Debug, Clone, Copy)]
pub(crate) struct Scope<'a> {
    /// The datamodel.
    pub(crate) data: &'a Map,
    /// The chart whose state ids `In()` resolves.
    pub(crate) chart: &'a Chart,
    /// The indexes of the active states.
    pub(crate) configuration: &'a BTreeSet<usize>,
}

impl<'a> Scope<'a> {
    /// The options an evaluation at this site passes to the predicator
    /// crate: `In` as a host function and the unbound policy [`UNBOUND`].
    pub(crate) fn options(&self) -> Options<'a> {
        let chart = self.chart;
        let configuration = self.configuration;
        Options::new()
            .on_unbound(UNBOUND)
            .function("In", move |arguments| {
                in_state(chart, configuration, arguments)
            })
    }

    /// The context an evaluation at this site reads: the datamodel's roots.
    fn context(&self) -> Context {
        Context::from(self.data.clone())
    }
}

/// `In(stateId)`: true when the id names a state of `chart` that is in
/// `configuration`, false for an inactive state and for an id the chart
/// never declared, as the reference answers. An argument that is not a
/// string names no state, so it answers false too. It takes exactly one
/// argument, as the reference's arity does.
pub(crate) fn in_state(
    chart: &Chart,
    configuration: &BTreeSet<usize>,
    arguments: &[Value],
) -> Result<Value, String> {
    match arguments {
        [Value::String(id)] => Ok(Value::Bool(
            chart
                .id_to_index
                .get(id)
                .is_some_and(|index| configuration.contains(index)),
        )),
        [_] => Ok(Value::Bool(false)),
        _ => Err(format!(
            "In expects one argument, a state id; it was given {}",
            arguments.len()
        )),
    }
}

/// Why an evaluation, a program or a delay failed: the reason the
/// `error.execution` it raises carries as its data.
#[derive(Debug, Clone, PartialEq)]
pub(crate) enum Failure {
    /// The predicator crate refused: `source` is the expression's text and
    /// `error` the crate's own error, unwrapped.
    Evaluation {
        /// The expression or program as written.
        source: String,
        /// The predicator crate's error.
        error: Error,
    },
    /// The expression did not compile; the reference defers that refusal to
    /// when the node runs.
    Compile(Box<Refusal>),
    /// A condition answered something other than true or false.
    NonBooleanCond(Value),
    /// A `<data>` whose value is a `src` to fetch: nothing here fetches
    /// one, so it binds nothing, as the reference binds nothing for one.
    Src(String),
    /// A write reached `root`, a system variable's root (one spelled with a
    /// leading underscore).
    SystemVariable(String),
    /// A delay that is not one: text the duration reader refuses, or a value
    /// that is neither text nor a duration.
    InvalidDelay(Value),
    /// A location (`source`, as written) could not be resolved or written.
    Location {
        /// The location as written.
        source: String,
        /// Why.
        reason: LocationReason,
    },
    /// A location's root is not one the datamodel holds: a write never
    /// declares a root.
    UnboundLocation(String),
    /// A `<foreach>` `item` that is not a bare name.
    IllegalItemName(String),
    /// A `<foreach>` `index` that is not a bare name.
    IllegalIndexName(String),
    /// A `<foreach>` `array` that evaluated to something other than a list.
    NotIterable(Value),
    /// A node inside an `<if>` or a `<foreach>` failed: `content` is its
    /// index and `failure` its own failure.
    Nested {
        /// The failing node's index.
        content: usize,
        /// Its failure.
        failure: Box<Failure>,
    },
    /// A `<send>` refused for its type or its target, after its send id was
    /// minted and its `idlocation` written.
    SendRejected {
        /// The send id.
        send_id: String,
        /// Which `error.*` event the refusal raises.
        kind: RejectionKind,
        /// Why.
        rejection: Rejection,
    },
}

/// Which `error.*` event a refused `<send>` raises.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) enum RejectionKind {
    /// `error.execution`: a type or a target the processor does not carry.
    Execution,
    /// `error.communication`: a target the declared routes do not reach.
    Communication,
}

/// Why a `<send>` was refused, carrying the value as resolved.
#[derive(Debug, Clone, PartialEq)]
pub(crate) enum Rejection {
    /// The type is neither the SCXML Event I/O Processor's nor one the host
    /// registered.
    UnsupportedType(Value),
    /// The target names nothing the SCXML Event I/O Processor carries.
    InvalidTarget(Value),
    /// The routes the driver declared do not reach the target.
    UnreachableTarget(Value),
}

impl Rejection {
    /// The refusal as the data its `error.*` event carries: a map whose
    /// `"kind"` names it, with the value beside it.
    fn data(&self) -> Value {
        let (kind, field, value) = match self {
            Rejection::UnsupportedType(value) => ("unsupported_type", "type", value),
            Rejection::InvalidTarget(value) => ("invalid_target", "target", value),
            Rejection::UnreachableTarget(value) => ("unreachable_target", "target", value),
        };
        let mut map = Map::new();
        map.insert(field, value.clone());
        map.insert("kind", Value::from(kind));
        Value::Map(map)
    }
}

impl Failure {
    /// The failure as the predicator value an `error.*` event carries as its
    /// data, so a chart reads `_event.data` with one more evaluation: a map
    /// whose `"kind"` names the failure, with its fields beside it.
    pub(crate) fn data(&self) -> Value {
        let mut map = Map::new();
        let kind = match self {
            Failure::Evaluation { source, error } => {
                map.insert("source", Value::from(source.as_str()));
                map.insert("type", Value::from(error.type_name()));
                map.insert("reason", Value::from(error.reason()));
                map.insert("message", Value::from(error.message()));
                "evaluator_error"
            }
            Failure::Compile(refusal) => {
                map.insert("message", Value::from(refusal.message()));
                "compile_error"
            }
            Failure::NonBooleanCond(value) => {
                map.insert("value", value.clone());
                "non_boolean_cond"
            }
            Failure::Src(src) => {
                map.insert("src", Value::from(src.as_str()));
                "src"
            }
            Failure::SystemVariable(root) => {
                map.insert("root", Value::from(root.as_str()));
                "system_variable"
            }
            Failure::InvalidDelay(value) => {
                map.insert("value", value.clone());
                "invalid_delay"
            }
            Failure::Location { source, reason } => {
                map.insert("source", Value::from(source.as_str()));
                map.insert("type", Value::from("location_error"));
                map.insert("reason", Value::from(reason.as_str()));
                map.insert("message", Value::from(reason.message()));
                "evaluator_error"
            }
            Failure::UnboundLocation(source) => {
                map.insert("location", Value::from(source.as_str()));
                "unbound_location"
            }
            Failure::IllegalItemName(name) => {
                map.insert("name", Value::from(name.as_str()));
                "illegal_item_name"
            }
            Failure::IllegalIndexName(name) => {
                map.insert("name", Value::from(name.as_str()));
                "illegal_index_name"
            }
            Failure::NotIterable(value) => {
                map.insert("value", value.clone());
                "not_iterable"
            }
            Failure::Nested { content, failure } => {
                map.insert(
                    "c_index",
                    Value::Integer(i64::try_from(*content).unwrap_or(i64::MAX)),
                );
                map.insert("reason", failure.data());
                "nested_content"
            }
            Failure::SendRejected { rejection, .. } => return rejection.data(),
        };
        map.insert("kind", Value::from(kind));
        Value::Map(map)
    }

    /// The name of the platform event this failure raises: a refused
    /// `<send>`'s kind names it, `error.communication` for a target the
    /// routes do not reach; every other failure, a refusal nested inside an
    /// `<if>` or a `<foreach>` included, raises `error.execution`, as the
    /// reference raises it.
    pub(crate) fn event_name(&self) -> &'static str {
        match self {
            Failure::SendRejected {
                kind: RejectionKind::Communication,
                ..
            } => ERROR_COMMUNICATION,
            _ => ERROR_EXECUTION,
        }
    }

    /// `_event`'s value for the platform event this failure raises: its
    /// name ([`Failure::event_name`]), the type `platform`, the send id of a
    /// refused `<send>` and none otherwise, no origin or invoke id, and the
    /// failure ([`Failure::data`]) as its data.
    // The loop builds the event through `Event::from_failure`; the tests read
    // the value directly.
    #[cfg(test)]
    pub(crate) fn event(&self) -> Value {
        let sendid = match self {
            Failure::SendRejected { send_id, .. } => Some(send_id.as_str()),
            _ => None,
        };
        system_variables::event(&EventFields {
            name: self.event_name(),
            event_type: EventType::Platform,
            sendid,
            origin: None,
            origintype: None,
            invokeid: None,
            data: self.data(),
        })
    }
}

/// Evaluates `expr` at `scope`. A literal comes back untouched; a compiled
/// expression runs through the predicator crate, and a refusal is a
/// [`Failure::Evaluation`] carrying the expression's text.
pub(crate) fn evaluate(scope: &Scope<'_>, expr: &Expr) -> Result<Value, Failure> {
    match expr {
        Expr::Static(value) => Ok(value.clone()),
        Expr::Compiled {
            instructions,
            source,
        } => predicator_rs::evaluate(instructions, &scope.context(), &scope.options()).map_err(
            |error| Failure::Evaluation {
                source: source.clone(),
                error,
            },
        ),
    }
}

/// Evaluates a value whose compile refusal is deferred: a value that did
/// not compile answers that refusal, as the reference raises it when the
/// node runs.
pub(crate) fn evaluate_deferred(
    scope: &Scope<'_>,
    expr: &Deferred<Expr>,
) -> Result<Value, Failure> {
    match expr {
        Deferred::Ready(expr) => evaluate(scope, expr),
        Deferred::Invalid(refusal) => Err(Failure::Compile(refusal.clone())),
    }
}

/// Evaluates a transition's or a branch's condition: none written is true.
/// A condition that fails, or answers anything but true or false, is a
/// failure; the specification treats both as false and raises
/// `error.execution` for both, as the reference does.
pub(crate) fn evaluate_cond(scope: &Scope<'_>, cond: Option<&Expr>) -> Result<bool, Failure> {
    let Some(cond) = cond else {
        return Ok(true);
    };
    match evaluate(scope, cond)? {
        Value::Bool(answer) => Ok(answer),
        other => Err(Failure::NonBooleanCond(other)),
    }
}

/// What a program's run left: the datamodel, every write made before a
/// failure included, and the failure, if there was one.
#[derive(Debug, Clone, PartialEq)]
pub(crate) struct Executed {
    /// The datamodel the run leaves.
    pub(crate) data: Map,
    /// Why the run failed, if it did.
    pub(crate) failure: Option<Failure>,
}

/// Runs a `<script>` program at `scope`, as the reference runs one.
///
/// Every root the datamodel already holds whose name starts with an
/// underscore is protected through the predicator crate's own option: a
/// store into one fails at the attempt, so no later statement runs and none
/// reads the value, and the failure is a [`Failure::SystemVariable`] naming
/// it. The four system variables are always among those roots, since a
/// session seeds them ([`system_variables::seed`]). A system root the program creates fresh
/// is not on that list: its write lands, the run goes on, and the change
/// found after the run is never kept and fails the run, naming the first
/// such root in sort order. Every write to another root made before any
/// failure is kept, whether or not the value it stores compares equal to
/// the one it replaces (`-0.0` over `0.0` is kept, as the reference keeps
/// it); a stored system root is always a fresh one, since a store into one
/// already held is refused. A program that did not compile answers its refusal and
/// writes nothing.
pub(crate) fn execute(scope: &Scope<'_>, program: &Deferred<Program>) -> Executed {
    let program = match program {
        Deferred::Ready(program) => program,
        Deferred::Invalid(refusal) => {
            return Executed {
                data: scope.data.clone(),
                failure: Some(Failure::Compile(refusal.clone())),
            };
        }
    };
    let before = scope.data;
    let options = scope.options().protected_roots(protected_roots(before));
    let (context, stored, run_failure) =
        match predicator_rs::execute(&program.instructions, &scope.context(), &options) {
            Ok(execution) => {
                let stored = execution.stored_roots().to_vec();
                (execution.into_context(), stored, None)
            }
            Err(stopped) => {
                let stored = stopped.stored_roots().to_vec();
                let failure = run_failure(&program.source, stopped.error());
                (stopped.into_context(), stored, Some(failure))
            }
        };
    let mut data = before.clone();
    let mut system_changed = Vec::new();
    for root in stored {
        let after = context.get(&root).cloned().unwrap_or(Value::Undefined);
        match &root {
            Key::String(name) if system_root(name) => system_changed.push(name.clone()),
            _ => {
                data.insert(root, after);
            }
        }
    }
    system_changed.sort();
    let failure = run_failure.or_else(|| {
        system_changed
            .into_iter()
            .next()
            .map(Failure::SystemVariable)
    });
    Executed { data, failure }
}

/// The failure a stopped run answers: the crate's refusal of a protected
/// root names the root; any other is the crate's own error.
fn run_failure(source: &str, error: &Error) -> Failure {
    match error {
        Error::Evaluation(refusal) if refusal.reason() == "protected_root" => {
            match refusal.root() {
                Some(root) => Failure::SystemVariable(root.to_owned()),
                None => Failure::Evaluation {
                    source: source.to_owned(),
                    error: error.clone(),
                },
            }
        }
        _ => Failure::Evaluation {
            source: source.to_owned(),
            error: error.clone(),
        },
    }
}

/// The roots a program may not store into, derived per run as the reference
/// derives them: every root `data` holds that is a system root. The crate's
/// option is a membership set and the rule is a prefix, so the set is
/// built from the roots already there.
pub(crate) fn protected_roots(data: &Map) -> Vec<String> {
    data.keys()
        .filter_map(|key| match key {
            Key::String(name) if system_root(name) => Some(name.clone()),
            _ => None,
        })
        .collect()
}

/// Whether `root` is a system variable's: the rule is the underscore
/// prefix, as the reference's, so it covers the four seeded variables and
/// any other root spelled that way.
pub(crate) fn system_root(root: &str) -> bool {
    root.starts_with('_')
}