OOP support.

This commit is contained in:
Stephen Chung
2020-06-26 10:39:18 +08:00
parent 259b6d0fcf
commit 175c3ccaec
27 changed files with 498 additions and 234 deletions

View File

@@ -39,9 +39,9 @@ fn test_bool_op_short_circuit() -> Result<(), Box<EvalAltResult>> {
assert_eq!(
engine.eval::<bool>(
r"
let this = true;
let x = true;
this || { throw; };
x || { throw; };
"
)?,
true
@@ -50,9 +50,9 @@ fn test_bool_op_short_circuit() -> Result<(), Box<EvalAltResult>> {
assert_eq!(
engine.eval::<bool>(
r"
let this = false;
let x = false;
this && { throw; };
x && { throw; };
"
)?,
false
@@ -68,9 +68,9 @@ fn test_bool_op_no_short_circuit1() {
assert!(engine
.eval::<bool>(
r"
let this = true;
let x = true;
this | { throw; }
x | { throw; }
"
)
.is_err());
@@ -83,9 +83,9 @@ fn test_bool_op_no_short_circuit2() {
assert!(engine
.eval::<bool>(
r"
let this = false;
let x = false;
this & { throw; }
x & { throw; }
"
)
.is_err());

View File

@@ -19,28 +19,33 @@ fn test_functions() -> Result<(), Box<EvalAltResult>> {
#[cfg(not(feature = "no_object"))]
assert_eq!(
engine.eval::<INT>("fn add(x, n) { x + n } let x = 40; x.add(2)")?,
engine.eval::<INT>("fn add(n) { this + n } let x = 40; x.add(2)")?,
42
);
#[cfg(not(feature = "no_object"))]
assert_eq!(
engine.eval::<INT>("fn add(x, n) { x += n; } let x = 40; x.add(2); x")?,
40
engine.eval::<INT>("fn add(n) { this += n; } let x = 40; x.add(2); x")?,
42
);
assert_eq!(engine.eval::<INT>("fn mul2(x) { x * 2 } mul2(21)")?, 42);
assert_eq!(
engine.eval::<INT>("fn mul2(x) { x *= 2 } let a = 21; mul2(a); a")?,
21
);
#[cfg(not(feature = "no_object"))]
assert_eq!(
engine.eval::<INT>("fn mul2(x) { x * 2 } let x = 21; x.mul2()")?,
engine.eval::<INT>("fn mul2() { this * 2 } let x = 21; x.mul2()")?,
42
);
#[cfg(not(feature = "no_object"))]
assert_eq!(
engine.eval::<INT>("fn mul2(x) { x *= 2; } let x = 21; x.mul2(); x")?,
21
engine.eval::<INT>("fn mul2() { this *= 2; } let x = 21; x.mul2(); x")?,
42
);
Ok(())

View File

@@ -250,3 +250,25 @@ fn test_map_json() -> Result<(), Box<EvalAltResult>> {
Ok(())
}
#[test]
#[cfg(not(feature = "no_function"))]
fn test_map_oop() -> Result<(), Box<EvalAltResult>> {
let engine = Engine::new();
assert_eq!(
engine.eval::<INT>(
r#"
let obj = #{ data: 40, action: Fn("abc") };
fn abc(x) { this.data += x; }
obj.action(2);
obj.data
"#,
)?,
42
);
Ok(())
}

View File

@@ -1,9 +1,7 @@
#![cfg(not(feature = "no_module"))]
use rhai::{
module_resolvers, Dynamic, Engine, EvalAltResult, Module, ParseError, ParseErrorType, Scope,
INT,
module_resolvers, Engine, EvalAltResult, Module, ParseError, ParseErrorType, Scope, INT,
};
use std::any::TypeId;
#[test]
fn test_module() {