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

View File

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

View File

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

View File

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

View File

@ -80,7 +80,7 @@ pub fn main() {
// Compile the handler script. // Compile the handler script.
println!("> Loading script file: {path}"); 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, Ok(ast) => ast,
Err(err) => { Err(err) => {
eprintln!("! Error: {err}"); eprintln!("! Error: {err}");

View File

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

View File

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

View File

@ -97,7 +97,7 @@ impl Engine {
/// ///
/// // Compile a script to an AST and store it for later evaluation. /// // 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. /// // 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)?; /// let result = engine.eval_ast::<i64>(&ast)?;
/// # } /// # }

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@ -155,7 +155,9 @@ mod time_functions {
}) })
} }
} else { } 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 { } 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. /// Test if the given character is a numeric digit.
#[inline(always)] #[inline(always)]
const fn is_numeric_digit(c: char) -> bool { 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. /// Test if the comment block is a doc-comment.

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@ -111,7 +111,7 @@ b`: 1}; y["a\nb"]
fn test_map_prop() -> Result<(), Box<EvalAltResult>> { fn test_map_prop() -> Result<(), Box<EvalAltResult>> {
let mut engine = Engine::new(); 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); 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"#)?; 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["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"); assert_eq!(x["c$"].clone_cast::<String>(), "hello");
Ok(()) Ok(())
@ -195,7 +195,7 @@ fn test_map_return() -> Result<(), Box<EvalAltResult>> {
let x = engine.eval::<Map>(r#"#{a: 1, b: true, "c$": "hello"}"#)?; let x = engine.eval::<Map>(r#"#{a: 1, b: true, "c$": "hello"}"#)?;
assert_eq!(x["a"].as_int().unwrap(), 1); 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"); assert_eq!(x["c$"].clone_cast::<String>(), "hello");
Ok(()) Ok(())
@ -240,10 +240,10 @@ fn test_map_json() -> Result<(), Box<EvalAltResult>> {
assert!(!map.contains_key("x")); assert!(!map.contains_key("x"));
assert_eq!(map["a"].as_int().unwrap(), 1); 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["c"].as_int().unwrap(), 42);
assert_eq!(map["$d e f!"].clone_cast::<String>(), "hello"); 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"))] #[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.set_optimization_level(rhai::OptimizationLevel::Full);
engine engine
.register_fn("new_ts", || TestStruct::new()) .register_fn("new_ts", TestStruct::new)
.register_fn("ymd", |_: INT, _: INT, _: INT| 42 as INT) .register_fn("ymd", |_: INT, _: INT, _: INT| 42 as INT)
.register_fn("range", |_: &mut TestStruct, _: INT, _: INT| { .register_fn("range", |_: &mut TestStruct, _: INT, _: INT| {
TestStruct::new() TestStruct::new()

View File

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

View File

@ -1,9 +1,12 @@
#![cfg(not(feature = "no_module"))] #![cfg(not(feature = "no_module"))]
use rhai::{ use rhai::{
module_resolvers::{DummyModuleResolver, StaticModuleResolver}, module_resolvers::{DummyModuleResolver, StaticModuleResolver},
Dynamic, Engine, EvalAltResult, FnNamespace, FnPtr, ImmutableString, Module, NativeCallContext, Dynamic, Engine, EvalAltResult, FnNamespace, ImmutableString, Module, ParseError,
ParseError, ParseErrorType, Scope, INT, ParseErrorType, Scope, INT,
}; };
//
#[cfg(all(not(feature = "no_function"), feature = "internals"))]
use rhai::{FnPtr, NativeCallContext};
#[test] #[test]
fn test_module() { fn test_module() {
@ -248,7 +251,7 @@ fn test_module_resolver() -> Result<(), Box<EvalAltResult>> {
"# "#
) )
.expect_err("should error"), .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); engine.set_max_modules(1000);
@ -276,9 +279,9 @@ fn test_module_resolver() -> Result<(), Box<EvalAltResult>> {
} }
foo(1) + { import "hello" as h; h::answer } 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()); engine.set_module_resolver(DummyModuleResolver::new());
@ -534,8 +537,7 @@ fn test_module_ast_namespace2() -> Result<(), Box<EvalAltResult>> {
Ok(()) Ok(())
} }
#[cfg(not(feature = "no_function"))] #[cfg(all(not(feature = "no_function"), feature = "internals"))]
#[cfg(feature = "internals")]
#[test] #[test]
fn test_module_context() -> Result<(), Box<EvalAltResult>> { fn test_module_context() -> Result<(), Box<EvalAltResult>> {
let script = "fn bar() { calc(|x| x + 1) }"; let script = "fn bar() { calc(|x| x + 1) }";

View File

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

View File

@ -4,15 +4,14 @@ use rhai::{Engine, EvalAltResult};
fn test_not() -> Result<(), Box<EvalAltResult>> { fn test_not() -> Result<(), Box<EvalAltResult>> {
let engine = Engine::new(); let engine = Engine::new();
assert_eq!( assert!(!engine
engine.eval::<bool>("let not_true = !true; not_true")?, .eval::<bool>("let not_true = !true; not_true")
false .unwrap());
);
#[cfg(not(feature = "no_function"))] #[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(()) 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()); assert!(engine.compile("let x = if y { z } else { w };").is_err());
#[cfg(not(feature = "no_object"))] #[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;")?; engine.compile("let y = 42; let x = y;")?;

View File

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

View File

@ -19,6 +19,7 @@ impl Command {
} }
} }
#[allow(clippy::upper_case_acronyms)]
type API = Arc<Mutex<Command>>; type API = Arc<Mutex<Command>>;
#[cfg(not(feature = "no_object"))] #[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 }")?, engine.eval::<char>("switch 2 { 1 => (), 2 => 'a', 42 => true }")?,
'a' 'a'
); );
assert_eq!( engine
engine.run("switch 3 { 1 => (), 2 => 'a', 42 => true }")?, .run("switch 3 { 1 => (), 2 => 'a', 42 => true }")
() .unwrap();
);
assert_eq!( assert_eq!(
engine.eval::<INT>("switch 3 { 1 => (), 2 => 'a', 42 => true, _ => 123 }")?, engine.eval::<INT>("switch 3 { 1 => (), 2 => 'a', 42 => true, _ => 123 }")?,
123 123
@ -32,18 +31,16 @@ fn test_switch() -> Result<(), Box<EvalAltResult>> {
)?, )?,
'a' 'a'
); );
assert_eq!( assert!(engine
engine.eval_with_scope::<bool>(&mut scope, "switch x { 1 => (), 2 => 'a', 42 => true }")?, .eval_with_scope::<bool>(&mut scope, "switch x { 1 => (), 2 => 'a', 42 => true }")
true .unwrap());
); assert!(engine
assert_eq!( .eval_with_scope::<bool>(&mut scope, "switch x { 1 => (), 2 => 'a', _ => true }")
engine.eval_with_scope::<bool>(&mut scope, "switch x { 1 => (), 2 => 'a', _ => true }")?, .unwrap());
true let _: () = engine
); .eval_with_scope::<()>(&mut scope, "switch x { 1 => 123, 2 => 'a' }")
assert_eq!( .unwrap();
engine.eval_with_scope::<()>(&mut scope, "switch x { 1 => 123, 2 => 'a' }")?,
()
);
assert_eq!( assert_eq!(
engine.eval_with_scope::<INT>( engine.eval_with_scope::<INT>(
&mut scope, &mut scope,

View File

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

View File

@ -10,13 +10,15 @@ fn test_unit() -> Result<(), Box<EvalAltResult>> {
#[test] #[test]
fn test_unit_eq() -> Result<(), Box<EvalAltResult>> { fn test_unit_eq() -> Result<(), Box<EvalAltResult>> {
let engine = Engine::new(); 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(()) Ok(())
} }
#[test] #[test]
fn test_unit_with_spaces() -> Result<(), Box<EvalAltResult>> { fn test_unit_with_spaces() -> Result<(), Box<EvalAltResult>> {
let engine = Engine::new(); let engine = Engine::new();
engine.run("let x = ( ); x").expect_err("should error"); let _ = engine.run("let x = ( ); x").expect_err("should error");
Ok(()) Ok(())
} }

View File

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