This commit is contained in:
Stephen Chung 2023-02-10 18:32:30 +08:00
commit 97e0578165
41 changed files with 204 additions and 194 deletions

View File

@ -235,7 +235,7 @@ mod generate_tests {
fn assert_streams_eq(actual: TokenStream, expected: TokenStream) {
let actual = actual.to_string();
let expected = expected.to_string();
if &actual != &expected {
if actual != expected {
let mut counter = 0;
let _iter = actual.chars().zip(expected.chars()).skip_while(|(a, e)| {
if *a == *e {
@ -254,7 +254,7 @@ mod generate_tests {
}
(actual_diff, expected_diff)
};
eprintln!("actual != expected, diverge at char {}", counter);
eprintln!("actual != expected, diverge at char {counter}");
// eprintln!(" actual: {}", _actual_diff);
// eprintln!("expected: {}", _expected_diff);
// assert!(false);

View File

@ -86,11 +86,7 @@ mod module_tests {
assert_eq!(item_mod.fns().len(), 1);
assert_eq!(item_mod.fns()[0].name().to_string(), "get_mystic_number");
assert_eq!(
item_mod.fns()[0]
.comments()
.iter()
.cloned()
.collect::<Vec<_>>(),
item_mod.fns()[0].comments().to_vec(),
vec![
"\
/// This is a doc-comment.\n\
@ -286,7 +282,7 @@ mod generate_tests {
fn assert_streams_eq(actual: TokenStream, expected: TokenStream) {
let actual = actual.to_string();
let expected = expected.to_string();
if &actual != &expected {
if actual != expected {
let mut counter = 0;
let _iter = actual.chars().zip(expected.chars()).skip_while(|(a, e)| {
if *a == *e {
@ -305,7 +301,7 @@ mod generate_tests {
}
(actual_diff, expected_diff)
};
eprintln!("actual != expected, diverge at char {}", counter);
eprintln!("actual != expected, diverge at char {counter}");
// eprintln!(" actual: {}", _actual_diff);
// eprintln!("expected: {}", _expected_diff);
// assert!(false);

View File

@ -62,7 +62,7 @@ mod raw_fn_str {
#[export_fn]
pub fn write_out_str(message: &str) -> bool {
eprintln!("{}", message);
eprintln!("{message}");
true
}
}
@ -75,10 +75,9 @@ fn raw_fn_str_test() -> Result<(), Box<EvalAltResult>> {
rhai::set_exported_fn!(m, "write_out_str", raw_fn_str::write_out_str);
engine.register_static_module("Host::IO", m.into());
assert_eq!(
engine.eval::<bool>(r#"let x = Host::IO::write_out_str("hello world!"); x"#)?,
true
);
assert!(engine
.eval::<bool>(r#"let x = Host::IO::write_out_str("hello world!"); x"#)
.unwrap());
Ok(())
}
@ -86,6 +85,7 @@ mod mut_opaque_ref {
use rhai::plugin::*;
use rhai::INT;
#[allow(dead_code)] // used inside `export_module!`
#[derive(Clone)]
pub struct StatusMessage {
os_code: Option<INT>,
@ -127,17 +127,16 @@ fn mut_opaque_ref_test() -> Result<(), Box<EvalAltResult>> {
rhai::set_exported_fn!(m, "write_out_message", mut_opaque_ref::write_out_message);
engine.register_static_module("Host::Msg", m.into());
assert_eq!(
engine.eval::<bool>(
assert!(engine
.eval::<bool>(
r#"
let message1 = Host::Msg::new_message(true, "it worked");
let ok1 = Host::Msg::write_out_message(message1);
let message2 = Host::Msg::new_os_message(true, 0);
let ok2 = Host::Msg::write_out_message(message2);
ok1 && ok2"#
)?,
true
);
)
.unwrap());
Ok(())
}

View File

@ -3,6 +3,7 @@ use rhai::{Array, Engine, EvalAltResult, FLOAT, INT};
pub mod empty_module {
use rhai::plugin::*;
#[allow(non_snake_case)]
#[export_module]
pub mod EmptyModule {}
}
@ -81,7 +82,7 @@ pub mod raw_fn_str_module {
#[export_module]
pub mod host_io {
pub fn write_out_str(message: &str) -> bool {
eprintln!("{}", message);
eprintln!("{message}");
true
}
}
@ -93,10 +94,9 @@ fn raw_fn_str_module_test() -> Result<(), Box<EvalAltResult>> {
let m = rhai::exported_module!(crate::raw_fn_str_module::host_io);
engine.register_static_module("Host::IO", m.into());
assert_eq!(
engine.eval::<bool>(r#"let x = Host::IO::write_out_str("hello world!"); x"#)?,
true
);
assert!(engine
.eval::<bool>(r#"let x = Host::IO::write_out_str("hello world!"); x"#)
.unwrap());
Ok(())
}
@ -104,6 +104,7 @@ pub mod mut_opaque_ref_module {
use rhai::plugin::*;
use rhai::INT;
#[allow(dead_code)] // used inside `exported_module!`
#[derive(Clone)]
pub struct StatusMessage {
os_code: Option<INT>,
@ -144,8 +145,8 @@ fn mut_opaque_ref_test() -> Result<(), Box<EvalAltResult>> {
let m = rhai::exported_module!(crate::mut_opaque_ref_module::host_msg);
engine.register_static_module("Host::Msg", m.into());
assert_eq!(
engine.eval::<bool>(
assert!(engine
.eval::<bool>(
r#"
let success = "it worked";
let message1 = Host::Msg::new_message(true, success);
@ -154,9 +155,8 @@ fn mut_opaque_ref_test() -> Result<(), Box<EvalAltResult>> {
let ok2 = Host::Msg::write_out_message(message2);
ok1 && ok2
"#
)?,
true
);
)
.unwrap());
Ok(())
}
@ -267,6 +267,7 @@ fn multiple_fn_rename_test() -> Result<(), Box<EvalAltResult>> {
Ok(())
}
#[allow(dead_code)] // used inside `export_module!`
mod export_by_prefix {
use rhai::plugin::*;
@ -331,7 +332,7 @@ fn export_by_prefix_test() -> Result<(), Box<EvalAltResult>> {
let fx = Math::Advanced::foo_add_float2(ex, 1.0);
fx
").unwrap_err(),
EvalAltResult::ErrorFunctionNotFound(s, p)
EvalAltResult::ErrorFunctionNotFound(s, ..)
if s == "Math::Advanced::foo_add_float2 (f64, f64)"));
assert!(matches!(*engine.eval::<FLOAT>(
@ -340,12 +341,13 @@ fn export_by_prefix_test() -> Result<(), Box<EvalAltResult>> {
let fx = Math::Advanced::bar_m(ex, 1.0);
fx
").unwrap_err(),
EvalAltResult::ErrorFunctionNotFound(s, p)
EvalAltResult::ErrorFunctionNotFound(s, ..)
if s == "Math::Advanced::bar_m (f64, f64)"));
Ok(())
}
#[allow(dead_code)] // used inside `export_module!`
mod export_all {
use rhai::plugin::*;
@ -411,7 +413,7 @@ fn export_all_test() -> Result<(), Box<EvalAltResult>> {
let fx = Math::Advanced::foo_p(ex, 1);
fx
").unwrap_err(),
EvalAltResult::ErrorFunctionNotFound(s, p)
EvalAltResult::ErrorFunctionNotFound(s, ..)
if s == "Math::Advanced::foo_p (i64, i64)"));
Ok(())

View File

@ -92,6 +92,7 @@ mod export_nested_by_prefix {
}
}
#[allow(dead_code)] // used inside a `exported_module!`
#[rhai_mod(name = "foo_third_adders")]
pub mod baz_third_adders {
use rhai::{FLOAT, INT};
@ -105,6 +106,7 @@ mod export_nested_by_prefix {
}
}
#[allow(dead_code)] // used inside a `exported_module!`
pub mod bar_fourth_adders {
use rhai::{FLOAT, INT};
@ -153,7 +155,7 @@ fn export_nested_by_prefix_test() -> Result<(), Box<EvalAltResult>> {
let fx = Math::Advanced::foo_third_adders::add_float(ex, 1.0);
fx
").unwrap_err(),
EvalAltResult::ErrorFunctionNotFound(s, p)
EvalAltResult::ErrorFunctionNotFound(s, ..)
if s == "Math::Advanced::foo_third_adders::add_float (f64, f64)"));
assert!(matches!(*engine.eval::<FLOAT>(
@ -162,7 +164,7 @@ fn export_nested_by_prefix_test() -> Result<(), Box<EvalAltResult>> {
let fx = Math::Advanced::foo_third_adders::add_int(ex, 1);
fx
").unwrap_err(),
EvalAltResult::ErrorFunctionNotFound(s, p)
EvalAltResult::ErrorFunctionNotFound(s, ..)
if s == "Math::Advanced::foo_third_adders::add_int (i64, i64)"));
assert!(matches!(*engine.eval::<FLOAT>(
@ -171,7 +173,7 @@ fn export_nested_by_prefix_test() -> Result<(), Box<EvalAltResult>> {
let fx = Math::Advanced::bar_fourth_adders::add_int(ex, 1);
fx
").unwrap_err(),
EvalAltResult::ErrorFunctionNotFound(s, p)
EvalAltResult::ErrorFunctionNotFound(s, ..)
if s == "Math::Advanced::bar_fourth_adders::add_int (i64, i64)"));
assert!(matches!(*engine.eval::<FLOAT>(
@ -180,7 +182,7 @@ fn export_nested_by_prefix_test() -> Result<(), Box<EvalAltResult>> {
let fx = Math::Advanced::bar_fourth_adders::add_float(ex, 1.0);
fx
").unwrap_err(),
EvalAltResult::ErrorFunctionNotFound(s, p)
EvalAltResult::ErrorFunctionNotFound(s, ..)
if s == "Math::Advanced::bar_fourth_adders::add_float (f64, f64)"));
Ok(())

View File

@ -80,7 +80,7 @@ pub fn main() {
// Compile the handler script.
println!("> Loading script file: {path}");
let ast = match engine.compile_file_with_scope(&mut scope, path.into()) {
let ast = match engine.compile_file_with_scope(&scope, path.into()) {
Ok(ast) => ast,
Err(err) => {
eprintln!("! Error: {err}");

View File

@ -44,7 +44,7 @@ pub fn main() {
let mut input = String::new();
// Read script file
print!("Script file [{}]: ", SCRIPT_FILE);
print!("Script file [{SCRIPT_FILE}]: ");
stdout().flush().expect("flush stdout");
input.clear();
@ -69,7 +69,7 @@ pub fn main() {
// Compile the handler script.
println!("> Loading script file: {path}");
let ast = match engine.compile_file_with_scope(&mut scope, path.into()) {
let ast = match engine.compile_file_with_scope(&scope, path.into()) {
Ok(ast) => ast,
Err(err) => {
eprintln!("! Error: {}", err);

View File

@ -83,7 +83,7 @@ pub fn main() {
// Compile the handler script.
println!("> Loading script file: {path}");
let ast = match engine.compile_file_with_scope(&mut scope, path.into()) {
let ast = match engine.compile_file_with_scope(&scope, path.into()) {
Ok(ast) => ast,
Err(err) => {
eprintln!("! Error: {err}");

View File

@ -212,12 +212,12 @@ impl Engine {
}
/// Evaluate an [`AST`] with own scope, returning the result value or an error.
#[inline]
pub(crate) fn eval_ast_with_scope_raw<'a>(
pub(crate) fn eval_ast_with_scope_raw(
&self,
global: &mut GlobalRuntimeState,
caches: &mut Caches,
scope: &mut Scope,
ast: &'a AST,
ast: &AST,
) -> RhaiResult {
let orig_source = mem::replace(&mut global.source, ast.source_raw().cloned());
@ -245,16 +245,16 @@ impl Engine {
g.source = orig_source;
});
self.eval_global_statements(global, caches, scope, ast.statements())
.and_then(|r| {
#[cfg(feature = "debugging")]
if self.is_debugger_registered() {
global.debugger_mut().status = crate::eval::DebuggerStatus::Terminate;
let node = &crate::ast::Stmt::Noop(Position::NONE);
self.run_debugger(global, caches, scope, None, node)?;
}
Ok(r)
})
let r = self.eval_global_statements(global, caches, scope, ast.statements())?;
#[cfg(feature = "debugging")]
if self.is_debugger_registered() {
global.debugger_mut().status = crate::eval::DebuggerStatus::Terminate;
let node = &crate::ast::Stmt::Noop(Position::NONE);
self.run_debugger(global, caches, scope, None, node)?;
}
Ok(r)
}
}

View File

@ -97,7 +97,7 @@ impl Engine {
///
/// // Compile a script to an AST and store it for later evaluation.
/// // Notice that a PathBuf is required which can easily be constructed from a string.
/// let ast = engine.compile_file_with_scope(&mut scope, "script.rhai".into())?;
/// let ast = engine.compile_file_with_scope(&scope, "script.rhai".into())?;
///
/// let result = engine.eval_ast::<i64>(&ast)?;
/// # }

View File

@ -126,16 +126,16 @@ impl Engine {
global.embedded_module_resolver = ast.resolver().cloned();
}
self.eval_global_statements(global, caches, scope, ast.statements())
.and_then(|_| {
#[cfg(feature = "debugging")]
if self.is_debugger_registered() {
global.debugger_mut().status = crate::eval::DebuggerStatus::Terminate;
let node = &crate::ast::Stmt::Noop(crate::Position::NONE);
self.run_debugger(global, caches, scope, None, node)?;
}
Ok(())
})
let _ = self.eval_global_statements(global, caches, scope, ast.statements())?;
#[cfg(feature = "debugging")]
if self.is_debugger_registered() {
global.debugger_mut().status = crate::eval::DebuggerStatus::Terminate;
let node = &crate::ast::Stmt::Noop(crate::Position::NONE);
self.run_debugger(global, caches, scope, None, node)?;
}
Ok(())
}
}

View File

@ -103,11 +103,11 @@ impl Dynamic {
pub(crate) fn calc_data_sizes(&self, _top: bool) -> (usize, usize, usize) {
match self.0 {
#[cfg(not(feature = "no_index"))]
Union::Array(ref arr, ..) => Self::calc_array_sizes(&**arr),
Union::Array(ref arr, ..) => Self::calc_array_sizes(arr),
#[cfg(not(feature = "no_index"))]
Union::Blob(ref blob, ..) => (blob.len(), 0, 0),
#[cfg(not(feature = "no_object"))]
Union::Map(ref map, ..) => Self::calc_map_sizes(&**map),
Union::Map(ref map, ..) => Self::calc_map_sizes(map),
Union::Str(ref s, ..) => (0, 0, s.len()),
#[cfg(not(feature = "no_closure"))]
Union::Shared(..) if _top => self.read_lock::<Self>().unwrap().calc_data_sizes(true),

View File

@ -42,7 +42,7 @@
//!
//! # #[cfg(not(feature = "no_std"))]
//! # #[cfg(not(target_family = "wasm"))]
//! #
//! #
//! // Evaluate the script, expecting a 'bool' result
//! let result: bool = engine.eval_file("my_script.rhai".into())?;
//!
@ -82,8 +82,8 @@
// The lints below can be turned off to reduce signal/noise ratio
// #![allow(clippy::too_many_lines)]
// #![allow(clippy::let_underscore_drop)]
// #![allow(clippy::absurd_extreme_comparisons)]
// #![allow(clippy::unnecessary_cast)]
#![allow(clippy::absurd_extreme_comparisons)]
#![allow(clippy::unnecessary_cast)]
// #![allow(clippy::wildcard_imports)]
#[cfg(feature = "no_std")]
@ -166,8 +166,7 @@ const MAX_USIZE_INT: INT = INT::MAX;
const MAX_USIZE_INT: INT = usize::MAX as INT;
/// The maximum integer that can fit into a [`usize`].
#[cfg(feature = "only_i32")]
#[cfg(target_pointer_width = "32")]
#[cfg(all(feature = "only_i32", target_pointer_width = "32"))]
const MAX_USIZE_INT: INT = INT::MAX;
/// Number of bits in [`INT`].
@ -316,8 +315,7 @@ pub type OptimizationLevel = ();
#[cfg(feature = "internals")]
pub use types::dynamic::{AccessMode, DynamicReadLock, DynamicWriteLock, Variant};
#[cfg(feature = "internals")]
#[cfg(not(feature = "no_float"))]
#[cfg(all(feature = "internals", not(feature = "no_float")))]
pub use types::FloatWrapper;
#[cfg(feature = "internals")]

View File

@ -140,15 +140,15 @@ mod print_debug_functions {
}
/// Return the empty string.
#[allow(unused_variables)]
#[rhai_fn(name = "print", name = "to_string")]
pub fn print_unit(ctx: NativeCallContext, unit: ()) -> ImmutableString {
let _ = unit;
ctx.engine().const_empty_string()
}
/// Convert the unit into a string in debug format.
#[allow(unused_variables)]
#[rhai_fn(name = "debug", name = "to_debug")]
pub fn debug_unit(unit: ()) -> ImmutableString {
let _ = unit;
"()".into()
}

View File

@ -83,13 +83,14 @@ mod string_functions {
buf.into()
}
#[allow(unused_variables)]
#[rhai_fn(name = "+")]
pub fn add_append_unit(string: ImmutableString, item: ()) -> ImmutableString {
let _ = item;
string
}
#[allow(unused_variables)]
#[rhai_fn(name = "+")]
pub fn add_prepend_unit(_item: (), string: ImmutableString) -> ImmutableString {
pub fn add_prepend_unit(item: (), string: ImmutableString) -> ImmutableString {
string
}
@ -101,11 +102,9 @@ mod string_functions {
pub fn add_assign_append_char(string: &mut ImmutableString, character: char) {
*string += character;
}
#[allow(unused_variables)]
#[rhai_fn(name = "+=")]
pub fn add_assign_append_unit(string: &mut ImmutableString, item: ()) {
let _ = string;
let _ = item;
}
pub fn add_assign_append_unit(string: &mut ImmutableString, item: ()) {}
#[cfg(not(feature = "no_index"))]
pub mod blob_functions {

View File

@ -155,7 +155,9 @@ mod time_functions {
})
}
} else {
Ok(timestamp - Duration::from_millis((seconds * 1000.0) as u64))
Ok(timestamp
.checked_sub(Duration::from_millis((seconds * 1000.0) as u64))
.unwrap())
}
}
@ -212,7 +214,9 @@ mod time_functions {
))
})
} else {
Ok(timestamp - Duration::from_secs(seconds as u64))
Ok(timestamp
.checked_sub(Duration::from_secs(seconds as u64))
.unwrap())
}
}

View File

@ -1204,7 +1204,7 @@ const fn is_hex_digit(c: char) -> bool {
/// Test if the given character is a numeric digit.
#[inline(always)]
const fn is_numeric_digit(c: char) -> bool {
matches!(c, '0'..='9')
c.is_ascii_digit()
}
/// Test if the comment block is a doc-comment.

View File

@ -1,10 +1,10 @@
#![cfg(not(feature = "no_index"))]
use rhai::{Array, Dynamic, Engine, EvalAltResult, ParseErrorType, INT};
use std::iter::FromIterator;
#[test]
fn test_arrays() -> Result<(), Box<EvalAltResult>> {
let mut a = Array::new();
a.push((42 as INT).into());
let a = Array::from_iter([(42 as INT).into()]);
assert_eq!(a[0].clone_cast::<INT>(), 42);
@ -125,7 +125,7 @@ fn test_arrays() -> Result<(), Box<EvalAltResult>> {
let y = [4, 5];
x.append(y);
x
x
"
)?
.into_typed_array::<INT>()?,
@ -515,15 +515,14 @@ fn test_arrays_map_reduce() -> Result<(), Box<EvalAltResult>> {
3
);
assert_eq!(
engine.eval::<()>(
engine
.eval::<()>(
"
let x = [1, 2, 3, 2, 1];
x.find(|v| v > 4)
"
)?,
()
);
",
)
.unwrap();
assert_eq!(
engine.eval::<INT>(
@ -535,15 +534,14 @@ fn test_arrays_map_reduce() -> Result<(), Box<EvalAltResult>> {
2
);
assert_eq!(
engine.eval::<()>(
engine
.eval::<()>(
"
let x = [#{alice: 1}, #{bob: 2}, #{clara: 3}];
x.find_map(|v| v.dave)
"
)?,
()
);
",
)
.unwrap();
Ok(())
}
@ -552,7 +550,7 @@ fn test_arrays_map_reduce() -> Result<(), Box<EvalAltResult>> {
fn test_arrays_elvis() -> Result<(), Box<EvalAltResult>> {
let engine = Engine::new();
assert_eq!(engine.eval::<()>("let x = (); x?[2]")?, ());
engine.eval::<()>("let x = (); x?[2]").unwrap();
engine.run("let x = (); x?[2] = 42")?;

View File

@ -1,12 +1,10 @@
#![cfg(not(feature = "no_index"))]
use rhai::{Blob, Engine, EvalAltResult, Scope, INT};
use std::iter::FromIterator;
#[test]
fn test_blobs() -> Result<(), Box<EvalAltResult>> {
let mut a = Blob::new();
a.push(1);
a.push(2);
a.push(3);
let a = Blob::from_iter([1, 2, 3]);
let engine = Engine::new();
let mut scope = Scope::new();

View File

@ -4,8 +4,8 @@ use rhai::{Engine, EvalAltResult};
fn test_bool_op1() -> Result<(), Box<EvalAltResult>> {
let engine = Engine::new();
assert_eq!(engine.eval::<bool>("true && (false || true)")?, true);
assert_eq!(engine.eval::<bool>("true & (false | true)")?, true);
assert!(engine.eval::<bool>("true && (false || true)").unwrap());
assert!(engine.eval::<bool>("true & (false | true)").unwrap());
Ok(())
}
@ -14,8 +14,8 @@ fn test_bool_op1() -> Result<(), Box<EvalAltResult>> {
fn test_bool_op2() -> Result<(), Box<EvalAltResult>> {
let engine = Engine::new();
assert_eq!(engine.eval::<bool>("false && (false || true)")?, false);
assert_eq!(engine.eval::<bool>("false & (false | true)")?, false);
assert!(!engine.eval::<bool>("false && (false || true)").unwrap());
assert!(!engine.eval::<bool>("false & (false | true)").unwrap());
Ok(())
}
@ -25,9 +25,9 @@ fn test_bool_op3() -> Result<(), Box<EvalAltResult>> {
let engine = Engine::new();
assert!(engine.eval::<bool>("true && (false || 123)").is_err());
assert_eq!(engine.eval::<bool>("true && (true || { throw })")?, true);
assert!(engine.eval::<bool>("true && (true || { throw })").unwrap());
assert!(engine.eval::<bool>("123 && (false || true)").is_err());
assert_eq!(engine.eval::<bool>("false && (true || { throw })")?, false);
assert!(!engine.eval::<bool>("false && (true || { throw })").unwrap());
Ok(())
}
@ -36,25 +36,23 @@ fn test_bool_op3() -> Result<(), Box<EvalAltResult>> {
fn test_bool_op_short_circuit() -> Result<(), Box<EvalAltResult>> {
let engine = Engine::new();
assert_eq!(
engine.eval::<bool>(
assert!(engine
.eval::<bool>(
"
let x = true;
x || { throw; };
"
)?,
true
);
)
.unwrap());
assert_eq!(
engine.eval::<bool>(
assert!(!engine
.eval::<bool>(
"
let x = false;
x && { throw; };
"
)?,
false
);
)
.unwrap());
Ok(())
}
@ -63,14 +61,14 @@ fn test_bool_op_short_circuit() -> Result<(), Box<EvalAltResult>> {
fn test_bool_op_no_short_circuit1() {
let engine = Engine::new();
assert!(engine
let _ = engine
.eval::<bool>(
"
let x = true;
x | { throw; }
"
",
)
.is_err());
.unwrap_err();
}
#[test]

View File

@ -169,7 +169,7 @@ fn test_fn_ptr_raw() -> Result<(), Box<EvalAltResult>> {
.register_fn("mul", |x: &mut INT, y: INT| *x *= y)
.register_raw_fn(
"bar",
&[
[
TypeId::of::<INT>(),
TypeId::of::<FnPtr>(),
TypeId::of::<INT>(),

View File

@ -21,7 +21,7 @@ fn test_comments() -> Result<(), Box<EvalAltResult>> {
42
);
assert_eq!(engine.run("/* Hello world */")?, ());
engine.run("/* Hello world */").unwrap();
Ok(())
}

View File

@ -5,8 +5,8 @@ fn test_or_equals() -> Result<(), Box<EvalAltResult>> {
let engine = Engine::new();
assert_eq!(engine.eval::<INT>("let x = 16; x |= 74; x")?, 90);
assert_eq!(engine.eval::<bool>("let x = true; x |= false; x")?, true);
assert_eq!(engine.eval::<bool>("let x = false; x |= true; x")?, true);
assert!(engine.eval::<bool>("let x = true; x |= false; x").unwrap());
assert!(engine.eval::<bool>("let x = false; x |= true; x").unwrap());
Ok(())
}
@ -16,9 +16,9 @@ fn test_and_equals() -> Result<(), Box<EvalAltResult>> {
let engine = Engine::new();
assert_eq!(engine.eval::<INT>("let x = 16; x &= 31; x")?, 16);
assert_eq!(engine.eval::<bool>("let x = true; x &= false; x")?, false);
assert_eq!(engine.eval::<bool>("let x = false; x &= true; x")?, false);
assert_eq!(engine.eval::<bool>("let x = true; x &= true; x")?, true);
assert!(!engine.eval::<bool>("let x = true; x &= false; x").unwrap());
assert!(!engine.eval::<bool>("let x = false; x &= true; x").unwrap());
assert!(engine.eval::<bool>("let x = true; x &= true; x").unwrap());
Ok(())
}

View File

@ -91,11 +91,12 @@ fn test_custom_syntax() -> Result<(), Box<EvalAltResult>> {
}
// Do not rewind if the variable is upper-case
if var_name.to_uppercase() == var_name {
context.eval_expression_tree_raw(stmt, false)?;
let _: Dynamic = if var_name.to_uppercase() == var_name {
#[allow(deprecated)] // not deprecated but unstable
context.eval_expression_tree_raw(stmt, false)
} else {
context.eval_expression_tree(stmt)?;
}
context.eval_expression_tree(stmt)
}?;
count += 1;

View File

@ -90,6 +90,7 @@ fn test_expressions() -> Result<(), Box<EvalAltResult>> {
#[test]
#[cfg(not(feature = "no_object"))]
fn test_expressions_eval() -> Result<(), Box<EvalAltResult>> {
#[allow(clippy::upper_case_acronyms)]
#[derive(Debug, Clone)]
struct AGENT {
pub gender: String,
@ -124,14 +125,12 @@ fn test_expressions_eval() -> Result<(), Box<EvalAltResult>> {
scope.push_constant("agent", my_agent);
// Evaluate the expression
let result: bool = engine.eval_expression_with_scope(
assert!(engine.eval_expression_with_scope(
&mut scope,
r#"
agent.age > 10 && agent.gender == "male"
"#,
)?;
assert_eq!(result, true);
)?);
Ok(())
}

View File

@ -7,9 +7,11 @@ const EPSILON: FLOAT = 0.000_000_000_1;
fn test_float() -> Result<(), Box<EvalAltResult>> {
let engine = Engine::new();
assert!(engine.eval::<bool>("let x = 0.0; let y = 1.0; x < y")?,);
assert!(!engine.eval::<bool>("let x = 0.0; let y = 1.0; x > y")?,);
assert_eq!(engine.eval::<bool>("let x = 0.; let y = 1.; x > y")?, false);
assert!(engine.eval::<bool>("let x = 0.0; let y = 1.0; x < y")?);
assert!(!engine.eval::<bool>("let x = 0.0; let y = 1.0; x > y")?);
assert!(!engine
.eval::<bool>("let x = 0.; let y = 1.; x > y")
.unwrap());
assert!((engine.eval::<FLOAT>("let x = 9.9999; x")? - 9.9999 as FLOAT).abs() < EPSILON);
Ok(())

View File

@ -8,6 +8,7 @@ fn test_functions_trait_object() -> Result<(), Box<EvalAltResult>> {
fn greet(&self) -> INT;
}
#[allow(clippy::upper_case_acronyms)]
#[derive(Debug, Clone)]
struct ABC(INT);

View File

@ -267,7 +267,7 @@ fn test_get_set_collection() -> Result<(), Box<EvalAltResult>> {
engine
.register_type_with_name::<MyBag>("MyBag")
.register_iterator::<MyBag>()
.register_fn("new_bag", || MyBag::new())
.register_fn("new_bag", MyBag::new)
.register_fn("len", |col: &mut MyBag| col.len() as INT)
.register_get("len", |col: &mut MyBag| col.len() as INT)
.register_fn("clear", |col: &mut MyBag| col.clear())
@ -314,7 +314,7 @@ fn test_get_set_indexer() -> Result<(), Box<EvalAltResult>> {
engine
.register_type_with_name::<MyMap>("MyMap")
.register_fn("new_map", || MyMap::new())
.register_fn("new_map", MyMap::new)
.register_indexer_get(
|map: &mut MyMap, index: &str| -> Result<_, Box<EvalAltResult>> {
map.get(index).cloned().ok_or_else(|| {
@ -376,7 +376,7 @@ fn test_get_set_indexer() -> Result<(), Box<EvalAltResult>> {
r#"
let my_map = new_map();
my_map["eggs"] = 42;
try {
let eggs = my_map["eggs"];
let eggs = my_map["not found"];
@ -385,7 +385,7 @@ fn test_get_set_indexer() -> Result<(), Box<EvalAltResult>> {
{
print("Not found!");
}
my_map["eggs"]
"#,
)?,
@ -399,9 +399,11 @@ fn test_get_set_indexer() -> Result<(), Box<EvalAltResult>> {
fn test_get_set_elvis() -> Result<(), Box<EvalAltResult>> {
let engine = Engine::new();
assert_eq!(engine.eval::<()>("let x = (); x?.foo.bar.baz")?, ());
assert_eq!(engine.eval::<()>("let x = (); x?.foo(1,2,3)")?, ());
assert_eq!(engine.eval::<()>("let x = #{a:()}; x.a?.foo.bar.baz")?, ());
engine.eval::<()>("let x = (); x?.foo.bar.baz").unwrap();
engine.eval::<()>("let x = (); x?.foo(1,2,3)").unwrap();
engine
.eval::<()>("let x = #{a:()}; x.a?.foo.bar.baz")
.unwrap();
assert_eq!(engine.eval::<String>("let x = 'x'; x?.type_of()")?, "char");
Ok(())

View File

@ -111,7 +111,7 @@ b`: 1}; y["a\nb"]
fn test_map_prop() -> Result<(), Box<EvalAltResult>> {
let mut engine = Engine::new();
assert_eq!(engine.eval::<()>("let x = #{a: 42}; x.b")?, ());
engine.eval::<()>("let x = #{a: 42}; x.b").unwrap();
engine.set_fail_on_invalid_map_property(true);
@ -182,7 +182,7 @@ fn test_map_assign() -> Result<(), Box<EvalAltResult>> {
let x = engine.eval::<Map>(r#"let x = #{a: 1, b: true, "c$": "hello"}; x"#)?;
assert_eq!(x["a"].as_int().unwrap(), 1);
assert_eq!(x["b"].as_bool().unwrap(), true);
assert!(x["b"].as_bool().unwrap());
assert_eq!(x["c$"].clone_cast::<String>(), "hello");
Ok(())
@ -195,7 +195,7 @@ fn test_map_return() -> Result<(), Box<EvalAltResult>> {
let x = engine.eval::<Map>(r#"#{a: 1, b: true, "c$": "hello"}"#)?;
assert_eq!(x["a"].as_int().unwrap(), 1);
assert_eq!(x["b"].as_bool().unwrap(), true);
assert!(x["b"].as_bool().unwrap());
assert_eq!(x["c$"].clone_cast::<String>(), "hello");
Ok(())
@ -240,10 +240,10 @@ fn test_map_json() -> Result<(), Box<EvalAltResult>> {
assert!(!map.contains_key("x"));
assert_eq!(map["a"].as_int().unwrap(), 1);
assert_eq!(map["b"].as_bool().unwrap(), true);
assert!(map["b"].as_bool().unwrap());
assert_eq!(map["c"].as_int().unwrap(), 42);
assert_eq!(map["$d e f!"].clone_cast::<String>(), "hello");
assert_eq!(map["z"].as_unit().unwrap(), ());
let _: () = map["z"].as_unit().unwrap();
#[cfg(not(feature = "no_index"))]
{

View File

@ -56,7 +56,7 @@ fn test_method_call_with_full_optimization() -> Result<(), Box<EvalAltResult>> {
engine.set_optimization_level(rhai::OptimizationLevel::Full);
engine
.register_fn("new_ts", || TestStruct::new())
.register_fn("new_ts", TestStruct::new)
.register_fn("ymd", |_: INT, _: INT, _: INT| 42 as INT)
.register_fn("range", |_: &mut TestStruct, _: INT, _: INT| {
TestStruct::new()

View File

@ -13,6 +13,7 @@ fn test_mismatched_op() {
#[test]
#[cfg(not(feature = "no_object"))]
fn test_mismatched_op_custom_type() -> Result<(), Box<EvalAltResult>> {
#[allow(dead_code)] // used inside `register_type_with_name`
#[derive(Debug, Clone)]
struct TestStruct {
x: INT,

View File

@ -1,9 +1,12 @@
#![cfg(not(feature = "no_module"))]
use rhai::{
module_resolvers::{DummyModuleResolver, StaticModuleResolver},
Dynamic, Engine, EvalAltResult, FnNamespace, FnPtr, ImmutableString, Module, NativeCallContext,
ParseError, ParseErrorType, Scope, INT,
Dynamic, Engine, EvalAltResult, FnNamespace, ImmutableString, Module, ParseError,
ParseErrorType, Scope, INT,
};
//
#[cfg(all(not(feature = "no_function"), feature = "internals"))]
use rhai::{FnPtr, NativeCallContext};
#[test]
fn test_module() {
@ -248,7 +251,7 @@ fn test_module_resolver() -> Result<(), Box<EvalAltResult>> {
"#
)
.expect_err("should error"),
EvalAltResult::ErrorInFunctionCall(fn_name, _, ..) if fn_name == "foo"
EvalAltResult::ErrorInFunctionCall(fn_name, ..) if fn_name == "foo"
));
engine.set_max_modules(1000);
@ -276,9 +279,9 @@ fn test_module_resolver() -> Result<(), Box<EvalAltResult>> {
}
foo(1) + { import "hello" as h; h::answer }
"#;
let mut scope = Scope::new();
let scope = Scope::new();
let ast = engine.compile_into_self_contained(&mut scope, script)?;
let ast = engine.compile_into_self_contained(&scope, script)?;
engine.set_module_resolver(DummyModuleResolver::new());
@ -336,15 +339,15 @@ fn test_module_from_ast() -> Result<(), Box<EvalAltResult>> {
private fn hidden() {
throw "you shouldn't see me!";
}
// Imported modules become sub-modules
import "another module" as extra;
// Variables defined at global level become module variables
export const x = 123;
let foo = 41;
let hello;
// Final variable values become constant module variable values
foo = calc(foo);
hello = `hello, ${foo} worlds!`;
@ -534,8 +537,7 @@ fn test_module_ast_namespace2() -> Result<(), Box<EvalAltResult>> {
Ok(())
}
#[cfg(not(feature = "no_function"))]
#[cfg(feature = "internals")]
#[cfg(all(not(feature = "no_function"), feature = "internals"))]
#[test]
fn test_module_context() -> Result<(), Box<EvalAltResult>> {
let script = "fn bar() { calc(|x| x + 1) }";

View File

@ -33,12 +33,12 @@ fn test_native_context_fn_name() -> Result<(), Box<EvalAltResult>> {
engine
.register_raw_fn(
"add_double",
&[TypeId::of::<INT>(), TypeId::of::<INT>()],
[TypeId::of::<INT>(), TypeId::of::<INT>()],
add_double,
)
.register_raw_fn(
"append_x2",
&[TypeId::of::<INT>(), TypeId::of::<INT>()],
[TypeId::of::<INT>(), TypeId::of::<INT>()],
add_double,
);

View File

@ -4,15 +4,14 @@ use rhai::{Engine, EvalAltResult};
fn test_not() -> Result<(), Box<EvalAltResult>> {
let engine = Engine::new();
assert_eq!(
engine.eval::<bool>("let not_true = !true; not_true")?,
false
);
assert!(!engine
.eval::<bool>("let not_true = !true; not_true")
.unwrap());
#[cfg(not(feature = "no_function"))]
assert_eq!(engine.eval::<bool>("fn not(x) { !x } not(false)")?, true);
assert!(engine.eval::<bool>("fn not(x) { !x } not(false)").unwrap());
assert_eq!(engine.eval::<bool>("!!!!true")?, true);
assert!(engine.eval::<bool>("!!!!true").unwrap());
Ok(())
}

View File

@ -83,7 +83,7 @@ fn test_options_strict_var() -> Result<(), Box<EvalAltResult>> {
assert!(engine.compile("let x = if y { z } else { w };").is_err());
#[cfg(not(feature = "no_object"))]
engine.compile_with_scope(&mut scope, "if x.abs() { y } else { x + y.len };")?;
engine.compile_with_scope(&scope, "if x.abs() { y } else { x + y.len };")?;
engine.compile("let y = 42; let x = y;")?;

View File

@ -127,6 +127,7 @@ fn test_serde_ser_unit_enum() -> Result<(), Box<EvalAltResult>> {
#[test]
#[cfg(not(feature = "no_object"))]
fn test_serde_ser_externally_tagged_enum() -> Result<(), Box<EvalAltResult>> {
#[allow(clippy::enum_variant_names)]
#[derive(Serialize)]
enum MyEnum {
VariantUnit,
@ -227,6 +228,7 @@ fn test_serde_ser_internally_tagged_enum() -> Result<(), Box<EvalAltResult>> {
#[test]
#[cfg(not(feature = "no_object"))]
fn test_serde_ser_adjacently_tagged_enum() -> Result<(), Box<EvalAltResult>> {
#[allow(clippy::enum_variant_names)]
#[derive(Serialize)]
#[serde(tag = "tag", content = "content")]
enum MyEnum {
@ -355,8 +357,8 @@ fn test_serde_ser_untagged_enum() -> Result<(), Box<EvalAltResult>> {
fn test_serde_de_primary_types() -> Result<(), Box<EvalAltResult>> {
assert_eq!(42, from_dynamic::<u16>(&Dynamic::from(42_u16))?);
assert_eq!(42, from_dynamic::<INT>(&(42 as INT).into())?);
assert_eq!(true, from_dynamic::<bool>(&true.into())?);
assert_eq!((), from_dynamic::<()>(&().into())?);
assert!(from_dynamic::<bool>(&true.into())?);
let _: () = from_dynamic::<()>(&().into()).unwrap();
#[cfg(not(feature = "no_float"))]
{
@ -447,12 +449,14 @@ fn test_serde_de_struct() -> Result<(), Box<EvalAltResult>> {
#[cfg(not(feature = "no_object"))]
#[cfg(not(feature = "no_float"))]
fn test_serde_de_script() -> Result<(), Box<EvalAltResult>> {
#[allow(dead_code)]
#[derive(Debug, Deserialize)]
struct Point {
x: FLOAT,
y: FLOAT,
}
#[allow(dead_code)]
#[derive(Debug, Deserialize)]
struct MyStruct {
a: i64,
@ -500,6 +504,7 @@ fn test_serde_de_unit_enum() -> Result<(), Box<EvalAltResult>> {
#[test]
#[cfg(not(feature = "no_object"))]
fn test_serde_de_externally_tagged_enum() -> Result<(), Box<EvalAltResult>> {
#[allow(clippy::enum_variant_names)]
#[derive(Debug, PartialEq, Deserialize)]
#[serde(deny_unknown_fields)]
enum MyEnum {
@ -598,6 +603,7 @@ fn test_serde_de_internally_tagged_enum() -> Result<(), Box<EvalAltResult>> {
#[test]
#[cfg(not(feature = "no_object"))]
fn test_serde_de_adjacently_tagged_enum() -> Result<(), Box<EvalAltResult>> {
#[allow(clippy::enum_variant_names)]
#[derive(Debug, PartialEq, Deserialize)]
#[serde(tag = "tag", content = "content", deny_unknown_fields)]
enum MyEnum {
@ -814,7 +820,7 @@ fn test_serde_optional() -> Result<(), Box<EvalAltResult>> {
let map = r.cast::<Map>();
assert_eq!(map.len(), 1);
assert_eq!(map.get("foo").unwrap().as_unit().unwrap(), ());
let _: () = map.get("foo").unwrap().as_unit().unwrap();
Ok(())
}
@ -882,7 +888,7 @@ fn test_serde_scope() {
assert_eq!(scope.len(), 3);
assert_eq!(scope.get_value::<INT>("x").unwrap(), 42);
assert_eq!(scope.get_value::<bool>("y").unwrap(), true);
assert!(scope.get_value::<bool>("y").unwrap());
assert_eq!(
scope.get_value::<String>("z").unwrap(),
"serde::test_serde_scope::TestStruct"

View File

@ -19,6 +19,7 @@ impl Command {
}
}
#[allow(clippy::upper_case_acronyms)]
type API = Arc<Mutex<Command>>;
#[cfg(not(feature = "no_object"))]

View File

@ -10,10 +10,9 @@ fn test_switch() -> Result<(), Box<EvalAltResult>> {
engine.eval::<char>("switch 2 { 1 => (), 2 => 'a', 42 => true }")?,
'a'
);
assert_eq!(
engine.run("switch 3 { 1 => (), 2 => 'a', 42 => true }")?,
()
);
engine
.run("switch 3 { 1 => (), 2 => 'a', 42 => true }")
.unwrap();
assert_eq!(
engine.eval::<INT>("switch 3 { 1 => (), 2 => 'a', 42 => true, _ => 123 }")?,
123
@ -32,18 +31,16 @@ fn test_switch() -> Result<(), Box<EvalAltResult>> {
)?,
'a'
);
assert_eq!(
engine.eval_with_scope::<bool>(&mut scope, "switch x { 1 => (), 2 => 'a', 42 => true }")?,
true
);
assert_eq!(
engine.eval_with_scope::<bool>(&mut scope, "switch x { 1 => (), 2 => 'a', _ => true }")?,
true
);
assert_eq!(
engine.eval_with_scope::<()>(&mut scope, "switch x { 1 => 123, 2 => 'a' }")?,
()
);
assert!(engine
.eval_with_scope::<bool>(&mut scope, "switch x { 1 => (), 2 => 'a', 42 => true }")
.unwrap());
assert!(engine
.eval_with_scope::<bool>(&mut scope, "switch x { 1 => (), 2 => 'a', _ => true }")
.unwrap());
let _: () = engine
.eval_with_scope::<()>(&mut scope, "switch x { 1 => 123, 2 => 'a' }")
.unwrap();
assert_eq!(
engine.eval_with_scope::<INT>(
&mut scope,

View File

@ -2,6 +2,7 @@ use rhai::{Engine, EvalAltResult, INT};
#[test]
fn test_type_of() -> Result<(), Box<EvalAltResult>> {
#[allow(dead_code)]
#[derive(Clone)]
struct TestStruct {
x: INT,

View File

@ -10,13 +10,15 @@ fn test_unit() -> Result<(), Box<EvalAltResult>> {
#[test]
fn test_unit_eq() -> Result<(), Box<EvalAltResult>> {
let engine = Engine::new();
assert_eq!(engine.eval::<bool>("let x = (); let y = (); x == y")?, true);
assert!(engine
.eval::<bool>("let x = (); let y = (); x == y")
.unwrap());
Ok(())
}
#[test]
fn test_unit_with_spaces() -> Result<(), Box<EvalAltResult>> {
let engine = Engine::new();
engine.run("let x = ( ); x").expect_err("should error");
let _ = engine.run("let x = ( ); x").expect_err("should error");
Ok(())
}

View File

@ -167,6 +167,7 @@ fn test_var_resolver() -> Result<(), Box<EvalAltResult>> {
#[cfg(not(feature = "no_closure"))]
let shared = base.clone();
#[allow(deprecated)] // not deprecated but unstable
engine.on_var(move |name, _, context| {
match name {
"MYSTIC_NUMBER" => Ok(Some((42 as INT).into())),
@ -222,6 +223,7 @@ fn test_var_def_filter() -> Result<(), Box<EvalAltResult>> {
let ast = engine.compile("let x = 42;")?;
engine.run_ast(&ast)?;
#[allow(deprecated)] // not deprecated but unstable
engine.on_def_var(|_, info, _| match (info.name, info.nesting_level) {
("x", 0 | 1) => Ok(false),
_ => Ok(true),