use rhai::{Dynamic, Engine, Scope, AST};
use serde_json::Value;
use std::collections::BTreeSet;
use std::rc::Rc;
const FUEL: u64 = 100_000;
thread_local! {
static ENGINE: Rc<Engine> = Rc::new({
let mut e = Engine::new();
e.set_max_operations(FUEL);
e.set_optimization_level(rhai::OptimizationLevel::Simple);
e.register_fn("markdown", |text: &str| crate::html::markdown(text));
e
});
}
thread_local! {
static COMPILED: std::cell::RefCell<std::collections::HashMap<String, Expr>> = std::cell::RefCell::new(std::collections::HashMap::new());
static COMPILES: std::cell::Cell<u64> = const { std::cell::Cell::new(0) };
}
pub fn compiles() -> u64 {
COMPILES.with(|c| c.get())
}
pub fn engine() -> Rc<Engine> {
ENGINE.with(Rc::clone)
}
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct Reads {
pub names: BTreeSet<String>,
pub state_keys: Option<BTreeSet<String>>,
}
#[derive(Clone)]
pub struct Expr {
pub text: String,
pub ast: Rc<AST>,
pub reads: Reads,
pub path: Option<Rc<Vec<String>>>,
}
impl std::fmt::Debug for Expr {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "Expr({})", self.text)
}
}
impl Expr {
pub fn compile(text: &str) -> Result<Self, String> {
if let Some(e) = COMPILED.with(|c| c.borrow().get(text).cloned()) {
return Ok(e);
}
COMPILES.with(|c| c.set(c.get() + 1));
let ast = engine().compile_expression(text).map_err(|e| e.to_string())?;
let e = Self { text: text.to_string(), ast: Rc::new(ast), reads: scan(text), path: path_of(text).map(Rc::new) };
COMPILED.with(|c| c.borrow_mut().insert(text.to_string(), e.clone()));
Ok(e)
}
pub fn eval(&self, scope: &mut Scope<'static>) -> Result<Dynamic, String> {
engine().eval_ast_with_scope::<Dynamic>(scope, &self.ast).map_err(|e| e.to_string())
}
}
pub fn path_of(text: &str) -> Option<Vec<String>> {
let parts: Vec<String> = text.trim().split('.').map(|p| p.trim().to_string()).collect();
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'_');
if !parts.iter().all(ident) || matches!(parts[0].as_str(), "true" | "false" | "this" | "fn" | "let" | "if" | "while" | "for" | "loop" | "return") {
return None;
}
Some(parts)
}
pub fn walk<'a>(v: &'a Value, fields: &[String]) -> Option<&'a Value> {
let mut at = v;
for f in fields {
at = at.as_object()?.get(f)?;
}
Some(at)
}
pub fn scan(text: &str) -> Reads {
let b = text.as_bytes();
let mut reads = Reads { names: BTreeSet::new(), state_keys: Some(BTreeSet::new()) };
let mut i = 0;
let mut after_dot = false;
while i < b.len() {
let c = b[i];
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;
after_dot = false;
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 word = &text[start..i];
if !after_dot {
reads.names.insert(word.to_string());
if word == "state" {
let mut j = i;
while j < b.len() && b[j] == b' ' {
j += 1;
}
let key = (j < b.len() && b[j] == b'.').then(|| {
let mut k = j + 1;
while k < b.len() && b[k] == b' ' {
k += 1;
}
let s = k;
while k < b.len() && (b[k].is_ascii_alphanumeric() || b[k] == b'_') {
k += 1;
}
(k > s).then(|| text[s..k].to_string())
});
match (key.flatten(), reads.state_keys.as_mut()) {
(Some(k), Some(keys)) => {
keys.insert(k);
}
(None, _) => reads.state_keys = None,
_ => {}
}
}
}
after_dot = false;
continue;
}
if c.is_ascii_digit() {
while i < b.len() && (b[i].is_ascii_alphanumeric() || b[i] == b'_' || b[i] == b'.') {
i += 1;
}
after_dot = false;
continue;
}
after_dot = c == b'.' || (after_dot && c == b' ');
i += 1;
}
if !reads.names.contains("state") {
reads.state_keys = Some(BTreeSet::new());
}
reads
}
pub fn to_dynamic(v: &Value) -> Dynamic {
rhai::serde::to_dynamic(v).unwrap_or(Dynamic::UNIT)
}
pub fn to_value(d: &Dynamic) -> Value {
rhai::serde::from_dynamic::<Value>(d).unwrap_or(Value::Null)
}
pub fn as_text(d: &Dynamic) -> String {
if d.is_unit() {
String::new()
} else if let Some(s) = d.clone().try_cast::<rhai::ImmutableString>() {
s.to_string()
} else {
d.to_string()
}
}
pub fn truthy(d: &Dynamic) -> bool {
match d.as_bool() {
Ok(b) => b,
Err(_) => !d.is_unit(),
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn scan_finds_names_and_state_keys() {
let r = scan(r#""one " + id + ": " + state.n"#);
assert!(r.names.contains("id") && r.names.contains("state"));
assert_eq!(r.state_keys, Some(["n".to_string()].into()));
assert_eq!(scan("rows.rows").names, ["rows".to_string()].into());
assert_eq!(scan("state").state_keys, None);
assert_eq!(scan(r#""state.x""#).names.len(), 0);
assert_eq!(scan("r.id + \" \" + r.title").names, ["r".to_string()].into());
}
#[test]
fn a_path_is_a_name_and_its_fields() {
assert_eq!(path_of("r.id"), Some(vec!["r".to_string(), "id".to_string()]));
assert_eq!(path_of(" things.rows "), Some(vec!["things".to_string(), "rows".to_string()]));
assert_eq!(path_of("filter"), Some(vec!["filter".to_string()]));
for no in ["true", "r.id + 1", "\"a\"", "a[0]", "f(x)", "1.5", "a..b", ""] {
assert_eq!(path_of(no), None, "{no}");
}
}
#[test]
fn an_expression_compiles_once() {
let text = "r.id + \" once \" + r.title";
let before = compiles();
Expr::compile(text).unwrap();
Expr::compile(text).unwrap();
Expr::compile(text).unwrap();
assert_eq!(compiles() - before, 1, "one compile, then the kept one");
}
}