skyray: Rhai with Starlark's guarantees
See the README. Skyray evaluates a script and returns its last value as a
Value. Every script terminates (no while, loop or do, bounded recursion,
an operation budget) and is deterministic (no clock, no eval, no import, none of
the functions Rhai marks volatile, sorted maps). Rhai itself is never in this
crate's public API.
Keywords a script cannot use: the loops that need not end, and eval, which would
run text the host never saw.
19pub const FORBIDDEN_KEYWORDS: [&str; 4] = ["while", "loop", "do", "eval"];
The names Rhai marks volatile in the release skyray is built against, read from its
source at build time. Calling any of them fails with ErrorKind::Forbidden.
The Rhai release the volatile list was read from.
How far a script may go before it is stopped.
Operations in one evaluation: the bound that makes every script end.
36 pub operations: u64,
Nested function calls, recursion included.
38 pub call_levels: usize,
Nesting depth of an expression at the top level.
40 pub expression_depth: usize,
Nesting depth of an expression inside a function.
42 pub function_expression_depth: usize,
Bytes in one string.
44 pub string_len: usize,
Elements in one array.
46 pub array_len: usize,
Data in and out of a script. Map keys are sorted, so a map always iterates in the same order.
What went wrong, so a caller can tell a typo from a runaway script.
The script does not parse.
82 Syntax,
A forbidden keyword, or a function Rhai marks volatile.
84 Forbidden,
A variable that was never defined.
86 UndefinedVariable,
A function no one registered.
88 UnknownFunction,
A map property that is not there.
90 MissingProperty,
The operation budget ran out.
92 TooManyOperations,
Calls nested deeper than the limit.
94 TooDeep,
A string, array or map grew past its limit.
96 TooLarge,
The result holds something that is not data (a function pointer, say).
98 NotData,
A host function returned an error.
100 Host,
A failed evaluation, with the line and column Rhai reported when it had one.
114impl fmt::Display for Error { 115 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { 116 match (self.line, self.column) { 117 (Some(l), Some(c)) => write!(f, "{l}:{c}: {}", self.message), 118 (Some(l), None) => write!(f, "{l}: {}", self.message), 119 _ => f.write_str(&self.message), 120 } 121 } 122} 123 124impl std::error::Error for Error {}
A configured engine. One Skyray can evaluate many scripts, from many threads.
An engine with the default Limits.
155 pub fn with_limits(limits: Limits) -> Self { 156 let mut engine = Engine::new(); 157 for keyword in FORBIDDEN_KEYWORDS { 158 engine.disable_symbol(keyword); 159 } 160 engine.set_strict_variables(true); 161 engine.set_fail_on_invalid_map_property(true); 162 engine.set_max_operations(limits.operations); 163 engine.set_max_call_levels(limits.call_levels); 164 engine.set_max_expr_depths(limits.expression_depth, limits.function_expression_depth); 165 engine.set_max_string_size(limits.string_len); 166 engine.set_max_array_size(limits.array_len); 167 engine.set_max_map_size(limits.map_len); 168 engine.on_print(|_| {}); 169 engine.on_debug(|_, _, _| {}); 170 volatile::deny(&mut engine); 171 Skyray { engine } 172 }
Where print goes; by default it is discarded.
A host function scripts call as name(a, b, ..) with exactly arity
arguments. An Err from it fails the script with ErrorKind::Host at the
call.
183 pub fn function( 184 &mut self, 185 name: &str, 186 arity: usize, 187 f: impl Fn(&[Value]) -> Result<Value, String> + Send + Sync + 'static, 188 ) -> &mut Self { 189 let types = vec![TypeId::of::<Dynamic>(); arity]; 190 self.engine.register_raw_fn(name, types, move |_, args| { 191 let values = args 192 .iter() 193 .map(|a| to_value(a)) 194 .collect::<Result<Vec<_>, String>>() 195 .map_err(host_error)?; 196 f(&values).map(from_value).map_err(host_error) 197 }); 198 self 199 }
Runs source and returns the value of its last expression.
202 pub fn eval(&self, source: &str) -> Result<Value, Error> { 203 let ast = self.engine.compile(source).map_err(parse_error)?; 204 let out: Dynamic = self.engine.eval_ast(&ast).map_err(|e| eval_error(*e))?; 205 to_value(&out).map_err(|message| Error { kind: ErrorKind::NotData, message, line: None, column: None }) 206 } 207}
209fn host_error(message: String) -> Box<EvalAltResult> { 210 EvalAltResult::ErrorRuntime(Dynamic::from(Host(message)), Position::NONE).into() 211} 212 213fn to_value(d: &Dynamic) -> Result<Value, String> { 214 if d.is_unit() { 215 return Ok(Value::Unit); 216 } 217 if let Ok(b) = d.as_bool() { 218 return Ok(Value::Bool(b)); 219 } 220 if let Ok(i) = d.as_int() { 221 return Ok(Value::Int(i)); 222 } 223 if let Ok(x) = d.as_float() { 224 return Ok(Value::Float(x)); 225 } 226 if let Ok(c) = d.as_char() { 227 return Ok(Value::Str(c.to_string())); 228 } 229 if d.is_string() { 230 return d.clone().into_string().map(Value::Str).map_err(|t| format!("a {t} is not a string")); 231 } 232 if d.is_array() { 233 let items = d.clone().into_array().map_err(|t| format!("a {t} is not an array"))?; 234 return items.iter().map(to_value).collect::<Result<_, _>>().map(Value::Array); 235 } 236 if d.is_map() { 237 let map = d.clone().try_cast::<rhai::Map>().ok_or("not a map")?; 238 return map 239 .iter() 240 .map(|(k, v)| to_value(v).map(|v| (k.to_string(), v))) 241 .collect::<Result<_, _>>() 242 .map(Value::Map); 243 } 244 Err(format!("a {} is not data", d.type_name())) 245} 246 247fn from_value(v: Value) -> Dynamic { 248 match v { 249 Value::Unit => Dynamic::UNIT, 250 Value::Bool(b) => Dynamic::from_bool(b), 251 Value::Int(i) => Dynamic::from_int(i), 252 Value::Float(x) => Dynamic::from_float(x), 253 Value::Str(s) => s.into(), 254 Value::Array(items) => Dynamic::from_array(items.into_iter().map(from_value).collect()), 255 Value::Map(map) => Dynamic::from_map(map.into_iter().map(|(k, v)| (k.into(), from_value(v))).collect()), 256 } 257} 258 259fn at(pos: Position) -> (Option<usize>, Option<usize>) { 260 (pos.line(), pos.position()) 261} 262 263fn parse_error(e: rhai::ParseError) -> Error { 264 let (line, column) = at(e.1); 265 // A disabled keyword surfaces two ways: an active one (`while`) as `Reserved`, one 266 // that is only reserved (`eval`) as the tokenizer's `ImproperSymbol`. 267 let forbidden = |word: &str| FORBIDDEN_KEYWORDS.contains(&word); 268 let kind = match &*e.0 { 269 ParseErrorType::Reserved(word) if forbidden(word) => ErrorKind::Forbidden, 270 ParseErrorType::BadInput(LexError::ImproperSymbol(word, _)) if forbidden(word) => ErrorKind::Forbidden, 271 ParseErrorType::VariableUndefined(_) => ErrorKind::UndefinedVariable, 272 _ => ErrorKind::Syntax, 273 }; 274 Error { kind, message: e.0.to_string(), line, column } 275} 276 277fn eval_error(mut e: EvalAltResult) -> Error { 278 // A failure inside a script-defined function is wrapped; the cause decides the kind. 279 if let EvalAltResult::ErrorInFunctionCall(_, _, inner, _) = e { 280 return eval_error(*inner); 281 } 282 let pos = e.take_position(); 283 let (line, column) = at(pos); 284 let (kind, message) = match &e { 285 EvalAltResult::ErrorRuntime(d, _) if d.is::<Denied>() => { 286 let name = d.clone().cast::<Denied>().0; 287 (ErrorKind::Forbidden, format!("{name} is volatile in Rhai and not available in skyray")) 288 } 289 EvalAltResult::ErrorRuntime(d, _) if d.is::<Host>() => (ErrorKind::Host, d.clone().cast::<Host>().0), 290 EvalAltResult::ErrorVariableNotFound(..) => (ErrorKind::UndefinedVariable, e.to_string()), 291 EvalAltResult::ErrorFunctionNotFound(..) => (ErrorKind::UnknownFunction, e.to_string()), 292 EvalAltResult::ErrorPropertyNotFound(..) => (ErrorKind::MissingProperty, e.to_string()), 293 EvalAltResult::ErrorTooManyOperations(..) => (ErrorKind::TooManyOperations, e.to_string()), 294 EvalAltResult::ErrorStackOverflow(..) => (ErrorKind::TooDeep, e.to_string()), 295 EvalAltResult::ErrorDataTooLarge(..) => (ErrorKind::TooLarge, e.to_string()), 296 _ => (ErrorKind::Runtime, e.to_string()), 297 }; 298 Error { kind, message, line, column } 299} 300 301#[cfg(test)] 302mod tests { 303 use super::*; 304 305 fn kind(source: &str) -> ErrorKind { 306 let e = Skyray::new().eval(source).unwrap_err(); 307 eprintln!("{source:?} -> {e:?}"); 308 e.kind 309 } 310 311 #[test] 312 fn returns_the_last_value_as_data_with_sorted_keys() { 313 let v = Skyray::new().eval(r#"#{ b: [1, 2.5, "x"], a: true, c: () }"#).unwrap(); 314 let Value::Map(map) = v else { panic!("{v:?}") }; 315 assert_eq!(map.keys().collect::<Vec<_>>(), ["a", "b", "c"]); 316 assert_eq!(map["b"], Value::Array(vec![Value::Int(1), Value::Float(2.5), Value::Str("x".into())])); 317 assert_eq!(map["c"], Value::Unit); 318 } 319 320 #[test] 321 fn map_keys_iterate_in_sorted_order() { 322 assert_eq!( 323 Skyray::new().eval("let m = #{ z: 1, a: 2, m: 3 }; m.keys()").unwrap(), 324 Value::Array(vec![Value::Str("a".into()), Value::Str("m".into()), Value::Str("z".into())]) 325 ); 326 } 327 328 #[test] 329 fn unbounded_loops_and_eval_are_forbidden() { 330 assert_eq!(kind("while true {}"), ErrorKind::Forbidden); 331 assert_eq!(kind("loop { break; }"), ErrorKind::Forbidden); 332 assert_eq!(kind("do { } while false;"), ErrorKind::Forbidden); 333 assert_eq!(kind(r#"eval("1")"#), ErrorKind::Forbidden); 334 } 335 336 #[test] 337 fn for_over_a_collection_runs() { 338 assert_eq!(Skyray::new().eval("let n = 0; for x in [1, 2, 3] { n += x } n").unwrap(), Value::Int(6)); 339 } 340 341 #[test] 342 fn every_script_ends() { 343 assert_eq!(kind("fn f(x) { f(x) } f(1)"), ErrorKind::TooDeep); 344 assert_eq!(kind("let n = 0; for i in 0..1_000_000_000 { n += 1 } n"), ErrorKind::TooManyOperations); 345 } 346 347 #[test] 348 fn typos_fail_loudly() { 349 let e = Skyray::new().eval("let a = 1;\nb + 1").unwrap_err(); 350 assert_eq!(e.kind, ErrorKind::UndefinedVariable); 351 assert_eq!(e.line, Some(2)); 352 assert_eq!(kind("let m = #{ a: 1 }; m.b"), ErrorKind::MissingProperty); 353 } 354 355 #[test] 356 fn no_clock_and_no_import() { 357 // Rhai marks timestamp volatile, so the generated list refuses it outright. 358 assert_eq!(kind("timestamp()"), ErrorKind::Forbidden); 359 assert_eq!(kind(r#"import "x" as x;"#), ErrorKind::Syntax); 360 } 361 362 #[test] 363 fn volatile_functions_are_read_from_rhai_and_refused() { 364 assert!(volatile_functions().contains(&"sleep"), "{:?}", volatile_functions()); 365 assert!(!rhai_version().is_empty()); 366 assert_eq!(kind("sleep(0.0)"), ErrorKind::Forbidden); 367 assert_eq!(kind("sleep(0)"), ErrorKind::Forbidden); 368 assert_eq!(kind("exit()"), ErrorKind::Forbidden); 369 // Through a function pointer as well as by name. 370 assert_eq!(kind(r#"let f = Fn("sleep"); f.call(0.0)"#), ErrorKind::Forbidden); 371 } 372 373 #[test] 374 fn host_functions_take_and_return_values() { 375 let mut s = Skyray::new(); 376 s.function("add", 2, |args| match args { 377 [Value::Int(a), Value::Int(b)] => Ok(Value::Int(a + b)), 378 _ => Err("add takes two integers".into()), 379 }); 380 assert_eq!(s.eval("add(2, 3)").unwrap(), Value::Int(5)); 381 let e = s.eval("let x = 1;\nadd(x, \"no\")").unwrap_err(); 382 assert_eq!((e.kind, e.message.as_str(), e.line), (ErrorKind::Host, "add takes two integers", Some(2))); 383 } 384 385 #[test] 386 fn print_goes_where_the_host_says() { 387 let seen = std::sync::Arc::new(std::sync::Mutex::new(Vec::new())); 388 let sink = seen.clone(); 389 let mut s = Skyray::new(); 390 s.on_print(move |line| sink.lock().unwrap().push(line.to_string())); 391 s.eval(r#"print("hi")"#).unwrap(); 392 assert_eq!(*seen.lock().unwrap(), ["hi"]); 393 } 394 395 #[test] 396 fn a_function_pointer_is_not_data() { 397 assert_eq!(kind(r#"Fn("x")"#), ErrorKind::NotData); 398 } 399 400 #[test] 401 fn errors_show_line_and_column() { 402 let e = Skyray::new().eval("let a = 1;\n nope()").unwrap_err(); 403 assert_eq!(e.to_string(), format!("2:3: {}", e.message)); 404 } 405 406 #[test] 407 fn one_engine_serves_many_threads() { 408 fn shared<T: Send + Sync>() {} 409 shared::<Skyray>(); 410 } 411}