Minor refactor.

This commit is contained in:
Stephen Chung 2022-01-03 23:16:47 +08:00
parent d60f14ec27
commit 1d1e473ac4
8 changed files with 34 additions and 47 deletions

View File

@ -124,10 +124,9 @@ impl AST {
#[inline(always)] #[inline(always)]
#[must_use] #[must_use]
pub fn source(&self) -> Option<&str> { pub fn source(&self) -> Option<&str> {
if self.source.is_empty() { match self.source.as_str() {
None "" => None,
} else { s => Some(s),
Some(&self.source)
} }
} }
/// Get a reference to the source. /// Get a reference to the source.

View File

@ -890,10 +890,9 @@ impl<'x, 'px, 'pt> EvalContext<'_, 'x, 'px, '_, '_, '_, '_, 'pt> {
#[inline(always)] #[inline(always)]
#[must_use] #[must_use]
pub fn source(&self) -> Option<&str> { pub fn source(&self) -> Option<&str> {
if self.global.source.is_empty() { match self.global.source.as_str() {
None "" => None,
} else { s => Some(s),
Some(&self.global.source)
} }
} }
/// The current [`Scope`]. /// The current [`Scope`].
@ -3241,10 +3240,9 @@ impl Engine {
{ {
use crate::ModuleResolver; use crate::ModuleResolver;
let source = if global.source.is_empty() { let source = match global.source.as_str() {
None "" => None,
} else { s => Some(s),
Some(global.source.as_str())
}; };
let path_pos = expr.position(); let path_pos = expr.position();

View File

@ -155,7 +155,7 @@ impl Engine {
) -> String { ) -> String {
format!( format!(
"{}{}{} ({})", "{}{}{} ({})",
namespace.map_or(String::new(), |ns| ns.to_string()), namespace.map_or_else(|| String::new(), |ns| ns.to_string()),
if namespace.is_some() { if namespace.is_some() {
Token::DoubleColon.literal_syntax() Token::DoubleColon.literal_syntax()
} else { } else {
@ -372,14 +372,9 @@ impl Engine {
} }
// Run external function // Run external function
let source = if source.is_empty() { let source = match (source.as_str(), parent_source.as_str()) {
if parent_source.is_empty() { ("", "") => None,
None ("", s) | (s, _) => Some(s),
} else {
Some(parent_source.as_str())
}
} else {
Some(source.as_str())
}; };
let context = (self, name, source, &*global, lib, pos).into(); let context = (self, name, source, &*global, lib, pos).into();
@ -424,10 +419,9 @@ impl Engine {
pos, pos,
) )
})?; })?;
let source = if global.source.is_empty() { let source = match global.source.as_str() {
None "" => None,
} else { s => Some(s),
Some(global.source.as_str())
}; };
(debug(&text, source, pos).into(), false) (debug(&text, source, pos).into(), false)
} else { } else {

View File

@ -50,7 +50,7 @@ impl fmt::Display for CallableFunction {
Self::Plugin(_) => write!(f, "PluginFunction"), Self::Plugin(_) => write!(f, "PluginFunction"),
#[cfg(not(feature = "no_function"))] #[cfg(not(feature = "no_function"))]
CallableFunction::Script(s) => fmt::Display::fmt(s, f), Self::Script(s) => fmt::Display::fmt(s, f),
} }
} }
} }

View File

@ -9,7 +9,7 @@ use std::prelude::v1::*;
#[cfg(not(feature = "no_float"))] #[cfg(not(feature = "no_float"))]
use num_traits::Float; use num_traits::Float;
#[inline(never)] #[inline]
pub fn make_err(msg: impl Into<String>) -> RhaiError { pub fn make_err(msg: impl Into<String>) -> RhaiError {
ERR::ErrorArithmetic(msg.into(), Position::NONE).into() ERR::ErrorArithmetic(msg.into(), Position::NONE).into()
} }

View File

@ -44,7 +44,7 @@ fn collect_fn_metadata(ctx: NativeCallContext) -> crate::Array {
fn make_metadata( fn make_metadata(
dict: &BTreeSet<Identifier>, dict: &BTreeSet<Identifier>,
namespace: Option<Identifier>, namespace: Option<Identifier>,
f: &ScriptFnDef, func: &ScriptFnDef,
) -> Map { ) -> Map {
const DICT: &str = "key exists"; const DICT: &str = "key exists";
@ -53,10 +53,13 @@ fn collect_fn_metadata(ctx: NativeCallContext) -> crate::Array {
if let Some(ns) = namespace { if let Some(ns) = namespace {
map.insert(dict.get("namespace").expect(DICT).clone(), ns.into()); map.insert(dict.get("namespace").expect(DICT).clone(), ns.into());
} }
map.insert(dict.get("name").expect(DICT).clone(), f.name.clone().into()); map.insert(
dict.get("name").expect(DICT).clone(),
func.name.clone().into(),
);
map.insert( map.insert(
dict.get("access").expect(DICT).clone(), dict.get("access").expect(DICT).clone(),
match f.access { match func.access {
FnAccess::Public => dict.get("public").expect(DICT).clone(), FnAccess::Public => dict.get("public").expect(DICT).clone(),
FnAccess::Private => dict.get("private").expect(DICT).clone(), FnAccess::Private => dict.get("private").expect(DICT).clone(),
} }
@ -64,11 +67,11 @@ fn collect_fn_metadata(ctx: NativeCallContext) -> crate::Array {
); );
map.insert( map.insert(
dict.get("is_anonymous").expect(DICT).clone(), dict.get("is_anonymous").expect(DICT).clone(),
f.name.starts_with(crate::engine::FN_ANONYMOUS).into(), func.name.starts_with(crate::engine::FN_ANONYMOUS).into(),
); );
map.insert( map.insert(
dict.get("params").expect(DICT).clone(), dict.get("params").expect(DICT).clone(),
f.params func.params
.iter() .iter()
.cloned() .cloned()
.map(Into::into) .map(Into::into)

View File

@ -18,13 +18,6 @@ use rust_decimal::Decimal;
#[cfg(feature = "decimal")] #[cfg(feature = "decimal")]
use super::arithmetic::make_err; use super::arithmetic::make_err;
#[allow(dead_code)]
#[cfg(feature = "only_i32")]
pub const MAX_INT: INT = i32::MAX;
#[allow(dead_code)]
#[cfg(not(feature = "only_i32"))]
pub const MAX_INT: INT = i64::MAX;
macro_rules! gen_conversion_as_functions { macro_rules! gen_conversion_as_functions {
($root:ident => $func_name:ident ( $($arg_type:ident),+ ) -> $result_type:ty) => { ($root:ident => $func_name:ident ( $($arg_type:ident),+ ) -> $result_type:ty) => {
pub mod $root { $(pub mod $arg_type { pub mod $root { $(pub mod $arg_type {
@ -264,7 +257,7 @@ mod float_functions {
} }
#[rhai_fn(name = "to_int", return_raw)] #[rhai_fn(name = "to_int", return_raw)]
pub fn f32_to_int(x: f32) -> RhaiResultOf<INT> { pub fn f32_to_int(x: f32) -> RhaiResultOf<INT> {
if cfg!(not(feature = "unchecked")) && x > (MAX_INT as f32) { if cfg!(not(feature = "unchecked")) && x > (INT::MAX as f32) {
Err( Err(
ERR::ErrorArithmetic(format!("Integer overflow: to_int({})", x), Position::NONE) ERR::ErrorArithmetic(format!("Integer overflow: to_int({})", x), Position::NONE)
.into(), .into(),
@ -275,7 +268,7 @@ mod float_functions {
} }
#[rhai_fn(name = "to_int", return_raw)] #[rhai_fn(name = "to_int", return_raw)]
pub fn f64_to_int(x: f64) -> RhaiResultOf<INT> { pub fn f64_to_int(x: f64) -> RhaiResultOf<INT> {
if cfg!(not(feature = "unchecked")) && x > (MAX_INT as f64) { if cfg!(not(feature = "unchecked")) && x > (INT::MAX as f64) {
Err( Err(
ERR::ErrorArithmetic(format!("Integer overflow: to_int({})", x), Position::NONE) ERR::ErrorArithmetic(format!("Integer overflow: to_int({})", x), Position::NONE)
.into(), .into(),

View File

@ -1,6 +1,6 @@
#![cfg(not(feature = "no_std"))] #![cfg(not(feature = "no_std"))]
use super::{arithmetic::make_err as make_arithmetic_err, math_basic::MAX_INT}; use super::arithmetic::make_err as make_arithmetic_err;
use crate::plugin::*; use crate::plugin::*;
use crate::{def_package, Dynamic, EvalAltResult, RhaiResult, RhaiResultOf, INT}; use crate::{def_package, Dynamic, EvalAltResult, RhaiResult, RhaiResultOf, INT};
@ -42,7 +42,7 @@ mod time_functions {
{ {
let seconds = timestamp.elapsed().as_secs(); let seconds = timestamp.elapsed().as_secs();
if cfg!(not(feature = "unchecked")) && seconds > (MAX_INT as u64) { if cfg!(not(feature = "unchecked")) && seconds > (INT::MAX as u64) {
Err(make_arithmetic_err(format!( Err(make_arithmetic_err(format!(
"Integer overflow for timestamp.elapsed: {}", "Integer overflow for timestamp.elapsed: {}",
seconds seconds
@ -69,7 +69,7 @@ mod time_functions {
if timestamp2 > timestamp1 { if timestamp2 > timestamp1 {
let seconds = (timestamp2 - timestamp1).as_secs(); let seconds = (timestamp2 - timestamp1).as_secs();
if cfg!(not(feature = "unchecked")) && seconds > (MAX_INT as u64) { if cfg!(not(feature = "unchecked")) && seconds > (INT::MAX as u64) {
Err(make_arithmetic_err(format!( Err(make_arithmetic_err(format!(
"Integer overflow for timestamp duration: -{}", "Integer overflow for timestamp duration: -{}",
seconds seconds
@ -80,7 +80,7 @@ mod time_functions {
} else { } else {
let seconds = (timestamp1 - timestamp2).as_secs(); let seconds = (timestamp1 - timestamp2).as_secs();
if cfg!(not(feature = "unchecked")) && seconds > (MAX_INT as u64) { if cfg!(not(feature = "unchecked")) && seconds > (INT::MAX as u64) {
Err(make_arithmetic_err(format!( Err(make_arithmetic_err(format!(
"Integer overflow for timestamp duration: {}", "Integer overflow for timestamp duration: {}",
seconds seconds
@ -97,7 +97,7 @@ mod time_functions {
if seconds < 0.0 { if seconds < 0.0 {
subtract_impl(timestamp, -seconds) subtract_impl(timestamp, -seconds)
} else if cfg!(not(feature = "unchecked")) { } else if cfg!(not(feature = "unchecked")) {
if seconds > (MAX_INT as FLOAT) { if seconds > (INT::MAX as FLOAT) {
Err(make_arithmetic_err(format!( Err(make_arithmetic_err(format!(
"Integer overflow for timestamp add: {}", "Integer overflow for timestamp add: {}",
seconds seconds
@ -120,7 +120,7 @@ mod time_functions {
if seconds < 0.0 { if seconds < 0.0 {
add_impl(timestamp, -seconds) add_impl(timestamp, -seconds)
} else if cfg!(not(feature = "unchecked")) { } else if cfg!(not(feature = "unchecked")) {
if seconds > (MAX_INT as FLOAT) { if seconds > (INT::MAX as FLOAT) {
Err(make_arithmetic_err(format!( Err(make_arithmetic_err(format!(
"Integer overflow for timestamp add: {}", "Integer overflow for timestamp add: {}",
seconds seconds