Reformat code.

This commit is contained in:
Stephen Chung 2020-07-04 22:53:00 +08:00
parent 23f21c7808
commit 368b4a480b
11 changed files with 156 additions and 200 deletions

View File

@ -26,7 +26,7 @@ Features
* Freely pass Rust variables/constants into a script via an external [`Scope`](https://schungx.github.io/rhai/rust/scope.html).
* Easily [call a script-defined function](https://schungx.github.io/rhai/engine/call-fn.html) from Rust.
* Fairly low compile-time overhead.
* Fairly efficient evaluation (1 million iterations in 0.4 sec on a single core, 2.3 GHz Linux VM).
* Fairly efficient evaluation (1 million iterations in 0.3 sec on a single core, 2.3 GHz Linux VM).
* Relatively little `unsafe` code (yes there are some for performance reasons, and most `unsafe` code is limited to
one single source file, all with names starting with `"unsafe_"`).
* Re-entrant scripting engine can be made `Send + Sync` (via the `sync` feature).

View File

@ -22,7 +22,7 @@ Fast
* Fairly low compile-time overhead.
* Fairly efficient evaluation (1 million iterations in 0.4 sec on a single core, 2.3 GHz Linux VM).
* Fairly efficient evaluation (1 million iterations in 0.3 sec on a single core, 2.3 GHz Linux VM).
* Scripts are [optimized][script optimization] (useful for template-based machine-generated scripts) for repeated evaluations.

View File

@ -346,11 +346,9 @@ impl Dynamic {
}
#[cfg(not(feature = "no_float"))]
{
if let Some(result) = <dyn Any>::downcast_ref::<FLOAT>(&value) {
return result.clone().into();
}
}
let mut boxed = Box::new(value);

View File

@ -353,18 +353,15 @@ pub fn make_getter(id: &str) -> String {
/// Extract the property name from a getter function name.
fn extract_prop_from_getter(fn_name: &str) -> Option<&str> {
#[cfg(not(feature = "no_object"))]
{
if fn_name.starts_with(FN_GET) {
Some(&fn_name[FN_GET.len()..])
} else {
None
}
}
#[cfg(feature = "no_object")]
{
None
}
}
/// Make setter function
pub fn make_setter(id: &str) -> String {
@ -374,18 +371,15 @@ pub fn make_setter(id: &str) -> String {
/// Extract the property name from a setter function name.
fn extract_prop_from_setter(fn_name: &str) -> Option<&str> {
#[cfg(not(feature = "no_object"))]
{
if fn_name.starts_with(FN_SET) {
Some(&fn_name[FN_SET.len()..])
} else {
None
}
}
#[cfg(feature = "no_object")]
{
None
}
}
/// Print/debug to stdout
fn default_print(s: &str) {
@ -701,13 +695,11 @@ impl Engine {
// Check for stack overflow
#[cfg(not(feature = "no_function"))]
#[cfg(not(feature = "unchecked"))]
{
if level > self.max_call_stack_depth {
return Err(Box::new(
EvalAltResult::ErrorStackOverflow(Position::none()),
));
}
}
let mut this_copy: Dynamic = Default::default();
let mut old_this_ptr: Option<&mut Dynamic> = None;
@ -2344,7 +2336,6 @@ impl Engine {
.try_cast::<ImmutableString>()
{
#[cfg(not(feature = "no_module"))]
{
if let Some(resolver) = &self.module_resolver {
let mut module = resolver.resolve(self, &path, expr.position())?;
module.index_all_sub_modules();
@ -2359,7 +2350,6 @@ impl Engine {
expr.position(),
)))
}
}
#[cfg(feature = "no_module")]
Ok(Default::default())
@ -2509,14 +2499,12 @@ impl Engine {
state.operations += 1;
#[cfg(not(feature = "unchecked"))]
{
// Guard against too many operations
if self.max_operations > 0 && state.operations > self.max_operations {
return Err(Box::new(EvalAltResult::ErrorTooManyOperations(
Position::none(),
)));
}
}
// Report progress - only in steps
if let Some(progress) = &self.progress {
@ -2641,7 +2629,6 @@ fn run_builtin_binary_op(
}
#[cfg(not(feature = "no_float"))]
{
if args_type == TypeId::of::<FLOAT>() {
let x = *x.downcast_ref::<FLOAT>().unwrap();
let y = *y.downcast_ref::<FLOAT>().unwrap();
@ -2662,7 +2649,6 @@ fn run_builtin_binary_op(
_ => (),
}
}
}
Ok(None)
}
@ -2737,7 +2723,6 @@ fn run_builtin_op_assignment(
}
#[cfg(not(feature = "no_float"))]
{
if args_type == TypeId::of::<FLOAT>() {
let x = x.downcast_mut::<FLOAT>().unwrap();
let y = *y.downcast_ref::<FLOAT>().unwrap();
@ -2752,7 +2737,6 @@ fn run_builtin_op_assignment(
_ => (),
}
}
}
Ok(None)
}

View File

@ -27,13 +27,9 @@ pub type Shared<T> = Arc<T>;
/// If the resource is shared (i.e. has other outstanding references), a cloned copy is used.
pub fn shared_make_mut<T: Clone>(value: &mut Shared<T>) -> &mut T {
#[cfg(not(feature = "sync"))]
{
Rc::make_mut(value)
}
return Rc::make_mut(value);
#[cfg(feature = "sync")]
{
Arc::make_mut(value)
}
return Arc::make_mut(value);
}
/// Consume a `Shared` resource, assuming that it is unique (i.e. not shared).
@ -43,13 +39,9 @@ pub fn shared_make_mut<T: Clone>(value: &mut Shared<T>) -> &mut T {
/// Panics if the resource is shared (i.e. has other outstanding references).
pub fn shared_take<T: Clone>(value: Shared<T>) -> T {
#[cfg(not(feature = "sync"))]
{
Rc::try_unwrap(value).map_err(|_| ()).unwrap()
}
return Rc::try_unwrap(value).map_err(|_| ()).unwrap();
#[cfg(feature = "sync")]
{
Arc::try_unwrap(value).map_err(|_| ()).unwrap()
}
return Arc::try_unwrap(value).map_err(|_| ()).unwrap();
}
pub type FnCallArgs<'a> = [&'a mut Dynamic];

View File

@ -190,7 +190,6 @@ fn modulo_u<T: Rem>(x: T, y: T) -> FuncReturn<<T as Rem>::Output> {
// Checked power
pub(crate) fn pow_i_i(x: INT, y: INT) -> FuncReturn<INT> {
#[cfg(not(feature = "only_i32"))]
{
if y > (u32::MAX as INT) {
Err(Box::new(EvalAltResult::ErrorArithmetic(
format!("Integer raised to too large an index: {} ~ {}", x, y),
@ -209,10 +208,8 @@ pub(crate) fn pow_i_i(x: INT, y: INT) -> FuncReturn<INT> {
))
})
}
}
#[cfg(feature = "only_i32")]
{
if y < 0 {
Err(Box::new(EvalAltResult::ErrorArithmetic(
format!("Integer raised to a negative index: {} ~ {}", x, y),
@ -227,7 +224,6 @@ pub(crate) fn pow_i_i(x: INT, y: INT) -> FuncReturn<INT> {
})
}
}
}
// Unchecked integer power - may panic on overflow or if the power index is too high (> u32::MAX)
pub(crate) fn pow_i_i_u(x: INT, y: INT) -> FuncReturn<INT> {
Ok(x.pow(y as u32))

View File

@ -30,7 +30,6 @@ fn pad<T: Variant + Clone>(engine: &Engine, args: &mut [&mut Dynamic]) -> FuncRe
// Check if array will be over max size limit
#[cfg(not(feature = "unchecked"))]
{
if engine.max_array_size > 0 && len > 0 && (len as usize) > engine.max_array_size {
return Err(Box::new(EvalAltResult::ErrorDataTooLarge(
"Size of array".to_string(),
@ -39,7 +38,6 @@ fn pad<T: Variant + Clone>(engine: &Engine, args: &mut [&mut Dynamic]) -> FuncRe
Position::none(),
)));
}
}
if len > 0 {
let item = args[2].clone();

View File

@ -231,7 +231,6 @@ def_package!(crate:MoreStringPackage:"Additional string utilities, including str
// Check if string will be over max size limit
#[cfg(not(feature = "unchecked"))]
{
if engine.max_string_size > 0 && len > 0 && (len as usize) > engine.max_string_size {
return Err(Box::new(EvalAltResult::ErrorDataTooLarge(
"Length of string".to_string(),
@ -240,7 +239,6 @@ def_package!(crate:MoreStringPackage:"Additional string utilities, including str
Position::none(),
)));
}
}
if len > 0 {
let ch = *args[2].downcast_ref::< char>().unwrap();

View File

@ -33,7 +33,6 @@ def_package!(crate:BasicTimePackage:"Basic timing utilities.", lib, {
let seconds = (ts2 - ts1).as_secs();
#[cfg(not(feature = "unchecked"))]
{
if seconds > (MAX_INT as u64) {
return Err(Box::new(EvalAltResult::ErrorArithmetic(
format!(
@ -43,7 +42,7 @@ def_package!(crate:BasicTimePackage:"Basic timing utilities.", lib, {
Position::none(),
)));
}
}
return Ok(-(seconds as INT));
}
} else {
@ -55,14 +54,13 @@ def_package!(crate:BasicTimePackage:"Basic timing utilities.", lib, {
let seconds = (ts1 - ts2).as_secs();
#[cfg(not(feature = "unchecked"))]
{
if seconds > (MAX_INT as u64) {
return Err(Box::new(EvalAltResult::ErrorArithmetic(
format!("Integer overflow for timestamp duration: {}", seconds),
Position::none(),
)));
}
}
return Ok(seconds as INT);
}
}
@ -86,14 +84,13 @@ def_package!(crate:BasicTimePackage:"Basic timing utilities.", lib, {
let seconds = timestamp.elapsed().as_secs();
#[cfg(not(feature = "unchecked"))]
{
if seconds > (MAX_INT as u64) {
return Err(Box::new(EvalAltResult::ErrorArithmetic(
format!("Integer overflow for timestamp.elapsed: {}", seconds),
Position::none(),
)));
}
}
Ok(seconds as INT)
}

View File

@ -1495,13 +1495,9 @@ fn parse_unary(
.map(|i| Expr::IntegerConstant(Box::new((i, pos))))
.or_else(|| {
#[cfg(not(feature = "no_float"))]
{
Some(Expr::FloatConstant(Box::new((-(x.0 as FLOAT), pos))))
}
return Some(Expr::FloatConstant(Box::new((-(x.0 as FLOAT), pos))));
#[cfg(feature = "no_float")]
{
None
}
return None;
})
.ok_or_else(|| LexError::MalformedNumber(format!("-{}", x.0)).into_err(pos))
}
@ -2618,7 +2614,6 @@ impl Engine {
};
match input.peek().unwrap() {
#[cfg(not(feature = "no_function"))]
(Token::Fn, pos) => {
let mut state = ParseState::new(
self.max_function_expr_depth,

View File

@ -208,24 +208,24 @@ impl<'de> Deserializer<'de> for &mut DynamicDeserializer<'de> {
fn deserialize_f32<V: Visitor<'de>>(self, visitor: V) -> Result<V::Value, Box<EvalAltResult>> {
#[cfg(not(feature = "no_float"))]
{
self.value
return self
.value
.downcast_ref::<f32>()
.map_or_else(|| self.type_error(), |&x| visitor.visit_f32(x))
}
.map_or_else(|| self.type_error(), |&x| visitor.visit_f32(x));
#[cfg(feature = "no_float")]
self.type_error_str("f32")
return self.type_error_str("f32");
}
fn deserialize_f64<V: Visitor<'de>>(self, visitor: V) -> Result<V::Value, Box<EvalAltResult>> {
#[cfg(not(feature = "no_float"))]
{
self.value
return self
.value
.downcast_ref::<f64>()
.map_or_else(|| self.type_error(), |&x| visitor.visit_f64(x))
}
.map_or_else(|| self.type_error(), |&x| visitor.visit_f64(x));
#[cfg(feature = "no_float")]
self.type_error_str("f64")
return self.type_error_str("f64");
}
fn deserialize_char<V: Visitor<'de>>(self, visitor: V) -> Result<V::Value, Box<EvalAltResult>> {
@ -284,14 +284,13 @@ impl<'de> Deserializer<'de> for &mut DynamicDeserializer<'de> {
fn deserialize_seq<V: Visitor<'de>>(self, visitor: V) -> Result<V::Value, Box<EvalAltResult>> {
#[cfg(not(feature = "no_index"))]
{
self.value.downcast_ref::<Array>().map_or_else(
return self.value.downcast_ref::<Array>().map_or_else(
|| self.type_error(),
|arr| visitor.visit_seq(IterateArray::new(arr.iter())),
)
}
);
#[cfg(feature = "no_index")]
self.type_error()
return self.type_error();
}
fn deserialize_tuple<V: Visitor<'de>>(
@ -313,14 +312,13 @@ impl<'de> Deserializer<'de> for &mut DynamicDeserializer<'de> {
fn deserialize_map<V: Visitor<'de>>(self, visitor: V) -> Result<V::Value, Box<EvalAltResult>> {
#[cfg(not(feature = "no_object"))]
{
self.value.downcast_ref::<Map>().map_or_else(
return self.value.downcast_ref::<Map>().map_or_else(
|| self.type_error(),
|map| visitor.visit_map(IterateMap::new(map.keys(), map.values())),
)
}
);
#[cfg(feature = "no_object")]
self.type_error()
return self.type_error();
}
fn deserialize_struct<V: Visitor<'de>>(