Skip to main content

plexus_ui_engine/folds/
mod.rs

1//! UI-6: **the folds** — a component's handlers, `components/<name>.rhai`,
2//! run in Rhai: every `fn name(state, ev)` returns the new state.
3//!
4//! One `rhai::Engine` per component with only `call(method, params)`,
5//! `navigate(route)` and, FRAME-12, the bus's `emit(topic, data)` and
6//! `slots_set(layout, slot, component[, version])` registered — no DOM, no
7//! socket, no other component. A topic the component hears (`on("topic",
8//! "fold")`, the tree's `bus`) runs its fold with `ev.bus = { topic, data }`.
9//! The props are constants in the scope by name. `call` is held to the
10//! component's `uses`: a handler naming a method outside it is refused when
11//! the component is compiled (at mount), naming the method; the engine
12//! checks it again at the call. FRAME-37: `call(method, params, "fold")` —
13//! the fold a handler of this component, by a literal name, refused at
14//! mount otherwise — runs that fold once when the call's stream ends, with
15//! `ev = #{ method, params, ok, events, message }` ([`Host::call_then`]).
16
17use rhai::{Dynamic, Engine, Scope, AST};
18use serde_json::{json, Map, Value};
19use std::collections::BTreeSet;
20use std::rc::Rc;
21
22/// The most operations one fold may take.
23const FUEL: u64 = 1_000_000;
24
25/// What a handler reaches: the engine's `call` and `navigate`.
26pub trait Host {
27    /// A Plexus call through the engine's one socket (its answer is not the
28    /// handler's: a `live` collection hears the change).
29    fn call(&self, method: &str, params: Value);
30    /// FRAME-37: `call(method, params, "fold")` — the call sent once, and
31    /// `fold` run once when its stream ends, with the answer
32    /// (`crate::bus::Answer`) and the call on `ev`. A host that runs no
33    /// fold sends it as [`Self::call`].
34    fn call_then(&self, method: &str, params: Value, fold: &str) {
35        let _ = fold;
36        self.call(method, params)
37    }
38    /// Moves the page to `route` (`#/ticket/T-1`).
39    fn navigate(&self, route: &str);
40    /// FRAME-12: `data` on the bus's `topic`; a refusal's words.
41    fn emit(&self, topic: &str, data: Value) -> Result<(), String> {
42        let _ = (topic, data);
43        Err("this host has no bus".into())
44    }
45    /// FRAME-53: `bus_last(topic)` — the topic's kept event, null when none.
46    fn last(&self, topic: &str) -> Value {
47        let _ = topic;
48        Value::Null
49    }
50    /// FRAME-12: `ui.slots.set`, held to the component's `uses`.
51    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/// Why handlers did not compile or a fold did not run.
58#[derive(Debug, Clone, PartialEq)]
59pub enum FoldError {
60    /// The Rhai did not compile: why.
61    Compile(String),
62    /// A handler calls `method`, which the component's `uses` does not name.
63    NotInUses { handler: Option<String>, method: String },
64    /// A handler's `call` names its method by an expression that is not a
65    /// string (or strings joined by `+`): the handler, and the expression.
66    Computed { handler: String, expr: String },
67    /// FRAME-37: a handler's `call(…, "fold")` names no handler of this
68    /// component: the handler, and the name.
69    NoAnswerFold { handler: String, fold: String },
70    /// FRAME-37: a handler's `call(…, fold)` names its fold by an
71    /// expression: the handler, and the expression as written.
72    ComputedFold { handler: String, expr: String },
73    /// FRAME-37: a handler's `call` with more than three arguments.
74    CallArity { handler: String, args: usize },
75    /// A `fn` that is not a fold `(state, ev)`.
76    NotAFold { name: String },
77    /// No handler of that name.
78    NoHandler(String),
79    /// The fold failed, or returned no map: why.
80    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
106/// A component's compiled handlers.
107pub struct Folds {
108    engine: Engine,
109    ast: AST,
110    handlers: Vec<String>,
111}
112
113/// What the engine registers `call` as: Rhai keeps `call(…)` for calling a
114/// function pointer, so a handler's `call(` is renamed before compiling.
115const HOST_CALL: &str = "host_call";
116
117/// `source` with each `call(` that is a call of the host's (not a method,
118/// not inside a string or a comment) renamed [`HOST_CALL`].
119fn 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
168/// Where `e` begins in the source: an operator's left operand, not the
169/// operator (rhai places a binary call at its operator).
170fn 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
179/// FRAME-37: the argument that begins at `at` in `source`, as written — up
180/// to the `,` or `)` that ends it at its own depth.
181fn 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
212/// The method a `call`'s first argument names, when written as a string
213/// (or strings joined by `+`).
214fn 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    /// Compiles `source` for a component whose `uses` is `uses`; refused
224    /// when it does not compile, when a `fn` is not a fold, or when a
225    /// handler calls a method outside `uses` — or by a name computed at run
226    /// time — naming it.
227    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        // Each call attributed to the handler whose body holds it (by
274        // position: rhai 1.27 names a body's type only inside itself).
275        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                // FRAME-37: at most three arguments, the third a handler named
289                // as written — as the compiler refuses, so a tree stored
290                // without it does not mount and fail at the click.
291                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    /// The handlers by name.
316    pub fn handlers(&self) -> Vec<String> {
317        self.handlers.clone()
318    }
319
320    /// Runs `handler` on `state` and the event: `ev` is the DOM event's
321    /// payload (`value`, `checked`, `target`, `key`, the scroll metrics) with the props as `ev.props` and each
322    /// `live` collection's rows as `ev.live.<name>`. The new state.
323    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        // UI-10: what the DOM gave (value, checked, target, key, scroll_top,
335        // scroll_height, client_height, as they apply), then the props and
336        // the live rows.
337        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;