| 1 | //! Fusion SimpleExpression evaluation: `mlua` (Lua 5.4) natively, a pure-Rust subset on `wasm32`. |
| 2 | //! |
| 3 | //! Supports Fusion globals (`time`, `iif`, `Point`, `Text`, `sin`/`cos`/`floor`/`ceil`/etc.) |
| 4 | //! and `NodeName.ParamName` lookups without requiring full Fusion runtime scripting. |
| 5 | |
| 6 | /// An input readable from an expression. Text inputs surface as `{ Value = "..." }` tables that |
| 7 | /// also stringify, matching Fusion's `Node.StyledText.Value`. |
| 8 | #[derive(Clone, Debug, PartialEq)] |
| 9 | pub enum ExprValue { |
| 10 | Number(f64), |
| 11 | Text(String), |
| 12 | Point([f64; 2]), |
| 13 | } |
| 14 | |
| 15 | /// Lua's `tostring` for a float: C `%.14g`, so `0.1 + 0.2` reads `0.3` and `3.0` reads `3`. |
| 16 | fn format_number(n: f64) -> String { |
| 17 | if !n.is_finite() { |
| 18 | return if n.is_nan() { "nan" } else if n > 0.0 { "inf" } else { "-inf" }.to_owned(); |
| 19 | } |
| 20 | let sci = format!("{:.13e}", n.abs()); |
| 21 | let (mantissa, exp) = sci.split_once('e').expect("`{:e}` always has an exponent"); |
| 22 | let exp: i32 = exp.parse().expect("exponent is an integer"); |
| 23 | let digits: String = mantissa.chars().filter(char::is_ascii_digit).collect(); |
| 24 | let digits = digits.trim_end_matches('0'); |
| 25 | let digits = if digits.is_empty() { "0" } else { digits }; |
| 26 | let sign = if n.is_sign_negative() { "-" } else { "" }; |
| 27 | let (head, tail) = digits.split_at(1); |
| 28 | if !(-4..14).contains(&exp) { |
| 29 | let point = if tail.is_empty() { "" } else { "." }; |
| 30 | return format!("{sign}{head}{point}{tail}e{}{:02}", if exp < 0 { '-' } else { '+' }, exp.abs()); |
| 31 | } |
| 32 | if exp < 0 { |
| 33 | return format!("{sign}0.{}{digits}", "0".repeat(exp.unsigned_abs() as usize - 1)); |
| 34 | } |
| 35 | let int_len = exp as usize + 1; |
| 36 | let padded = format!("{digits:0<int_len$}"); |
| 37 | let (int, frac) = padded.split_at(int_len); |
| 38 | format!("{sign}{int}{}{frac}", if frac.is_empty() { "" } else { "." }) |
| 39 | } |
| 40 | |
| 41 | #[cfg(not(target_arch = "wasm32"))] |
| 42 | mod lua { |
| 43 | use super::ExprValue; |
| 44 | use mlua::{ChunkMode, Function, HookTriggers, Lua, LuaOptions, MultiValue, StdLib, Table, Value, VmState}; |
| 45 | use std::cell::RefCell; |
| 46 | use std::collections::HashMap; |
| 47 | use std::sync::Arc; |
| 48 | use std::sync::atomic::{AtomicBool, AtomicU64, Ordering}; |
| 49 | |
| 50 | /// VM instructions one expression evaluation may execute before it is aborted. |
| 51 | const INSTRUCTION_BUDGET: u64 = 50_000; |
| 52 | /// Hook granularity; the budget is enforced in steps of this many instructions. |
| 53 | const HOOK_STEP: u32 = 1000; |
| 54 | const MEMORY_LIMIT: usize = 16 * 1024 * 1024; |
| 55 | /// Max compiled expression bytecodes cached per `ExprEngine`. |
| 56 | const CHUNK_CACHE_CAP: usize = 512; |
| 57 | |
| 58 | /// Bounded LRU cache of compiled Lua chunk bytecodes (`None` for cached syntax errors). |
| 59 | struct ChunkCache { |
| 60 | entries: HashMap<String, (Option<Vec<u8>>, u64)>, |
| 61 | tick: u64, |
| 62 | } |
| 63 | |
| 64 | impl ChunkCache { |
| 65 | fn new() -> Self { |
| 66 | Self { |
| 67 | entries: HashMap::new(), |
| 68 | tick: 0, |
| 69 | } |
| 70 | } |
| 71 | |
| 72 | #[cfg(test)] |
| 73 | fn len(&self) -> usize { |
| 74 | self.entries.len() |
| 75 | } |
| 76 | |
| 77 | #[cfg(test)] |
| 78 | fn get(&self, key: &str) -> Option<&Option<Vec<u8>>> { |
| 79 | self.entries.get(key).map(|(v, _)| v) |
| 80 | } |
| 81 | |
| 82 | fn touch(&mut self, key: &str) -> Option<&Option<Vec<u8>>> { |
| 83 | let next = self.tick.wrapping_add(1); |
| 84 | self.tick = next; |
| 85 | self.entries.get_mut(key).map(|(v, t)| { |
| 86 | *t = next; |
| 87 | &*v |
| 88 | }) |
| 89 | } |
| 90 | |
| 91 | fn insert(&mut self, key: String, val: Option<Vec<u8>>) { |
| 92 | let next = self.tick.wrapping_add(1); |
| 93 | self.tick = next; |
| 94 | if !self.entries.contains_key(&key) && self.entries.len() >= CHUNK_CACHE_CAP { |
| 95 | if let Some(oldest) = self |
| 96 | .entries |
| 97 | .iter() |
| 98 | .min_by_key(|(_, (_, t))| *t) |
| 99 | .map(|(k, _)| k.clone()) |
| 100 | { |
| 101 | self.entries.remove(&oldest); |
| 102 | } |
| 103 | } |
| 104 | self.entries.insert(key, (val, next)); |
| 105 | } |
| 106 | } |
| 107 | |
| 108 | /// Expressions come from `.comp` files, so the VM is sandboxed: no `os`/`io`/`debug`/`package`, |
| 109 | /// no code loading, and bounded instructions and memory per evaluation. |
| 110 | pub struct ExprEngine { |
| 111 | lua: Lua, |
| 112 | instructions_used: Arc<AtomicU64>, |
| 113 | /// Latched once the budget is exceeded so every later hook call also errors. |
| 114 | aborted: Arc<AtomicBool>, |
| 115 | env_mt: Table, |
| 116 | zero_mt: Table, |
| 117 | text_mt: Table, |
| 118 | point_mt: Table, |
| 119 | chunk_cache: RefCell<ChunkCache>, |
| 120 | } |
| 121 | |
| 122 | impl Default for ExprEngine { |
| 123 | fn default() -> Self { |
| 124 | Self::new() |
| 125 | } |
| 126 | } |
| 127 | |
| 128 | impl ExprEngine { |
| 129 | pub fn new() -> Self { |
| 130 | let lua = Lua::new_with(StdLib::MATH | StdLib::STRING | StdLib::TABLE, LuaOptions::default()) |
| 131 | .expect("safe Lua stdlib subset loads"); |
| 132 | // Install Fusion SimpleExpression standard library into global scope. |
| 133 | let init = r#" |
| 134 | abs = math.abs |
| 135 | acos = math.acos |
| 136 | asin = math.asin |
| 137 | atan = math.atan |
| 138 | atan2 = math.atan |
| 139 | ceil = math.ceil |
| 140 | cos = math.cos |
| 141 | cosh = function(x) return (math.exp(x) + math.exp(-x)) * 0.5 end |
| 142 | deg = math.deg |
| 143 | exp = math.exp |
| 144 | floor = math.floor |
| 145 | fmod = math.fmod |
| 146 | log = math.log |
| 147 | log10 = function(x) return math.log(x, 10) end |
| 148 | max = math.max |
| 149 | min = math.min |
| 150 | mod = math.fmod |
| 151 | pi = math.pi |
| 152 | pow = function(a, b) return a ^ b end |
| 153 | rad = math.rad |
| 154 | sin = math.sin |
| 155 | sinh = function(x) return (math.exp(x) - math.exp(-x)) * 0.5 end |
| 156 | sqrt = math.sqrt |
| 157 | tan = math.tan |
| 158 | tanh = function(x) local e = math.exp(2*x); return (e - 1) / (e + 1) end |
| 159 | iif = function(cond, a, b) if cond and cond ~= 0 then return a else return b end end |
| 160 | local lua_tostring = tostring |
| 161 | tostring = function(v) if type(v) == "number" then return string.format("%.14g", v) end return lua_tostring(v) end |
| 162 | Text = function(s) return tostring(s or "") end |
| 163 | clamp = function(x, lo, hi) if x < lo then return lo elseif x > hi then return hi else return x end end |
| 164 | mix = function(a, b, t) return a + (b - a) * t end |
| 165 | "#; |
| 166 | let _ = lua.load(init).exec(); |
| 167 | |
| 168 | let globals = lua.globals(); |
| 169 | let point_mt = lua.create_table().expect("table creates"); |
| 170 | let make_pt = |lua: &Lua, mt: &Table, x: f64, y: f64| -> mlua::Result<Table> { |
| 171 | let pt = lua.create_table()?; |
| 172 | pt.set("X", x)?; |
| 173 | pt.set("Y", y)?; |
| 174 | pt.set(1, x)?; |
| 175 | pt.set(2, y)?; |
| 176 | pt.set_metatable(Some(mt.clone())); |
| 177 | Ok(pt) |
| 178 | }; |
| 179 | let read_pt = |v: &Value| -> Option<[f64; 2]> { |
| 180 | let Value::Table(t) = v else { return None }; |
| 181 | let x = t.get::<f64>("X").or_else(|_| t.get::<f64>(1)).ok()?; |
| 182 | let y = t.get::<f64>("Y").or_else(|_| t.get::<f64>(2)).ok()?; |
| 183 | Some([x, y]) |
| 184 | }; |
| 185 | let read_num = |v: &Value| -> Option<f64> { |
| 186 | match v { |
| 187 | Value::Number(n) => Some(*n), |
| 188 | Value::Integer(i) => Some(*i as f64), |
| 189 | _ => None, |
| 190 | } |
| 191 | }; |
| 192 | let mt_ref = point_mt.clone(); |
| 193 | point_mt |
| 194 | .set( |
| 195 | "__add", |
| 196 | lua.create_function(move |lua, (a, b): (Value, Value)| -> mlua::Result<Table> { |
| 197 | let (Some([ax, ay]), Some([bx, by])) = (read_pt(&a), read_pt(&b)) else { |
| 198 | return Err(mlua::Error::runtime("Point addition requires two Points")); |
| 199 | }; |
| 200 | make_pt(lua, &mt_ref, ax + bx, ay + by) |
| 201 | }) |
| 202 | .expect("function creates"), |
| 203 | ) |
| 204 | .expect("table sets"); |
| 205 | let mt_ref = point_mt.clone(); |
| 206 | point_mt |
| 207 | .set( |
| 208 | "__sub", |
| 209 | lua.create_function(move |lua, (a, b): (Value, Value)| -> mlua::Result<Table> { |
| 210 | let (Some([ax, ay]), Some([bx, by])) = (read_pt(&a), read_pt(&b)) else { |
| 211 | return Err(mlua::Error::runtime("Point subtraction requires two Points")); |
| 212 | }; |
| 213 | make_pt(lua, &mt_ref, ax - bx, ay - by) |
| 214 | }) |
| 215 | .expect("function creates"), |
| 216 | ) |
| 217 | .expect("table sets"); |
| 218 | let mt_ref = point_mt.clone(); |
| 219 | point_mt |
| 220 | .set( |
| 221 | "__mul", |
| 222 | lua.create_function(move |lua, (a, b): (Value, Value)| -> mlua::Result<Table> { |
| 223 | match (read_pt(&a), read_pt(&b), read_num(&a), read_num(&b)) { |
| 224 | (Some([ax, ay]), Some([bx, by]), _, _) => make_pt(lua, &mt_ref, ax * bx, ay * by), |
| 225 | (Some([ax, ay]), None, _, Some(s)) | (None, Some([ax, ay]), Some(s), _) => { |
| 226 | make_pt(lua, &mt_ref, ax * s, ay * s) |
| 227 | } |
| 228 | _ => Err(mlua::Error::runtime("invalid Point multiplication")), |
| 229 | } |
| 230 | }) |
| 231 | .expect("function creates"), |
| 232 | ) |
| 233 | .expect("table sets"); |
| 234 | let mt_ref = point_mt.clone(); |
| 235 | point_mt |
| 236 | .set( |
| 237 | "__div", |
| 238 | lua.create_function(move |lua, (a, b): (Value, Value)| -> mlua::Result<Table> { |
| 239 | match (read_pt(&a), read_pt(&b), read_num(&b)) { |
| 240 | (Some([ax, ay]), Some([bx, by]), _) => make_pt(lua, &mt_ref, ax / bx, ay / by), |
| 241 | (Some([ax, ay]), None, Some(s)) => make_pt(lua, &mt_ref, ax / s, ay / s), |
| 242 | _ => Err(mlua::Error::runtime("invalid Point division")), |
| 243 | } |
| 244 | }) |
| 245 | .expect("function creates"), |
| 246 | ) |
| 247 | .expect("table sets"); |
| 248 | let mt_ref = point_mt.clone(); |
| 249 | point_mt |
| 250 | .set( |
| 251 | "__unm", |
| 252 | lua.create_function(move |lua, a: Value| -> mlua::Result<Table> { |
| 253 | let Some([ax, ay]) = read_pt(&a) else { |
| 254 | return Err(mlua::Error::runtime("invalid Point negation")); |
| 255 | }; |
| 256 | make_pt(lua, &mt_ref, -ax, -ay) |
| 257 | }) |
| 258 | .expect("function creates"), |
| 259 | ) |
| 260 | .expect("table sets"); |
| 261 | let mt_ref = point_mt.clone(); |
| 262 | globals |
| 263 | .set( |
| 264 | "Point", |
| 265 | lua.create_function(move |lua, (x, y): (Option<f64>, Option<f64>)| { |
| 266 | make_pt(lua, &mt_ref, x.unwrap_or(0.0), y.unwrap_or(0.0)) |
| 267 | }) |
| 268 | .expect("function creates"), |
| 269 | ) |
| 270 | .expect("global sets"); |
| 271 | // Stdlib tables become write-protected proxies so no evaluation can alter them for the next. |
| 272 | let read_only = lua |
| 273 | .create_function(|_, _: MultiValue| -> mlua::Result<()> { |
| 274 | Err(mlua::Error::runtime("attempt to modify a read-only table")) |
| 275 | }) |
| 276 | .expect("function creates"); |
| 277 | for name in ["math", "string", "table"] { |
| 278 | let real: mlua::Table = globals.get(name).expect("stdlib table exists"); |
| 279 | let proxy = lua.create_table().expect("table creates"); |
| 280 | let mt = lua.create_table().expect("table creates"); |
| 281 | mt.set("__index", real).expect("table sets"); |
| 282 | mt.set("__newindex", read_only.clone()).expect("table sets"); |
| 283 | proxy.set_metatable(Some(mt)); |
| 284 | globals.set(name, proxy).expect("global sets"); |
| 285 | } |
| 286 | // `pcall`/`xpcall` would swallow the budget error; the rest reach shared tables or metatables. |
| 287 | for name in [ |
| 288 | "dofile", "loadfile", "load", "require", "collectgarbage", "os", "io", "debug", "package", |
| 289 | "pcall", "xpcall", "rawget", "rawset", "rawequal", "getmetatable", "setmetatable", "_G", |
| 290 | ] { |
| 291 | let _ = globals.set(name, Value::Nil); |
| 292 | } |
| 293 | |
| 294 | let instructions_used = Arc::new(AtomicU64::new(0)); |
| 295 | let aborted = Arc::new(AtomicBool::new(false)); |
| 296 | let counter = Arc::clone(&instructions_used); |
| 297 | let latch = Arc::clone(&aborted); |
| 298 | lua.set_hook(HookTriggers::new().every_nth_instruction(HOOK_STEP), move |_, _| { |
| 299 | if latch.load(Ordering::Relaxed) |
| 300 | || counter.fetch_add(u64::from(HOOK_STEP), Ordering::Relaxed) >= INSTRUCTION_BUDGET |
| 301 | { |
| 302 | latch.store(true, Ordering::Relaxed); |
| 303 | Err(mlua::Error::runtime("expression instruction budget exceeded")) |
| 304 | } else { |
| 305 | Ok(VmState::Continue) |
| 306 | } |
| 307 | }); |
| 308 | lua.set_memory_limit(MEMORY_LIMIT).expect("memory limit applies"); |
| 309 | |
| 310 | let env_mt = lua.create_table().expect("table creates"); |
| 311 | env_mt.set("__index", globals).expect("table sets"); |
| 312 | let zero_mt = lua.create_table().expect("table creates"); |
| 313 | zero_mt |
| 314 | .set( |
| 315 | "__index", |
| 316 | lua.create_function(|_, _args: MultiValue| Ok(0.0_f64)) |
| 317 | .expect("function creates"), |
| 318 | ) |
| 319 | .expect("table sets"); |
| 320 | let text_mt = lua.create_table().expect("table creates"); |
| 321 | text_mt |
| 322 | .set( |
| 323 | "__tostring", |
| 324 | lua.create_function(|_, this: Table| this.get::<String>("Value")) |
| 325 | .expect("function creates"), |
| 326 | ) |
| 327 | .expect("table sets"); |
| 328 | |
| 329 | Self { |
| 330 | lua, |
| 331 | instructions_used, |
| 332 | aborted, |
| 333 | env_mt, |
| 334 | zero_mt, |
| 335 | text_mt, |
| 336 | point_mt, |
| 337 | chunk_cache: RefCell::new(ChunkCache::new()), |
| 338 | } |
| 339 | } |
| 340 | |
| 341 | fn load_cached(&self, expr: &str, env: Table) -> Option<Function> { |
| 342 | { |
| 343 | let mut cache = self.chunk_cache.borrow_mut(); |
| 344 | if let Some(hit) = cache.touch(expr) { |
| 345 | let bytes = hit.as_ref()?; |
| 346 | return self |
| 347 | .lua |
| 348 | .load(bytes.as_slice()) |
| 349 | .set_mode(ChunkMode::Binary) |
| 350 | .set_environment(env) |
| 351 | .into_function() |
| 352 | .ok(); |
| 353 | } |
| 354 | } |
| 355 | let chunk_src = Self::expr_chunk(expr); |
| 356 | match self |
| 357 | .lua |
| 358 | .load(&chunk_src) |
| 359 | .set_mode(ChunkMode::Text) |
| 360 | .set_environment(env) |
| 361 | .into_function() |
| 362 | { |
| 363 | Ok(func) => { |
| 364 | let bytes = func.dump(true); |
| 365 | self.chunk_cache.borrow_mut().insert(expr.to_owned(), Some(bytes)); |
| 366 | Some(func) |
| 367 | } |
| 368 | Err(mlua::Error::SyntaxError { .. }) => { |
| 369 | self.chunk_cache.borrow_mut().insert(expr.to_owned(), None); |
| 370 | None |
| 371 | } |
| 372 | Err(_) => None, |
| 373 | } |
| 374 | } |
| 375 | |
| 376 | /// Evaluates `expr` in a fresh environment with a fresh instruction budget. |
| 377 | fn run( |
| 378 | &self, |
| 379 | expr: &str, |
| 380 | time: f64, |
| 381 | self_params: &HashMap<String, f64>, |
| 382 | self_points: &HashMap<String, [f64; 2]>, |
| 383 | env_nodes: &HashMap<String, HashMap<String, ExprValue>>, |
| 384 | ) -> Option<Value> { |
| 385 | let env = self.build_env(time, self_params, self_points, env_nodes).ok()?; |
| 386 | let func = self.load_cached(expr, env)?; |
| 387 | self.instructions_used.store(0, Ordering::Relaxed); |
| 388 | self.aborted.store(false, Ordering::Relaxed); |
| 389 | func.call::<Value>(()).ok() |
| 390 | } |
| 391 | |
| 392 | fn expr_chunk(expr: &str) -> String { |
| 393 | let trimmed = expr.trim_start(); |
| 394 | if let Some(body) = trimmed.strip_prefix(':') { |
| 395 | body.to_owned() |
| 396 | } else { |
| 397 | format!("return ({expr})") |
| 398 | } |
| 399 | } |
| 400 | |
| 401 | /// Evaluates a Fusion SimpleExpression returning a number. |
| 402 | /// `env_nodes` provides `node_name -> (param_name -> value)` and `self_params` provides |
| 403 | /// unqualified parameter names on the current node. |
| 404 | pub fn eval_number( |
| 405 | &self, |
| 406 | expr: &str, |
| 407 | time: f64, |
| 408 | self_params: &HashMap<String, f64>, |
| 409 | self_points: &HashMap<String, [f64; 2]>, |
| 410 | env_nodes: &HashMap<String, HashMap<String, ExprValue>>, |
| 411 | ) -> Option<f64> { |
| 412 | let val = self.run(expr, time, self_params, self_points, env_nodes)?; |
| 413 | match val { |
| 414 | Value::Number(n) => Some(n), |
| 415 | Value::Integer(i) => Some(i as f64), |
| 416 | Value::Boolean(b) => Some(if b { 1.0 } else { 0.0 }), |
| 417 | Value::String(s) => s.to_str().ok()?.trim().parse::<f64>().ok(), |
| 418 | _ => None, |
| 419 | } |
| 420 | } |
| 421 | |
| 422 | /// Evaluates a Fusion SimpleExpression returning a 2D point `[x, y]`. |
| 423 | pub fn eval_point( |
| 424 | &self, |
| 425 | expr: &str, |
| 426 | time: f64, |
| 427 | self_params: &HashMap<String, f64>, |
| 428 | self_points: &HashMap<String, [f64; 2]>, |
| 429 | env_nodes: &HashMap<String, HashMap<String, ExprValue>>, |
| 430 | ) -> Option<[f64; 2]> { |
| 431 | let val = self.run(expr, time, self_params, self_points, env_nodes)?; |
| 432 | if let Value::Table(t) = val { |
| 433 | let x = t.get::<f64>("X").or_else(|_| t.get::<f64>(1)).ok()?; |
| 434 | let y = t.get::<f64>("Y").or_else(|_| t.get::<f64>(2)).ok()?; |
| 435 | return Some([x, y]); |
| 436 | } |
| 437 | None |
| 438 | } |
| 439 | |
| 440 | /// Evaluates a Fusion SimpleExpression returning a string. |
| 441 | pub fn eval_string( |
| 442 | &self, |
| 443 | expr: &str, |
| 444 | time: f64, |
| 445 | self_params: &HashMap<String, f64>, |
| 446 | self_points: &HashMap<String, [f64; 2]>, |
| 447 | env_nodes: &HashMap<String, HashMap<String, ExprValue>>, |
| 448 | ) -> Option<String> { |
| 449 | let val = self.run(expr, time, self_params, self_points, env_nodes)?; |
| 450 | match val { |
| 451 | Value::String(s) => Some(s.to_str().ok()?.to_owned()), |
| 452 | Value::Number(n) => Some(super::format_number(n)), |
| 453 | Value::Integer(i) => Some(format!("{i}")), |
| 454 | Value::Table(t) => t.get::<String>("Value").ok(), |
| 455 | _ => None, |
| 456 | } |
| 457 | } |
| 458 | |
| 459 | fn make_point(&self, p: [f64; 2]) -> mlua::Result<Table> { |
| 460 | let pt = self.lua.create_table()?; |
| 461 | pt.set("X", p[0])?; |
| 462 | pt.set("Y", p[1])?; |
| 463 | pt.set(1, p[0])?; |
| 464 | pt.set(2, p[1])?; |
| 465 | pt.set_metatable(Some(self.point_mt.clone())); |
| 466 | Ok(pt) |
| 467 | } |
| 468 | |
| 469 | fn build_env( |
| 470 | &self, |
| 471 | time: f64, |
| 472 | self_params: &HashMap<String, f64>, |
| 473 | self_points: &HashMap<String, [f64; 2]>, |
| 474 | env_nodes: &HashMap<String, HashMap<String, ExprValue>>, |
| 475 | ) -> mlua::Result<Table> { |
| 476 | let env = self.lua.create_table()?; |
| 477 | env.set_metatable(Some(self.env_mt.clone())); |
| 478 | env.set("time", time)?; |
| 479 | env.set("comp", self.lua.create_table()?)?; |
| 480 | for (k, v) in self_params { |
| 481 | env.set(k.as_str(), *v)?; |
| 482 | } |
| 483 | for (k, p) in self_points { |
| 484 | env.set(k.as_str(), self.make_point(*p)?)?; |
| 485 | } |
| 486 | // Missing node fields default to 0 so expressions don't nil-crash. |
| 487 | for (node_name, params) in env_nodes { |
| 488 | let nt = self.lua.create_table()?; |
| 489 | for (pk, pv) in params { |
| 490 | match pv { |
| 491 | ExprValue::Number(n) => nt.set(pk.as_str(), *n)?, |
| 492 | ExprValue::Text(s) => { |
| 493 | let text = self.lua.create_table()?; |
| 494 | text.set("Value", s.as_str())?; |
| 495 | text.set_metatable(Some(self.text_mt.clone())); |
| 496 | nt.set(pk.as_str(), text)?; |
| 497 | } |
| 498 | ExprValue::Point(p) => nt.set(pk.as_str(), self.make_point(*p)?)?, |
| 499 | } |
| 500 | } |
| 501 | nt.set_metatable(Some(self.zero_mt.clone())); |
| 502 | env.set(node_name.as_str(), nt)?; |
| 503 | } |
| 504 | Ok(env) |
| 505 | } |
| 506 | } |
| 507 | |
| 508 | #[cfg(test)] |
| 509 | mod tests { |
| 510 | use super::*; |
| 511 | |
| 512 | fn num(expr: &str) -> Option<f64> { |
| 513 | let e = HashMap::new(); |
| 514 | ExprEngine::new().eval_number(expr, 2.0, &HashMap::new(), &HashMap::new(), &e) |
| 515 | } |
| 516 | |
| 517 | #[test] |
| 518 | fn fusion_expressions_still_evaluate() { |
| 519 | let v = num("time * 2 + math.sin(0.5)").unwrap(); |
| 520 | assert!((v - (4.0 + 0.5_f64.sin())).abs() < 1e-12); |
| 521 | assert_eq!(num("clamp(5, 0, 1)"), Some(1.0)); |
| 522 | assert_eq!(num(":local a = 3; return a * time"), Some(6.0)); |
| 523 | } |
| 524 | |
| 525 | #[test] |
| 526 | fn os_io_and_loaders_are_unavailable() { |
| 527 | let marker = std::env::temp_dir().join("fission_expr_sandbox_marker"); |
| 528 | let _ = std::fs::remove_file(&marker); |
| 529 | let cmd = format!("os.execute('touch {}')", marker.display()); |
| 530 | assert_eq!(num(&format!(":{cmd}; return 1")), None); |
| 531 | assert!(!marker.exists()); |
| 532 | for src in [ |
| 533 | "io.open('/etc/passwd')", |
| 534 | "require('os')", |
| 535 | "load('return 1')()", |
| 536 | "dofile('/etc/passwd')", |
| 537 | "debug.getinfo(1)", |
| 538 | "package.loaded", |
| 539 | "collectgarbage('count')", |
| 540 | ] { |
| 541 | assert_eq!(num(src), None, "{src}"); |
| 542 | } |
| 543 | } |
| 544 | |
| 545 | #[test] |
| 546 | fn runaway_loops_and_allocations_error_out() { |
| 547 | let engine = ExprEngine::new(); |
| 548 | let e = HashMap::new(); |
| 549 | let eval = |src: &str| engine.eval_number(src, 0.0, &HashMap::new(), &HashMap::new(), &e); |
| 550 | assert_eq!(eval(":while true do end"), None); |
| 551 | assert_eq!(eval(":local s = 'x'; while true do s = s .. s end"), None); |
| 552 | assert_eq!(eval("string.rep('x', 1e9) and 1"), None); |
| 553 | // Budget resets per evaluation, so the engine stays usable. |
| 554 | assert_eq!(eval("1 + 1"), Some(2.0)); |
| 555 | } |
| 556 | |
| 557 | #[test] |
| 558 | fn pcall_cannot_swallow_the_budget() { |
| 559 | let engine = ExprEngine::new(); |
| 560 | let e = HashMap::new(); |
| 561 | let eval = |src: &str| engine.eval_number(src, 0.0, &HashMap::new(), &HashMap::new(), &e); |
| 562 | let start = std::time::Instant::now(); |
| 563 | assert_eq!(eval(":while true do pcall(function() while true do end end) end"), None); |
| 564 | assert_eq!(eval(":while true do xpcall(function() while true do end end, print) end"), None); |
| 565 | assert!(start.elapsed() < std::time::Duration::from_millis(50), "{:?}", start.elapsed()); |
| 566 | assert_eq!(eval("1 + 1"), Some(2.0)); |
| 567 | } |
| 568 | |
| 569 | #[test] |
| 570 | fn evaluations_cannot_mutate_shared_state() { |
| 571 | let engine = ExprEngine::new(); |
| 572 | let e = HashMap::new(); |
| 573 | let eval = |src: &str| engine.eval_number(src, 0.0, &HashMap::new(), &HashMap::new(), &e); |
| 574 | for src in [ |
| 575 | ":math.floor = function() return 42 end; return 1", |
| 576 | ":string.upper = function() return 42 end; return 1", |
| 577 | ":table.insert = nil; return 1", |
| 578 | ":_G.leak = 1; return 1", |
| 579 | ":getmetatable('').__index.upper = nil; return 1", |
| 580 | ":setmetatable(math, nil); return 1", |
| 581 | ] { |
| 582 | assert_eq!(eval(src), None, "{src}"); |
| 583 | } |
| 584 | assert_eq!(eval(":floor = function() return 42 end; return floor(1.5)"), Some(42.0)); |
| 585 | assert_eq!(eval("floor(1.5)"), Some(1.0)); |
| 586 | assert_eq!(eval("math.floor(1.5)"), Some(1.0)); |
| 587 | assert_eq!(eval("leak"), None); |
| 588 | let upper = engine.eval_string("('a'):upper()", 0.0, &HashMap::new(), &HashMap::new(), &e); |
| 589 | assert_eq!(upper.as_deref(), Some("A")); |
| 590 | assert_eq!(eval("string.len('abc') + select('#', table.unpack({1, 2}))"), Some(5.0)); |
| 591 | } |
| 592 | |
| 593 | #[test] |
| 594 | fn chunk_cache_reuses_compiled_bytecode_with_isolated_envs() { |
| 595 | let engine = ExprEngine::new(); |
| 596 | let expr = "time + x + N1.Gain"; |
| 597 | let mut sp = HashMap::from([("x".to_owned(), 10.0)]); |
| 598 | let mut n1 = HashMap::from([("Gain".to_owned(), ExprValue::Number(2.0))]); |
| 599 | let mut env = HashMap::from([("N1".to_owned(), n1.clone())]); |
| 600 | |
| 601 | assert_eq!(engine.eval_number(expr, 1.0, &sp, &HashMap::new(), &env), Some(13.0)); |
| 602 | assert_eq!(engine.chunk_cache.borrow().len(), 1); |
| 603 | |
| 604 | sp.insert("x".to_owned(), 20.0); |
| 605 | n1.insert("Gain".to_owned(), ExprValue::Number(5.0)); |
| 606 | env.insert("N1".to_owned(), n1); |
| 607 | assert_eq!(engine.eval_number(expr, 3.0, &sp, &HashMap::new(), &env), Some(28.0)); |
| 608 | assert_eq!(engine.chunk_cache.borrow().len(), 1); |
| 609 | |
| 610 | // Cached compilation error stays cached as None and does not pollute valid runs. |
| 611 | assert_eq!(engine.eval_number("1 + )", 0.0, &HashMap::new(), &HashMap::new(), &HashMap::new()), None); |
| 612 | assert_eq!(engine.chunk_cache.borrow().get("1 + )"), Some(&None)); |
| 613 | } |
| 614 | |
| 615 | #[test] |
| 616 | fn binary_bytecode_prefix_is_rejected_in_text_mode() { |
| 617 | let engine = ExprEngine::new(); |
| 618 | let empty = HashMap::new(); |
| 619 | // Even with a Lua binary signature `\x1bLua...`, ChunkMode::Text rejects it safely. |
| 620 | for bad in [":\x1bLua", ":\x1bLuaT\0\x19\x0d\x0a\x1a\x0a", "\x1bLua"] { |
| 621 | assert_eq!(engine.eval_number(bad, 0.0, &HashMap::new(), &HashMap::new(), &empty), None); |
| 622 | assert_eq!(engine.chunk_cache.borrow().get(bad), Some(&None)); |
| 623 | } |
| 624 | // Valid expressions continue to evaluate cleanly afterwards. |
| 625 | assert_eq!(engine.eval_number("2 + 3", 0.0, &HashMap::new(), &HashMap::new(), &empty), Some(5.0)); |
| 626 | } |
| 627 | |
| 628 | #[test] |
| 629 | fn syntax_vs_runtime_and_memory_error_caching_and_lru() { |
| 630 | let engine = ExprEngine::new(); |
| 631 | let empty = HashMap::new(); |
| 632 | |
| 633 | // SyntaxError is negative-cached as None. |
| 634 | assert_eq!(engine.eval_number("1 + )", 0.0, &HashMap::new(), &HashMap::new(), &empty), None); |
| 635 | assert_eq!(engine.chunk_cache.borrow().get("1 + )"), Some(&None)); |
| 636 | |
| 637 | // Runtime error compiles cleanly (cached as Some(bytecode)), fails on call, and doesn't poison valid runs. |
| 638 | assert_eq!( |
| 639 | engine.eval_number("1 + nil", 0.0, &HashMap::new(), &HashMap::new(), &empty), |
| 640 | None |
| 641 | ); |
| 642 | assert!(matches!(engine.chunk_cache.borrow().get("1 + nil"), Some(Some(_)))); |
| 643 | |
| 644 | // MemoryError during compilation is NOT negative-cached. |
| 645 | engine.lua.set_memory_limit(1).expect("tight limit applies"); |
| 646 | let mem_expr = format!("1{}", " + 1".repeat(200)); |
| 647 | assert_eq!(engine.eval_number(&mem_expr, 0.0, &HashMap::new(), &HashMap::new(), &empty), None); |
| 648 | assert_eq!(engine.chunk_cache.borrow().get(&mem_expr), None); |
| 649 | engine.lua.set_memory_limit(MEMORY_LIMIT).expect("restore memory limit"); |
| 650 | assert_eq!(engine.eval_number(&mem_expr, 0.0, &HashMap::new(), &HashMap::new(), &empty), Some(201.0)); |
| 651 | assert!(matches!(engine.chunk_cache.borrow().get(&mem_expr), Some(Some(_)))); |
| 652 | |
| 653 | // LRU eviction keeps hot entries when exceeding CHUNK_CACHE_CAP. |
| 654 | let lru_engine = ExprEngine::new(); |
| 655 | for i in 0..CHUNK_CACHE_CAP { |
| 656 | let expr = format!("{i} + 1"); |
| 657 | assert_eq!( |
| 658 | lru_engine.eval_number(&expr, 0.0, &HashMap::new(), &HashMap::new(), &empty), |
| 659 | Some((i + 1) as f64) |
| 660 | ); |
| 661 | } |
| 662 | assert_eq!(lru_engine.chunk_cache.borrow().len(), CHUNK_CACHE_CAP); |
| 663 | // Touch entry 0 so entry 1 becomes the least recently used. |
| 664 | assert_eq!(lru_engine.eval_number("0 + 1", 0.0, &HashMap::new(), &HashMap::new(), &empty), Some(1.0)); |
| 665 | assert_eq!( |
| 666 | lru_engine.eval_number("9999 + 1", 0.0, &HashMap::new(), &HashMap::new(), &empty), |
| 667 | Some(10000.0) |
| 668 | ); |
| 669 | let cache = lru_engine.chunk_cache.borrow(); |
| 670 | assert_eq!(cache.len(), CHUNK_CACHE_CAP); |
| 671 | assert!(cache.get("0 + 1").is_some(), "hot entry 0 must stay in LRU cache"); |
| 672 | assert!(cache.get("1 + 1").is_none(), "cold entry 1 must be evicted"); |
| 673 | } |
| 674 | } |
| 675 | } |
| 676 | |
| 677 | #[cfg(not(target_arch = "wasm32"))] |
| 678 | pub use lua::ExprEngine; |
| 679 | #[cfg(target_arch = "wasm32")] |
| 680 | pub use pure::ExprEngine; |
| 681 | |
| 682 | /// Lua-subset evaluator for targets without a C toolchain: literals, `+ - * / // % ^ ..`, |
| 683 | /// comparisons, `and`/`or`/`not`, calls, `a.b` / `a[b]`, the Fusion globals and `math.*`. |
| 684 | /// Statement bodies (`:local x = ...`) and method calls are unsupported and evaluate to `None`. |
| 685 | #[cfg(any(target_arch = "wasm32", test))] |
| 686 | mod pure { |
| 687 | use super::ExprValue; |
| 688 | use std::collections::HashMap; |
| 689 | |
| 690 | const MAX_DEPTH: usize = 64; |
| 691 | const MAX_TOKENS: usize = 2048; |
| 692 | const MATH_FNS: &[&str] = &[ |
| 693 | "abs", "acos", "asin", "atan", "ceil", "cos", "deg", "exp", "floor", "fmod", "log", "max", "min", "rad", |
| 694 | "sin", "sqrt", "tan", |
| 695 | ]; |
| 696 | const GLOBAL_FNS: &[&str] = &[ |
| 697 | "atan2", "clamp", "cosh", "iif", "log10", "mix", "mod", "pow", "Point", "sinh", "tanh", "Text", |
| 698 | "tonumber", "tostring", |
| 699 | ]; |
| 700 | |
| 701 | #[derive(Clone, Debug, PartialEq)] |
| 702 | enum Tok { |
| 703 | /// `true` for a Lua integer literal, which divides by zero as an error rather than `inf`. |
| 704 | Num(f64, bool), |
| 705 | Str(String), |
| 706 | Name(String), |
| 707 | Op(&'static str), |
| 708 | } |
| 709 | |
| 710 | fn lex(src: &str) -> Option<Vec<Tok>> { |
| 711 | const OPS: &[&str] = &[ |
| 712 | "..", "==", "~=", "<=", ">=", "//", "+", "-", "*", "/", "%", "^", "<", ">", "(", ")", "[", "]", ",", ".", |
| 713 | ]; |
| 714 | let chars: Vec<char> = src.chars().collect(); |
| 715 | let mut toks = Vec::new(); |
| 716 | let mut i = 0; |
| 717 | while i < chars.len() { |
| 718 | if toks.len() >= MAX_TOKENS { |
| 719 | return None; |
| 720 | } |
| 721 | let c = chars[i]; |
| 722 | if c.is_whitespace() { |
| 723 | i += 1; |
| 724 | } else if c.is_ascii_digit() || (c == '.' && chars.get(i + 1).is_some_and(char::is_ascii_digit)) { |
| 725 | let start = i; |
| 726 | if c == '0' && matches!(chars.get(i + 1), Some('x' | 'X')) { |
| 727 | i += 2; |
| 728 | while chars.get(i).is_some_and(char::is_ascii_hexdigit) { |
| 729 | i += 1; |
| 730 | } |
| 731 | let digits: String = chars[start + 2..i].iter().collect(); |
| 732 | toks.push(Tok::Num(u64::from_str_radix(&digits, 16).ok()? as f64, true)); |
| 733 | continue; |
| 734 | } |
| 735 | while chars.get(i).is_some_and(char::is_ascii_digit) { |
| 736 | i += 1; |
| 737 | } |
| 738 | let mut integer = true; |
| 739 | if chars.get(i) == Some(&'.') && chars.get(i + 1) != Some(&'.') { |
| 740 | integer = false; |
| 741 | i += 1; |
| 742 | while chars.get(i).is_some_and(char::is_ascii_digit) { |
| 743 | i += 1; |
| 744 | } |
| 745 | } |
| 746 | if matches!(chars.get(i), Some('e' | 'E')) { |
| 747 | integer = false; |
| 748 | i += 1; |
| 749 | if matches!(chars.get(i), Some('+' | '-')) { |
| 750 | i += 1; |
| 751 | } |
| 752 | while chars.get(i).is_some_and(char::is_ascii_digit) { |
| 753 | i += 1; |
| 754 | } |
| 755 | } |
| 756 | let value: f64 = chars[start..i].iter().collect::<String>().parse().ok()?; |
| 757 | toks.push(Tok::Num(value, integer && value < 2f64.powi(63))); |
| 758 | } else if c.is_alphabetic() || c == '_' { |
| 759 | let start = i; |
| 760 | while chars.get(i).is_some_and(|c| c.is_alphanumeric() || *c == '_') { |
| 761 | i += 1; |
| 762 | } |
| 763 | toks.push(Tok::Name(chars[start..i].iter().collect())); |
| 764 | } else if c == '"' || c == '\'' { |
| 765 | let mut s = String::new(); |
| 766 | i += 1; |
| 767 | loop { |
| 768 | match *chars.get(i)? { |
| 769 | q if q == c => break, |
| 770 | '\\' => { |
| 771 | i += 1; |
| 772 | s.push(match *chars.get(i)? { |
| 773 | 'n' => '\n', |
| 774 | 't' => '\t', |
| 775 | other => other, |
| 776 | }); |
| 777 | } |
| 778 | other => s.push(other), |
| 779 | } |
| 780 | i += 1; |
| 781 | } |
| 782 | i += 1; |
| 783 | toks.push(Tok::Str(s)); |
| 784 | } else { |
| 785 | let rest: String = chars[i..chars.len().min(i + 2)].iter().collect(); |
| 786 | let op = OPS.iter().find(|op| rest.starts_with(**op))?; |
| 787 | i += op.len(); |
| 788 | toks.push(Tok::Op(op)); |
| 789 | } |
| 790 | } |
| 791 | Some(toks) |
| 792 | } |
| 793 | |
| 794 | #[derive(Debug)] |
| 795 | enum Ast { |
| 796 | Nil, |
| 797 | Bool(bool), |
| 798 | Num(f64), |
| 799 | /// An integer literal. |
| 800 | Int(f64), |
| 801 | Str(String), |
| 802 | Name(String), |
| 803 | Index(Box<Ast>, Box<Ast>), |
| 804 | Call(Box<Ast>, Vec<Ast>), |
| 805 | Neg(Box<Ast>), |
| 806 | Not(Box<Ast>), |
| 807 | Bin(&'static str, Box<Ast>, Box<Ast>), |
| 808 | } |
| 809 | |
| 810 | struct Parser { |
| 811 | toks: Vec<Tok>, |
| 812 | pos: usize, |
| 813 | depth: usize, |
| 814 | } |
| 815 | |
| 816 | impl Parser { |
| 817 | fn peek(&self) -> Option<&Tok> { |
| 818 | self.toks.get(self.pos) |
| 819 | } |
| 820 | |
| 821 | fn eat_op(&mut self, op: &str) -> bool { |
| 822 | let hit = matches!(self.peek(), Some(Tok::Op(o)) if *o == op); |
| 823 | self.pos += usize::from(hit); |
| 824 | hit |
| 825 | } |
| 826 | |
| 827 | fn binary_op(&self) -> Option<(&'static str, u8, u8)> { |
| 828 | let op = match self.peek()? { |
| 829 | Tok::Op(op) => *op, |
| 830 | Tok::Name(n) if n == "and" => "and", |
| 831 | Tok::Name(n) if n == "or" => "or", |
| 832 | _ => return None, |
| 833 | }; |
| 834 | // Lua precedence, lowest first; `..` and `^` are right associative. |
| 835 | let (left, right) = match op { |
| 836 | "or" => (1, 2), |
| 837 | "and" => (3, 4), |
| 838 | "<" | ">" | "<=" | ">=" | "==" | "~=" => (5, 6), |
| 839 | ".." => (9, 8), |
| 840 | "+" | "-" => (10, 11), |
| 841 | "*" | "/" | "//" | "%" => (12, 13), |
| 842 | "^" => (16, 15), |
| 843 | _ => return None, |
| 844 | }; |
| 845 | Some((op, left, right)) |
| 846 | } |
| 847 | |
| 848 | /// One more level of tree height, which nesting and every left-associative link add alike, |
| 849 | /// so recursive eval and drop stay bounded. |
| 850 | fn descend(&mut self) -> Option<()> { |
| 851 | self.depth += 1; |
| 852 | (self.depth <= MAX_DEPTH).then_some(()) |
| 853 | } |
| 854 | |
| 855 | fn expr(&mut self, min_bp: u8) -> Option<Ast> { |
| 856 | let outer = self.depth; |
| 857 | self.descend()?; |
| 858 | let ast = self.binary(min_bp)?; |
| 859 | self.depth = outer; |
| 860 | Some(ast) |
| 861 | } |
| 862 | |
| 863 | fn binary(&mut self, min_bp: u8) -> Option<Ast> { |
| 864 | let outer = self.depth; |
| 865 | let mut lhs = self.unary()?; |
| 866 | while let Some((op, left, right)) = self.binary_op() { |
| 867 | if left < min_bp { |
| 868 | break; |
| 869 | } |
| 870 | self.pos += 1; |
| 871 | self.descend()?; |
| 872 | let rhs = self.expr(right)?; |
| 873 | lhs = Ast::Bin(op, Box::new(lhs), Box::new(rhs)); |
| 874 | } |
| 875 | self.depth = outer; |
| 876 | Some(lhs) |
| 877 | } |
| 878 | |
| 879 | fn unary(&mut self) -> Option<Ast> { |
| 880 | if self.eat_op("-") { |
| 881 | return Some(Ast::Neg(Box::new(self.expr(14)?))); |
| 882 | } |
| 883 | if matches!(self.peek(), Some(Tok::Name(n)) if n == "not") { |
| 884 | self.pos += 1; |
| 885 | return Some(Ast::Not(Box::new(self.expr(14)?))); |
| 886 | } |
| 887 | self.postfix() |
| 888 | } |
| 889 | |
| 890 | fn postfix(&mut self) -> Option<Ast> { |
| 891 | let mut node = match self.toks.get(self.pos)?.clone() { |
| 892 | Tok::Num(n, true) => Ast::Int(n), |
| 893 | Tok::Num(n, false) => Ast::Num(n), |
| 894 | Tok::Str(s) => Ast::Str(s), |
| 895 | Tok::Name(n) => match n.as_str() { |
| 896 | "nil" => Ast::Nil, |
| 897 | "true" => Ast::Bool(true), |
| 898 | "false" => Ast::Bool(false), |
| 899 | "and" | "or" | "not" => return None, |
| 900 | _ => Ast::Name(n), |
| 901 | }, |
| 902 | Tok::Op("(") => { |
| 903 | self.pos += 1; |
| 904 | let inner = self.expr(0)?; |
| 905 | if !matches!(self.peek(), Some(Tok::Op(")"))) { |
| 906 | return None; |
| 907 | } |
| 908 | inner |
| 909 | } |
| 910 | Tok::Op(_) => return None, |
| 911 | }; |
| 912 | self.pos += 1; |
| 913 | let outer = self.depth; |
| 914 | loop { |
| 915 | if self.eat_op(".") { |
| 916 | self.descend()?; |
| 917 | let Some(Tok::Name(key)) = self.peek().cloned() else { return None }; |
| 918 | self.pos += 1; |
| 919 | node = Ast::Index(Box::new(node), Box::new(Ast::Str(key))); |
| 920 | } else if self.eat_op("[") { |
| 921 | self.descend()?; |
| 922 | let key = self.expr(0)?; |
| 923 | if !self.eat_op("]") { |
| 924 | return None; |
| 925 | } |
| 926 | node = Ast::Index(Box::new(node), Box::new(key)); |
| 927 | } else if self.eat_op("(") { |
| 928 | self.descend()?; |
| 929 | let mut args = Vec::new(); |
| 930 | if !self.eat_op(")") { |
| 931 | loop { |
| 932 | args.push(self.expr(0)?); |
| 933 | if self.eat_op(")") { |
| 934 | break; |
| 935 | } |
| 936 | if !self.eat_op(",") { |
| 937 | return None; |
| 938 | } |
| 939 | } |
| 940 | } |
| 941 | node = Ast::Call(Box::new(node), args); |
| 942 | } else { |
| 943 | self.depth = outer; |
| 944 | return Some(node); |
| 945 | } |
| 946 | } |
| 947 | } |
| 948 | } |
| 949 | |
| 950 | #[derive(Clone, Debug, PartialEq)] |
| 951 | enum Val<'a> { |
| 952 | Nil, |
| 953 | Bool(bool), |
| 954 | Num(f64), |
| 955 | Str(String), |
| 956 | Point([f64; 2]), |
| 957 | /// `{ Value = "..." }` that also stringifies. |
| 958 | Text(String), |
| 959 | Node(&'a HashMap<String, ExprValue>), |
| 960 | Math, |
| 961 | Func(&'static str), |
| 962 | } |
| 963 | |
| 964 | impl Val<'_> { |
| 965 | fn truthy(&self) -> bool { |
| 966 | !matches!(self, Val::Nil | Val::Bool(false)) |
| 967 | } |
| 968 | |
| 969 | /// Lua's arithmetic coercion: numbers and numeric strings. |
| 970 | fn num(&self) -> Option<f64> { |
| 971 | match self { |
| 972 | Val::Num(n) => Some(*n), |
| 973 | Val::Str(s) => s.trim().parse().ok(), |
| 974 | _ => None, |
| 975 | } |
| 976 | } |
| 977 | |
| 978 | /// What `..` accepts: numbers and strings. |
| 979 | fn text(&self) -> Option<String> { |
| 980 | match self { |
| 981 | Val::Num(n) => Some(super::format_number(*n)), |
| 982 | Val::Str(s) | Val::Text(s) => Some(s.clone()), |
| 983 | _ => None, |
| 984 | } |
| 985 | } |
| 986 | |
| 987 | /// Lua's `tostring`, which also names `nil` and booleans. |
| 988 | fn tostring(&self) -> Option<String> { |
| 989 | match self { |
| 990 | Val::Nil => Some("nil".to_owned()), |
| 991 | Val::Bool(b) => Some(b.to_string()), |
| 992 | other => other.text(), |
| 993 | } |
| 994 | } |
| 995 | } |
| 996 | |
| 997 | struct Scope<'a> { |
| 998 | time: f64, |
| 999 | params: &'a HashMap<String, f64>, |
| 1000 | points: &'a HashMap<String, [f64; 2]>, |
| 1001 | nodes: &'a HashMap<String, HashMap<String, ExprValue>>, |
| 1002 | } |
| 1003 | |
| 1004 | impl<'a> Scope<'a> { |
| 1005 | /// Nodes shadow points shadow params shadow `time` shadow the stdlib, as in the Lua env. |
| 1006 | fn name(&self, name: &str) -> Val<'a> { |
| 1007 | if let Some(node) = self.nodes.get(name) { |
| 1008 | Val::Node(node) |
| 1009 | } else if let Some(p) = self.points.get(name) { |
| 1010 | Val::Point(*p) |
| 1011 | } else if let Some(n) = self.params.get(name) { |
| 1012 | Val::Num(*n) |
| 1013 | } else if name == "time" { |
| 1014 | Val::Num(self.time) |
| 1015 | } else if name == "pi" { |
| 1016 | Val::Num(std::f64::consts::PI) |
| 1017 | } else if name == "math" { |
| 1018 | Val::Math |
| 1019 | } else if let Some(f) = MATH_FNS.iter().chain(GLOBAL_FNS).find(|f| **f == name) { |
| 1020 | Val::Func(f) |
| 1021 | } else { |
| 1022 | Val::Nil |
| 1023 | } |
| 1024 | } |
| 1025 | |
| 1026 | fn eval(&self, ast: &Ast) -> Option<Val<'a>> { |
| 1027 | Some(match ast { |
| 1028 | Ast::Nil => Val::Nil, |
| 1029 | Ast::Bool(b) => Val::Bool(*b), |
| 1030 | Ast::Num(n) | Ast::Int(n) => Val::Num(*n), |
| 1031 | Ast::Str(s) => Val::Str(s.clone()), |
| 1032 | Ast::Name(n) => self.name(n), |
| 1033 | Ast::Neg(a) => match self.eval(a)? { |
| 1034 | Val::Point([x, y]) => Val::Point([-x, -y]), |
| 1035 | v => Val::Num(-v.num()?), |
| 1036 | }, |
| 1037 | Ast::Not(a) => Val::Bool(!self.eval(a)?.truthy()), |
| 1038 | Ast::Index(base, key) => index(self.eval(base)?, self.eval(key)?)?, |
| 1039 | Ast::Call(callee, args) => { |
| 1040 | let Val::Func(name) = self.eval(callee)? else { return None }; |
| 1041 | let args = args.iter().map(|a| self.eval(a)).collect::<Option<Vec<_>>>()?; |
| 1042 | call(name, &args)? |
| 1043 | } |
| 1044 | Ast::Bin("and", a, b) => { |
| 1045 | let a = self.eval(a)?; |
| 1046 | if a.truthy() { self.eval(b)? } else { a } |
| 1047 | } |
| 1048 | Ast::Bin("or", a, b) => { |
| 1049 | let a = self.eval(a)?; |
| 1050 | if a.truthy() { a } else { self.eval(b)? } |
| 1051 | } |
| 1052 | Ast::Bin(op, a, b) => { |
| 1053 | let (a_val, b_val) = (self.eval(a)?, self.eval(b)?); |
| 1054 | // Lua 5.4 errors on integer `//` and `%` by zero; floats give `inf`/`nan`. |
| 1055 | if matches!(*op, "//" | "%") && b_val.num() == Some(0.0) && is_integer(a) && is_integer(b) { |
| 1056 | return None; |
| 1057 | } |
| 1058 | binary(op, a_val, b_val)? |
| 1059 | } |
| 1060 | }) |
| 1061 | } |
| 1062 | } |
| 1063 | |
| 1064 | /// Whether Lua 5.4 types `ast` as an integer: integer literals and `+ - * // %` of them. |
| 1065 | fn is_integer(ast: &Ast) -> bool { |
| 1066 | match ast { |
| 1067 | Ast::Int(_) => true, |
| 1068 | Ast::Neg(a) => is_integer(a), |
| 1069 | Ast::Bin("+" | "-" | "*" | "//" | "%", a, b) => is_integer(a) && is_integer(b), |
| 1070 | _ => false, |
| 1071 | } |
| 1072 | } |
| 1073 | |
| 1074 | fn index<'a>(base: Val<'a>, key: Val<'a>) -> Option<Val<'a>> { |
| 1075 | Some(match (base, key) { |
| 1076 | (Val::Node(fields), key) => match key { |
| 1077 | Val::Str(k) => match fields.get(&k) { |
| 1078 | Some(ExprValue::Number(n)) => Val::Num(*n), |
| 1079 | Some(ExprValue::Text(s)) => Val::Text(s.clone()), |
| 1080 | Some(ExprValue::Point(p)) => Val::Point(*p), |
| 1081 | None => Val::Num(0.0), |
| 1082 | }, |
| 1083 | _ => Val::Num(0.0), |
| 1084 | }, |
| 1085 | (Val::Text(s), Val::Str(k)) if k == "Value" => Val::Str(s), |
| 1086 | (Val::Text(_), _) => Val::Nil, |
| 1087 | (Val::Point(p), Val::Str(k)) if k == "X" => Val::Num(p[0]), |
| 1088 | (Val::Point(p), Val::Str(k)) if k == "Y" => Val::Num(p[1]), |
| 1089 | (Val::Point(p), Val::Num(1.0)) => Val::Num(p[0]), |
| 1090 | (Val::Point(p), Val::Num(2.0)) => Val::Num(p[1]), |
| 1091 | (Val::Point(_), _) => Val::Nil, |
| 1092 | (Val::Math, Val::Str(k)) => match k.as_str() { |
| 1093 | "pi" => Val::Num(std::f64::consts::PI), |
| 1094 | "huge" => Val::Num(f64::INFINITY), |
| 1095 | _ => MATH_FNS.iter().find(|f| **f == k).map_or(Val::Nil, |f| Val::Func(f)), |
| 1096 | }, |
| 1097 | _ => return None, |
| 1098 | }) |
| 1099 | } |
| 1100 | |
| 1101 | fn binary<'a>(op: &str, a: Val<'a>, b: Val<'a>) -> Option<Val<'a>> { |
| 1102 | use std::cmp::Ordering; |
| 1103 | let ordering = |a: &Val, b: &Val| match (a, b) { |
| 1104 | (Val::Num(a), Val::Num(b)) => Some(a.partial_cmp(b)), |
| 1105 | (Val::Str(a), Val::Str(b)) => Some(Some(a.cmp(b))), |
| 1106 | _ => None, |
| 1107 | }; |
| 1108 | Some(match op { |
| 1109 | "==" => Val::Bool(a == b), |
| 1110 | "~=" => Val::Bool(a != b), |
| 1111 | "<" => Val::Bool(ordering(&a, &b)?.is_some_and(|o| o == Ordering::Less)), |
| 1112 | "<=" => Val::Bool(ordering(&a, &b)?.is_some_and(|o| o != Ordering::Greater)), |
| 1113 | ">" => Val::Bool(ordering(&a, &b)?.is_some_and(|o| o == Ordering::Greater)), |
| 1114 | ">=" => Val::Bool(ordering(&a, &b)?.is_some_and(|o| o != Ordering::Less)), |
| 1115 | ".." => Val::Str(a.text()? + &b.text()?), |
| 1116 | "+" | "-" | "*" | "/" if matches!((&a, &b), (Val::Point(_), _) | (_, Val::Point(_))) => { |
| 1117 | match (op, a, b) { |
| 1118 | ("+", Val::Point([ax, ay]), Val::Point([bx, by])) => Val::Point([ax + bx, ay + by]), |
| 1119 | ("-", Val::Point([ax, ay]), Val::Point([bx, by])) => Val::Point([ax - bx, ay - by]), |
| 1120 | ("*", Val::Point([ax, ay]), Val::Point([bx, by])) => Val::Point([ax * bx, ay * by]), |
| 1121 | ("/", Val::Point([ax, ay]), Val::Point([bx, by])) => Val::Point([ax / bx, ay / by]), |
| 1122 | ("*", Val::Point([ax, ay]), other) | ("*", other, Val::Point([ax, ay])) => { |
| 1123 | let s = other.num()?; |
| 1124 | Val::Point([ax * s, ay * s]) |
| 1125 | } |
| 1126 | ("/", Val::Point([ax, ay]), other) => { |
| 1127 | let s = other.num()?; |
| 1128 | Val::Point([ax / s, ay / s]) |
| 1129 | } |
| 1130 | _ => return None, |
| 1131 | } |
| 1132 | } |
| 1133 | _ => { |
| 1134 | let (a, b) = (a.num()?, b.num()?); |
| 1135 | Val::Num(match op { |
| 1136 | "+" => a + b, |
| 1137 | "-" => a - b, |
| 1138 | "*" => a * b, |
| 1139 | "/" => a / b, |
| 1140 | "//" => (a / b).floor(), |
| 1141 | "%" => a - (a / b).floor() * b, |
| 1142 | "^" => a.powf(b), |
| 1143 | _ => return None, |
| 1144 | }) |
| 1145 | } |
| 1146 | }) |
| 1147 | } |
| 1148 | |
| 1149 | fn call<'a>(name: &str, args: &[Val<'a>]) -> Option<Val<'a>> { |
| 1150 | let arg = |i: usize| args.get(i).and_then(Val::num); |
| 1151 | let unary: Option<fn(f64) -> f64> = match name { |
| 1152 | "abs" => Some(f64::abs), |
| 1153 | "acos" => Some(f64::acos), |
| 1154 | "asin" => Some(f64::asin), |
| 1155 | "ceil" => Some(f64::ceil), |
| 1156 | "cos" => Some(f64::cos), |
| 1157 | "cosh" => Some(f64::cosh), |
| 1158 | "deg" => Some(f64::to_degrees), |
| 1159 | "exp" => Some(f64::exp), |
| 1160 | "floor" => Some(f64::floor), |
| 1161 | "log10" => Some(f64::log10), |
| 1162 | "rad" => Some(f64::to_radians), |
| 1163 | "sin" => Some(f64::sin), |
| 1164 | "sinh" => Some(f64::sinh), |
| 1165 | "sqrt" => Some(f64::sqrt), |
| 1166 | "tan" => Some(f64::tan), |
| 1167 | "tanh" => Some(f64::tanh), |
| 1168 | _ => None, |
| 1169 | }; |
| 1170 | if let Some(f) = unary { |
| 1171 | return Some(Val::Num(f(arg(0)?))); |
| 1172 | } |
| 1173 | Some(match name { |
| 1174 | "atan" | "atan2" => Val::Num(match arg(1) { |
| 1175 | Some(x) => arg(0)?.atan2(x), |
| 1176 | None => arg(0)?.atan(), |
| 1177 | }), |
| 1178 | "fmod" | "mod" => Val::Num(arg(0)? % arg(1)?), |
| 1179 | "pow" => Val::Num(arg(0)?.powf(arg(1)?)), |
| 1180 | "log" => Val::Num(match arg(1) { |
| 1181 | Some(2.0) => arg(0)?.log2(), |
| 1182 | Some(10.0) => arg(0)?.log10(), |
| 1183 | Some(base) => arg(0)?.ln() / base.ln(), |
| 1184 | None => arg(0)?.ln(), |
| 1185 | }), |
| 1186 | "max" | "min" => { |
| 1187 | let mut nums = (0..args.len()).map(arg); |
| 1188 | let first = nums.next()??; |
| 1189 | let pick = if name == "max" { f64::max } else { f64::min }; |
| 1190 | Val::Num(nums.try_fold(first, |acc, n| n.map(|n| pick(acc, n)))?) |
| 1191 | } |
| 1192 | "iif" => { |
| 1193 | let cond = args.first()?; |
| 1194 | let pass = cond.truthy() && cond.num() != Some(0.0); |
| 1195 | args.get(if pass { 1 } else { 2 }).cloned().unwrap_or(Val::Nil) |
| 1196 | } |
| 1197 | "clamp" => { |
| 1198 | let (x, lo, hi) = (arg(0)?, arg(1)?, arg(2)?); |
| 1199 | Val::Num(if x < lo { lo } else if x > hi { hi } else { x }) |
| 1200 | } |
| 1201 | "mix" => Val::Num(arg(0)? + (arg(1)? - arg(0)?) * arg(2)?), |
| 1202 | "Point" => Val::Point([arg(0).unwrap_or(0.0), arg(1).unwrap_or(0.0)]), |
| 1203 | "tostring" => Val::Str(args.first()?.tostring()?), |
| 1204 | "Text" => Val::Str(args.first().filter(|a| a.truthy()).map_or(Some(String::new()), Val::tostring)?), |
| 1205 | "tonumber" => args.first()?.num().map_or(Val::Nil, Val::Num), |
| 1206 | _ => return None, |
| 1207 | }) |
| 1208 | } |
| 1209 | |
| 1210 | #[derive(Default)] |
| 1211 | pub struct ExprEngine; |
| 1212 | |
| 1213 | impl ExprEngine { |
| 1214 | pub fn new() -> Self { |
| 1215 | Self |
| 1216 | } |
| 1217 | |
| 1218 | fn run<R>( |
| 1219 | &self, |
| 1220 | expr: &str, |
| 1221 | time: f64, |
| 1222 | self_params: &HashMap<String, f64>, |
| 1223 | self_points: &HashMap<String, [f64; 2]>, |
| 1224 | env_nodes: &HashMap<String, HashMap<String, ExprValue>>, |
| 1225 | read: impl FnOnce(Val) -> Option<R>, |
| 1226 | ) -> Option<R> { |
| 1227 | let body = match expr.trim_start().strip_prefix(':') { |
| 1228 | Some(stmt) => { |
| 1229 | let value = stmt.trim_start().strip_prefix("return ")?.trim_end(); |
| 1230 | value.strip_suffix(';').unwrap_or(value) |
| 1231 | } |
| 1232 | None => expr, |
| 1233 | }; |
| 1234 | // Every AST node consumes a token, so this also caps the tree's size. |
| 1235 | let toks = lex(body).filter(|t| t.len() <= MAX_TOKENS)?; |
| 1236 | let mut parser = Parser { toks, pos: 0, depth: 0 }; |
| 1237 | let ast = parser.expr(0)?; |
| 1238 | if parser.pos != parser.toks.len() { |
| 1239 | return None; |
| 1240 | } |
| 1241 | let scope = Scope { time, params: self_params, points: self_points, nodes: env_nodes }; |
| 1242 | read(scope.eval(&ast)?) |
| 1243 | } |
| 1244 | |
| 1245 | pub fn eval_number( |
| 1246 | &self, |
| 1247 | expr: &str, |
| 1248 | time: f64, |
| 1249 | self_params: &HashMap<String, f64>, |
| 1250 | self_points: &HashMap<String, [f64; 2]>, |
| 1251 | env_nodes: &HashMap<String, HashMap<String, ExprValue>>, |
| 1252 | ) -> Option<f64> { |
| 1253 | self.run(expr, time, self_params, self_points, env_nodes, |v| match v { |
| 1254 | Val::Bool(b) => Some(f64::from(b)), |
| 1255 | other => other.num(), |
| 1256 | }) |
| 1257 | } |
| 1258 | |
| 1259 | pub fn eval_point( |
| 1260 | &self, |
| 1261 | expr: &str, |
| 1262 | time: f64, |
| 1263 | self_params: &HashMap<String, f64>, |
| 1264 | self_points: &HashMap<String, [f64; 2]>, |
| 1265 | env_nodes: &HashMap<String, HashMap<String, ExprValue>>, |
| 1266 | ) -> Option<[f64; 2]> { |
| 1267 | self.run(expr, time, self_params, self_points, env_nodes, |v| match v { |
| 1268 | Val::Point(p) => Some(p), |
| 1269 | _ => None, |
| 1270 | }) |
| 1271 | } |
| 1272 | |
| 1273 | pub fn eval_string( |
| 1274 | &self, |
| 1275 | expr: &str, |
| 1276 | time: f64, |
| 1277 | self_params: &HashMap<String, f64>, |
| 1278 | self_points: &HashMap<String, [f64; 2]>, |
| 1279 | env_nodes: &HashMap<String, HashMap<String, ExprValue>>, |
| 1280 | ) -> Option<String> { |
| 1281 | self.run(expr, time, self_params, self_points, env_nodes, |v| v.text()) |
| 1282 | } |
| 1283 | } |
| 1284 | |
| 1285 | #[cfg(test)] |
| 1286 | mod tests { |
| 1287 | use super::*; |
| 1288 | |
| 1289 | fn nodes() -> HashMap<String, HashMap<String, ExprValue>> { |
| 1290 | HashMap::from([( |
| 1291 | "Ctl".to_owned(), |
| 1292 | HashMap::from([ |
| 1293 | ("Size".to_owned(), ExprValue::Number(0.25)), |
| 1294 | ("StyledText".to_owned(), ExprValue::Text("hi".to_owned())), |
| 1295 | ]), |
| 1296 | )]) |
| 1297 | } |
| 1298 | |
| 1299 | fn num(expr: &str, time: f64) -> Option<f64> { |
| 1300 | let params = HashMap::from([("Width".to_owned(), 8.0)]); |
| 1301 | let points = HashMap::from([("Center".to_owned(), [0.5, 0.25])]); |
| 1302 | ExprEngine::new().eval_number(expr, time, &params, &points, &nodes()) |
| 1303 | } |
| 1304 | |
| 1305 | #[test] |
| 1306 | fn falling_comp_expressions() { |
| 1307 | assert_eq!(num("floor(time/3)*3", 7.0), Some(6.0)); |
| 1308 | assert_eq!(num("floor(time/2)/4", 9.0), Some(1.0)); |
| 1309 | assert_eq!(num("floor(time/5)*42", 11.0), Some(84.0)); |
| 1310 | assert_eq!(num("math.floor(time / 5) * 42", 11.0), Some(84.0)); |
| 1311 | } |
| 1312 | |
| 1313 | #[test] |
| 1314 | fn precedence_and_associativity() { |
| 1315 | assert_eq!(num("-2^2", 0.0), Some(-4.0)); |
| 1316 | assert_eq!(num("2^3^2", 0.0), Some(512.0)); |
| 1317 | assert_eq!(num("2^-1", 0.0), Some(0.5)); |
| 1318 | assert_eq!(num("1 + 2 * 3 - 4 / 2", 0.0), Some(5.0)); |
| 1319 | assert_eq!(num("-7 % 3", 0.0), Some(2.0)); |
| 1320 | assert_eq!(num("7 // 2", 0.0), Some(3.0)); |
| 1321 | assert_eq!(num("1 .. 2 + 1", 0.0), Some(13.0)); |
| 1322 | } |
| 1323 | |
| 1324 | #[test] |
| 1325 | fn logic_and_ternaries() { |
| 1326 | assert_eq!(num("iif(time > 1, 10, 20)", 2.0), Some(10.0)); |
| 1327 | assert_eq!(num("iif(0, 10, 20)", 2.0), Some(20.0)); |
| 1328 | assert_eq!(num("time > 1 and 5 or 6", 0.0), Some(6.0)); |
| 1329 | assert_eq!(num("nil or 3", 0.0), Some(3.0)); |
| 1330 | assert_eq!(num("not (1 == 1)", 0.0), Some(0.0)); |
| 1331 | assert_eq!(num("clamp(5, 0, 1) + min(3, 2, 9) + max(1, 4)", 0.0), Some(7.0)); |
| 1332 | assert_eq!(num("mix(10, 20, 0.5)", 0.0), Some(15.0)); |
| 1333 | } |
| 1334 | |
| 1335 | #[test] |
| 1336 | fn scope_lookups() { |
| 1337 | assert_eq!(num("Width * 2", 0.0), Some(16.0)); |
| 1338 | assert_eq!(num("Center.X + Center[2]", 0.0), Some(0.75)); |
| 1339 | assert_eq!(num("Ctl.Size", 0.0), Some(0.25)); |
| 1340 | assert_eq!(num("Ctl.Missing", 0.0), Some(0.0)); |
| 1341 | assert_eq!(num("Nope.Size", 0.0), None); |
| 1342 | assert_eq!(num("sin(pi / 2) + atan(1, 1) * 0", 0.0), Some(1.0)); |
| 1343 | } |
| 1344 | |
| 1345 | #[test] |
| 1346 | fn points_and_strings() { |
| 1347 | let e = ExprEngine::new(); |
| 1348 | let (p, q, n) = (HashMap::new(), HashMap::new(), nodes()); |
| 1349 | assert_eq!(e.eval_point("Point(time, 0.5)", 2.0, &p, &q, &n), Some([2.0, 0.5])); |
| 1350 | assert_eq!(e.eval_string("Ctl.StyledText.Value .. '!'", 0.0, &p, &q, &n).as_deref(), Some("hi!")); |
| 1351 | assert_eq!(e.eval_string("Ctl.StyledText", 0.0, &p, &q, &n).as_deref(), Some("hi")); |
| 1352 | assert_eq!(e.eval_string("Text('f' .. time)", 3.0, &p, &q, &n).as_deref(), Some("f3")); |
| 1353 | assert_eq!(e.eval_string("time", 2.5, &p, &q, &n).as_deref(), Some("2.5")); |
| 1354 | } |
| 1355 | |
| 1356 | #[test] |
| 1357 | fn unsupported_and_malformed_input_is_none() { |
| 1358 | for src in ["", "1 +", "(1", "1 2", "foo(1)", "'a':upper()", ":local a = 1; return a", "1 @ 2", "'abc", "{}"] { |
| 1359 | assert_eq!(num(src, 0.0), None, "{src:?}"); |
| 1360 | } |
| 1361 | assert_eq!(num(":return time * 2", 2.0), Some(4.0)); |
| 1362 | assert_eq!(num(":return time * 2;", 2.0), Some(4.0)); |
| 1363 | assert_eq!(num(&"(".repeat(200), 0.0), None); |
| 1364 | } |
| 1365 | |
| 1366 | #[test] |
| 1367 | fn long_chains_are_bounded_instead_of_overflowing_the_stack() { |
| 1368 | let sum = |terms: usize| vec!["1"; terms].join("+"); |
| 1369 | assert_eq!(num(&sum(40), 0.0), Some(40.0)); |
| 1370 | for terms in [100, 10_000, 200_000] { |
| 1371 | assert_eq!(num(&sum(terms), 0.0), None, "{terms} terms"); |
| 1372 | } |
| 1373 | let path = |links: usize| format!("Ctl{}", ".Size".repeat(links)); |
| 1374 | assert_eq!(num(&path(1), 0.0), Some(0.25)); |
| 1375 | assert_eq!(num(&path(100), 0.0), None); |
| 1376 | assert_eq!(num(&format!("max({})", vec!["1"; 5000].join(",")), 0.0), None); |
| 1377 | assert_eq!(num(&format!("{}1{}", "-".repeat(500), ""), 0.0), None); |
| 1378 | } |
| 1379 | |
| 1380 | #[test] |
| 1381 | fn nan_compares_false_instead_of_failing() { |
| 1382 | for (src, want) in [("0/0 < 1", 0.0), ("0/0 >= 1", 0.0), ("0/0 <= 0/0", 0.0), ("0/0 == 0/0", 0.0), ("0/0 ~= 0/0", 1.0)] { |
| 1383 | assert_eq!(num(src, 0.0), Some(want), "{src}"); |
| 1384 | } |
| 1385 | } |
| 1386 | |
| 1387 | #[test] |
| 1388 | fn integer_division_by_zero_errors_but_float_gives_inf() { |
| 1389 | assert_eq!(num("1 // 0", 0.0), None); |
| 1390 | assert_eq!(num("1 % 0", 0.0), None); |
| 1391 | assert_eq!(num("(2 + 3) % (1 - 1)", 0.0), None); |
| 1392 | assert_eq!(num("1.0 // 0", 0.0), Some(f64::INFINITY)); |
| 1393 | assert_eq!(num("1 // 0.0", 0.0), Some(f64::INFINITY)); |
| 1394 | assert_eq!(num("time // 0", 2.0), Some(f64::INFINITY)); |
| 1395 | assert!(num("time % 0", 2.0).is_some_and(f64::is_nan)); |
| 1396 | } |
| 1397 | |
| 1398 | #[test] |
| 1399 | fn tostring_names_nil_and_booleans() { |
| 1400 | let e = ExprEngine::new(); |
| 1401 | let (p, q, n) = (HashMap::new(), HashMap::new(), nodes()); |
| 1402 | let s = |src: &str| e.eval_string(src, 0.0, &p, &q, &n); |
| 1403 | assert_eq!(s("tostring(true)").as_deref(), Some("true")); |
| 1404 | assert_eq!(s("tostring(false)").as_deref(), Some("false")); |
| 1405 | assert_eq!(s("tostring(nil)").as_deref(), Some("nil")); |
| 1406 | assert_eq!(s("Text(nil)").as_deref(), Some("")); |
| 1407 | assert_eq!(s("Text(false)").as_deref(), Some("")); |
| 1408 | assert_eq!(s("'a' .. nil"), None); |
| 1409 | assert_eq!(s("0.1 + 0.2").as_deref(), Some("0.3")); |
| 1410 | } |
| 1411 | } |
| 1412 | } |
| 1413 | |
| 1414 | #[cfg(test)] |
| 1415 | mod tests { |
| 1416 | use super::format_number; |
| 1417 | |
| 1418 | #[test] |
| 1419 | fn numbers_format_like_c_percent_14g() { |
| 1420 | for (n, want) in [ |
| 1421 | (3.0, "3"), |
| 1422 | (-0.0, "-0"), |
| 1423 | (0.0, "0"), |
| 1424 | (0.1 + 0.2, "0.3"), |
| 1425 | (1.0 / 3.0, "0.33333333333333"), |
| 1426 | (2.5, "2.5"), |
| 1427 | (100.0, "100"), |
| 1428 | (123456789012345.0, "1.2345678901234e+14"), |
| 1429 | (99999999999999.0, "99999999999999"), |
| 1430 | (1e15, "1e+15"), |
| 1431 | (2f64.powi(53), "9.007199254741e+15"), |
| 1432 | (1e100, "1e+100"), |
| 1433 | (0.0001, "0.0001"), |
| 1434 | (0.00001, "1e-05"), |
| 1435 | (-1234.5, "-1234.5"), |
| 1436 | (f64::INFINITY, "inf"), |
| 1437 | (f64::NEG_INFINITY, "-inf"), |
| 1438 | (f64::NAN, "nan"), |
| 1439 | ] { |
| 1440 | assert_eq!(format_number(n), want, "{n:e}"); |
| 1441 | } |
| 1442 | } |
| 1443 | } |
| 1444 | |
| 1445 | #[cfg(test)] |
| 1446 | mod parity { |
| 1447 | use super::{ExprEngine, ExprValue, pure}; |
| 1448 | use std::collections::HashMap; |
| 1449 | |
| 1450 | #[test] |
| 1451 | fn pure_matches_lua_on_shared_subset() { |
| 1452 | let params = HashMap::from([("Width".to_owned(), 8.0)]); |
| 1453 | let points = HashMap::from([("Center".to_owned(), [0.5, 0.25])]); |
| 1454 | let nodes = HashMap::from([( |
| 1455 | "Ctl".to_owned(), |
| 1456 | HashMap::from([("Size".to_owned(), ExprValue::Number(0.25))]), |
| 1457 | )]); |
| 1458 | let (lua, pure) = (ExprEngine::new(), pure::ExprEngine::new()); |
| 1459 | for time in [0.0, 2.5, 7.0, 11.0] { |
| 1460 | for src in [ |
| 1461 | "floor(time/3)*3", |
| 1462 | "floor(time/2)/4", |
| 1463 | "floor(time/5)*42", |
| 1464 | "time * 2 + math.sin(0.5)", |
| 1465 | "-2^2", |
| 1466 | "2^3^2", |
| 1467 | "-7 % 3", |
| 1468 | "7 // 2", |
| 1469 | "iif(time > 3, 10, 20)", |
| 1470 | "time > 3 and 5 or 6", |
| 1471 | "clamp(time, 1, 4) + mix(1, 3, 0.5)", |
| 1472 | "Width / 3 + Center.X + Center[2] + Ctl.Size + Ctl.Missing", |
| 1473 | "atan(1, 2) + atan2(1, 2) + log(8, 2) + log10(100) + fmod(-7, 3) + pow(2, 0.5)", |
| 1474 | "max(1, time, 3) + min(time, 9) + abs(-time) + ceil(time) + sqrt(time)", |
| 1475 | "cosh(time) + sinh(time) + tanh(time) + deg(1) + rad(90)", |
| 1476 | "time ~= 2.5", |
| 1477 | "0/0 < 1", |
| 1478 | "0/0 >= 1", |
| 1479 | "1 // 0", |
| 1480 | "1 % 0", |
| 1481 | "time // 0", |
| 1482 | "1.0 % 0 < 1", |
| 1483 | ":return time * 2;", |
| 1484 | "'10' + 1", |
| 1485 | "Nope.Size", |
| 1486 | "1 +", |
| 1487 | ] { |
| 1488 | let args = (src, time, &params, &points, &nodes); |
| 1489 | let l = lua.eval_number(args.0, args.1, args.2, args.3, args.4); |
| 1490 | let p = pure.eval_number(args.0, args.1, args.2, args.3, args.4); |
| 1491 | match (l, p) { |
| 1492 | (Some(l), Some(p)) => assert!(l == p || (l - p).abs() < 1e-9 || (l.is_nan() && p.is_nan()), "{src} @ {time}: {l} vs {p}"), |
| 1493 | _ => assert_eq!(l, p, "{src} @ {time}"), |
| 1494 | } |
| 1495 | } |
| 1496 | } |
| 1497 | } |
| 1498 | |
| 1499 | #[test] |
| 1500 | fn pure_formats_numbers_like_lua() { |
| 1501 | let nodes = HashMap::new(); |
| 1502 | let (lua, pure) = (ExprEngine::new(), pure::ExprEngine::new()); |
| 1503 | for src in [ |
| 1504 | "0.1 + 0.2", "3.0", "time", "1e15", "2^53", "1e100", "0.00001", "1/3", "-0.0", "7 // 2", "100 * 1.0", |
| 1505 | "tostring(true)", "tostring(nil)", "Text(nil)", "Text(time)", "123456789.123456789", |
| 1506 | ] { |
| 1507 | let l = lua.eval_string(src, 2.0, &HashMap::new(), &HashMap::new(), &nodes); |
| 1508 | let p = pure.eval_string(src, 2.0, &HashMap::new(), &HashMap::new(), &nodes); |
| 1509 | assert_eq!(l, p, "{src}"); |
| 1510 | } |
| 1511 | } |
| 1512 | } |