use rhai::{Dynamic, Engine, Scope, AST};
use serde_json::{json, Map, Value};
use std::collections::BTreeSet;
use std::rc::Rc;
const FUEL: u64 = 1_000_000;
pub trait Host {
fn call(&self, method: &str, params: Value);
fn call_then(&self, method: &str, params: Value, fold: &str) {
let _ = fold;
self.call(method, params)
}
fn navigate(&self, route: &str);
fn emit(&self, topic: &str, data: Value) -> Result<(), String> {
let _ = (topic, data);
Err("this host has no bus".into())
}
fn last(&self, topic: &str) -> Value {
let _ = topic;
Value::Null
}
fn slots_set(&self, layout: &str, slot: &str, component: &str, version: Option<&str>) -> Result<(), String> {
let _ = (layout, slot, component, version);
Err("this host has no bus".into())
}
}
#[derive(Debug, Clone, PartialEq)]
pub enum FoldError {
Compile(String),
NotInUses { handler: Option<String>, method: String },
Computed { handler: String, expr: String },
NoAnswerFold { handler: String, fold: String },
ComputedFold { handler: String, expr: String },
CallArity { handler: String, args: usize },
NotAFold { name: String },
NoHandler(String),
Run { handler: String, message: String },
}
impl std::fmt::Display for FoldError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
FoldError::Compile(m) => write!(f, "the handlers do not compile: {m}"),
FoldError::NotInUses { handler: Some(h), method } => write!(f, "{h} calls {method}, which this component's uses does not name"),
FoldError::NotInUses { handler: None, method } => write!(f, "a handler calls {method}, which this component's uses does not name"),
FoldError::Computed { handler, expr } => write!(f, "{handler} calls a method named by `{expr}`: a call's method is a string as written"),
FoldError::NoAnswerFold { handler, fold } => {
write!(f, "{handler} calls with the answer to `{fold}`, and this component has no fn {fold}(state, ev)")
}
FoldError::ComputedFold { handler, expr } => {
write!(f, "{handler} calls with the answer to a fold named by `{expr}`: the third argument of call(…) is the name of a fn (state, ev), a literal string")
}
FoldError::CallArity { handler, args } => {
write!(f, "{handler} calls with {args} arguments: call(method, params) or call(method, params, \"fold\"), nothing more")
}
FoldError::NotAFold { name } => write!(f, "fn {name} is not a fold (state, ev) → state"),
FoldError::NoHandler(h) => write!(f, "no handler {h}"),
FoldError::Run { handler, message } => write!(f, "{handler} failed: {message}"),
}
}
}
pub struct Folds {
engine: Engine,
ast: AST,
handlers: Vec<String>,
}
const HOST_CALL: &str = "host_call";
fn rename_calls(source: &str) -> String {
let b = source.as_bytes();
let mut out = String::with_capacity(source.len() + 32);
let mut i = 0;
let mut last = 0;
while i < b.len() {
let c = b[i];
if c == b'/' && b.get(i + 1) == Some(&b'/') {
while i < b.len() && b[i] != b'\n' {
i += 1;
}
continue;
}
if c == b'/' && b.get(i + 1) == Some(&b'*') {
i += 2;
while i + 1 < b.len() && !(b[i] == b'*' && b[i + 1] == b'/') {
i += 1;
}
i += 2;
continue;
}
if c == b'"' || c == b'`' || c == b'\'' {
i += 1;
while i < b.len() && b[i] != c {
i += if b[i] == b'\\' { 2 } else { 1 };
}
i += 1;
continue;
}
if c.is_ascii_alphabetic() || c == b'_' {
let start = i;
while i < b.len() && (b[i].is_ascii_alphanumeric() || b[i] == b'_') {
i += 1;
}
let prev = source[..start].trim_end().as_bytes().last().copied();
let next = source[i..].trim_start().as_bytes().first().copied();
if &source[start..i] == "call" && prev != Some(b'.') && next == Some(b'(') {
out.push_str(&source[last..start]);
out.push_str(HOST_CALL);
last = i;
}
continue;
}
i += 1;
}
out.push_str(&source[last..]);
out
}
fn start_of(e: &rhai::Expr) -> rhai::Position {
match e {
rhai::Expr::FnCall(f, _) if !f.args.is_empty() && !f.name.starts_with(|c: char| c.is_alphanumeric() || c == '_') => start_of(&f.args[0]),
rhai::Expr::Index(x, ..) | rhai::Expr::Dot(x, ..) => start_of(&x.lhs),
rhai::Expr::And(x, _) | rhai::Expr::Or(x, _) | rhai::Expr::Coalesce(x, _) => start_of(&x[0]),
_ => e.start_position(),
}
}
fn as_written(source: &str, at: rhai::Position) -> String {
let (Some(line), Some(col)) = (at.line(), at.position()) else { return "an expression".into() };
let Some(text) = source.lines().nth(line - 1) else { return "an expression".into() };
let start: usize = text.char_indices().nth(col - 1).map_or(text.len(), |(i, _)| i);
let rest = &source[source.lines().take(line - 1).map(|l| l.len() + 1).sum::<usize>() + start..];
let (mut depth, mut quote, mut end) = (0i32, None::<char>, rest.len());
let mut chars = rest.char_indices();
while let Some((i, c)) = chars.next() {
match (quote, c) {
(Some(_), '\\') => {
chars.next();
}
(Some(q), c) if c == q => quote = None,
(Some(_), _) => {}
(None, '"' | '\'' | '`') => quote = Some(c),
(None, '(' | '[' | '{') => depth += 1,
(None, ')' | ']' | '}') if depth == 0 => {
end = i;
break;
}
(None, ')' | ']' | '}') => depth -= 1,
(None, ',') if depth == 0 => {
end = i;
break;
}
_ => {}
}
}
rest[..end].trim().to_string()
}
fn literal(e: &rhai::Expr) -> Option<String> {
match e {
rhai::Expr::StringConstant(s, _) => Some(s.to_string()),
rhai::Expr::FnCall(f, _) if f.name.as_str() == "+" && f.args.len() == 2 => Some(literal(&f.args[0])? + literal(&f.args[1])?.as_str()),
_ => None,
}
}
impl Folds {
pub fn compile(source: &str, uses: &[String], host: Rc<dyn Host>) -> Result<Self, FoldError> {
let uses: Rc<BTreeSet<String>> = Rc::new(uses.iter().cloned().collect());
let mut engine = Engine::new();
engine.set_max_operations(FUEL);
engine.set_optimization_level(rhai::OptimizationLevel::Simple);
let (h, u) = (host.clone(), uses.clone());
engine.register_fn(HOST_CALL, move |method: &str, params: rhai::Map| -> Result<(), Box<rhai::EvalAltResult>> {
if !u.contains(method) {
return Err(format!("{method} is not in this component's uses").into());
}
h.call(method, rhai::serde::from_dynamic(&Dynamic::from_map(params)).unwrap_or(Value::Null));
Ok(())
});
let (h, u) = (host.clone(), uses.clone());
engine.register_fn(HOST_CALL, move |method: &str, params: rhai::Map, fold: &str| -> Result<(), Box<rhai::EvalAltResult>> {
if !u.contains(method) {
return Err(format!("{method} is not in this component's uses").into());
}
h.call_then(method, rhai::serde::from_dynamic(&Dynamic::from_map(params)).unwrap_or(Value::Null), fold);
Ok(())
});
let h = host.clone();
engine.register_fn("navigate", move |route: &str| h.navigate(route));
let h = host.clone();
engine.register_fn("emit", move |topic: &str, data: Dynamic| -> Result<(), Box<rhai::EvalAltResult>> {
h.emit(topic, rhai::serde::from_dynamic(&data).unwrap_or(Value::Null)).map_err(|m| m.into())
});
let h = host.clone();
engine.register_fn("bus_last", move |topic: &str| -> Dynamic { rhai::serde::to_dynamic(h.last(topic)).unwrap_or(Dynamic::UNIT) });
let h = host.clone();
engine.register_fn("slots_set", move |layout: &str, slot: &str, component: &str| -> Result<(), Box<rhai::EvalAltResult>> {
h.slots_set(layout, slot, component, None).map_err(|m| m.into())
});
let h = host.clone();
engine.register_fn("slots_set", move |layout: &str, slot: &str, component: &str, version: &str| -> Result<(), Box<rhai::EvalAltResult>> {
h.slots_set(layout, slot, component, Some(version)).map_err(|m| m.into())
});
let renamed = rename_calls(source);
let ast = engine.compile(&renamed).map_err(|e| FoldError::Compile(e.to_string()))?;
let mut handlers = Vec::new();
for f in ast.iter_functions() {
if f.params.len() != 2 {
return Err(FoldError::NotAFold { name: f.name.to_string() });
}
handlers.push(f.name.to_string());
}
let at = |p: rhai::Position| (p.line().unwrap_or(0), p.position().unwrap_or(0));
#[allow(deprecated)]
let spans: Vec<(String, (usize, usize), (usize, usize))> =
ast.lib().iter_script_fn_info().map(|(_, _, name, _, def)| (name.to_string(), at(def.body.start_position()), at(def.body.end_position()))).collect();
let owner = |p: rhai::Position| spans.iter().find(|(_, s, e)| (*s..=*e).contains(&at(p))).map(|(n, _, _)| n.clone()).unwrap_or_else(|| "a handler".into());
let mut refusal = None;
ast.walk(&mut |path: &[rhai::ASTNode]| {
let call = match path.last() {
Some(rhai::ASTNode::Expr(rhai::Expr::FnCall(f, pos))) | Some(rhai::ASTNode::Stmt(rhai::Stmt::FnCall(f, pos))) => Some((f, *pos)),
_ => None,
};
if let Some((f, pos)) = call.filter(|(f, _)| f.name.as_str() == HOST_CALL) {
let name = owner(pos);
let fold = match f.args.get(2) {
_ if f.args.len() > 3 => Some(FoldError::CallArity { handler: name.clone(), args: f.args.len() }),
None => None,
Some(rhai::Expr::StringConstant(s, _)) if handlers.iter().any(|h| h == s.as_str()) => None,
Some(rhai::Expr::StringConstant(s, _)) => Some(FoldError::NoAnswerFold { handler: name.clone(), fold: s.to_string() }),
Some(other) => Some(FoldError::ComputedFold { handler: name.clone(), expr: as_written(&renamed, start_of(other)) }),
};
refusal = match f.args.first().map(|a| (literal(a), a)) {
Some((Some(_), _)) if fold.is_some() => fold,
Some((Some(m), _)) if uses.contains(&m) => None,
Some((Some(method), _)) => Some(FoldError::NotInUses { handler: Some(name), method }),
Some((None, a)) => Some(FoldError::Computed { handler: name, expr: as_written(&renamed, start_of(a)) }),
None => Some(FoldError::Computed { handler: name, expr: "nothing".into() }),
};
return refusal.is_none();
}
true
});
if let Some(r) = refusal {
return Err(r);
}
Ok(Self { engine, ast, handlers })
}
pub fn handlers(&self) -> Vec<String> {
self.handlers.clone()
}
pub fn run(
&self,
handler: &str,
state: &Map<String, Value>,
event: &Value,
props: &Map<String, Value>,
live: &Map<String, Value>,
) -> Result<Map<String, Value>, FoldError> {
if !self.handlers.iter().any(|h| h == handler) {
return Err(FoldError::NoHandler(handler.to_string()));
}
let mut ev = event.as_object().cloned().unwrap_or_default();
for k in ["value", "target"] {
ev.entry(k).or_insert(Value::Null);
}
ev.insert("props".into(), json!(props));
ev.insert("live".into(), json!(live));
let ev = Value::Object(ev);
let to = |v: &Value| rhai::serde::to_dynamic(v).unwrap_or(Dynamic::UNIT);
let run = |message: String| FoldError::Run { handler: handler.to_string(), message };
let out: Dynamic = self
.engine
.call_fn(&mut Scope::new(), &self.ast, handler, (to(&Value::Object(state.clone())), to(&ev)))
.map_err(|e| run(e.to_string()))?;
match rhai::serde::from_dynamic::<Value>(&out) {
Ok(Value::Object(m)) => Ok(m),
_ => Err(run(format!("returned {} where a fold returns the state, a map", out.type_name()))),
}
}
}
#[cfg(test)]
mod tests;