#[cfg(test)]
mod tests;
use super::{Run, Site, scope};
use crate::datamodel::delay;
use crate::datamodel::event_data;
use crate::datamodel::location::write_location;
use crate::datamodel::system_variables::SCXML_EVENT_PROCESSOR;
use crate::datamodel::{Failure, Rejection, RejectionKind, Scope, evaluate, evaluate_deferred};
use crate::effect::Effect;
use crate::machine::{Expr, Send};
use predicator_rs::Value;
use std::collections::BTreeSet;
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub(crate) struct Sends {
pub(crate) send_counter: u64,
pub(crate) timer_counter: u64,
}
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub(crate) struct Routes {
pub(crate) sessions: BTreeSet<String>,
pub(crate) parent: bool,
pub(crate) invokes: BTreeSet<String>,
}
impl Routes {
fn reachable(&self, route: &Route) -> bool {
match route {
Route::Own | Route::Internal => true,
Route::Parent => self.parent,
Route::Session(id) => self.sessions.contains(id),
Route::Invoke(id) => self.invokes.contains(id),
Route::Invalid => false,
}
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub(crate) enum Route {
Own,
Internal,
Parent,
Session(String),
Invoke(String),
Invalid,
}
pub(crate) fn parse_target(target: Option<&Value>) -> Route {
let text = match target {
None | Some(Value::Null) => return Route::Own,
Some(Value::String(text)) => text.as_str(),
Some(_) => return Route::Invalid,
};
match text {
"#_internal" | "_internal" => Route::Internal,
"#_parent" | "_parent" => Route::Parent,
_ => match (text.strip_prefix("#_scxml_"), text.strip_prefix("#_")) {
(Some(session), _) if !session.is_empty() => Route::Session(session.to_owned()),
(_, Some(invoke)) if !invoke.is_empty() => Route::Invoke(invoke.to_owned()),
_ => Route::Invalid,
},
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum TypeClass {
BuiltIn,
Registered,
Unsupported,
}
fn classify(send_types: &BTreeSet<String>, send_type: Option<&Value>) -> TypeClass {
match send_type {
None | Some(Value::Null) => TypeClass::BuiltIn,
Some(Value::String(text)) if text == "scxml" || text == SCXML_EVENT_PROCESSOR => {
TypeClass::BuiltIn
}
Some(Value::String(text)) if send_types.contains(text) => TypeClass::Registered,
Some(_) => TypeClass::Unsupported,
}
}
fn reject_reason(
site: &Site<'_>,
target: Option<&Value>,
send_type: Option<&Value>,
delayed: bool,
) -> Option<(RejectionKind, Rejection)> {
let resolved = |value: Option<&Value>| value.cloned().unwrap_or(Value::Null);
match classify(site.send_types, send_type) {
TypeClass::Unsupported => Some((
RejectionKind::Execution,
Rejection::UnsupportedType(resolved(send_type)),
)),
TypeClass::Registered => None,
TypeClass::BuiltIn => {
let route = parse_target(target);
if route == Route::Invalid {
return Some((
RejectionKind::Execution,
Rejection::InvalidTarget(resolved(target)),
));
}
match site.routes {
Some(routes) if !delayed && !routes.reachable(&route) => Some((
RejectionKind::Communication,
Rejection::UnreachableTarget(resolved(target)),
)),
_ => None,
}
}
}
}
fn optional(scope: &Scope<'_>, expr: Option<&Expr>) -> Result<Option<Value>, Failure> {
expr.map(|expr| evaluate(scope, expr)).transpose()
}
fn present(value: Option<Value>) -> Option<Value> {
value.filter(|value| !matches!(value, Value::Null))
}
fn payload(scope: &Scope<'_>, node: &Send) -> Result<Value, Failure> {
let mut pairs = Vec::with_capacity(node.namelist.len() + node.params.len());
for param in node.namelist.iter().chain(&node.params) {
pairs.push((param.name.as_str(), evaluate_deferred(scope, ¶m.expr)?));
}
match &node.content {
None => Ok(event_data::params(pairs)),
Some(Expr::Static(Value::String(text))) => Ok(event_data::text(text)),
Some(expr) => evaluate(scope, expr),
}
}
pub(super) fn send(
site: &Site<'_>,
run: &mut Run,
index: usize,
node: &Send,
) -> Result<(), Failure> {
let scope = scope(site, &run.data);
let event = present(optional(&scope, node.event.as_ref())?);
let target = present(optional(&scope, node.target.as_ref())?);
let send_type = present(optional(&scope, node.send_type.as_ref())?);
let delay_ms = match &node.delay {
Some(expr) => Some(delay::milliseconds(&evaluate(&scope, expr)?)?),
None => None,
};
let data = payload(&scope, node)?;
let (send_id, send_counter) = match &node.id {
Some(id) => (id.clone(), run.sends.send_counter),
None => {
let next = run.sends.send_counter.saturating_add(1);
(format!("send_{next}"), next)
}
};
let written = match &node.idlocation {
Some(location) => Some(write_location(
&run.data,
location,
Value::from(send_id.as_str()),
)?),
None => None,
};
run.sends.send_counter = send_counter;
let change = written.map(|written| {
run.data = written.data;
Effect::DatamodelChange {
location_path: written.path,
location_source: node.idlocation.clone().unwrap_or_default(),
new_value: written.new_value,
prior_value: written.prior_value,
data_index: None,
content_index: Some(index),
owner: Some(site.owner),
macrostep: site.counters.macrostep,
microstep: site.counters.microstep,
round: site.counters.round,
}
});
if let Some((kind, rejection)) = reject_reason(
site,
target.as_ref(),
send_type.as_ref(),
delay_ms.is_some(),
) {
return Err(Failure::SendRejected {
send_id,
kind,
rejection,
});
}
let registered = classify(site.send_types, send_type.as_ref()) == TypeClass::Registered;
let ordinal = (delay_ms.is_some() || registered).then(|| {
run.sends.timer_counter = run.sends.timer_counter.saturating_add(1);
run.sends.timer_counter
});
run.effects.extend(change);
let id_from_author = node.id.is_some() || node.idlocation.is_some();
let counters = site.counters;
run.effects.push(match (delay_ms, ordinal) {
(Some(delay_ms), Some(ordinal)) => Effect::SendDelayed {
event,
target,
send_type,
data,
send_id,
id_from_author,
delay_ms,
ordinal,
content_index: index,
owner: site.owner,
macrostep: counters.macrostep,
microstep: counters.microstep,
round: counters.round,
},
_ => Effect::Send {
event,
target,
send_type,
data,
send_id,
id_from_author,
ordinal,
content_index: index,
owner: site.owner,
macrostep: counters.macrostep,
microstep: counters.microstep,
round: counters.round,
},
});
Ok(())
}
pub(super) fn cancel(
site: &Site<'_>,
run: &mut Run,
index: usize,
sendid: Option<&Expr>,
) -> Result<(), Failure> {
let send_id = optional(&scope(site, &run.data), sendid)?.unwrap_or(Value::Undefined);
run.sends.timer_counter = run.sends.timer_counter.saturating_add(1);
run.effects.push(Effect::Cancel {
send_id,
ordinal: run.sends.timer_counter,
content_index: index,
owner: site.owner,
macrostep: site.counters.macrostep,
microstep: site.counters.microstep,
round: site.counters.round,
});
Ok(())
}