Skip to content

Commit

Permalink
Add multiline support for Rhai evaluation (#89)
Browse files Browse the repository at this point in the history
  • Loading branch information
mkeeter authored Apr 17, 2024
1 parent 009886a commit b1ca887
Show file tree
Hide file tree
Showing 2 changed files with 27 additions and 10 deletions.
16 changes: 14 additions & 2 deletions fidget/src/error.rs
Original file line number Diff line number Diff line change
Expand Up @@ -55,11 +55,23 @@ pub enum Error {

#[cfg(feature = "rhai")]
/// Rhai error; see inner code for details
#[error("Rhai error: {0}")]
RhaiError(#[from] rhai::EvalAltResult),
#[error("Rhai evaluation error: {0}")]
RhaiParseError(#[from] rhai::ParseError),

#[cfg(feature = "rhai")]
/// Rhai error; see inner code for details
#[error("Rhai evaluation error: {0}")]
RhaiEvalError(#[from] rhai::EvalAltResult),

#[cfg(feature = "jit")]
/// Dynasm error; see inner code for details
#[error("dynasm error: {0}")]
DynasmError(#[from] dynasmrt::DynasmError),
}

#[cfg(feature = "rhai")]
impl From<Box<rhai::EvalAltResult>> for Error {
fn from(e: Box<rhai::EvalAltResult>) -> Self {
Error::RhaiEvalError(*e)
}
}
21 changes: 13 additions & 8 deletions fidget/src/rhai/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@
//! # Ok::<(), fidget::Error>(())
//! ```
//!
//! `eval` only evaluates a single expression. To evaluate a full script,
//! `eval` returns a single value. To evaluate a script with multiple outputs,
//! construct an [`Engine`] then call [`Engine::run`]:
//!
//! ```
Expand Down Expand Up @@ -149,9 +149,7 @@ impl Engine {
scope.push("x", Tree::x());
scope.push("y", Tree::y());
scope.push("z", Tree::z());
self.engine
.run_with_scope(&mut scope, script)
.map_err(|e| *e)?;
self.engine.run_with_scope(&mut scope, script)?;

// Steal the ScriptContext's contents
let mut lock = self.context.lock().unwrap();
Expand All @@ -160,6 +158,7 @@ impl Engine {

/// Evaluates a single expression, in terms of `x`, `y`, and `z`
pub fn eval(&mut self, script: &str) -> Result<Tree, Error> {
let ast = self.engine.compile(script)?;
let mut scope = {
let mut ctx = self.context.lock().unwrap();
ctx.clear();
Expand All @@ -172,10 +171,7 @@ impl Engine {
scope
};

let out = self
.engine
.eval_expression_with_scope::<Tree>(&mut scope, script)
.map_err(|e| *e)?;
let out = self.engine.eval_ast_with_scope::<Tree>(&mut scope, &ast)?;

Ok(out)
}
Expand Down Expand Up @@ -404,6 +400,15 @@ mod test {
assert_eq!(ctx.eval_xyz(sum, 1.0, 2.0, 0.0).unwrap(), 3.0);
}

#[test]
fn test_eval_multiline() {
let mut engine = Engine::new();
let t = engine.eval("let foo = x; foo + y").unwrap();
let mut ctx = Context::new();
let sum = ctx.import(&t);
assert_eq!(ctx.eval_xyz(sum, 1.0, 2.0, 0.0).unwrap(), 3.0);
}

#[test]
fn test_simple_script() {
let mut engine = Engine::new();
Expand Down

0 comments on commit b1ca887

Please sign in to comment.