Skip to main content

plexus_ui_engine/tree/
expr.rs

1//! UI-6: the template's expressions — Rhai, over the scope: the props by
2//! name, `state`, each `live` collection by name (`{ rows, status }`), and
3//! each `{#each}`'s variable. An expression is compiled once; what it reads
4//! is found by scanning its text ([`Reads`]), so a binding reads (and so
5//! tracks) only the state keys and names it names.
6
7use rhai::{Dynamic, Engine, Scope, AST};
8use serde_json::Value;
9use std::collections::BTreeSet;
10use std::rc::Rc;
11
12/// The most operations one expression may take.
13const FUEL: u64 = 100_000;
14
15thread_local! {
16    static ENGINE: Rc<Engine> = Rc::new({
17        let mut e = Engine::new();
18        e.set_max_operations(FUEL);
19        e.set_optimization_level(rhai::OptimizationLevel::Simple);
20        // UI-10: markdown(text) → HTML, sanitized where `{@html}` draws it.
21        e.register_fn("markdown", |text: &str| crate::html::markdown(text));
22        e
23    });
24}
25
26thread_local! {
27    /// FRAME-17: every expression compiled once a page — at its tree's
28    /// parse — and taken from here at every mount and every evaluation
29    /// after (it was compiled three times per mount: the parse's check, the
30    /// mount's check, the mount's own cache). Keyed by its text; a text
31    /// that does not compile is not kept.
32    static COMPILED: std::cell::RefCell<std::collections::HashMap<String, Expr>> = std::cell::RefCell::new(std::collections::HashMap::new());
33    static COMPILES: std::cell::Cell<u64> = const { std::cell::Cell::new(0) };
34}
35
36/// FRAME-17: how many times an expression went through Rhai's compiler
37/// on this thread (the tests read it).
38pub fn compiles() -> u64 {
39    COMPILES.with(|c| c.get())
40}
41
42/// The expressions' engine (one per thread: the page has one).
43pub fn engine() -> Rc<Engine> {
44    ENGINE.with(Rc::clone)
45}
46
47/// What an expression's text reads.
48#[derive(Debug, Clone, Default, PartialEq, Eq)]
49pub struct Reads {
50    /// Every name it reads as a variable.
51    pub names: BTreeSet<String>,
52    /// The state keys it reads as `state.<key>`; `None` when it reads
53    /// `state` some other way (all of it).
54    pub state_keys: Option<BTreeSet<String>>,
55}
56
57/// A compiled expression.
58#[derive(Clone)]
59pub struct Expr {
60    pub text: String,
61    pub ast: Rc<AST>,
62    pub reads: Reads,
63    /// FRAME-17: `name(.field)*` — read straight from the scope's values,
64    /// no Rhai and no conversion of what it reads into Rhai's.
65    pub path: Option<Rc<Vec<String>>>,
66}
67
68impl std::fmt::Debug for Expr {
69    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
70        write!(f, "Expr({})", self.text)
71    }
72}
73
74impl Expr {
75    /// Compiles `text`; refused, naming why.
76    pub fn compile(text: &str) -> Result<Self, String> {
77        if let Some(e) = COMPILED.with(|c| c.borrow().get(text).cloned()) {
78            return Ok(e);
79        }
80        COMPILES.with(|c| c.set(c.get() + 1));
81        let ast = engine().compile_expression(text).map_err(|e| e.to_string())?;
82        let e = Self { text: text.to_string(), ast: Rc::new(ast), reads: scan(text), path: path_of(text).map(Rc::new) };
83        COMPILED.with(|c| c.borrow_mut().insert(text.to_string(), e.clone()));
84        Ok(e)
85    }
86
87    /// Evaluates it in `scope`.
88    pub fn eval(&self, scope: &mut Scope<'static>) -> Result<Dynamic, String> {
89        engine().eval_ast_with_scope::<Dynamic>(scope, &self.ast).map_err(|e| e.to_string())
90    }
91}
92
93/// `text` as a path — `name` or `name.field…`, each an identifier and the
94/// first no Rhai word — or none.
95pub fn path_of(text: &str) -> Option<Vec<String>> {
96    let parts: Vec<String> = text.trim().split('.').map(|p| p.trim().to_string()).collect();
97    let ident = |p: &String| !p.is_empty() && p.bytes().next().is_some_and(|b| b.is_ascii_alphabetic() || b == b'_') && p.bytes().all(|b| b.is_ascii_alphanumeric() || b == b'_');
98    if !parts.iter().all(ident) || matches!(parts[0].as_str(), "true" | "false" | "this" | "fn" | "let" | "if" | "while" | "for" | "loop" | "return") {
99        return None;
100    }
101    Some(parts)
102}
103
104/// The value at `path` (fields after the first) inside `v`: null where a
105/// field is missing, as Rhai reads a map's missing property.
106pub fn walk<'a>(v: &'a Value, fields: &[String]) -> Option<&'a Value> {
107    let mut at = v;
108    for f in fields {
109        at = at.as_object()?.get(f)?;
110    }
111    Some(at)
112}
113
114/// The names and `state.<key>`s in `text`, string literals skipped.
115pub fn scan(text: &str) -> Reads {
116    let b = text.as_bytes();
117    let mut reads = Reads { names: BTreeSet::new(), state_keys: Some(BTreeSet::new()) };
118    let mut i = 0;
119    let mut after_dot = false;
120    while i < b.len() {
121        let c = b[i];
122        if c == b'"' || c == b'`' || c == b'\'' {
123            i += 1;
124            while i < b.len() && b[i] != c {
125                i += if b[i] == b'\\' { 2 } else { 1 };
126            }
127            i += 1;
128            after_dot = false;
129            continue;
130        }
131        if c.is_ascii_alphabetic() || c == b'_' {
132            let start = i;
133            while i < b.len() && (b[i].is_ascii_alphanumeric() || b[i] == b'_') {
134                i += 1;
135            }
136            let word = &text[start..i];
137            if !after_dot {
138                reads.names.insert(word.to_string());
139                if word == "state" {
140                    let mut j = i;
141                    while j < b.len() && b[j] == b' ' {
142                        j += 1;
143                    }
144                    let key = (j < b.len() && b[j] == b'.').then(|| {
145                        let mut k = j + 1;
146                        while k < b.len() && b[k] == b' ' {
147                            k += 1;
148                        }
149                        let s = k;
150                        while k < b.len() && (b[k].is_ascii_alphanumeric() || b[k] == b'_') {
151                            k += 1;
152                        }
153                        (k > s).then(|| text[s..k].to_string())
154                    });
155                    match (key.flatten(), reads.state_keys.as_mut()) {
156                        (Some(k), Some(keys)) => {
157                            keys.insert(k);
158                        }
159                        (None, _) => reads.state_keys = None,
160                        _ => {}
161                    }
162                }
163            }
164            after_dot = false;
165            continue;
166        }
167        if c.is_ascii_digit() {
168            while i < b.len() && (b[i].is_ascii_alphanumeric() || b[i] == b'_' || b[i] == b'.') {
169                i += 1;
170            }
171            after_dot = false;
172            continue;
173        }
174        after_dot = c == b'.' || (after_dot && c == b' ');
175        i += 1;
176    }
177    if !reads.names.contains("state") {
178        reads.state_keys = Some(BTreeSet::new());
179    }
180    reads
181}
182
183/// A JSON value as Rhai's.
184pub fn to_dynamic(v: &Value) -> Dynamic {
185    rhai::serde::to_dynamic(v).unwrap_or(Dynamic::UNIT)
186}
187
188/// Rhai's value as JSON.
189pub fn to_value(d: &Dynamic) -> Value {
190    rhai::serde::from_dynamic::<Value>(d).unwrap_or(Value::Null)
191}
192
193/// A value drawn as text: a string as it is, unit as nothing, anything
194/// else as Rhai prints it.
195pub fn as_text(d: &Dynamic) -> String {
196    if d.is_unit() {
197        String::new()
198    } else if let Some(s) = d.clone().try_cast::<rhai::ImmutableString>() {
199        s.to_string()
200    } else {
201        d.to_string()
202    }
203}
204
205/// A value as a condition: a bool as it is; unit false; anything else true.
206pub fn truthy(d: &Dynamic) -> bool {
207    match d.as_bool() {
208        Ok(b) => b,
209        Err(_) => !d.is_unit(),
210    }
211}
212
213#[cfg(test)]
214mod tests {
215    use super::*;
216
217    #[test]
218    fn scan_finds_names_and_state_keys() {
219        let r = scan(r#""one " + id + ": " + state.n"#);
220        assert!(r.names.contains("id") && r.names.contains("state"));
221        assert_eq!(r.state_keys, Some(["n".to_string()].into()));
222        assert_eq!(scan("rows.rows").names, ["rows".to_string()].into());
223        assert_eq!(scan("state").state_keys, None);
224        assert_eq!(scan(r#""state.x""#).names.len(), 0);
225        assert_eq!(scan("r.id + \" \" + r.title").names, ["r".to_string()].into());
226    }
227
228    #[test]
229    fn a_path_is_a_name_and_its_fields() {
230        assert_eq!(path_of("r.id"), Some(vec!["r".to_string(), "id".to_string()]));
231        assert_eq!(path_of(" things.rows "), Some(vec!["things".to_string(), "rows".to_string()]));
232        assert_eq!(path_of("filter"), Some(vec!["filter".to_string()]));
233        for no in ["true", "r.id + 1", "\"a\"", "a[0]", "f(x)", "1.5", "a..b", ""] {
234            assert_eq!(path_of(no), None, "{no}");
235        }
236    }
237
238    #[test]
239    fn an_expression_compiles_once() {
240        let text = "r.id + \" once \" + r.title";
241        let before = compiles();
242        Expr::compile(text).unwrap();
243        Expr::compile(text).unwrap();
244        Expr::compile(text).unwrap();
245        assert_eq!(compiles() - before, 1, "one compile, then the kept one");
246    }
247}