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;
pub(crate) const ERROR_EXECUTION: &str = "error.execution";
pub(crate) const ERROR_COMMUNICATION: &str = "error.communication";
pub(crate) const UNBOUND: OnUnbound = OnUnbound::Error;
#[derive(Debug, Clone, Copy)]
pub(crate) struct Scope<'a> {
pub(crate) data: &'a Map,
pub(crate) chart: &'a Chart,
pub(crate) configuration: &'a BTreeSet<usize>,
}
impl<'a> Scope<'a> {
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)
})
}
fn context(&self) -> Context {
Context::from(self.data.clone())
}
}
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()
)),
}
}
#[derive(Debug, Clone, PartialEq)]
pub(crate) enum Failure {
Evaluation {
source: String,
error: Error,
},
Compile(Box<Refusal>),
NonBooleanCond(Value),
Src(String),
SystemVariable(String),
InvalidDelay(Value),
Location {
source: String,
reason: LocationReason,
},
UnboundLocation(String),
IllegalItemName(String),
IllegalIndexName(String),
NotIterable(Value),
Nested {
content: usize,
failure: Box<Failure>,
},
SendRejected {
send_id: String,
kind: RejectionKind,
rejection: Rejection,
},
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) enum RejectionKind {
Execution,
Communication,
}
#[derive(Debug, Clone, PartialEq)]
pub(crate) enum Rejection {
UnsupportedType(Value),
InvalidTarget(Value),
UnreachableTarget(Value),
}
impl Rejection {
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 {
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)
}
pub(crate) fn event_name(&self) -> &'static str {
match self {
Failure::SendRejected {
kind: RejectionKind::Communication,
..
} => ERROR_COMMUNICATION,
_ => ERROR_EXECUTION,
}
}
#[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(),
})
}
}
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,
},
),
}
}
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())),
}
}
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)),
}
}
#[derive(Debug, Clone, PartialEq)]
pub(crate) struct Executed {
pub(crate) data: Map,
pub(crate) failure: Option<Failure>,
}
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 }
}
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(),
},
}
}
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()
}
pub(crate) fn system_root(root: &str) -> bool {
root.starts_with('_')
}