1use rhai::{Dynamic, Engine, Scope, AST};
18use serde_json::{json, Map, Value};
19use std::collections::BTreeSet;
20use std::rc::Rc;
21
22const FUEL: u64 = 1_000_000;
24
25pub trait Host {
27 fn call(&self, method: &str, params: Value);
30 fn call_then(&self, method: &str, params: Value, fold: &str) {
35 let _ = fold;
36 self.call(method, params)
37 }
38 fn navigate(&self, route: &str);
40 fn emit(&self, topic: &str, data: Value) -> Result<(), String> {
42 let _ = (topic, data);
43 Err("this host has no bus".into())
44 }
45 fn last(&self, topic: &str) -> Value {
47 let _ = topic;
48 Value::Null
49 }
50 fn slots_set(&self, layout: &str, slot: &str, component: &str, version: Option<&str>) -> Result<(), String> {
52 let _ = (layout, slot, component, version);
53 Err("this host has no bus".into())
54 }
55}
56
57#[derive(Debug, Clone, PartialEq)]
59pub enum FoldError {
60 Compile(String),
62 NotInUses { handler: Option<String>, method: String },
64 Computed { handler: String, expr: String },
67 NoAnswerFold { handler: String, fold: String },
70 ComputedFold { handler: String, expr: String },
73 CallArity { handler: String, args: usize },
75 NotAFold { name: String },
77 NoHandler(String),
79 Run { handler: String, message: String },
81}
82
83impl std::fmt::Display for FoldError {
84 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
85 match self {
86 FoldError::Compile(m) => write!(f, "the handlers do not compile: {m}"),
87 FoldError::NotInUses { handler: Some(h), method } => write!(f, "{h} calls {method}, which this component's uses does not name"),
88 FoldError::NotInUses { handler: None, method } => write!(f, "a handler calls {method}, which this component's uses does not name"),
89 FoldError::Computed { handler, expr } => write!(f, "{handler} calls a method named by `{expr}`: a call's method is a string as written"),
90 FoldError::NoAnswerFold { handler, fold } => {
91 write!(f, "{handler} calls with the answer to `{fold}`, and this component has no fn {fold}(state, ev)")
92 }
93 FoldError::ComputedFold { handler, expr } => {
94 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")
95 }
96 FoldError::CallArity { handler, args } => {
97 write!(f, "{handler} calls with {args} arguments: call(method, params) or call(method, params, \"fold\"), nothing more")
98 }
99 FoldError::NotAFold { name } => write!(f, "fn {name} is not a fold (state, ev) → state"),
100 FoldError::NoHandler(h) => write!(f, "no handler {h}"),
101 FoldError::Run { handler, message } => write!(f, "{handler} failed: {message}"),
102 }
103 }
104}
105
106pub struct Folds {
108 engine: Engine,
109 ast: AST,
110 handlers: Vec<String>,
111}
112
113const HOST_CALL: &str = "host_call";
116
117fn rename_calls(source: &str) -> String {
120 let b = source.as_bytes();
121 let mut out = String::with_capacity(source.len() + 32);
122 let mut i = 0;
123 let mut last = 0;
124 while i < b.len() {
125 let c = b[i];
126 if c == b'/' && b.get(i + 1) == Some(&b'/') {
127 while i < b.len() && b[i] != b'\n' {
128 i += 1;
129 }
130 continue;
131 }
132 if c == b'/' && b.get(i + 1) == Some(&b'*') {
133 i += 2;
134 while i + 1 < b.len() && !(b[i] == b'*' && b[i + 1] == b'/') {
135 i += 1;
136 }
137 i += 2;
138 continue;
139 }
140 if c == b'"' || c == b'`' || c == b'\'' {
141 i += 1;
142 while i < b.len() && b[i] != c {
143 i += if b[i] == b'\\' { 2 } else { 1 };
144 }
145 i += 1;
146 continue;
147 }
148 if c.is_ascii_alphabetic() || c == b'_' {
149 let start = i;
150 while i < b.len() && (b[i].is_ascii_alphanumeric() || b[i] == b'_') {
151 i += 1;
152 }
153 let prev = source[..start].trim_end().as_bytes().last().copied();
154 let next = source[i..].trim_start().as_bytes().first().copied();
155 if &source[start..i] == "call" && prev != Some(b'.') && next == Some(b'(') {
156 out.push_str(&source[last..start]);
157 out.push_str(HOST_CALL);
158 last = i;
159 }
160 continue;
161 }
162 i += 1;
163 }
164 out.push_str(&source[last..]);
165 out
166}
167
168fn start_of(e: &rhai::Expr) -> rhai::Position {
171 match e {
172 rhai::Expr::FnCall(f, _) if !f.args.is_empty() && !f.name.starts_with(|c: char| c.is_alphanumeric() || c == '_') => start_of(&f.args[0]),
173 rhai::Expr::Index(x, ..) | rhai::Expr::Dot(x, ..) => start_of(&x.lhs),
174 rhai::Expr::And(x, _) | rhai::Expr::Or(x, _) | rhai::Expr::Coalesce(x, _) => start_of(&x[0]),
175 _ => e.start_position(),
176 }
177}
178
179fn as_written(source: &str, at: rhai::Position) -> String {
182 let (Some(line), Some(col)) = (at.line(), at.position()) else { return "an expression".into() };
183 let Some(text) = source.lines().nth(line - 1) else { return "an expression".into() };
184 let start: usize = text.char_indices().nth(col - 1).map_or(text.len(), |(i, _)| i);
185 let rest = &source[source.lines().take(line - 1).map(|l| l.len() + 1).sum::<usize>() + start..];
186 let (mut depth, mut quote, mut end) = (0i32, None::<char>, rest.len());
187 let mut chars = rest.char_indices();
188 while let Some((i, c)) = chars.next() {
189 match (quote, c) {
190 (Some(_), '\\') => {
191 chars.next();
192 }
193 (Some(q), c) if c == q => quote = None,
194 (Some(_), _) => {}
195 (None, '"' | '\'' | '`') => quote = Some(c),
196 (None, '(' | '[' | '{') => depth += 1,
197 (None, ')' | ']' | '}') if depth == 0 => {
198 end = i;
199 break;
200 }
201 (None, ')' | ']' | '}') => depth -= 1,
202 (None, ',') if depth == 0 => {
203 end = i;
204 break;
205 }
206 _ => {}
207 }
208 }
209 rest[..end].trim().to_string()
210}
211
212fn literal(e: &rhai::Expr) -> Option<String> {
215 match e {
216 rhai::Expr::StringConstant(s, _) => Some(s.to_string()),
217 rhai::Expr::FnCall(f, _) if f.name.as_str() == "+" && f.args.len() == 2 => Some(literal(&f.args[0])? + literal(&f.args[1])?.as_str()),
218 _ => None,
219 }
220}
221
222impl Folds {
223 pub fn compile(source: &str, uses: &[String], host: Rc<dyn Host>) -> Result<Self, FoldError> {
228 let uses: Rc<BTreeSet<String>> = Rc::new(uses.iter().cloned().collect());
229 let mut engine = Engine::new();
230 engine.set_max_operations(FUEL);
231 engine.set_optimization_level(rhai::OptimizationLevel::Simple);
232 let (h, u) = (host.clone(), uses.clone());
233 engine.register_fn(HOST_CALL, move |method: &str, params: rhai::Map| -> Result<(), Box<rhai::EvalAltResult>> {
234 if !crate::bus::covers(u.iter().map(String::as_str), method) {
235 return Err(format!("{method} is not in this component's uses").into());
236 }
237 h.call(method, rhai::serde::from_dynamic(&Dynamic::from_map(params)).unwrap_or(Value::Null));
238 Ok(())
239 });
240 let (h, u) = (host.clone(), uses.clone());
241 engine.register_fn(HOST_CALL, move |method: &str, params: rhai::Map, fold: &str| -> Result<(), Box<rhai::EvalAltResult>> {
242 if !crate::bus::covers(u.iter().map(String::as_str), method) {
243 return Err(format!("{method} is not in this component's uses").into());
244 }
245 h.call_then(method, rhai::serde::from_dynamic(&Dynamic::from_map(params)).unwrap_or(Value::Null), fold);
246 Ok(())
247 });
248 let h = host.clone();
249 engine.register_fn("navigate", move |route: &str| h.navigate(route));
250 let h = host.clone();
251 engine.register_fn("emit", move |topic: &str, data: Dynamic| -> Result<(), Box<rhai::EvalAltResult>> {
252 h.emit(topic, rhai::serde::from_dynamic(&data).unwrap_or(Value::Null)).map_err(|m| m.into())
253 });
254 let h = host.clone();
255 engine.register_fn("bus_last", move |topic: &str| -> Dynamic { rhai::serde::to_dynamic(h.last(topic)).unwrap_or(Dynamic::UNIT) });
256 let h = host.clone();
257 engine.register_fn("slots_set", move |layout: &str, slot: &str, component: &str| -> Result<(), Box<rhai::EvalAltResult>> {
258 h.slots_set(layout, slot, component, None).map_err(|m| m.into())
259 });
260 let h = host.clone();
261 engine.register_fn("slots_set", move |layout: &str, slot: &str, component: &str, version: &str| -> Result<(), Box<rhai::EvalAltResult>> {
262 h.slots_set(layout, slot, component, Some(version)).map_err(|m| m.into())
263 });
264 let renamed = rename_calls(source);
265 let ast = engine.compile(&renamed).map_err(|e| FoldError::Compile(e.to_string()))?;
266 let mut handlers = Vec::new();
267 for f in ast.iter_functions() {
268 if f.params.len() != 2 {
269 return Err(FoldError::NotAFold { name: f.name.to_string() });
270 }
271 handlers.push(f.name.to_string());
272 }
273 let at = |p: rhai::Position| (p.line().unwrap_or(0), p.position().unwrap_or(0));
276 #[allow(deprecated)]
277 let spans: Vec<(String, (usize, usize), (usize, usize))> =
278 ast.lib().iter_script_fn_info().map(|(_, _, name, _, def)| (name.to_string(), at(def.body.start_position()), at(def.body.end_position()))).collect();
279 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());
280 let mut refusal = None;
281 ast.walk(&mut |path: &[rhai::ASTNode]| {
282 let call = match path.last() {
283 Some(rhai::ASTNode::Expr(rhai::Expr::FnCall(f, pos))) | Some(rhai::ASTNode::Stmt(rhai::Stmt::FnCall(f, pos))) => Some((f, *pos)),
284 _ => None,
285 };
286 if let Some((f, pos)) = call.filter(|(f, _)| f.name.as_str() == HOST_CALL) {
287 let name = owner(pos);
288 let fold = match f.args.get(2) {
292 _ if f.args.len() > 3 => Some(FoldError::CallArity { handler: name.clone(), args: f.args.len() }),
293 None => None,
294 Some(rhai::Expr::StringConstant(s, _)) if handlers.iter().any(|h| h == s.as_str()) => None,
295 Some(rhai::Expr::StringConstant(s, _)) => Some(FoldError::NoAnswerFold { handler: name.clone(), fold: s.to_string() }),
296 Some(other) => Some(FoldError::ComputedFold { handler: name.clone(), expr: as_written(&renamed, start_of(other)) }),
297 };
298 refusal = match f.args.first().map(|a| (literal(a), a)) {
299 Some((Some(_), _)) if fold.is_some() => fold,
300 Some((Some(m), _)) if crate::bus::covers(uses.iter().map(String::as_str), &m) => None,
301 Some((Some(method), _)) => Some(FoldError::NotInUses { handler: Some(name), method }),
302 Some((None, a)) => Some(FoldError::Computed { handler: name, expr: as_written(&renamed, start_of(a)) }),
303 None => Some(FoldError::Computed { handler: name, expr: "nothing".into() }),
304 };
305 return refusal.is_none();
306 }
307 true
308 });
309 if let Some(r) = refusal {
310 return Err(r);
311 }
312 Ok(Self { engine, ast, handlers })
313 }
314
315 pub fn handlers(&self) -> Vec<String> {
317 self.handlers.clone()
318 }
319
320 pub fn run(
324 &self,
325 handler: &str,
326 state: &Map<String, Value>,
327 event: &Value,
328 props: &Map<String, Value>,
329 live: &Map<String, Value>,
330 ) -> Result<Map<String, Value>, FoldError> {
331 if !self.handlers.iter().any(|h| h == handler) {
332 return Err(FoldError::NoHandler(handler.to_string()));
333 }
334 let mut ev = event.as_object().cloned().unwrap_or_default();
338 for k in ["value", "target"] {
339 ev.entry(k).or_insert(Value::Null);
340 }
341 ev.insert("props".into(), json!(props));
342 ev.insert("live".into(), json!(live));
343 let ev = Value::Object(ev);
344 let to = |v: &Value| rhai::serde::to_dynamic(v).unwrap_or(Dynamic::UNIT);
345 let run = |message: String| FoldError::Run { handler: handler.to_string(), message };
346 let out: Dynamic = self
347 .engine
348 .call_fn(&mut Scope::new(), &self.ast, handler, (to(&Value::Object(state.clone())), to(&ev)))
349 .map_err(|e| run(e.to_string()))?;
350 match rhai::serde::from_dynamic::<Value>(&out) {
351 Ok(Value::Object(m)) => Ok(m),
352 _ => Err(run(format!("returned {} where a fold returns the state, a map", out.type_name()))),
353 }
354 }
355}
356
357#[cfg(test)]
358mod tests;