plexus_ui_engine/tree/
expr.rs1use rhai::{Dynamic, Engine, Scope, AST};
8use serde_json::Value;
9use std::collections::BTreeSet;
10use std::rc::Rc;
11
12const 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 e.register_fn("markdown", |text: &str| crate::html::markdown(text));
22 e
23 });
24}
25
26thread_local! {
27 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
36pub fn compiles() -> u64 {
39 COMPILES.with(|c| c.get())
40}
41
42pub fn engine() -> Rc<Engine> {
44 ENGINE.with(Rc::clone)
45}
46
47#[derive(Debug, Clone, Default, PartialEq, Eq)]
49pub struct Reads {
50 pub names: BTreeSet<String>,
52 pub state_keys: Option<BTreeSet<String>>,
55}
56
57#[derive(Clone)]
59pub struct Expr {
60 pub text: String,
61 pub ast: Rc<AST>,
62 pub reads: Reads,
63 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 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 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
93pub 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
104pub 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
114pub 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
183pub fn to_dynamic(v: &Value) -> Dynamic {
185 rhai::serde::to_dynamic(v).unwrap_or(Dynamic::UNIT)
186}
187
188pub fn to_value(d: &Dynamic) -> Value {
190 rhai::serde::from_dynamic::<Value>(d).unwrap_or(Value::Null)
191}
192
193pub 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
205pub 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}