Satisfy clippy.
This commit is contained in:
parent
b8485b1909
commit
df482d3574
@ -132,7 +132,7 @@ pub fn inner_item_attributes<T: ExportedParams>(
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn deny_cfg_attr(attrs: &Vec<syn::Attribute>) -> syn::Result<()> {
|
pub fn deny_cfg_attr(attrs: &[syn::Attribute]) -> syn::Result<()> {
|
||||||
if let Some(cfg_attr) = attrs
|
if let Some(cfg_attr) = attrs
|
||||||
.iter()
|
.iter()
|
||||||
.find(|a| a.path.get_ident().map(|i| *i == "cfg").unwrap_or(false))
|
.find(|a| a.path.get_ident().map(|i| *i == "cfg").unwrap_or(false))
|
||||||
|
@ -152,13 +152,13 @@ impl ExportedParams for ExportedFnParams {
|
|||||||
("get", None) | ("set", None) | ("name", None) => {
|
("get", None) | ("set", None) | ("name", None) => {
|
||||||
return Err(syn::Error::new(key.span(), "requires value"))
|
return Err(syn::Error::new(key.span(), "requires value"))
|
||||||
}
|
}
|
||||||
("name", Some(s)) if &s.value() == FN_IDX_GET => {
|
("name", Some(s)) if s.value() == FN_IDX_GET => {
|
||||||
return Err(syn::Error::new(
|
return Err(syn::Error::new(
|
||||||
item_span,
|
item_span,
|
||||||
"use attribute 'index_get' instead",
|
"use attribute 'index_get' instead",
|
||||||
))
|
))
|
||||||
}
|
}
|
||||||
("name", Some(s)) if &s.value() == FN_IDX_SET => {
|
("name", Some(s)) if s.value() == FN_IDX_SET => {
|
||||||
return Err(syn::Error::new(
|
return Err(syn::Error::new(
|
||||||
item_span,
|
item_span,
|
||||||
"use attribute 'index_set' instead",
|
"use attribute 'index_set' instead",
|
||||||
@ -268,7 +268,6 @@ impl ExportedParams for ExportedFnParams {
|
|||||||
special,
|
special,
|
||||||
namespace,
|
namespace,
|
||||||
span: Some(span),
|
span: Some(span),
|
||||||
..Default::default()
|
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@ -317,7 +316,7 @@ impl Parse for ExportedFn {
|
|||||||
let skip_slots = if pass_context { 1 } else { 0 };
|
let skip_slots = if pass_context { 1 } else { 0 };
|
||||||
|
|
||||||
// Determine whether function generates a special calling convention for a mutable receiver.
|
// Determine whether function generates a special calling convention for a mutable receiver.
|
||||||
let mut_receiver = match fn_all.sig.inputs.iter().skip(skip_slots).next() {
|
let mut_receiver = match fn_all.sig.inputs.iter().nth(skip_slots) {
|
||||||
Some(syn::FnArg::Receiver(syn::Receiver {
|
Some(syn::FnArg::Receiver(syn::Receiver {
|
||||||
reference: Some(_), ..
|
reference: Some(_), ..
|
||||||
})) => true,
|
})) => true,
|
||||||
@ -474,7 +473,7 @@ impl ExportedFn {
|
|||||||
literals
|
literals
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn exported_name<'n>(&'n self) -> Cow<'n, str> {
|
pub fn exported_name(&self) -> Cow<str> {
|
||||||
self.params
|
self.params
|
||||||
.name
|
.name
|
||||||
.last()
|
.last()
|
||||||
@ -629,7 +628,7 @@ impl ExportedFn {
|
|||||||
let return_span = self
|
let return_span = self
|
||||||
.return_type()
|
.return_type()
|
||||||
.map(|r| r.span())
|
.map(|r| r.span())
|
||||||
.unwrap_or_else(|| proc_macro2::Span::call_site());
|
.unwrap_or_else(proc_macro2::Span::call_site);
|
||||||
if self.params.return_raw.is_some() {
|
if self.params.return_raw.is_some() {
|
||||||
quote_spanned! { return_span =>
|
quote_spanned! { return_span =>
|
||||||
pub #dynamic_signature {
|
pub #dynamic_signature {
|
||||||
@ -691,7 +690,7 @@ impl ExportedFn {
|
|||||||
})
|
})
|
||||||
.unwrap(),
|
.unwrap(),
|
||||||
);
|
);
|
||||||
if !self.params().pure.is_some() {
|
if self.params().pure.is_none() {
|
||||||
let arg_lit_str =
|
let arg_lit_str =
|
||||||
syn::LitStr::new(&pat.to_token_stream().to_string(), pat.span());
|
syn::LitStr::new(&pat.to_token_stream().to_string(), pat.span());
|
||||||
unpack_statements.push(
|
unpack_statements.push(
|
||||||
@ -812,8 +811,8 @@ impl ExportedFn {
|
|||||||
let return_span = self
|
let return_span = self
|
||||||
.return_type()
|
.return_type()
|
||||||
.map(|r| r.span())
|
.map(|r| r.span())
|
||||||
.unwrap_or_else(|| proc_macro2::Span::call_site());
|
.unwrap_or_else(proc_macro2::Span::call_site);
|
||||||
let return_expr = if !self.params.return_raw.is_some() {
|
let return_expr = if self.params.return_raw.is_none() {
|
||||||
quote_spanned! { return_span =>
|
quote_spanned! { return_span =>
|
||||||
Ok(Dynamic::from(#sig_name(#(#unpack_exprs),*)))
|
Ok(Dynamic::from(#sig_name(#(#unpack_exprs),*)))
|
||||||
}
|
}
|
||||||
|
@ -91,7 +91,6 @@ impl ExportedParams for ExportedModParams {
|
|||||||
name,
|
name,
|
||||||
skip,
|
skip,
|
||||||
scope: scope.unwrap_or_default(),
|
scope: scope.unwrap_or_default(),
|
||||||
..Default::default()
|
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
@ -214,7 +214,7 @@ pub fn generate_body(
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn check_rename_collisions(fns: &Vec<ExportedFn>) -> Result<(), syn::Error> {
|
pub fn check_rename_collisions(fns: &[ExportedFn]) -> Result<(), syn::Error> {
|
||||||
fn make_key(name: impl ToString, item_fn: &ExportedFn) -> String {
|
fn make_key(name: impl ToString, item_fn: &ExportedFn) -> String {
|
||||||
item_fn
|
item_fn
|
||||||
.arg_list()
|
.arg_list()
|
||||||
|
24
src/ast.rs
24
src/ast.rs
@ -147,16 +147,16 @@ impl fmt::Display for ScriptFnMetadata<'_> {
|
|||||||
}
|
}
|
||||||
|
|
||||||
#[cfg(not(feature = "no_function"))]
|
#[cfg(not(feature = "no_function"))]
|
||||||
impl<'a> Into<ScriptFnMetadata<'a>> for &'a ScriptFnDef {
|
impl<'a> From<&'a ScriptFnDef> for ScriptFnMetadata<'a> {
|
||||||
#[inline]
|
#[inline]
|
||||||
fn into(self) -> ScriptFnMetadata<'a> {
|
fn from(value: &'a ScriptFnDef) -> Self {
|
||||||
ScriptFnMetadata {
|
Self {
|
||||||
#[cfg(not(feature = "no_function"))]
|
#[cfg(not(feature = "no_function"))]
|
||||||
#[cfg(feature = "metadata")]
|
#[cfg(feature = "metadata")]
|
||||||
comments: self.comments.iter().map(|s| s.as_str()).collect(),
|
comments: self.comments.iter().map(|s| s.as_str()).collect(),
|
||||||
access: self.access,
|
access: value.access,
|
||||||
name: &self.name,
|
name: &value.name,
|
||||||
params: self.params.iter().map(|s| s.as_str()).collect(),
|
params: value.params.iter().map(|s| s.as_str()).collect(),
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@ -710,7 +710,6 @@ impl AST {
|
|||||||
#[cfg(not(feature = "no_function"))]
|
#[cfg(not(feature = "no_function"))]
|
||||||
#[cfg(not(feature = "no_module"))]
|
#[cfg(not(feature = "no_module"))]
|
||||||
#[inline(always)]
|
#[inline(always)]
|
||||||
#[must_use]
|
|
||||||
pub(crate) fn iter_fn_def(&self) -> impl Iterator<Item = &ScriptFnDef> {
|
pub(crate) fn iter_fn_def(&self) -> impl Iterator<Item = &ScriptFnDef> {
|
||||||
self.functions
|
self.functions
|
||||||
.iter_script_fn()
|
.iter_script_fn()
|
||||||
@ -721,7 +720,6 @@ impl AST {
|
|||||||
/// Not available under `no_function`.
|
/// Not available under `no_function`.
|
||||||
#[cfg(not(feature = "no_function"))]
|
#[cfg(not(feature = "no_function"))]
|
||||||
#[inline(always)]
|
#[inline(always)]
|
||||||
#[must_use]
|
|
||||||
pub fn iter_functions<'a>(&'a self) -> impl Iterator<Item = ScriptFnMetadata> + 'a {
|
pub fn iter_functions<'a>(&'a self) -> impl Iterator<Item = ScriptFnMetadata> + 'a {
|
||||||
self.functions
|
self.functions
|
||||||
.iter_script_fn()
|
.iter_script_fn()
|
||||||
@ -1042,10 +1040,7 @@ impl Stmt {
|
|||||||
#[inline(always)]
|
#[inline(always)]
|
||||||
#[must_use]
|
#[must_use]
|
||||||
pub const fn is_noop(&self) -> bool {
|
pub const fn is_noop(&self) -> bool {
|
||||||
match self {
|
matches!(self, Self::Noop(_))
|
||||||
Self::Noop(_) => true,
|
|
||||||
_ => false,
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
/// Get the [position][Position] of this statement.
|
/// Get the [position][Position] of this statement.
|
||||||
#[must_use]
|
#[must_use]
|
||||||
@ -2037,10 +2032,7 @@ impl Expr {
|
|||||||
#[inline(always)]
|
#[inline(always)]
|
||||||
#[must_use]
|
#[must_use]
|
||||||
pub const fn is_unit(&self) -> bool {
|
pub const fn is_unit(&self) -> bool {
|
||||||
match self {
|
matches!(self, Self::Unit(_))
|
||||||
Self::Unit(_) => true,
|
|
||||||
_ => false,
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
/// Is the expression a constant?
|
/// Is the expression a constant?
|
||||||
#[inline]
|
#[inline]
|
||||||
|
@ -134,7 +134,6 @@ impl EvalContext<'_, '_, '_, '_, '_, '_, '_, '_> {
|
|||||||
///
|
///
|
||||||
/// This function is very low level. It evaluates an expression from an [`AST`][crate::AST].
|
/// This function is very low level. It evaluates an expression from an [`AST`][crate::AST].
|
||||||
#[inline(always)]
|
#[inline(always)]
|
||||||
#[must_use]
|
|
||||||
pub fn eval_expression_tree(&mut self, expr: &Expression) -> RhaiResult {
|
pub fn eval_expression_tree(&mut self, expr: &Expression) -> RhaiResult {
|
||||||
self.engine.eval_expr(
|
self.engine.eval_expr(
|
||||||
self.scope,
|
self.scope,
|
||||||
@ -179,15 +178,12 @@ impl Engine {
|
|||||||
/// Replacing one variable with another (i.e. adding a new variable and removing one variable at
|
/// Replacing one variable with another (i.e. adding a new variable and removing one variable at
|
||||||
/// the same time so that the total _size_ of the [`Scope`][crate::Scope] is unchanged) also
|
/// the same time so that the total _size_ of the [`Scope`][crate::Scope] is unchanged) also
|
||||||
/// does NOT count, so `false` should be passed.
|
/// does NOT count, so `false` should be passed.
|
||||||
#[must_use]
|
|
||||||
pub fn register_custom_syntax<S: AsRef<str> + Into<Identifier>>(
|
pub fn register_custom_syntax<S: AsRef<str> + Into<Identifier>>(
|
||||||
&mut self,
|
&mut self,
|
||||||
keywords: &[S],
|
keywords: &[S],
|
||||||
scope_may_be_changed: bool,
|
scope_may_be_changed: bool,
|
||||||
func: impl Fn(&mut EvalContext, &[Expression]) -> RhaiResult + SendSync + 'static,
|
func: impl Fn(&mut EvalContext, &[Expression]) -> RhaiResult + SendSync + 'static,
|
||||||
) -> Result<&mut Self, ParseError> {
|
) -> Result<&mut Self, ParseError> {
|
||||||
let keywords = keywords.as_ref();
|
|
||||||
|
|
||||||
let mut segments: StaticVec<ImmutableString> = Default::default();
|
let mut segments: StaticVec<ImmutableString> = Default::default();
|
||||||
|
|
||||||
for s in keywords {
|
for s in keywords {
|
||||||
@ -240,8 +236,7 @@ impl Engine {
|
|||||||
s
|
s
|
||||||
),
|
),
|
||||||
)
|
)
|
||||||
.into_err(Position::NONE)
|
.into_err(Position::NONE));
|
||||||
.into());
|
|
||||||
}
|
}
|
||||||
// Identifier in first position
|
// Identifier in first position
|
||||||
s if segments.is_empty() && is_valid_identifier(s.chars()) => {
|
s if segments.is_empty() && is_valid_identifier(s.chars()) => {
|
||||||
@ -264,8 +259,7 @@ impl Engine {
|
|||||||
s
|
s
|
||||||
),
|
),
|
||||||
)
|
)
|
||||||
.into_err(Position::NONE)
|
.into_err(Position::NONE));
|
||||||
.into());
|
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
|
@ -378,10 +378,7 @@ impl Dynamic {
|
|||||||
#[inline(always)]
|
#[inline(always)]
|
||||||
#[must_use]
|
#[must_use]
|
||||||
pub const fn is_variant(&self) -> bool {
|
pub const fn is_variant(&self) -> bool {
|
||||||
match self.0 {
|
matches!(self.0, Union::Variant(_, _, _))
|
||||||
Union::Variant(_, _, _) => true,
|
|
||||||
_ => false,
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
/// Is the value held by this [`Dynamic`] shared?
|
/// Is the value held by this [`Dynamic`] shared?
|
||||||
///
|
///
|
||||||
@ -390,13 +387,11 @@ impl Dynamic {
|
|||||||
#[inline(always)]
|
#[inline(always)]
|
||||||
#[must_use]
|
#[must_use]
|
||||||
pub const fn is_shared(&self) -> bool {
|
pub const fn is_shared(&self) -> bool {
|
||||||
#[cfg(not(feature = "no_closure"))]
|
|
||||||
match self.0 {
|
match self.0 {
|
||||||
Union::Shared(_, _, _) => return true,
|
#[cfg(not(feature = "no_closure"))]
|
||||||
_ => (),
|
Union::Shared(_, _, _) => true,
|
||||||
|
_ => false,
|
||||||
}
|
}
|
||||||
|
|
||||||
false
|
|
||||||
}
|
}
|
||||||
/// Is the value held by this [`Dynamic`] a particular type?
|
/// Is the value held by this [`Dynamic`] a particular type?
|
||||||
///
|
///
|
||||||
@ -1054,21 +1049,21 @@ impl Dynamic {
|
|||||||
let val = value.as_any();
|
let val = value.as_any();
|
||||||
|
|
||||||
if TypeId::of::<T>() == TypeId::of::<INT>() {
|
if TypeId::of::<T>() == TypeId::of::<INT>() {
|
||||||
return val.downcast_ref::<INT>().expect(CHECKED).clone().into();
|
return (*val.downcast_ref::<INT>().expect(CHECKED)).into();
|
||||||
}
|
}
|
||||||
#[cfg(not(feature = "no_float"))]
|
#[cfg(not(feature = "no_float"))]
|
||||||
if TypeId::of::<T>() == TypeId::of::<FLOAT>() {
|
if TypeId::of::<T>() == TypeId::of::<FLOAT>() {
|
||||||
return val.downcast_ref::<FLOAT>().expect(CHECKED).clone().into();
|
return (*val.downcast_ref::<FLOAT>().expect(CHECKED)).into();
|
||||||
}
|
}
|
||||||
#[cfg(feature = "decimal")]
|
#[cfg(feature = "decimal")]
|
||||||
if TypeId::of::<T>() == TypeId::of::<Decimal>() {
|
if TypeId::of::<T>() == TypeId::of::<Decimal>() {
|
||||||
return val.downcast_ref::<Decimal>().expect(CHECKED).clone().into();
|
return (*val.downcast_ref::<Decimal>().expect(CHECKED)).into();
|
||||||
}
|
}
|
||||||
if TypeId::of::<T>() == TypeId::of::<bool>() {
|
if TypeId::of::<T>() == TypeId::of::<bool>() {
|
||||||
return val.downcast_ref::<bool>().expect(CHECKED).clone().into();
|
return (*val.downcast_ref::<bool>().expect(CHECKED)).into();
|
||||||
}
|
}
|
||||||
if TypeId::of::<T>() == TypeId::of::<char>() {
|
if TypeId::of::<T>() == TypeId::of::<char>() {
|
||||||
return val.downcast_ref::<char>().expect(CHECKED).clone().into();
|
return (*val.downcast_ref::<char>().expect(CHECKED)).into();
|
||||||
}
|
}
|
||||||
if TypeId::of::<T>() == TypeId::of::<ImmutableString>() {
|
if TypeId::of::<T>() == TypeId::of::<ImmutableString>() {
|
||||||
return val
|
return val
|
||||||
@ -1733,7 +1728,6 @@ impl Dynamic {
|
|||||||
/// Cast the [`Dynamic`] as a unit `()` and return it.
|
/// Cast the [`Dynamic`] as a unit `()` and return it.
|
||||||
/// Returns the name of the actual type if the cast fails.
|
/// Returns the name of the actual type if the cast fails.
|
||||||
#[inline(always)]
|
#[inline(always)]
|
||||||
#[must_use]
|
|
||||||
pub fn as_unit(&self) -> Result<(), &'static str> {
|
pub fn as_unit(&self) -> Result<(), &'static str> {
|
||||||
match self.0 {
|
match self.0 {
|
||||||
Union::Unit(value, _, _) => Ok(value),
|
Union::Unit(value, _, _) => Ok(value),
|
||||||
@ -1745,7 +1739,6 @@ impl Dynamic {
|
|||||||
/// Cast the [`Dynamic`] as the system integer type [`INT`] and return it.
|
/// Cast the [`Dynamic`] as the system integer type [`INT`] and return it.
|
||||||
/// Returns the name of the actual type if the cast fails.
|
/// Returns the name of the actual type if the cast fails.
|
||||||
#[inline(always)]
|
#[inline(always)]
|
||||||
#[must_use]
|
|
||||||
pub fn as_int(&self) -> Result<INT, &'static str> {
|
pub fn as_int(&self) -> Result<INT, &'static str> {
|
||||||
match self.0 {
|
match self.0 {
|
||||||
Union::Int(n, _, _) => Ok(n),
|
Union::Int(n, _, _) => Ok(n),
|
||||||
@ -1760,7 +1753,6 @@ impl Dynamic {
|
|||||||
/// Not available under `no_float`.
|
/// Not available under `no_float`.
|
||||||
#[cfg(not(feature = "no_float"))]
|
#[cfg(not(feature = "no_float"))]
|
||||||
#[inline(always)]
|
#[inline(always)]
|
||||||
#[must_use]
|
|
||||||
pub fn as_float(&self) -> Result<FLOAT, &'static str> {
|
pub fn as_float(&self) -> Result<FLOAT, &'static str> {
|
||||||
match self.0 {
|
match self.0 {
|
||||||
Union::Float(n, _, _) => Ok(*n),
|
Union::Float(n, _, _) => Ok(*n),
|
||||||
@ -1775,7 +1767,6 @@ impl Dynamic {
|
|||||||
/// Exported under the `decimal` feature only.
|
/// Exported under the `decimal` feature only.
|
||||||
#[cfg(feature = "decimal")]
|
#[cfg(feature = "decimal")]
|
||||||
#[inline(always)]
|
#[inline(always)]
|
||||||
#[must_use]
|
|
||||||
pub fn as_decimal(&self) -> Result<Decimal, &'static str> {
|
pub fn as_decimal(&self) -> Result<Decimal, &'static str> {
|
||||||
match self.0 {
|
match self.0 {
|
||||||
Union::Decimal(ref n, _, _) => Ok(**n),
|
Union::Decimal(ref n, _, _) => Ok(**n),
|
||||||
@ -1787,7 +1778,6 @@ impl Dynamic {
|
|||||||
/// Cast the [`Dynamic`] as a [`bool`] and return it.
|
/// Cast the [`Dynamic`] as a [`bool`] and return it.
|
||||||
/// Returns the name of the actual type if the cast fails.
|
/// Returns the name of the actual type if the cast fails.
|
||||||
#[inline(always)]
|
#[inline(always)]
|
||||||
#[must_use]
|
|
||||||
pub fn as_bool(&self) -> Result<bool, &'static str> {
|
pub fn as_bool(&self) -> Result<bool, &'static str> {
|
||||||
match self.0 {
|
match self.0 {
|
||||||
Union::Bool(b, _, _) => Ok(b),
|
Union::Bool(b, _, _) => Ok(b),
|
||||||
@ -1799,7 +1789,6 @@ impl Dynamic {
|
|||||||
/// Cast the [`Dynamic`] as a [`char`] and return it.
|
/// Cast the [`Dynamic`] as a [`char`] and return it.
|
||||||
/// Returns the name of the actual type if the cast fails.
|
/// Returns the name of the actual type if the cast fails.
|
||||||
#[inline(always)]
|
#[inline(always)]
|
||||||
#[must_use]
|
|
||||||
pub fn as_char(&self) -> Result<char, &'static str> {
|
pub fn as_char(&self) -> Result<char, &'static str> {
|
||||||
match self.0 {
|
match self.0 {
|
||||||
Union::Char(n, _, _) => Ok(n),
|
Union::Char(n, _, _) => Ok(n),
|
||||||
@ -1815,7 +1804,6 @@ impl Dynamic {
|
|||||||
///
|
///
|
||||||
/// Panics if the value is shared.
|
/// Panics if the value is shared.
|
||||||
#[inline(always)]
|
#[inline(always)]
|
||||||
#[must_use]
|
|
||||||
pub(crate) fn as_str_ref(&self) -> Result<&str, &'static str> {
|
pub(crate) fn as_str_ref(&self) -> Result<&str, &'static str> {
|
||||||
match self.0 {
|
match self.0 {
|
||||||
Union::Str(ref s, _, _) => Ok(s),
|
Union::Str(ref s, _, _) => Ok(s),
|
||||||
@ -1828,14 +1816,12 @@ impl Dynamic {
|
|||||||
/// If there are other references to the same string, a cloned copy is returned.
|
/// If there are other references to the same string, a cloned copy is returned.
|
||||||
/// Returns the name of the actual type if the cast fails.
|
/// Returns the name of the actual type if the cast fails.
|
||||||
#[inline(always)]
|
#[inline(always)]
|
||||||
#[must_use]
|
|
||||||
pub fn as_string(self) -> Result<String, &'static str> {
|
pub fn as_string(self) -> Result<String, &'static str> {
|
||||||
self.as_immutable_string().map(ImmutableString::into_owned)
|
self.as_immutable_string().map(ImmutableString::into_owned)
|
||||||
}
|
}
|
||||||
/// Convert the [`Dynamic`] into an [`ImmutableString`] and return it.
|
/// Convert the [`Dynamic`] into an [`ImmutableString`] and return it.
|
||||||
/// Returns the name of the actual type if the cast fails.
|
/// Returns the name of the actual type if the cast fails.
|
||||||
#[inline]
|
#[inline]
|
||||||
#[must_use]
|
|
||||||
pub fn as_immutable_string(self) -> Result<ImmutableString, &'static str> {
|
pub fn as_immutable_string(self) -> Result<ImmutableString, &'static str> {
|
||||||
match self.0 {
|
match self.0 {
|
||||||
Union::Str(s, _, _) => Ok(s),
|
Union::Str(s, _, _) => Ok(s),
|
||||||
@ -2055,6 +2041,6 @@ impl From<Instant> for Dynamic {
|
|||||||
impl From<crate::Shared<crate::Locked<Dynamic>>> for Dynamic {
|
impl From<crate::Shared<crate::Locked<Dynamic>>> for Dynamic {
|
||||||
#[inline(always)]
|
#[inline(always)]
|
||||||
fn from(value: crate::Shared<crate::Locked<Self>>) -> Self {
|
fn from(value: crate::Shared<crate::Locked<Self>>) -> Self {
|
||||||
Self(Union::Shared(value.into(), DEFAULT_TAG_VALUE, ReadWrite))
|
Self(Union::Shared(value, DEFAULT_TAG_VALUE, ReadWrite))
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
@ -122,7 +122,6 @@ impl Imports {
|
|||||||
/// Get an iterator to this stack of imported [modules][Module] in reverse order.
|
/// Get an iterator to this stack of imported [modules][Module] in reverse order.
|
||||||
#[allow(dead_code)]
|
#[allow(dead_code)]
|
||||||
#[inline(always)]
|
#[inline(always)]
|
||||||
#[must_use]
|
|
||||||
pub fn iter(&self) -> impl Iterator<Item = (&str, &Module)> {
|
pub fn iter(&self) -> impl Iterator<Item = (&str, &Module)> {
|
||||||
self.keys
|
self.keys
|
||||||
.iter()
|
.iter()
|
||||||
@ -133,14 +132,12 @@ impl Imports {
|
|||||||
/// Get an iterator to this stack of imported [modules][Module] in reverse order.
|
/// Get an iterator to this stack of imported [modules][Module] in reverse order.
|
||||||
#[allow(dead_code)]
|
#[allow(dead_code)]
|
||||||
#[inline(always)]
|
#[inline(always)]
|
||||||
#[must_use]
|
|
||||||
pub(crate) fn iter_raw(&self) -> impl Iterator<Item = (&Identifier, &Shared<Module>)> {
|
pub(crate) fn iter_raw(&self) -> impl Iterator<Item = (&Identifier, &Shared<Module>)> {
|
||||||
self.keys.iter().rev().zip(self.modules.iter().rev())
|
self.keys.iter().rev().zip(self.modules.iter().rev())
|
||||||
}
|
}
|
||||||
/// Get an iterator to this stack of imported [modules][Module] in forward order.
|
/// Get an iterator to this stack of imported [modules][Module] in forward order.
|
||||||
#[allow(dead_code)]
|
#[allow(dead_code)]
|
||||||
#[inline(always)]
|
#[inline(always)]
|
||||||
#[must_use]
|
|
||||||
pub(crate) fn scan_raw(&self) -> impl Iterator<Item = (&Identifier, &Shared<Module>)> {
|
pub(crate) fn scan_raw(&self) -> impl Iterator<Item = (&Identifier, &Shared<Module>)> {
|
||||||
self.keys.iter().zip(self.modules.iter())
|
self.keys.iter().zip(self.modules.iter())
|
||||||
}
|
}
|
||||||
@ -321,7 +318,7 @@ impl ChainArgument {
|
|||||||
#[inline(always)]
|
#[inline(always)]
|
||||||
#[cfg(not(feature = "no_index"))]
|
#[cfg(not(feature = "no_index"))]
|
||||||
#[must_use]
|
#[must_use]
|
||||||
pub fn as_index_value(self) -> Option<Dynamic> {
|
pub fn into_index_value(self) -> Option<Dynamic> {
|
||||||
match self {
|
match self {
|
||||||
Self::IndexValue(value, _) => Some(value),
|
Self::IndexValue(value, _) => Some(value),
|
||||||
#[cfg(not(feature = "no_object"))]
|
#[cfg(not(feature = "no_object"))]
|
||||||
@ -332,7 +329,7 @@ impl ChainArgument {
|
|||||||
#[inline(always)]
|
#[inline(always)]
|
||||||
#[cfg(not(feature = "no_object"))]
|
#[cfg(not(feature = "no_object"))]
|
||||||
#[must_use]
|
#[must_use]
|
||||||
pub fn as_fn_call_args(self) -> Option<(StaticVec<Dynamic>, Position)> {
|
pub fn into_fn_call_args(self) -> Option<(StaticVec<Dynamic>, Position)> {
|
||||||
match self {
|
match self {
|
||||||
Self::MethodCallArgs(values, pos) => Some((values, pos)),
|
Self::MethodCallArgs(values, pos) => Some((values, pos)),
|
||||||
_ => None,
|
_ => None,
|
||||||
@ -486,7 +483,6 @@ impl<'a> Target<'a> {
|
|||||||
/// Propagate a changed value back to the original source.
|
/// Propagate a changed value back to the original source.
|
||||||
/// This has no effect except for string indexing.
|
/// This has no effect except for string indexing.
|
||||||
#[inline]
|
#[inline]
|
||||||
#[must_use]
|
|
||||||
pub fn propagate_changed_value(&mut self) -> Result<(), Box<EvalAltResult>> {
|
pub fn propagate_changed_value(&mut self) -> Result<(), Box<EvalAltResult>> {
|
||||||
match self {
|
match self {
|
||||||
Self::RefMut(_) | Self::TempValue(_) => (),
|
Self::RefMut(_) | Self::TempValue(_) => (),
|
||||||
@ -834,7 +830,6 @@ impl<'x, 'px, 'pt> EvalContext<'_, 'x, 'px, '_, '_, '_, '_, 'pt> {
|
|||||||
/// Get an iterator over the current set of modules imported via `import` statements.
|
/// Get an iterator over the current set of modules imported via `import` statements.
|
||||||
#[cfg(not(feature = "no_module"))]
|
#[cfg(not(feature = "no_module"))]
|
||||||
#[inline(always)]
|
#[inline(always)]
|
||||||
#[must_use]
|
|
||||||
pub fn iter_imports(&self) -> impl Iterator<Item = (&str, &Module)> {
|
pub fn iter_imports(&self) -> impl Iterator<Item = (&str, &Module)> {
|
||||||
self.mods.iter()
|
self.mods.iter()
|
||||||
}
|
}
|
||||||
@ -849,7 +844,6 @@ impl<'x, 'px, 'pt> EvalContext<'_, 'x, 'px, '_, '_, '_, '_, 'pt> {
|
|||||||
}
|
}
|
||||||
/// Get an iterator over the namespaces containing definition of all script-defined functions.
|
/// Get an iterator over the namespaces containing definition of all script-defined functions.
|
||||||
#[inline(always)]
|
#[inline(always)]
|
||||||
#[must_use]
|
|
||||||
pub fn iter_namespaces(&self) -> impl Iterator<Item = &Module> {
|
pub fn iter_namespaces(&self) -> impl Iterator<Item = &Module> {
|
||||||
self.lib.iter().cloned()
|
self.lib.iter().cloned()
|
||||||
}
|
}
|
||||||
@ -1109,7 +1103,6 @@ impl Engine {
|
|||||||
|
|
||||||
/// Search for a variable within the scope or within imports,
|
/// Search for a variable within the scope or within imports,
|
||||||
/// depending on whether the variable name is namespace-qualified.
|
/// depending on whether the variable name is namespace-qualified.
|
||||||
#[must_use]
|
|
||||||
pub(crate) fn search_namespace<'s>(
|
pub(crate) fn search_namespace<'s>(
|
||||||
&self,
|
&self,
|
||||||
scope: &'s mut Scope,
|
scope: &'s mut Scope,
|
||||||
@ -1159,7 +1152,6 @@ impl Engine {
|
|||||||
/// # Panics
|
/// # Panics
|
||||||
///
|
///
|
||||||
/// Panics if `expr` is not [`Expr::Variable`].
|
/// Panics if `expr` is not [`Expr::Variable`].
|
||||||
#[must_use]
|
|
||||||
pub(crate) fn search_scope_only<'s>(
|
pub(crate) fn search_scope_only<'s>(
|
||||||
&self,
|
&self,
|
||||||
scope: &'s mut Scope,
|
scope: &'s mut Scope,
|
||||||
@ -1233,7 +1225,6 @@ impl Engine {
|
|||||||
/// Chain-evaluate a dot/index chain.
|
/// Chain-evaluate a dot/index chain.
|
||||||
/// [`Position`] in [`EvalAltResult`] is [`NONE`][Position::NONE] and must be set afterwards.
|
/// [`Position`] in [`EvalAltResult`] is [`NONE`][Position::NONE] and must be set afterwards.
|
||||||
#[cfg(any(not(feature = "no_index"), not(feature = "no_object")))]
|
#[cfg(any(not(feature = "no_index"), not(feature = "no_object")))]
|
||||||
#[must_use]
|
|
||||||
fn eval_dot_index_chain_helper(
|
fn eval_dot_index_chain_helper(
|
||||||
&self,
|
&self,
|
||||||
mods: &mut Imports,
|
mods: &mut Imports,
|
||||||
@ -1261,7 +1252,7 @@ impl Engine {
|
|||||||
ChainType::Indexing => {
|
ChainType::Indexing => {
|
||||||
let pos = rhs.position();
|
let pos = rhs.position();
|
||||||
let idx_val = idx_val
|
let idx_val = idx_val
|
||||||
.as_index_value()
|
.into_index_value()
|
||||||
.expect("never fails because `chain_type` is `ChainType::Index`");
|
.expect("never fails because `chain_type` is `ChainType::Index`");
|
||||||
|
|
||||||
match rhs {
|
match rhs {
|
||||||
@ -1339,7 +1330,7 @@ impl Engine {
|
|||||||
Expr::FnCall(x, pos) if !x.is_qualified() && new_val.is_none() => {
|
Expr::FnCall(x, pos) if !x.is_qualified() && new_val.is_none() => {
|
||||||
let FnCallExpr { name, hashes, .. } = x.as_ref();
|
let FnCallExpr { name, hashes, .. } = x.as_ref();
|
||||||
let call_args = &mut idx_val
|
let call_args = &mut idx_val
|
||||||
.as_fn_call_args()
|
.into_fn_call_args()
|
||||||
.expect("never fails because `chain_type` is `ChainType::Dot` with `Expr::FnCallExpr`");
|
.expect("never fails because `chain_type` is `ChainType::Dot` with `Expr::FnCallExpr`");
|
||||||
self.make_method_call(
|
self.make_method_call(
|
||||||
mods, state, lib, name, *hashes, target, call_args, *pos, level,
|
mods, state, lib, name, *hashes, target, call_args, *pos, level,
|
||||||
@ -1506,7 +1497,7 @@ impl Engine {
|
|||||||
Expr::FnCall(ref x, pos) if !x.is_qualified() => {
|
Expr::FnCall(ref x, pos) if !x.is_qualified() => {
|
||||||
let FnCallExpr { name, hashes, .. } = x.as_ref();
|
let FnCallExpr { name, hashes, .. } = x.as_ref();
|
||||||
let call_args = &mut idx_val
|
let call_args = &mut idx_val
|
||||||
.as_fn_call_args()
|
.into_fn_call_args()
|
||||||
.expect("never fails because `chain_type` is `ChainType::Dot` with `Expr::FnCallExpr`");
|
.expect("never fails because `chain_type` is `ChainType::Dot` with `Expr::FnCallExpr`");
|
||||||
let (val, _) = self.make_method_call(
|
let (val, _) = self.make_method_call(
|
||||||
mods, state, lib, name, *hashes, target, call_args, pos, level,
|
mods, state, lib, name, *hashes, target, call_args, pos, level,
|
||||||
@ -1628,7 +1619,7 @@ impl Engine {
|
|||||||
let FnCallExpr { name, hashes, .. } = f.as_ref();
|
let FnCallExpr { name, hashes, .. } = f.as_ref();
|
||||||
let rhs_chain = match_chaining_type(rhs);
|
let rhs_chain = match_chaining_type(rhs);
|
||||||
let args = &mut idx_val
|
let args = &mut idx_val
|
||||||
.as_fn_call_args()
|
.into_fn_call_args()
|
||||||
.expect("never fails because `chain_type` is `ChainType::Dot` with `Expr::FnCallExpr`");
|
.expect("never fails because `chain_type` is `ChainType::Dot` with `Expr::FnCallExpr`");
|
||||||
let (mut val, _) = self.make_method_call(
|
let (mut val, _) = self.make_method_call(
|
||||||
mods, state, lib, name, *hashes, target, args, pos, level,
|
mods, state, lib, name, *hashes, target, args, pos, level,
|
||||||
@ -1659,8 +1650,6 @@ impl Engine {
|
|||||||
|
|
||||||
/// Evaluate a dot/index chain.
|
/// Evaluate a dot/index chain.
|
||||||
#[cfg(any(not(feature = "no_index"), not(feature = "no_object")))]
|
#[cfg(any(not(feature = "no_index"), not(feature = "no_object")))]
|
||||||
#[must_use]
|
|
||||||
#[must_use]
|
|
||||||
fn eval_dot_index_chain(
|
fn eval_dot_index_chain(
|
||||||
&self,
|
&self,
|
||||||
scope: &mut Scope,
|
scope: &mut Scope,
|
||||||
@ -1692,9 +1681,10 @@ impl Engine {
|
|||||||
#[cfg(not(feature = "unchecked"))]
|
#[cfg(not(feature = "unchecked"))]
|
||||||
self.inc_operations(state, *var_pos)?;
|
self.inc_operations(state, *var_pos)?;
|
||||||
|
|
||||||
let (target, _) = self.search_namespace(scope, mods, state, lib, this_ptr, lhs)?;
|
let (mut target, _) =
|
||||||
|
self.search_namespace(scope, mods, state, lib, this_ptr, lhs)?;
|
||||||
|
|
||||||
let obj_ptr = &mut target.into();
|
let obj_ptr = &mut target;
|
||||||
let root = (x.2.as_str(), *var_pos);
|
let root = (x.2.as_str(), *var_pos);
|
||||||
|
|
||||||
self.eval_dot_index_chain_helper(
|
self.eval_dot_index_chain_helper(
|
||||||
@ -1725,7 +1715,6 @@ impl Engine {
|
|||||||
/// [`StaticVec`] is used to avoid an allocation in the overwhelming cases of
|
/// [`StaticVec`] is used to avoid an allocation in the overwhelming cases of
|
||||||
/// just a few levels of indexing.
|
/// just a few levels of indexing.
|
||||||
#[cfg(any(not(feature = "no_index"), not(feature = "no_object")))]
|
#[cfg(any(not(feature = "no_index"), not(feature = "no_object")))]
|
||||||
#[must_use]
|
|
||||||
fn eval_dot_index_chain_arguments(
|
fn eval_dot_index_chain_arguments(
|
||||||
&self,
|
&self,
|
||||||
scope: &mut Scope,
|
scope: &mut Scope,
|
||||||
@ -1852,7 +1841,6 @@ impl Engine {
|
|||||||
/// Get the value at the indexed position of a base type.
|
/// Get the value at the indexed position of a base type.
|
||||||
/// [`Position`] in [`EvalAltResult`] may be [`NONE`][Position::NONE] and should be set afterwards.
|
/// [`Position`] in [`EvalAltResult`] may be [`NONE`][Position::NONE] and should be set afterwards.
|
||||||
#[cfg(any(not(feature = "no_index"), not(feature = "no_object")))]
|
#[cfg(any(not(feature = "no_index"), not(feature = "no_object")))]
|
||||||
#[must_use]
|
|
||||||
fn get_indexed_mut<'t>(
|
fn get_indexed_mut<'t>(
|
||||||
&self,
|
&self,
|
||||||
mods: &mut Imports,
|
mods: &mut Imports,
|
||||||
@ -2023,7 +2011,6 @@ impl Engine {
|
|||||||
}
|
}
|
||||||
|
|
||||||
/// Evaluate an expression.
|
/// Evaluate an expression.
|
||||||
#[must_use]
|
|
||||||
pub(crate) fn eval_expr(
|
pub(crate) fn eval_expr(
|
||||||
&self,
|
&self,
|
||||||
scope: &mut Scope,
|
scope: &mut Scope,
|
||||||
@ -2224,7 +2211,6 @@ impl Engine {
|
|||||||
}
|
}
|
||||||
|
|
||||||
/// Evaluate a statements block.
|
/// Evaluate a statements block.
|
||||||
#[must_use]
|
|
||||||
pub(crate) fn eval_stmt_block(
|
pub(crate) fn eval_stmt_block(
|
||||||
&self,
|
&self,
|
||||||
scope: &mut Scope,
|
scope: &mut Scope,
|
||||||
@ -2302,7 +2288,6 @@ impl Engine {
|
|||||||
|
|
||||||
/// Evaluate an op-assignment statement.
|
/// Evaluate an op-assignment statement.
|
||||||
/// [`Position`] in [`EvalAltResult`] is [`NONE`][Position::NONE] and should be set afterwards.
|
/// [`Position`] in [`EvalAltResult`] is [`NONE`][Position::NONE] and should be set afterwards.
|
||||||
#[must_use]
|
|
||||||
pub(crate) fn eval_op_assignment(
|
pub(crate) fn eval_op_assignment(
|
||||||
&self,
|
&self,
|
||||||
mods: &mut Imports,
|
mods: &mut Imports,
|
||||||
@ -2376,7 +2361,6 @@ impl Engine {
|
|||||||
///
|
///
|
||||||
/// This method uses some unsafe code, mainly for avoiding cloning of local variable names via
|
/// This method uses some unsafe code, mainly for avoiding cloning of local variable names via
|
||||||
/// direct lifetime casting.
|
/// direct lifetime casting.
|
||||||
#[must_use]
|
|
||||||
pub(crate) fn eval_stmt(
|
pub(crate) fn eval_stmt(
|
||||||
&self,
|
&self,
|
||||||
scope: &mut Scope,
|
scope: &mut Scope,
|
||||||
@ -2446,7 +2430,7 @@ impl Engine {
|
|||||||
let rhs_val = self
|
let rhs_val = self
|
||||||
.eval_expr(scope, mods, state, lib, this_ptr, rhs_expr, level)?
|
.eval_expr(scope, mods, state, lib, this_ptr, rhs_expr, level)?
|
||||||
.flatten();
|
.flatten();
|
||||||
let _new_val = Some(((rhs_val, rhs_expr.position()), (op_info.clone(), *op_pos)));
|
let _new_val = Some(((rhs_val, rhs_expr.position()), (*op_info, *op_pos)));
|
||||||
|
|
||||||
// Must be either `var[index] op= val` or `var.prop op= val`
|
// Must be either `var[index] op= val` or `var.prop op= val`
|
||||||
match lhs_expr {
|
match lhs_expr {
|
||||||
@ -2963,7 +2947,7 @@ impl Engine {
|
|||||||
EvalAltResult::ErrorModuleNotFound(path.to_string(), path_pos).into()
|
EvalAltResult::ErrorModuleNotFound(path.to_string(), path_pos).into()
|
||||||
})?;
|
})?;
|
||||||
|
|
||||||
export.as_ref().map(|x| x.name.clone()).map(|name| {
|
if let Some(name) = export.as_ref().map(|x| x.name.clone()) {
|
||||||
if !module.is_indexed() {
|
if !module.is_indexed() {
|
||||||
// Index the module (making a clone copy if necessary) if it is not indexed
|
// Index the module (making a clone copy if necessary) if it is not indexed
|
||||||
let mut module = crate::fn_native::shared_take_or_clone(module);
|
let mut module = crate::fn_native::shared_take_or_clone(module);
|
||||||
@ -2972,7 +2956,7 @@ impl Engine {
|
|||||||
} else {
|
} else {
|
||||||
mods.push(name, module);
|
mods.push(name, module);
|
||||||
}
|
}
|
||||||
});
|
}
|
||||||
|
|
||||||
state.modules += 1;
|
state.modules += 1;
|
||||||
|
|
||||||
@ -3002,14 +2986,14 @@ impl Engine {
|
|||||||
// Share statement
|
// Share statement
|
||||||
#[cfg(not(feature = "no_closure"))]
|
#[cfg(not(feature = "no_closure"))]
|
||||||
Stmt::Share(name) => {
|
Stmt::Share(name) => {
|
||||||
scope.get_index(name).map(|(index, _)| {
|
if let Some((index, _)) = scope.get_index(name) {
|
||||||
let val = scope.get_mut_by_index(index);
|
let val = scope.get_mut_by_index(index);
|
||||||
|
|
||||||
if !val.is_shared() {
|
if !val.is_shared() {
|
||||||
// Replace the variable with a shared value.
|
// Replace the variable with a shared value.
|
||||||
*val = std::mem::take(val).into_shared();
|
*val = std::mem::take(val).into_shared();
|
||||||
}
|
}
|
||||||
});
|
}
|
||||||
Ok(Dynamic::UNIT)
|
Ok(Dynamic::UNIT)
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
@ -3021,7 +3005,6 @@ impl Engine {
|
|||||||
/// Check a result to ensure that the data size is within allowable limit.
|
/// Check a result to ensure that the data size is within allowable limit.
|
||||||
#[cfg(feature = "unchecked")]
|
#[cfg(feature = "unchecked")]
|
||||||
#[inline(always)]
|
#[inline(always)]
|
||||||
#[must_use]
|
|
||||||
fn check_return_value(&self, result: RhaiResult) -> RhaiResult {
|
fn check_return_value(&self, result: RhaiResult) -> RhaiResult {
|
||||||
result
|
result
|
||||||
}
|
}
|
||||||
@ -3029,20 +3012,17 @@ impl Engine {
|
|||||||
/// Check a result to ensure that the data size is within allowable limit.
|
/// Check a result to ensure that the data size is within allowable limit.
|
||||||
#[cfg(not(feature = "unchecked"))]
|
#[cfg(not(feature = "unchecked"))]
|
||||||
#[inline(always)]
|
#[inline(always)]
|
||||||
#[must_use]
|
|
||||||
fn check_return_value(&self, result: RhaiResult) -> RhaiResult {
|
fn check_return_value(&self, result: RhaiResult) -> RhaiResult {
|
||||||
result.and_then(|r| self.check_data_size(&r).map(|_| r))
|
result.and_then(|r| self.check_data_size(&r).map(|_| r))
|
||||||
}
|
}
|
||||||
|
|
||||||
#[cfg(feature = "unchecked")]
|
#[cfg(feature = "unchecked")]
|
||||||
#[inline(always)]
|
#[inline(always)]
|
||||||
#[must_use]
|
|
||||||
fn check_data_size(&self, _value: &Dynamic) -> Result<(), Box<EvalAltResult>> {
|
fn check_data_size(&self, _value: &Dynamic) -> Result<(), Box<EvalAltResult>> {
|
||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
|
|
||||||
#[cfg(not(feature = "unchecked"))]
|
#[cfg(not(feature = "unchecked"))]
|
||||||
#[must_use]
|
|
||||||
fn check_data_size(&self, value: &Dynamic) -> Result<(), Box<EvalAltResult>> {
|
fn check_data_size(&self, value: &Dynamic) -> Result<(), Box<EvalAltResult>> {
|
||||||
// Recursively calculate the size of a value (especially `Array` and `Map`)
|
// Recursively calculate the size of a value (especially `Array` and `Map`)
|
||||||
fn calc_size(value: &Dynamic) -> (usize, usize, usize) {
|
fn calc_size(value: &Dynamic) -> (usize, usize, usize) {
|
||||||
@ -3145,7 +3125,6 @@ impl Engine {
|
|||||||
|
|
||||||
/// Check if the number of operations stay within limit.
|
/// Check if the number of operations stay within limit.
|
||||||
#[cfg(not(feature = "unchecked"))]
|
#[cfg(not(feature = "unchecked"))]
|
||||||
#[must_use]
|
|
||||||
pub(crate) fn inc_operations(
|
pub(crate) fn inc_operations(
|
||||||
&self,
|
&self,
|
||||||
state: &mut EvalState,
|
state: &mut EvalState,
|
||||||
|
@ -879,7 +879,7 @@ impl Engine {
|
|||||||
pub fn register_indexer_get_set<T: Variant + Clone, X: Variant + Clone, V: Variant + Clone>(
|
pub fn register_indexer_get_set<T: Variant + Clone, X: Variant + Clone, V: Variant + Clone>(
|
||||||
&mut self,
|
&mut self,
|
||||||
get_fn: impl Fn(&mut T, X) -> V + SendSync + 'static,
|
get_fn: impl Fn(&mut T, X) -> V + SendSync + 'static,
|
||||||
set_fn: impl Fn(&mut T, X, V) -> () + SendSync + 'static,
|
set_fn: impl Fn(&mut T, X, V) + SendSync + 'static,
|
||||||
) -> &mut Self {
|
) -> &mut Self {
|
||||||
self.register_indexer_get(get_fn)
|
self.register_indexer_get(get_fn)
|
||||||
.register_indexer_set(set_fn)
|
.register_indexer_set(set_fn)
|
||||||
@ -1007,7 +1007,6 @@ impl Engine {
|
|||||||
/// # }
|
/// # }
|
||||||
/// ```
|
/// ```
|
||||||
#[inline(always)]
|
#[inline(always)]
|
||||||
#[must_use]
|
|
||||||
pub fn compile(&self, script: &str) -> Result<AST, ParseError> {
|
pub fn compile(&self, script: &str) -> Result<AST, ParseError> {
|
||||||
self.compile_with_scope(&Default::default(), script)
|
self.compile_with_scope(&Default::default(), script)
|
||||||
}
|
}
|
||||||
@ -1050,7 +1049,6 @@ impl Engine {
|
|||||||
/// # }
|
/// # }
|
||||||
/// ```
|
/// ```
|
||||||
#[inline(always)]
|
#[inline(always)]
|
||||||
#[must_use]
|
|
||||||
pub fn compile_with_scope(&self, scope: &Scope, script: &str) -> Result<AST, ParseError> {
|
pub fn compile_with_scope(&self, scope: &Scope, script: &str) -> Result<AST, ParseError> {
|
||||||
self.compile_scripts_with_scope(scope, &[script])
|
self.compile_scripts_with_scope(scope, &[script])
|
||||||
}
|
}
|
||||||
@ -1064,7 +1062,6 @@ impl Engine {
|
|||||||
/// [`AST`]. When it is evaluated later, `import` statement directly recall pre-resolved
|
/// [`AST`]. When it is evaluated later, `import` statement directly recall pre-resolved
|
||||||
/// [modules][Module] and the resolution process is not performed again.
|
/// [modules][Module] and the resolution process is not performed again.
|
||||||
#[cfg(not(feature = "no_module"))]
|
#[cfg(not(feature = "no_module"))]
|
||||||
#[must_use]
|
|
||||||
pub fn compile_into_self_contained(
|
pub fn compile_into_self_contained(
|
||||||
&self,
|
&self,
|
||||||
scope: &Scope,
|
scope: &Scope,
|
||||||
@ -1103,7 +1100,7 @@ impl Engine {
|
|||||||
let mut resolver = StaticModuleResolver::new();
|
let mut resolver = StaticModuleResolver::new();
|
||||||
let mut imports = Default::default();
|
let mut imports = Default::default();
|
||||||
|
|
||||||
collect_imports(&ast, &mut resolver, &mut imports);
|
collect_imports(&ast, &resolver, &mut imports);
|
||||||
|
|
||||||
if !imports.is_empty() {
|
if !imports.is_empty() {
|
||||||
while let Some(path) = imports.iter().next() {
|
while let Some(path) = imports.iter().next() {
|
||||||
@ -1111,7 +1108,7 @@ impl Engine {
|
|||||||
|
|
||||||
match module_resolver.resolve_ast(self, None, &path, Position::NONE) {
|
match module_resolver.resolve_ast(self, None, &path, Position::NONE) {
|
||||||
Some(Ok(module_ast)) => {
|
Some(Ok(module_ast)) => {
|
||||||
collect_imports(&module_ast, &mut resolver, &mut imports)
|
collect_imports(&module_ast, &resolver, &mut imports)
|
||||||
}
|
}
|
||||||
Some(err) => return err,
|
Some(err) => return err,
|
||||||
None => (),
|
None => (),
|
||||||
@ -1176,7 +1173,6 @@ impl Engine {
|
|||||||
/// # }
|
/// # }
|
||||||
/// ```
|
/// ```
|
||||||
#[inline(always)]
|
#[inline(always)]
|
||||||
#[must_use]
|
|
||||||
pub fn compile_scripts_with_scope(
|
pub fn compile_scripts_with_scope(
|
||||||
&self,
|
&self,
|
||||||
scope: &Scope,
|
scope: &Scope,
|
||||||
@ -1186,7 +1182,6 @@ impl Engine {
|
|||||||
}
|
}
|
||||||
/// Join a list of strings and compile into an [`AST`] using own scope at a specific optimization level.
|
/// Join a list of strings and compile into an [`AST`] using own scope at a specific optimization level.
|
||||||
#[inline]
|
#[inline]
|
||||||
#[must_use]
|
|
||||||
pub(crate) fn compile_with_scope_and_optimization_level(
|
pub(crate) fn compile_with_scope_and_optimization_level(
|
||||||
&self,
|
&self,
|
||||||
scope: &Scope,
|
scope: &Scope,
|
||||||
@ -1205,7 +1200,6 @@ impl Engine {
|
|||||||
/// Read the contents of a file into a string.
|
/// Read the contents of a file into a string.
|
||||||
#[cfg(not(feature = "no_std"))]
|
#[cfg(not(feature = "no_std"))]
|
||||||
#[cfg(not(any(target_arch = "wasm32", target_arch = "wasm64")))]
|
#[cfg(not(any(target_arch = "wasm32", target_arch = "wasm64")))]
|
||||||
#[must_use]
|
|
||||||
fn read_file(path: std::path::PathBuf) -> Result<String, Box<EvalAltResult>> {
|
fn read_file(path: std::path::PathBuf) -> Result<String, Box<EvalAltResult>> {
|
||||||
use std::io::Read;
|
use std::io::Read;
|
||||||
|
|
||||||
@ -1261,7 +1255,6 @@ impl Engine {
|
|||||||
#[cfg(not(feature = "no_std"))]
|
#[cfg(not(feature = "no_std"))]
|
||||||
#[cfg(not(any(target_arch = "wasm32", target_arch = "wasm64")))]
|
#[cfg(not(any(target_arch = "wasm32", target_arch = "wasm64")))]
|
||||||
#[inline(always)]
|
#[inline(always)]
|
||||||
#[must_use]
|
|
||||||
pub fn compile_file(&self, path: std::path::PathBuf) -> Result<AST, Box<EvalAltResult>> {
|
pub fn compile_file(&self, path: std::path::PathBuf) -> Result<AST, Box<EvalAltResult>> {
|
||||||
self.compile_file_with_scope(&Default::default(), path)
|
self.compile_file_with_scope(&Default::default(), path)
|
||||||
}
|
}
|
||||||
@ -1301,7 +1294,6 @@ impl Engine {
|
|||||||
#[cfg(not(feature = "no_std"))]
|
#[cfg(not(feature = "no_std"))]
|
||||||
#[cfg(not(any(target_arch = "wasm32", target_arch = "wasm64")))]
|
#[cfg(not(any(target_arch = "wasm32", target_arch = "wasm64")))]
|
||||||
#[inline(always)]
|
#[inline(always)]
|
||||||
#[must_use]
|
|
||||||
pub fn compile_file_with_scope(
|
pub fn compile_file_with_scope(
|
||||||
&self,
|
&self,
|
||||||
scope: &Scope,
|
scope: &Scope,
|
||||||
@ -1353,7 +1345,6 @@ impl Engine {
|
|||||||
/// # }
|
/// # }
|
||||||
/// ```
|
/// ```
|
||||||
#[cfg(not(feature = "no_object"))]
|
#[cfg(not(feature = "no_object"))]
|
||||||
#[must_use]
|
|
||||||
pub fn parse_json(
|
pub fn parse_json(
|
||||||
&self,
|
&self,
|
||||||
json: impl AsRef<str>,
|
json: impl AsRef<str>,
|
||||||
@ -1429,7 +1420,6 @@ impl Engine {
|
|||||||
/// # }
|
/// # }
|
||||||
/// ```
|
/// ```
|
||||||
#[inline(always)]
|
#[inline(always)]
|
||||||
#[must_use]
|
|
||||||
pub fn compile_expression(&self, script: &str) -> Result<AST, ParseError> {
|
pub fn compile_expression(&self, script: &str) -> Result<AST, ParseError> {
|
||||||
self.compile_expression_with_scope(&Default::default(), script)
|
self.compile_expression_with_scope(&Default::default(), script)
|
||||||
}
|
}
|
||||||
@ -1473,7 +1463,6 @@ impl Engine {
|
|||||||
/// # }
|
/// # }
|
||||||
/// ```
|
/// ```
|
||||||
#[inline]
|
#[inline]
|
||||||
#[must_use]
|
|
||||||
pub fn compile_expression_with_scope(
|
pub fn compile_expression_with_scope(
|
||||||
&self,
|
&self,
|
||||||
scope: &Scope,
|
scope: &Scope,
|
||||||
@ -1506,7 +1495,6 @@ impl Engine {
|
|||||||
#[cfg(not(feature = "no_std"))]
|
#[cfg(not(feature = "no_std"))]
|
||||||
#[cfg(not(any(target_arch = "wasm32", target_arch = "wasm64")))]
|
#[cfg(not(any(target_arch = "wasm32", target_arch = "wasm64")))]
|
||||||
#[inline(always)]
|
#[inline(always)]
|
||||||
#[must_use]
|
|
||||||
pub fn eval_file<T: Variant + Clone>(
|
pub fn eval_file<T: Variant + Clone>(
|
||||||
&self,
|
&self,
|
||||||
path: std::path::PathBuf,
|
path: std::path::PathBuf,
|
||||||
@ -1537,7 +1525,6 @@ impl Engine {
|
|||||||
#[cfg(not(feature = "no_std"))]
|
#[cfg(not(feature = "no_std"))]
|
||||||
#[cfg(not(any(target_arch = "wasm32", target_arch = "wasm64")))]
|
#[cfg(not(any(target_arch = "wasm32", target_arch = "wasm64")))]
|
||||||
#[inline(always)]
|
#[inline(always)]
|
||||||
#[must_use]
|
|
||||||
pub fn eval_file_with_scope<T: Variant + Clone>(
|
pub fn eval_file_with_scope<T: Variant + Clone>(
|
||||||
&self,
|
&self,
|
||||||
scope: &mut Scope,
|
scope: &mut Scope,
|
||||||
@ -1560,7 +1547,6 @@ impl Engine {
|
|||||||
/// # }
|
/// # }
|
||||||
/// ```
|
/// ```
|
||||||
#[inline(always)]
|
#[inline(always)]
|
||||||
#[must_use]
|
|
||||||
pub fn eval<T: Variant + Clone>(&self, script: &str) -> Result<T, Box<EvalAltResult>> {
|
pub fn eval<T: Variant + Clone>(&self, script: &str) -> Result<T, Box<EvalAltResult>> {
|
||||||
self.eval_with_scope(&mut Default::default(), script)
|
self.eval_with_scope(&mut Default::default(), script)
|
||||||
}
|
}
|
||||||
@ -1587,7 +1573,6 @@ impl Engine {
|
|||||||
/// # }
|
/// # }
|
||||||
/// ```
|
/// ```
|
||||||
#[inline(always)]
|
#[inline(always)]
|
||||||
#[must_use]
|
|
||||||
pub fn eval_with_scope<T: Variant + Clone>(
|
pub fn eval_with_scope<T: Variant + Clone>(
|
||||||
&self,
|
&self,
|
||||||
scope: &mut Scope,
|
scope: &mut Scope,
|
||||||
@ -1615,7 +1600,6 @@ impl Engine {
|
|||||||
/// # }
|
/// # }
|
||||||
/// ```
|
/// ```
|
||||||
#[inline(always)]
|
#[inline(always)]
|
||||||
#[must_use]
|
|
||||||
pub fn eval_expression<T: Variant + Clone>(
|
pub fn eval_expression<T: Variant + Clone>(
|
||||||
&self,
|
&self,
|
||||||
script: &str,
|
script: &str,
|
||||||
@ -1641,7 +1625,6 @@ impl Engine {
|
|||||||
/// # }
|
/// # }
|
||||||
/// ```
|
/// ```
|
||||||
#[inline]
|
#[inline]
|
||||||
#[must_use]
|
|
||||||
pub fn eval_expression_with_scope<T: Variant + Clone>(
|
pub fn eval_expression_with_scope<T: Variant + Clone>(
|
||||||
&self,
|
&self,
|
||||||
scope: &mut Scope,
|
scope: &mut Scope,
|
||||||
@ -1680,7 +1663,6 @@ impl Engine {
|
|||||||
/// # }
|
/// # }
|
||||||
/// ```
|
/// ```
|
||||||
#[inline(always)]
|
#[inline(always)]
|
||||||
#[must_use]
|
|
||||||
pub fn eval_ast<T: Variant + Clone>(&self, ast: &AST) -> Result<T, Box<EvalAltResult>> {
|
pub fn eval_ast<T: Variant + Clone>(&self, ast: &AST) -> Result<T, Box<EvalAltResult>> {
|
||||||
self.eval_ast_with_scope(&mut Default::default(), ast)
|
self.eval_ast_with_scope(&mut Default::default(), ast)
|
||||||
}
|
}
|
||||||
@ -1714,7 +1696,6 @@ impl Engine {
|
|||||||
/// # }
|
/// # }
|
||||||
/// ```
|
/// ```
|
||||||
#[inline]
|
#[inline]
|
||||||
#[must_use]
|
|
||||||
pub fn eval_ast_with_scope<T: Variant + Clone>(
|
pub fn eval_ast_with_scope<T: Variant + Clone>(
|
||||||
&self,
|
&self,
|
||||||
scope: &mut Scope,
|
scope: &mut Scope,
|
||||||
@ -1726,18 +1707,17 @@ impl Engine {
|
|||||||
|
|
||||||
let typ = self.map_type_name(result.type_name());
|
let typ = self.map_type_name(result.type_name());
|
||||||
|
|
||||||
return result.try_cast::<T>().ok_or_else(|| {
|
result.try_cast::<T>().ok_or_else(|| {
|
||||||
EvalAltResult::ErrorMismatchOutputType(
|
EvalAltResult::ErrorMismatchOutputType(
|
||||||
self.map_type_name(type_name::<T>()).into(),
|
self.map_type_name(type_name::<T>()).into(),
|
||||||
typ.into(),
|
typ.into(),
|
||||||
Position::NONE,
|
Position::NONE,
|
||||||
)
|
)
|
||||||
.into()
|
.into()
|
||||||
});
|
})
|
||||||
}
|
}
|
||||||
/// Evaluate an [`AST`] with own scope.
|
/// Evaluate an [`AST`] with own scope.
|
||||||
#[inline]
|
#[inline]
|
||||||
#[must_use]
|
|
||||||
pub(crate) fn eval_ast_with_scope_raw<'a>(
|
pub(crate) fn eval_ast_with_scope_raw<'a>(
|
||||||
&self,
|
&self,
|
||||||
scope: &mut Scope,
|
scope: &mut Scope,
|
||||||
@ -1886,7 +1866,6 @@ impl Engine {
|
|||||||
/// ```
|
/// ```
|
||||||
#[cfg(not(feature = "no_function"))]
|
#[cfg(not(feature = "no_function"))]
|
||||||
#[inline]
|
#[inline]
|
||||||
#[must_use]
|
|
||||||
pub fn call_fn<T: Variant + Clone>(
|
pub fn call_fn<T: Variant + Clone>(
|
||||||
&self,
|
&self,
|
||||||
scope: &mut Scope,
|
scope: &mut Scope,
|
||||||
@ -1967,7 +1946,6 @@ impl Engine {
|
|||||||
/// ```
|
/// ```
|
||||||
#[cfg(not(feature = "no_function"))]
|
#[cfg(not(feature = "no_function"))]
|
||||||
#[inline]
|
#[inline]
|
||||||
#[must_use]
|
|
||||||
pub fn call_fn_dynamic(
|
pub fn call_fn_dynamic(
|
||||||
&self,
|
&self,
|
||||||
scope: &mut Scope,
|
scope: &mut Scope,
|
||||||
@ -1992,7 +1970,6 @@ impl Engine {
|
|||||||
/// clone them _before_ calling this function.
|
/// clone them _before_ calling this function.
|
||||||
#[cfg(not(feature = "no_function"))]
|
#[cfg(not(feature = "no_function"))]
|
||||||
#[inline]
|
#[inline]
|
||||||
#[must_use]
|
|
||||||
pub(crate) fn call_fn_dynamic_raw(
|
pub(crate) fn call_fn_dynamic_raw(
|
||||||
&self,
|
&self,
|
||||||
scope: &mut Scope,
|
scope: &mut Scope,
|
||||||
|
@ -291,7 +291,6 @@ impl Engine {
|
|||||||
/// # Ok(())
|
/// # Ok(())
|
||||||
/// # }
|
/// # }
|
||||||
/// ```
|
/// ```
|
||||||
#[must_use]
|
|
||||||
pub fn register_custom_operator(
|
pub fn register_custom_operator(
|
||||||
&mut self,
|
&mut self,
|
||||||
keyword: impl AsRef<str> + Into<Identifier>,
|
keyword: impl AsRef<str> + Into<Identifier>,
|
||||||
@ -310,18 +309,18 @@ impl Engine {
|
|||||||
// Disabled keywords are OK
|
// Disabled keywords are OK
|
||||||
Some(token) if token.is_keyword() => {
|
Some(token) if token.is_keyword() => {
|
||||||
if !self.disabled_symbols.contains(token.syntax().as_ref()) {
|
if !self.disabled_symbols.contains(token.syntax().as_ref()) {
|
||||||
return Err(format!("'{}' is a reserved keyword", keyword.as_ref()).into());
|
return Err(format!("'{}' is a reserved keyword", keyword.as_ref()));
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
// Active standard symbols cannot be made custom
|
// Active standard symbols cannot be made custom
|
||||||
Some(token) if token.is_symbol() => {
|
Some(token) if token.is_symbol() => {
|
||||||
if !self.disabled_symbols.contains(token.syntax().as_ref()) {
|
if !self.disabled_symbols.contains(token.syntax().as_ref()) {
|
||||||
return Err(format!("'{}' is a reserved operator", keyword.as_ref()).into());
|
return Err(format!("'{}' is a reserved operator", keyword.as_ref()));
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
// Active standard symbols cannot be made custom
|
// Active standard symbols cannot be made custom
|
||||||
Some(token) if !self.disabled_symbols.contains(token.syntax().as_ref()) => {
|
Some(token) if !self.disabled_symbols.contains(token.syntax().as_ref()) => {
|
||||||
return Err(format!("'{}' is a reserved symbol", keyword.as_ref()).into())
|
return Err(format!("'{}' is a reserved symbol", keyword.as_ref()))
|
||||||
}
|
}
|
||||||
// Disabled symbols are OK
|
// Disabled symbols are OK
|
||||||
Some(_) => (),
|
Some(_) => (),
|
||||||
|
@ -84,7 +84,9 @@ impl<'a> ArgBackup<'a> {
|
|||||||
/// the current scope. Otherwise it is undefined behavior as the shorter lifetime will leak.
|
/// the current scope. Otherwise it is undefined behavior as the shorter lifetime will leak.
|
||||||
#[inline(always)]
|
#[inline(always)]
|
||||||
fn restore_first_arg(mut self, args: &mut FnCallArgs<'a>) {
|
fn restore_first_arg(mut self, args: &mut FnCallArgs<'a>) {
|
||||||
self.orig_mut.take().map(|p| args[0] = p);
|
if let Some(p) = self.orig_mut.take() {
|
||||||
|
args[0] = p;
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -101,7 +103,6 @@ impl Drop for ArgBackup<'_> {
|
|||||||
|
|
||||||
#[cfg(not(feature = "no_closure"))]
|
#[cfg(not(feature = "no_closure"))]
|
||||||
#[inline]
|
#[inline]
|
||||||
#[must_use]
|
|
||||||
pub fn ensure_no_data_race(
|
pub fn ensure_no_data_race(
|
||||||
fn_name: &str,
|
fn_name: &str,
|
||||||
args: &FnCallArgs,
|
args: &FnCallArgs,
|
||||||
@ -261,7 +262,6 @@ impl Engine {
|
|||||||
/// Function call arguments be _consumed_ when the function requires them to be passed by value.
|
/// Function call arguments be _consumed_ when the function requires them to be passed by value.
|
||||||
/// All function arguments not in the first position are always passed by value and thus consumed.
|
/// All function arguments not in the first position are always passed by value and thus consumed.
|
||||||
/// **DO NOT** reuse the argument values unless for the first `&mut` argument - all others are silently replaced by `()`!
|
/// **DO NOT** reuse the argument values unless for the first `&mut` argument - all others are silently replaced by `()`!
|
||||||
#[must_use]
|
|
||||||
pub(crate) fn call_native_fn(
|
pub(crate) fn call_native_fn(
|
||||||
&self,
|
&self,
|
||||||
mods: &Imports,
|
mods: &Imports,
|
||||||
@ -290,7 +290,7 @@ impl Engine {
|
|||||||
let mut backup: Option<ArgBackup> = None;
|
let mut backup: Option<ArgBackup> = None;
|
||||||
if is_method_call && func.is_pure() && !args.is_empty() {
|
if is_method_call && func.is_pure() && !args.is_empty() {
|
||||||
backup = Some(Default::default());
|
backup = Some(Default::default());
|
||||||
backup.as_mut().map(|bk| bk.change_first_arg_to_copy(args));
|
backup.as_mut().unwrap().change_first_arg_to_copy(args);
|
||||||
}
|
}
|
||||||
|
|
||||||
// Run external function
|
// Run external function
|
||||||
@ -311,7 +311,9 @@ impl Engine {
|
|||||||
};
|
};
|
||||||
|
|
||||||
// Restore the original reference
|
// Restore the original reference
|
||||||
backup.map(|bk| bk.restore_first_arg(args));
|
if let Some(bk) = backup {
|
||||||
|
bk.restore_first_arg(args)
|
||||||
|
}
|
||||||
|
|
||||||
let result = result.map_err(|err| err.fill_position(pos))?;
|
let result = result.map_err(|err| err.fill_position(pos))?;
|
||||||
|
|
||||||
@ -433,7 +435,6 @@ impl Engine {
|
|||||||
/// All function arguments not in the first position are always passed by value and thus consumed.
|
/// All function arguments not in the first position are always passed by value and thus consumed.
|
||||||
/// **DO NOT** reuse the argument values unless for the first `&mut` argument - all others are silently replaced by `()`!
|
/// **DO NOT** reuse the argument values unless for the first `&mut` argument - all others are silently replaced by `()`!
|
||||||
#[cfg(not(feature = "no_function"))]
|
#[cfg(not(feature = "no_function"))]
|
||||||
#[must_use]
|
|
||||||
pub(crate) fn call_script_fn(
|
pub(crate) fn call_script_fn(
|
||||||
&self,
|
&self,
|
||||||
scope: &mut Scope,
|
scope: &mut Scope,
|
||||||
@ -601,7 +602,6 @@ impl Engine {
|
|||||||
/// Function call arguments may be _consumed_ when the function requires them to be passed by value.
|
/// Function call arguments may be _consumed_ when the function requires them to be passed by value.
|
||||||
/// All function arguments not in the first position are always passed by value and thus consumed.
|
/// All function arguments not in the first position are always passed by value and thus consumed.
|
||||||
/// **DO NOT** reuse the argument values unless for the first `&mut` argument - all others are silently replaced by `()`!
|
/// **DO NOT** reuse the argument values unless for the first `&mut` argument - all others are silently replaced by `()`!
|
||||||
#[must_use]
|
|
||||||
pub(crate) fn exec_fn_call(
|
pub(crate) fn exec_fn_call(
|
||||||
&self,
|
&self,
|
||||||
mods: &mut Imports,
|
mods: &mut Imports,
|
||||||
@ -702,7 +702,7 @@ impl Engine {
|
|||||||
// Move captured variables into scope
|
// Move captured variables into scope
|
||||||
#[cfg(not(feature = "no_closure"))]
|
#[cfg(not(feature = "no_closure"))]
|
||||||
if !func.externals.is_empty() {
|
if !func.externals.is_empty() {
|
||||||
_capture_scope.map(|captured| {
|
if let Some(captured) = _capture_scope {
|
||||||
captured
|
captured
|
||||||
.into_iter()
|
.into_iter()
|
||||||
.filter(|(name, _, _)| func.externals.contains(name.as_ref()))
|
.filter(|(name, _, _)| func.externals.contains(name.as_ref()))
|
||||||
@ -710,7 +710,7 @@ impl Engine {
|
|||||||
// Consume the scope values.
|
// Consume the scope values.
|
||||||
scope.push_dynamic(name, value);
|
scope.push_dynamic(name, value);
|
||||||
})
|
})
|
||||||
});
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
let result = if _is_method_call {
|
let result = if _is_method_call {
|
||||||
@ -746,7 +746,7 @@ impl Engine {
|
|||||||
let mut backup: Option<ArgBackup> = None;
|
let mut backup: Option<ArgBackup> = None;
|
||||||
if is_ref_mut && !args.is_empty() {
|
if is_ref_mut && !args.is_empty() {
|
||||||
backup = Some(Default::default());
|
backup = Some(Default::default());
|
||||||
backup.as_mut().map(|bk| bk.change_first_arg_to_copy(args));
|
backup.as_mut().unwrap().change_first_arg_to_copy(args);
|
||||||
}
|
}
|
||||||
|
|
||||||
let orig_source = state.source.take();
|
let orig_source = state.source.take();
|
||||||
@ -761,7 +761,9 @@ impl Engine {
|
|||||||
state.source = orig_source;
|
state.source = orig_source;
|
||||||
|
|
||||||
// Restore the original reference
|
// Restore the original reference
|
||||||
backup.map(|bk| bk.restore_first_arg(args));
|
if let Some(bk) = backup {
|
||||||
|
bk.restore_first_arg(args)
|
||||||
|
}
|
||||||
|
|
||||||
result?
|
result?
|
||||||
};
|
};
|
||||||
@ -779,7 +781,6 @@ impl Engine {
|
|||||||
/// Evaluate a list of statements with no `this` pointer.
|
/// Evaluate a list of statements with no `this` pointer.
|
||||||
/// This is commonly used to evaluate a list of statements in an [`AST`] or a script function body.
|
/// This is commonly used to evaluate a list of statements in an [`AST`] or a script function body.
|
||||||
#[inline]
|
#[inline]
|
||||||
#[must_use]
|
|
||||||
pub(crate) fn eval_global_statements(
|
pub(crate) fn eval_global_statements(
|
||||||
&self,
|
&self,
|
||||||
scope: &mut Scope,
|
scope: &mut Scope,
|
||||||
@ -800,7 +801,6 @@ impl Engine {
|
|||||||
}
|
}
|
||||||
|
|
||||||
/// Evaluate a text script in place - used primarily for 'eval'.
|
/// Evaluate a text script in place - used primarily for 'eval'.
|
||||||
#[must_use]
|
|
||||||
fn eval_script_expr_in_place(
|
fn eval_script_expr_in_place(
|
||||||
&self,
|
&self,
|
||||||
scope: &mut Scope,
|
scope: &mut Scope,
|
||||||
@ -852,7 +852,6 @@ impl Engine {
|
|||||||
|
|
||||||
/// Call a dot method.
|
/// Call a dot method.
|
||||||
#[cfg(not(feature = "no_object"))]
|
#[cfg(not(feature = "no_object"))]
|
||||||
#[must_use]
|
|
||||||
pub(crate) fn make_method_call(
|
pub(crate) fn make_method_call(
|
||||||
&self,
|
&self,
|
||||||
mods: &mut Imports,
|
mods: &mut Imports,
|
||||||
@ -891,7 +890,7 @@ impl Engine {
|
|||||||
)
|
)
|
||||||
}
|
}
|
||||||
KEYWORD_FN_PTR_CALL => {
|
KEYWORD_FN_PTR_CALL => {
|
||||||
if call_args.len() > 0 {
|
if !call_args.is_empty() {
|
||||||
if !call_args[0].is::<FnPtr>() {
|
if !call_args[0].is::<FnPtr>() {
|
||||||
return Err(self.make_type_mismatch_err::<FnPtr>(
|
return Err(self.make_type_mismatch_err::<FnPtr>(
|
||||||
self.map_type_name(call_args[0].type_name()),
|
self.map_type_name(call_args[0].type_name()),
|
||||||
@ -1015,7 +1014,6 @@ impl Engine {
|
|||||||
|
|
||||||
/// Evaluate an argument.
|
/// Evaluate an argument.
|
||||||
#[inline]
|
#[inline]
|
||||||
#[must_use]
|
|
||||||
pub(crate) fn get_arg_value(
|
pub(crate) fn get_arg_value(
|
||||||
&self,
|
&self,
|
||||||
scope: &mut Scope,
|
scope: &mut Scope,
|
||||||
@ -1037,7 +1035,6 @@ impl Engine {
|
|||||||
}
|
}
|
||||||
|
|
||||||
/// Call a function in normal function-call style.
|
/// Call a function in normal function-call style.
|
||||||
#[must_use]
|
|
||||||
pub(crate) fn make_function_call(
|
pub(crate) fn make_function_call(
|
||||||
&self,
|
&self,
|
||||||
scope: &mut Scope,
|
scope: &mut Scope,
|
||||||
@ -1103,7 +1100,7 @@ impl Engine {
|
|||||||
return arg
|
return arg
|
||||||
.as_immutable_string()
|
.as_immutable_string()
|
||||||
.map_err(|typ| self.make_type_mismatch_err::<ImmutableString>(typ, arg_pos))
|
.map_err(|typ| self.make_type_mismatch_err::<ImmutableString>(typ, arg_pos))
|
||||||
.and_then(|s| FnPtr::try_from(s))
|
.and_then(FnPtr::try_from)
|
||||||
.map(Into::<Dynamic>::into)
|
.map(Into::<Dynamic>::into)
|
||||||
.map_err(|err| err.fill_position(arg_pos));
|
.map_err(|err| err.fill_position(arg_pos));
|
||||||
}
|
}
|
||||||
@ -1289,7 +1286,6 @@ impl Engine {
|
|||||||
}
|
}
|
||||||
|
|
||||||
/// Call a namespace-qualified function in normal function-call style.
|
/// Call a namespace-qualified function in normal function-call style.
|
||||||
#[must_use]
|
|
||||||
pub(crate) fn make_qualified_function_call(
|
pub(crate) fn make_qualified_function_call(
|
||||||
&self,
|
&self,
|
||||||
scope: &mut Scope,
|
scope: &mut Scope,
|
||||||
@ -1386,10 +1382,10 @@ impl Engine {
|
|||||||
|
|
||||||
// Clone first argument if the function is not a method after-all
|
// Clone first argument if the function is not a method after-all
|
||||||
if !func.map(|f| f.is_method()).unwrap_or(true) {
|
if !func.map(|f| f.is_method()).unwrap_or(true) {
|
||||||
first_arg_value.map(|first| {
|
if let Some(first) = first_arg_value {
|
||||||
*first = args[0].clone();
|
*first = args[0].clone();
|
||||||
args[0] = first;
|
args[0] = first;
|
||||||
});
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
match func {
|
match func {
|
||||||
|
@ -124,7 +124,10 @@ pub fn calc_fn_hash(fn_name: &str, num: usize) -> u64 {
|
|||||||
pub fn calc_fn_params_hash(params: impl Iterator<Item = TypeId>) -> u64 {
|
pub fn calc_fn_params_hash(params: impl Iterator<Item = TypeId>) -> u64 {
|
||||||
let s = &mut get_hasher();
|
let s = &mut get_hasher();
|
||||||
let mut len = 0;
|
let mut len = 0;
|
||||||
params.inspect(|_| len += 1).for_each(|t| t.hash(s));
|
params.for_each(|t| {
|
||||||
|
len += 1;
|
||||||
|
t.hash(s);
|
||||||
|
});
|
||||||
len.hash(s);
|
len.hash(s);
|
||||||
s.finish()
|
s.finish()
|
||||||
}
|
}
|
||||||
|
@ -144,7 +144,6 @@ impl<'a> NativeCallContext<'a> {
|
|||||||
/// Not available under `no_module`.
|
/// Not available under `no_module`.
|
||||||
#[cfg(not(feature = "no_module"))]
|
#[cfg(not(feature = "no_module"))]
|
||||||
#[inline(always)]
|
#[inline(always)]
|
||||||
#[must_use]
|
|
||||||
pub fn iter_imports(&self) -> impl Iterator<Item = (&str, &Module)> {
|
pub fn iter_imports(&self) -> impl Iterator<Item = (&str, &Module)> {
|
||||||
self.mods.iter().flat_map(|&m| m.iter())
|
self.mods.iter().flat_map(|&m| m.iter())
|
||||||
}
|
}
|
||||||
@ -152,7 +151,6 @@ impl<'a> NativeCallContext<'a> {
|
|||||||
#[cfg(not(feature = "no_module"))]
|
#[cfg(not(feature = "no_module"))]
|
||||||
#[allow(dead_code)]
|
#[allow(dead_code)]
|
||||||
#[inline(always)]
|
#[inline(always)]
|
||||||
#[must_use]
|
|
||||||
pub(crate) fn iter_imports_raw(
|
pub(crate) fn iter_imports_raw(
|
||||||
&self,
|
&self,
|
||||||
) -> impl Iterator<Item = (&crate::Identifier, &Shared<Module>)> {
|
) -> impl Iterator<Item = (&crate::Identifier, &Shared<Module>)> {
|
||||||
@ -171,7 +169,6 @@ impl<'a> NativeCallContext<'a> {
|
|||||||
}
|
}
|
||||||
/// Get an iterator over the namespaces containing definitions of all script-defined functions.
|
/// Get an iterator over the namespaces containing definitions of all script-defined functions.
|
||||||
#[inline(always)]
|
#[inline(always)]
|
||||||
#[must_use]
|
|
||||||
pub fn iter_namespaces(&self) -> impl Iterator<Item = &Module> {
|
pub fn iter_namespaces(&self) -> impl Iterator<Item = &Module> {
|
||||||
self.lib.iter().cloned()
|
self.lib.iter().cloned()
|
||||||
}
|
}
|
||||||
@ -196,7 +193,6 @@ impl<'a> NativeCallContext<'a> {
|
|||||||
/// If `is_method` is [`true`], the first argument is assumed to be passed
|
/// If `is_method` is [`true`], the first argument is assumed to be passed
|
||||||
/// by reference and is not consumed.
|
/// by reference and is not consumed.
|
||||||
#[inline]
|
#[inline]
|
||||||
#[must_use]
|
|
||||||
pub fn call_fn_dynamic_raw(
|
pub fn call_fn_dynamic_raw(
|
||||||
&self,
|
&self,
|
||||||
fn_name: impl AsRef<str>,
|
fn_name: impl AsRef<str>,
|
||||||
@ -249,7 +245,6 @@ pub fn shared_take_or_clone<T: Clone>(value: Shared<T>) -> T {
|
|||||||
|
|
||||||
/// Consume a [`Shared`] resource if is unique (i.e. not shared).
|
/// Consume a [`Shared`] resource if is unique (i.e. not shared).
|
||||||
#[inline(always)]
|
#[inline(always)]
|
||||||
#[must_use]
|
|
||||||
pub fn shared_try_take<T>(value: Shared<T>) -> Result<T, Shared<T>> {
|
pub fn shared_try_take<T>(value: Shared<T>) -> Result<T, Shared<T>> {
|
||||||
Shared::try_unwrap(value)
|
Shared::try_unwrap(value)
|
||||||
}
|
}
|
||||||
@ -493,7 +488,7 @@ impl CallableFunction {
|
|||||||
/// Get a shared reference to a plugin function.
|
/// Get a shared reference to a plugin function.
|
||||||
#[inline]
|
#[inline]
|
||||||
#[must_use]
|
#[must_use]
|
||||||
pub fn get_plugin_fn<'s>(&'s self) -> Option<&Shared<FnPlugin>> {
|
pub fn get_plugin_fn(&self) -> Option<&Shared<FnPlugin>> {
|
||||||
match self {
|
match self {
|
||||||
Self::Plugin(f) => Some(f),
|
Self::Plugin(f) => Some(f),
|
||||||
Self::Pure(_) | Self::Method(_) | Self::Iterator(_) => None,
|
Self::Pure(_) | Self::Method(_) | Self::Iterator(_) => None,
|
||||||
@ -555,6 +550,6 @@ impl<T: PluginFunction + 'static + SendSync> From<T> for CallableFunction {
|
|||||||
impl From<Shared<FnPlugin>> for CallableFunction {
|
impl From<Shared<FnPlugin>> for CallableFunction {
|
||||||
#[inline(always)]
|
#[inline(always)]
|
||||||
fn from(func: Shared<FnPlugin>) -> Self {
|
fn from(func: Shared<FnPlugin>) -> Self {
|
||||||
Self::Plugin(func.into())
|
Self::Plugin(func)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
@ -19,7 +19,6 @@ pub struct FnPtr(Identifier, StaticVec<Dynamic>);
|
|||||||
impl FnPtr {
|
impl FnPtr {
|
||||||
/// Create a new function pointer.
|
/// Create a new function pointer.
|
||||||
#[inline(always)]
|
#[inline(always)]
|
||||||
#[must_use]
|
|
||||||
pub fn new(name: impl Into<Identifier>) -> Result<Self, Box<EvalAltResult>> {
|
pub fn new(name: impl Into<Identifier>) -> Result<Self, Box<EvalAltResult>> {
|
||||||
name.into().try_into()
|
name.into().try_into()
|
||||||
}
|
}
|
||||||
@ -27,7 +26,7 @@ impl FnPtr {
|
|||||||
#[inline(always)]
|
#[inline(always)]
|
||||||
#[must_use]
|
#[must_use]
|
||||||
pub(crate) fn new_unchecked(name: Identifier, curry: StaticVec<Dynamic>) -> Self {
|
pub(crate) fn new_unchecked(name: Identifier, curry: StaticVec<Dynamic>) -> Self {
|
||||||
Self(name.into(), curry)
|
Self(name, curry)
|
||||||
}
|
}
|
||||||
/// Get the name of the function.
|
/// Get the name of the function.
|
||||||
#[inline(always)]
|
#[inline(always)]
|
||||||
@ -97,7 +96,6 @@ impl FnPtr {
|
|||||||
/// Do not use the arguments after this call. If they are needed afterwards,
|
/// Do not use the arguments after this call. If they are needed afterwards,
|
||||||
/// clone them _before_ calling this function.
|
/// clone them _before_ calling this function.
|
||||||
#[inline]
|
#[inline]
|
||||||
#[must_use]
|
|
||||||
pub fn call_dynamic(
|
pub fn call_dynamic(
|
||||||
&self,
|
&self,
|
||||||
ctx: &NativeCallContext,
|
ctx: &NativeCallContext,
|
||||||
|
@ -255,12 +255,10 @@ impl Add<&str> for ImmutableString {
|
|||||||
|
|
||||||
#[inline]
|
#[inline]
|
||||||
fn add(mut self, rhs: &str) -> Self::Output {
|
fn add(mut self, rhs: &str) -> Self::Output {
|
||||||
if rhs.is_empty() {
|
if !rhs.is_empty() {
|
||||||
self
|
|
||||||
} else {
|
|
||||||
self.make_mut().push_str(rhs);
|
self.make_mut().push_str(rhs);
|
||||||
self
|
|
||||||
}
|
}
|
||||||
|
self
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@ -457,7 +457,6 @@ impl Module {
|
|||||||
/// Get a reference to a namespace-qualified variable.
|
/// Get a reference to a namespace-qualified variable.
|
||||||
/// Name and Position in [`EvalAltResult`] are [`None`] and [`NONE`][Position::NONE] and must be set afterwards.
|
/// Name and Position in [`EvalAltResult`] are [`None`] and [`NONE`][Position::NONE] and must be set afterwards.
|
||||||
#[inline(always)]
|
#[inline(always)]
|
||||||
#[must_use]
|
|
||||||
pub(crate) fn get_qualified_var(&self, hash_var: u64) -> Result<&Dynamic, Box<EvalAltResult>> {
|
pub(crate) fn get_qualified_var(&self, hash_var: u64) -> Result<&Dynamic, Box<EvalAltResult>> {
|
||||||
self.all_variables.get(&hash_var).ok_or_else(|| {
|
self.all_variables.get(&hash_var).ok_or_else(|| {
|
||||||
EvalAltResult::ErrorVariableNotFound(String::new(), Position::NONE).into()
|
EvalAltResult::ErrorVariableNotFound(String::new(), Position::NONE).into()
|
||||||
@ -1207,7 +1206,7 @@ impl Module {
|
|||||||
/// Merge another [`Module`] into this [`Module`].
|
/// Merge another [`Module`] into this [`Module`].
|
||||||
#[inline(always)]
|
#[inline(always)]
|
||||||
pub fn merge(&mut self, other: &Self) -> &mut Self {
|
pub fn merge(&mut self, other: &Self) -> &mut Self {
|
||||||
self.merge_filtered(other, &mut |_, _, _, _, _| true)
|
self.merge_filtered(other, &|_, _, _, _, _| true)
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Merge another [`Module`] into this [`Module`] based on a filter predicate.
|
/// Merge another [`Module`] into this [`Module`] based on a filter predicate.
|
||||||
@ -1292,14 +1291,12 @@ impl Module {
|
|||||||
|
|
||||||
/// Get an iterator to the sub-modules in the [`Module`].
|
/// Get an iterator to the sub-modules in the [`Module`].
|
||||||
#[inline(always)]
|
#[inline(always)]
|
||||||
#[must_use]
|
|
||||||
pub fn iter_sub_modules(&self) -> impl Iterator<Item = (&str, Shared<Module>)> {
|
pub fn iter_sub_modules(&self) -> impl Iterator<Item = (&str, Shared<Module>)> {
|
||||||
self.modules.iter().map(|(k, m)| (k.as_str(), m.clone()))
|
self.modules.iter().map(|(k, m)| (k.as_str(), m.clone()))
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Get an iterator to the variables in the [`Module`].
|
/// Get an iterator to the variables in the [`Module`].
|
||||||
#[inline(always)]
|
#[inline(always)]
|
||||||
#[must_use]
|
|
||||||
pub fn iter_var(&self) -> impl Iterator<Item = (&str, &Dynamic)> {
|
pub fn iter_var(&self) -> impl Iterator<Item = (&str, &Dynamic)> {
|
||||||
self.variables.iter().map(|(k, v)| (k.as_str(), v))
|
self.variables.iter().map(|(k, v)| (k.as_str(), v))
|
||||||
}
|
}
|
||||||
@ -1307,7 +1304,6 @@ impl Module {
|
|||||||
/// Get an iterator to the functions in the [`Module`].
|
/// Get an iterator to the functions in the [`Module`].
|
||||||
#[inline(always)]
|
#[inline(always)]
|
||||||
#[allow(dead_code)]
|
#[allow(dead_code)]
|
||||||
#[must_use]
|
|
||||||
pub(crate) fn iter_fn(&self) -> impl Iterator<Item = &FuncInfo> {
|
pub(crate) fn iter_fn(&self) -> impl Iterator<Item = &FuncInfo> {
|
||||||
self.functions.values().map(Box::as_ref)
|
self.functions.values().map(Box::as_ref)
|
||||||
}
|
}
|
||||||
@ -1322,7 +1318,6 @@ impl Module {
|
|||||||
/// 5) Shared reference to function definition [`ScriptFnDef`][crate::ast::ScriptFnDef].
|
/// 5) Shared reference to function definition [`ScriptFnDef`][crate::ast::ScriptFnDef].
|
||||||
#[cfg(not(feature = "no_function"))]
|
#[cfg(not(feature = "no_function"))]
|
||||||
#[inline(always)]
|
#[inline(always)]
|
||||||
#[must_use]
|
|
||||||
pub(crate) fn iter_script_fn(
|
pub(crate) fn iter_script_fn(
|
||||||
&self,
|
&self,
|
||||||
) -> impl Iterator<
|
) -> impl Iterator<
|
||||||
@ -1360,7 +1355,6 @@ impl Module {
|
|||||||
#[cfg(not(feature = "no_function"))]
|
#[cfg(not(feature = "no_function"))]
|
||||||
#[cfg(not(feature = "internals"))]
|
#[cfg(not(feature = "internals"))]
|
||||||
#[inline(always)]
|
#[inline(always)]
|
||||||
#[must_use]
|
|
||||||
pub fn iter_script_fn_info(
|
pub fn iter_script_fn_info(
|
||||||
&self,
|
&self,
|
||||||
) -> impl Iterator<Item = (FnNamespace, FnAccess, &str, usize)> {
|
) -> impl Iterator<Item = (FnNamespace, FnAccess, &str, usize)> {
|
||||||
@ -1419,7 +1413,6 @@ impl Module {
|
|||||||
/// # }
|
/// # }
|
||||||
/// ```
|
/// ```
|
||||||
#[cfg(not(feature = "no_module"))]
|
#[cfg(not(feature = "no_module"))]
|
||||||
#[must_use]
|
|
||||||
pub fn eval_ast_as_new(
|
pub fn eval_ast_as_new(
|
||||||
mut scope: crate::Scope,
|
mut scope: crate::Scope,
|
||||||
ast: &crate::AST,
|
ast: &crate::AST,
|
||||||
@ -1529,13 +1522,13 @@ impl Module {
|
|||||||
|
|
||||||
// Index all variables
|
// Index all variables
|
||||||
module.variables.iter().for_each(|(var_name, value)| {
|
module.variables.iter().for_each(|(var_name, value)| {
|
||||||
let hash_var = crate::calc_qualified_var_hash(path.iter().map(|&v| v), var_name);
|
let hash_var = crate::calc_qualified_var_hash(path.iter().copied(), var_name);
|
||||||
variables.insert(hash_var, value.clone());
|
variables.insert(hash_var, value.clone());
|
||||||
});
|
});
|
||||||
|
|
||||||
// Index type iterators
|
// Index type iterators
|
||||||
module.type_iterators.iter().for_each(|(&type_id, func)| {
|
module.type_iterators.iter().for_each(|(&type_id, func)| {
|
||||||
type_iterators.insert(type_id, func.clone());
|
type_iterators.insert(type_id, *func);
|
||||||
contains_indexed_global_functions = true;
|
contains_indexed_global_functions = true;
|
||||||
});
|
});
|
||||||
|
|
||||||
@ -1614,7 +1607,7 @@ impl Module {
|
|||||||
#[inline]
|
#[inline]
|
||||||
pub fn set_iter(&mut self, type_id: TypeId, func: IteratorFn) -> &mut Self {
|
pub fn set_iter(&mut self, type_id: TypeId, func: IteratorFn) -> &mut Self {
|
||||||
if self.indexed {
|
if self.indexed {
|
||||||
self.all_type_iterators.insert(type_id, func.clone());
|
self.all_type_iterators.insert(type_id, func);
|
||||||
self.contains_indexed_global_functions = true;
|
self.contains_indexed_global_functions = true;
|
||||||
}
|
}
|
||||||
self.type_iterators.insert(type_id, func);
|
self.type_iterators.insert(type_id, func);
|
||||||
|
@ -77,16 +77,9 @@ impl ModuleResolversCollection {
|
|||||||
}
|
}
|
||||||
/// Get an iterator of all the [module resolvers][ModuleResolver].
|
/// Get an iterator of all the [module resolvers][ModuleResolver].
|
||||||
#[inline(always)]
|
#[inline(always)]
|
||||||
#[must_use]
|
|
||||||
pub fn iter(&self) -> impl Iterator<Item = &dyn ModuleResolver> {
|
pub fn iter(&self) -> impl Iterator<Item = &dyn ModuleResolver> {
|
||||||
self.0.iter().map(|v| v.as_ref())
|
self.0.iter().map(|v| v.as_ref())
|
||||||
}
|
}
|
||||||
/// Get a mutable iterator of all the [module resolvers][ModuleResolver].
|
|
||||||
#[inline(always)]
|
|
||||||
#[must_use]
|
|
||||||
pub fn into_iter(self) -> impl Iterator<Item = Box<dyn ModuleResolver>> {
|
|
||||||
self.0.into_iter()
|
|
||||||
}
|
|
||||||
/// Remove all [module resolvers][ModuleResolver].
|
/// Remove all [module resolvers][ModuleResolver].
|
||||||
#[inline(always)]
|
#[inline(always)]
|
||||||
pub fn clear(&mut self) -> &mut Self {
|
pub fn clear(&mut self) -> &mut Self {
|
||||||
@ -114,6 +107,16 @@ impl ModuleResolversCollection {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
impl IntoIterator for ModuleResolversCollection {
|
||||||
|
type Item = Box<dyn ModuleResolver>;
|
||||||
|
type IntoIter = std::vec::IntoIter<Box<dyn ModuleResolver>>;
|
||||||
|
|
||||||
|
#[inline(always)]
|
||||||
|
fn into_iter(self) -> Self::IntoIter {
|
||||||
|
self.0.into_iter()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
impl ModuleResolver for ModuleResolversCollection {
|
impl ModuleResolver for ModuleResolversCollection {
|
||||||
fn resolve(
|
fn resolve(
|
||||||
&self,
|
&self,
|
||||||
|
@ -23,7 +23,6 @@ pub use stat::StaticModuleResolver;
|
|||||||
/// Trait that encapsulates a module resolution service.
|
/// Trait that encapsulates a module resolution service.
|
||||||
pub trait ModuleResolver: SendSync {
|
pub trait ModuleResolver: SendSync {
|
||||||
/// Resolve a module based on a path string.
|
/// Resolve a module based on a path string.
|
||||||
#[must_use]
|
|
||||||
fn resolve(
|
fn resolve(
|
||||||
&self,
|
&self,
|
||||||
engine: &Engine,
|
engine: &Engine,
|
||||||
|
@ -64,33 +64,28 @@ impl StaticModuleResolver {
|
|||||||
}
|
}
|
||||||
/// Get an iterator of all the [modules][Module].
|
/// Get an iterator of all the [modules][Module].
|
||||||
#[inline(always)]
|
#[inline(always)]
|
||||||
#[must_use]
|
|
||||||
pub fn iter(&self) -> impl Iterator<Item = (&str, &Shared<Module>)> {
|
pub fn iter(&self) -> impl Iterator<Item = (&str, &Shared<Module>)> {
|
||||||
self.0.iter().map(|(k, v)| (k.as_str(), v))
|
self.0.iter().map(|(k, v)| (k.as_str(), v))
|
||||||
}
|
}
|
||||||
/// Get a mutable iterator of all the [modules][Module].
|
/// Get a mutable iterator of all the [modules][Module].
|
||||||
#[inline(always)]
|
#[inline(always)]
|
||||||
#[must_use]
|
|
||||||
pub fn iter_mut(&mut self) -> impl Iterator<Item = (&str, &mut Shared<Module>)> {
|
pub fn iter_mut(&mut self) -> impl Iterator<Item = (&str, &mut Shared<Module>)> {
|
||||||
self.0.iter_mut().map(|(k, v)| (k.as_str(), v))
|
self.0.iter_mut().map(|(k, v)| (k.as_str(), v))
|
||||||
}
|
}
|
||||||
/// Get a mutable iterator of all the modules.
|
/// Get a mutable iterator of all the modules.
|
||||||
#[inline(always)]
|
#[inline(always)]
|
||||||
#[must_use]
|
|
||||||
pub fn into_iter(self) -> impl Iterator<Item = (Identifier, Shared<Module>)> {
|
pub fn into_iter(self) -> impl Iterator<Item = (Identifier, Shared<Module>)> {
|
||||||
self.0.into_iter()
|
self.0.into_iter()
|
||||||
}
|
}
|
||||||
/// Get an iterator of all the [module][Module] paths.
|
/// Get an iterator of all the [module][Module] paths.
|
||||||
#[inline(always)]
|
#[inline(always)]
|
||||||
#[must_use]
|
|
||||||
pub fn paths(&self) -> impl Iterator<Item = &str> {
|
pub fn paths(&self) -> impl Iterator<Item = &str> {
|
||||||
self.0.keys().map(|s| s.as_str())
|
self.0.keys().map(|s| s.as_str())
|
||||||
}
|
}
|
||||||
/// Get an iterator of all the [modules][Module].
|
/// Get an iterator of all the [modules][Module].
|
||||||
#[inline(always)]
|
#[inline(always)]
|
||||||
#[must_use]
|
|
||||||
pub fn values(&self) -> impl Iterator<Item = &Shared<Module>> {
|
pub fn values(&self) -> impl Iterator<Item = &Shared<Module>> {
|
||||||
self.0.values().map(|m| m)
|
self.0.values()
|
||||||
}
|
}
|
||||||
/// Remove all [modules][Module].
|
/// Remove all [modules][Module].
|
||||||
#[inline(always)]
|
#[inline(always)]
|
||||||
|
@ -130,7 +130,7 @@ impl<'a> OptimizerState<'a> {
|
|||||||
) -> Option<Dynamic> {
|
) -> Option<Dynamic> {
|
||||||
self.engine
|
self.engine
|
||||||
.call_native_fn(
|
.call_native_fn(
|
||||||
&mut Default::default(),
|
&Default::default(),
|
||||||
&mut Default::default(),
|
&mut Default::default(),
|
||||||
self.lib,
|
self.lib,
|
||||||
fn_name,
|
fn_name,
|
||||||
@ -713,7 +713,7 @@ fn optimize_expr(expr: &mut Expr, state: &mut OptimizerState, _chaining: bool) {
|
|||||||
// Map literal where everything is pure - promote the indexed item.
|
// Map literal where everything is pure - promote the indexed item.
|
||||||
// All other items can be thrown away.
|
// All other items can be thrown away.
|
||||||
state.set_dirty();
|
state.set_dirty();
|
||||||
*expr = mem::take(&mut m.0).into_iter().find(|(x, _)| &x.name == prop)
|
*expr = mem::take(&mut m.0).into_iter().find(|(x, _)| x.name == prop)
|
||||||
.map(|(_, mut expr)| { expr.set_position(*pos); expr })
|
.map(|(_, mut expr)| { expr.set_position(*pos); expr })
|
||||||
.unwrap_or_else(|| Expr::Unit(*pos));
|
.unwrap_or_else(|| Expr::Unit(*pos));
|
||||||
}
|
}
|
||||||
|
@ -155,7 +155,7 @@ mod array_functions {
|
|||||||
len as usize
|
len as usize
|
||||||
};
|
};
|
||||||
|
|
||||||
array[start..start + len].iter().cloned().collect()
|
array[start..start + len].to_vec()
|
||||||
}
|
}
|
||||||
#[rhai_fn(name = "extract")]
|
#[rhai_fn(name = "extract")]
|
||||||
pub fn extract_tail(array: &mut Array, start: INT) -> Array {
|
pub fn extract_tail(array: &mut Array, start: INT) -> Array {
|
||||||
@ -170,7 +170,7 @@ mod array_functions {
|
|||||||
start as usize
|
start as usize
|
||||||
};
|
};
|
||||||
|
|
||||||
array[start..].iter().cloned().collect()
|
array[start..].to_vec()
|
||||||
}
|
}
|
||||||
#[rhai_fn(name = "split")]
|
#[rhai_fn(name = "split")]
|
||||||
pub fn split_at(array: &mut Array, start: INT) -> Array {
|
pub fn split_at(array: &mut Array, start: INT) -> Array {
|
||||||
|
@ -50,14 +50,11 @@ fn collect_fn_metadata(ctx: NativeCallContext) -> crate::Array {
|
|||||||
let mut map = Map::new();
|
let mut map = Map::new();
|
||||||
|
|
||||||
if let Some(ns) = namespace {
|
if let Some(ns) = namespace {
|
||||||
map.insert(dict.get("namespace").expect(DICT).clone().into(), 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(
|
map.insert(
|
||||||
dict.get("name").expect(DICT).clone().into(),
|
dict.get("access").expect(DICT).clone(),
|
||||||
f.name.clone().into(),
|
|
||||||
);
|
|
||||||
map.insert(
|
|
||||||
dict.get("access").expect(DICT).clone().into(),
|
|
||||||
match f.access {
|
match f.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(),
|
||||||
@ -65,11 +62,11 @@ fn collect_fn_metadata(ctx: NativeCallContext) -> crate::Array {
|
|||||||
.into(),
|
.into(),
|
||||||
);
|
);
|
||||||
map.insert(
|
map.insert(
|
||||||
dict.get("is_anonymous").expect(DICT).clone().into(),
|
dict.get("is_anonymous").expect(DICT).clone(),
|
||||||
f.name.starts_with(crate::engine::FN_ANONYMOUS).into(),
|
f.name.starts_with(crate::engine::FN_ANONYMOUS).into(),
|
||||||
);
|
);
|
||||||
map.insert(
|
map.insert(
|
||||||
dict.get("params").expect(DICT).clone().into(),
|
dict.get("params").expect(DICT).clone(),
|
||||||
f.params
|
f.params
|
||||||
.iter()
|
.iter()
|
||||||
.cloned()
|
.cloned()
|
||||||
@ -78,7 +75,7 @@ fn collect_fn_metadata(ctx: NativeCallContext) -> crate::Array {
|
|||||||
.into(),
|
.into(),
|
||||||
);
|
);
|
||||||
|
|
||||||
map.into()
|
map
|
||||||
}
|
}
|
||||||
|
|
||||||
// Intern strings
|
// Intern strings
|
||||||
|
@ -54,31 +54,19 @@ where
|
|||||||
None
|
None
|
||||||
} else if self.0 < self.1 {
|
} else if self.0 < self.1 {
|
||||||
#[cfg(not(feature = "unchecked"))]
|
#[cfg(not(feature = "unchecked"))]
|
||||||
let diff1 = if let Some(diff) = self.1.checked_sub(&self.0) {
|
let diff1 = self.1.checked_sub(&self.0)?;
|
||||||
diff
|
|
||||||
} else {
|
|
||||||
return None;
|
|
||||||
};
|
|
||||||
#[cfg(feature = "unchecked")]
|
#[cfg(feature = "unchecked")]
|
||||||
let diff1 = self.1 - self.0;
|
let diff1 = self.1 - self.0;
|
||||||
|
|
||||||
let v = self.0;
|
let v = self.0;
|
||||||
|
|
||||||
#[cfg(not(feature = "unchecked"))]
|
#[cfg(not(feature = "unchecked"))]
|
||||||
let n = if let Some(num) = self.0.checked_add(&self.2) {
|
let n = self.0.checked_add(&self.2)?;
|
||||||
num
|
|
||||||
} else {
|
|
||||||
return None;
|
|
||||||
};
|
|
||||||
#[cfg(feature = "unchecked")]
|
#[cfg(feature = "unchecked")]
|
||||||
let n = self.0 + self.2;
|
let n = self.0 + self.2;
|
||||||
|
|
||||||
#[cfg(not(feature = "unchecked"))]
|
#[cfg(not(feature = "unchecked"))]
|
||||||
let diff2 = if let Some(diff) = self.1.checked_sub(&n) {
|
let diff2 = self.1.checked_sub(&n)?;
|
||||||
diff
|
|
||||||
} else {
|
|
||||||
return None;
|
|
||||||
};
|
|
||||||
#[cfg(feature = "unchecked")]
|
#[cfg(feature = "unchecked")]
|
||||||
let diff2 = self.1 - n;
|
let diff2 = self.1 - n;
|
||||||
|
|
||||||
@ -90,31 +78,19 @@ where
|
|||||||
}
|
}
|
||||||
} else {
|
} else {
|
||||||
#[cfg(not(feature = "unchecked"))]
|
#[cfg(not(feature = "unchecked"))]
|
||||||
let diff1 = if let Some(diff) = self.0.checked_sub(&self.1) {
|
let diff1 = self.0.checked_sub(&self.1)?;
|
||||||
diff
|
|
||||||
} else {
|
|
||||||
return None;
|
|
||||||
};
|
|
||||||
#[cfg(feature = "unchecked")]
|
#[cfg(feature = "unchecked")]
|
||||||
let diff1 = self.0 - self.1;
|
let diff1 = self.0 - self.1;
|
||||||
|
|
||||||
let v = self.0;
|
let v = self.0;
|
||||||
|
|
||||||
#[cfg(not(feature = "unchecked"))]
|
#[cfg(not(feature = "unchecked"))]
|
||||||
let n = if let Some(num) = self.0.checked_add(&self.2) {
|
let n = self.0.checked_add(&self.2)?;
|
||||||
num
|
|
||||||
} else {
|
|
||||||
return None;
|
|
||||||
};
|
|
||||||
#[cfg(feature = "unchecked")]
|
#[cfg(feature = "unchecked")]
|
||||||
let n = self.0 + self.2;
|
let n = self.0 + self.2;
|
||||||
|
|
||||||
#[cfg(not(feature = "unchecked"))]
|
#[cfg(not(feature = "unchecked"))]
|
||||||
let diff2 = if let Some(diff) = n.checked_sub(&self.1) {
|
let diff2 = n.checked_sub(&self.1)?;
|
||||||
diff
|
|
||||||
} else {
|
|
||||||
return None;
|
|
||||||
};
|
|
||||||
#[cfg(feature = "unchecked")]
|
#[cfg(feature = "unchecked")]
|
||||||
let diff2 = n - self.1;
|
let diff2 = n - self.1;
|
||||||
|
|
||||||
@ -395,7 +371,7 @@ def_package!(crate:BasicIteratorPackage:"Basic range iterators.", lib, {
|
|||||||
|
|
||||||
lib.set_iterator::<StepFloatRange>();
|
lib.set_iterator::<StepFloatRange>();
|
||||||
|
|
||||||
let _hash = lib.set_native_fn("range", |from, to, step| StepFloatRange::new(from, to, step));
|
let _hash = lib.set_native_fn("range", StepFloatRange::new);
|
||||||
#[cfg(feature = "metadata")]
|
#[cfg(feature = "metadata")]
|
||||||
lib.update_fn_metadata(_hash, &["from: FLOAT", "to: FLOAT", "step: FLOAT", "Iterator<Item=FLOAT>"]);
|
lib.update_fn_metadata(_hash, &["from: FLOAT", "to: FLOAT", "step: FLOAT", "Iterator<Item=FLOAT>"]);
|
||||||
}
|
}
|
||||||
@ -457,7 +433,7 @@ def_package!(crate:BasicIteratorPackage:"Basic range iterators.", lib, {
|
|||||||
|
|
||||||
lib.set_iterator::<StepDecimalRange>();
|
lib.set_iterator::<StepDecimalRange>();
|
||||||
|
|
||||||
let _hash = lib.set_native_fn("range", |from, to, step| StepDecimalRange::new(from, to, step));
|
let _hash = lib.set_native_fn("range", StepDecimalRange::new);
|
||||||
#[cfg(feature = "metadata")]
|
#[cfg(feature = "metadata")]
|
||||||
lib.update_fn_metadata(_hash, &["from: Decimal", "to: Decimal", "step: Decimal", "Iterator<Item=Decimal>"]);
|
lib.update_fn_metadata(_hash, &["from: Decimal", "to: Decimal", "step: Decimal", "Iterator<Item=Decimal>"]);
|
||||||
}
|
}
|
||||||
@ -480,7 +456,7 @@ def_package!(crate:BasicIteratorPackage:"Basic range iterators.", lib, {
|
|||||||
// Register bit-field iterator
|
// Register bit-field iterator
|
||||||
lib.set_iterator::<BitRange>();
|
lib.set_iterator::<BitRange>();
|
||||||
|
|
||||||
let _hash = lib.set_native_fn("bits", |value, from, len| BitRange::new(value, from, len));
|
let _hash = lib.set_native_fn("bits", BitRange::new);
|
||||||
#[cfg(feature = "metadata")]
|
#[cfg(feature = "metadata")]
|
||||||
lib.update_fn_metadata(_hash, &["value: INT", "from: INT", "len: INT", "Iterator<Item=bool>"]);
|
lib.update_fn_metadata(_hash, &["value: INT", "from: INT", "len: INT", "Iterator<Item=bool>"]);
|
||||||
|
|
||||||
|
@ -113,7 +113,7 @@ def_package!(crate:BasicMathPackage:"Basic mathematic functions.", lib, {
|
|||||||
mod int_functions {
|
mod int_functions {
|
||||||
#[rhai_fn(name = "parse_int", return_raw)]
|
#[rhai_fn(name = "parse_int", return_raw)]
|
||||||
pub fn parse_int_radix(s: &str, radix: INT) -> Result<INT, Box<EvalAltResult>> {
|
pub fn parse_int_radix(s: &str, radix: INT) -> Result<INT, Box<EvalAltResult>> {
|
||||||
if radix < 2 || radix > 36 {
|
if !(2..=36).contains(&radix) {
|
||||||
return EvalAltResult::ErrorArithmetic(
|
return EvalAltResult::ErrorArithmetic(
|
||||||
format!("Invalid radix: '{}'", radix),
|
format!("Invalid radix: '{}'", radix),
|
||||||
Position::NONE,
|
Position::NONE,
|
||||||
|
@ -79,8 +79,13 @@ macro_rules! def_package {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
impl Default for $package {
|
||||||
|
fn default() -> Self {
|
||||||
|
Self::new()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
impl $package {
|
impl $package {
|
||||||
#[allow(dead_code)]
|
|
||||||
pub fn new() -> Self {
|
pub fn new() -> Self {
|
||||||
let mut module = $root::Module::new();
|
let mut module = $root::Module::new();
|
||||||
<Self as $root::packages::Package>::init(&mut module);
|
<Self as $root::packages::Package>::init(&mut module);
|
||||||
|
@ -12,8 +12,8 @@ use crate::Array;
|
|||||||
#[cfg(not(feature = "no_object"))]
|
#[cfg(not(feature = "no_object"))]
|
||||||
use crate::Map;
|
use crate::Map;
|
||||||
|
|
||||||
pub const FUNC_TO_STRING: &'static str = "to_string";
|
pub const FUNC_TO_STRING: &str = "to_string";
|
||||||
pub const FUNC_TO_DEBUG: &'static str = "to_debug";
|
pub const FUNC_TO_DEBUG: &str = "to_debug";
|
||||||
|
|
||||||
def_package!(crate:BasicStringPackage:"Basic string utilities, including printing.", lib, {
|
def_package!(crate:BasicStringPackage:"Basic string utilities, including printing.", lib, {
|
||||||
combine_with_exported_module!(lib, "print_debug", print_debug_functions);
|
combine_with_exported_module!(lib, "print_debug", print_debug_functions);
|
||||||
@ -106,7 +106,7 @@ mod print_debug_functions {
|
|||||||
pub fn format_array(ctx: NativeCallContext, array: &mut Array) -> ImmutableString {
|
pub fn format_array(ctx: NativeCallContext, array: &mut Array) -> ImmutableString {
|
||||||
let len = array.len();
|
let len = array.len();
|
||||||
let mut result = String::with_capacity(len * 5 + 2);
|
let mut result = String::with_capacity(len * 5 + 2);
|
||||||
result.push_str("[");
|
result.push('[');
|
||||||
|
|
||||||
array.iter_mut().enumerate().for_each(|(i, x)| {
|
array.iter_mut().enumerate().for_each(|(i, x)| {
|
||||||
result.push_str(&print_with_func(FUNC_TO_DEBUG, &ctx, x));
|
result.push_str(&print_with_func(FUNC_TO_DEBUG, &ctx, x));
|
||||||
@ -115,7 +115,7 @@ mod print_debug_functions {
|
|||||||
}
|
}
|
||||||
});
|
});
|
||||||
|
|
||||||
result.push_str("]");
|
result.push(']');
|
||||||
result.into()
|
result.into()
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@ -144,7 +144,7 @@ mod print_debug_functions {
|
|||||||
));
|
));
|
||||||
});
|
});
|
||||||
|
|
||||||
result.push_str("}");
|
result.push('}');
|
||||||
result.into()
|
result.into()
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
@ -38,12 +38,11 @@ mod string_functions {
|
|||||||
) -> ImmutableString {
|
) -> ImmutableString {
|
||||||
let mut s = print_with_func(FUNC_TO_STRING, &ctx, item);
|
let mut s = print_with_func(FUNC_TO_STRING, &ctx, item);
|
||||||
|
|
||||||
if string.is_empty() {
|
if !string.is_empty() {
|
||||||
s
|
|
||||||
} else {
|
|
||||||
s.make_mut().push_str(string);
|
s.make_mut().push_str(string);
|
||||||
s.into()
|
|
||||||
}
|
}
|
||||||
|
|
||||||
|
s
|
||||||
}
|
}
|
||||||
|
|
||||||
#[rhai_fn(name = "+", name = "append")]
|
#[rhai_fn(name = "+", name = "append")]
|
||||||
@ -240,7 +239,7 @@ mod string_functions {
|
|||||||
let mut chars = StaticVec::with_capacity(string.len());
|
let mut chars = StaticVec::with_capacity(string.len());
|
||||||
|
|
||||||
let offset = if string.is_empty() || len <= 0 {
|
let offset = if string.is_empty() || len <= 0 {
|
||||||
return ctx.engine().empty_string.clone().into();
|
return ctx.engine().empty_string.clone();
|
||||||
} else if start < 0 {
|
} else if start < 0 {
|
||||||
if let Some(n) = start.checked_abs() {
|
if let Some(n) = start.checked_abs() {
|
||||||
chars.extend(string.chars());
|
chars.extend(string.chars());
|
||||||
@ -253,7 +252,7 @@ mod string_functions {
|
|||||||
0
|
0
|
||||||
}
|
}
|
||||||
} else if start as usize >= string.chars().count() {
|
} else if start as usize >= string.chars().count() {
|
||||||
return ctx.engine().empty_string.clone().into();
|
return ctx.engine().empty_string.clone();
|
||||||
} else {
|
} else {
|
||||||
start as usize
|
start as usize
|
||||||
};
|
};
|
||||||
|
35
src/parse.rs
35
src/parse.rs
@ -243,7 +243,6 @@ impl ParseSettings {
|
|||||||
/// Make sure that the current level of expression nesting is within the maximum limit.
|
/// Make sure that the current level of expression nesting is within the maximum limit.
|
||||||
#[cfg(not(feature = "unchecked"))]
|
#[cfg(not(feature = "unchecked"))]
|
||||||
#[inline]
|
#[inline]
|
||||||
#[must_use]
|
|
||||||
pub fn ensure_level_within_max_limit(
|
pub fn ensure_level_within_max_limit(
|
||||||
&self,
|
&self,
|
||||||
limit: Option<NonZeroUsize>,
|
limit: Option<NonZeroUsize>,
|
||||||
@ -412,7 +411,7 @@ fn parse_paren_expr(
|
|||||||
// ( xxx )
|
// ( xxx )
|
||||||
(Token::RightParen, _) => Ok(expr),
|
(Token::RightParen, _) => Ok(expr),
|
||||||
// ( <error>
|
// ( <error>
|
||||||
(Token::LexError(err), pos) => return Err(err.into_err(pos)),
|
(Token::LexError(err), pos) => Err(err.into_err(pos)),
|
||||||
// ( xxx ???
|
// ( xxx ???
|
||||||
(_, pos) => Err(PERR::MissingToken(
|
(_, pos) => Err(PERR::MissingToken(
|
||||||
Token::RightParen.into(),
|
Token::RightParen.into(),
|
||||||
@ -712,7 +711,7 @@ fn parse_index_chain(
|
|||||||
)),
|
)),
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
(Token::LexError(err), pos) => return Err(err.clone().into_err(*pos)),
|
(Token::LexError(err), pos) => Err(err.clone().into_err(*pos)),
|
||||||
(_, pos) => Err(PERR::MissingToken(
|
(_, pos) => Err(PERR::MissingToken(
|
||||||
Token::RightBracket.into(),
|
Token::RightBracket.into(),
|
||||||
"for a matching [ in this index expression".into(),
|
"for a matching [ in this index expression".into(),
|
||||||
@ -880,7 +879,7 @@ fn parse_map_literal(
|
|||||||
|
|
||||||
let expr = parse_expr(input, state, lib, settings.level_up())?;
|
let expr = parse_expr(input, state, lib, settings.level_up())?;
|
||||||
let name = state.get_identifier(name);
|
let name = state.get_identifier(name);
|
||||||
template.insert(name.clone().into(), Default::default());
|
template.insert(name.clone(), Default::default());
|
||||||
map.push((Ident { name, pos }, expr));
|
map.push((Ident { name, pos }, expr));
|
||||||
|
|
||||||
match input.peek().expect(NEVER_ENDS) {
|
match input.peek().expect(NEVER_ENDS) {
|
||||||
@ -1087,7 +1086,7 @@ fn parse_primary(
|
|||||||
},
|
},
|
||||||
#[cfg(not(feature = "no_float"))]
|
#[cfg(not(feature = "no_float"))]
|
||||||
Token::FloatConstant(x) => {
|
Token::FloatConstant(x) => {
|
||||||
let x = (*x).into();
|
let x = *x;
|
||||||
input.next().expect(NEVER_ENDS);
|
input.next().expect(NEVER_ENDS);
|
||||||
Expr::FloatConstant(x, settings.pos)
|
Expr::FloatConstant(x, settings.pos)
|
||||||
}
|
}
|
||||||
@ -1410,15 +1409,17 @@ fn parse_primary(
|
|||||||
}
|
}
|
||||||
|
|
||||||
// Cache the hash key for namespace-qualified variables
|
// Cache the hash key for namespace-qualified variables
|
||||||
match root_expr {
|
let namespaced_variable = match root_expr {
|
||||||
Expr::Variable(_, _, ref mut x) if x.1.is_some() => Some(x.as_mut()),
|
Expr::Variable(_, _, ref mut x) if x.1.is_some() => Some(x.as_mut()),
|
||||||
Expr::Index(ref mut x, _, _) | Expr::Dot(ref mut x, _, _) => match x.lhs {
|
Expr::Index(ref mut x, _, _) | Expr::Dot(ref mut x, _, _) => match x.lhs {
|
||||||
Expr::Variable(_, _, ref mut x) if x.1.is_some() => Some(x.as_mut()),
|
Expr::Variable(_, _, ref mut x) if x.1.is_some() => Some(x.as_mut()),
|
||||||
_ => None,
|
_ => None,
|
||||||
},
|
},
|
||||||
_ => None,
|
_ => None,
|
||||||
}
|
};
|
||||||
.map(|x| match x {
|
|
||||||
|
if let Some(x) = namespaced_variable {
|
||||||
|
match x {
|
||||||
(_, Some((namespace, hash)), name) => {
|
(_, Some((namespace, hash)), name) => {
|
||||||
*hash = calc_qualified_var_hash(namespace.iter().map(|v| v.name.as_str()), name);
|
*hash = calc_qualified_var_hash(namespace.iter().map(|v| v.name.as_str()), name);
|
||||||
|
|
||||||
@ -1426,7 +1427,8 @@ fn parse_primary(
|
|||||||
namespace.set_index(state.find_module(&namespace[0].name));
|
namespace.set_index(state.find_module(&namespace[0].name));
|
||||||
}
|
}
|
||||||
_ => unreachable!("expecting namespace-qualified variable access"),
|
_ => unreachable!("expecting namespace-qualified variable access"),
|
||||||
});
|
}
|
||||||
|
}
|
||||||
|
|
||||||
// Make sure identifiers are valid
|
// Make sure identifiers are valid
|
||||||
Ok(root_expr)
|
Ok(root_expr)
|
||||||
@ -1531,7 +1533,7 @@ fn parse_unary(
|
|||||||
}
|
}
|
||||||
|
|
||||||
/// Make an assignment statement.
|
/// Make an assignment statement.
|
||||||
fn make_assignment_stmt<'a>(
|
fn make_assignment_stmt(
|
||||||
op: Option<Token>,
|
op: Option<Token>,
|
||||||
state: &mut ParseState,
|
state: &mut ParseState,
|
||||||
lhs: Expr,
|
lhs: Expr,
|
||||||
@ -1556,7 +1558,7 @@ fn make_assignment_stmt<'a>(
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
let op_info = op.map(|v| OpAssignment::new(v));
|
let op_info = op.map(OpAssignment::new);
|
||||||
|
|
||||||
match lhs {
|
match lhs {
|
||||||
// const_expr = rhs
|
// const_expr = rhs
|
||||||
@ -2717,7 +2719,7 @@ fn parse_stmt(
|
|||||||
is_function_scope: true,
|
is_function_scope: true,
|
||||||
is_breakable: false,
|
is_breakable: false,
|
||||||
level: 0,
|
level: 0,
|
||||||
pos: pos,
|
pos,
|
||||||
};
|
};
|
||||||
|
|
||||||
let func = parse_fn(
|
let func = parse_fn(
|
||||||
@ -3035,8 +3037,7 @@ fn parse_anon_fn(
|
|||||||
|
|
||||||
let mut params_list: StaticVec<_> = Default::default();
|
let mut params_list: StaticVec<_> = Default::default();
|
||||||
|
|
||||||
if input.next().expect(NEVER_ENDS).0 != Token::Or {
|
if input.next().expect(NEVER_ENDS).0 != Token::Or && !match_token(input, Token::Pipe).0 {
|
||||||
if !match_token(input, Token::Pipe).0 {
|
|
||||||
loop {
|
loop {
|
||||||
match input.next().expect(NEVER_ENDS) {
|
match input.next().expect(NEVER_ENDS) {
|
||||||
(Token::Pipe, _) => break,
|
(Token::Pipe, _) => break,
|
||||||
@ -3072,7 +3073,6 @@ fn parse_anon_fn(
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
|
||||||
|
|
||||||
// Parse function body
|
// Parse function body
|
||||||
settings.is_breakable = false;
|
settings.is_breakable = false;
|
||||||
@ -3121,7 +3121,7 @@ fn parse_anon_fn(
|
|||||||
comments: Default::default(),
|
comments: Default::default(),
|
||||||
};
|
};
|
||||||
|
|
||||||
let fn_ptr = crate::FnPtr::new_unchecked(fn_name.into(), Default::default());
|
let fn_ptr = crate::FnPtr::new_unchecked(fn_name, Default::default());
|
||||||
let expr = Expr::DynamicConstant(Box::new(fn_ptr.into()), settings.pos);
|
let expr = Expr::DynamicConstant(Box::new(fn_ptr.into()), settings.pos);
|
||||||
|
|
||||||
#[cfg(not(feature = "no_closure"))]
|
#[cfg(not(feature = "no_closure"))]
|
||||||
@ -3132,7 +3132,6 @@ fn parse_anon_fn(
|
|||||||
|
|
||||||
impl Engine {
|
impl Engine {
|
||||||
/// Parse a global level expression.
|
/// Parse a global level expression.
|
||||||
#[must_use]
|
|
||||||
pub(crate) fn parse_global_expr(
|
pub(crate) fn parse_global_expr(
|
||||||
&self,
|
&self,
|
||||||
input: &mut TokenStream,
|
input: &mut TokenStream,
|
||||||
@ -3174,7 +3173,6 @@ impl Engine {
|
|||||||
}
|
}
|
||||||
|
|
||||||
/// Parse the global level statements.
|
/// Parse the global level statements.
|
||||||
#[must_use]
|
|
||||||
fn parse_global_level(
|
fn parse_global_level(
|
||||||
&self,
|
&self,
|
||||||
input: &mut TokenStream,
|
input: &mut TokenStream,
|
||||||
@ -3236,7 +3234,6 @@ impl Engine {
|
|||||||
|
|
||||||
/// Run the parser on an input stream, returning an AST.
|
/// Run the parser on an input stream, returning an AST.
|
||||||
#[inline(always)]
|
#[inline(always)]
|
||||||
#[must_use]
|
|
||||||
pub(crate) fn parse(
|
pub(crate) fn parse(
|
||||||
&self,
|
&self,
|
||||||
input: &mut TokenStream,
|
input: &mut TokenStream,
|
||||||
|
@ -22,7 +22,6 @@ pub use rhai_codegen::{export_fn, register_exported_fn};
|
|||||||
/// Use the `#[export_module]` and `#[export_fn]` procedural attributes instead.
|
/// Use the `#[export_module]` and `#[export_fn]` procedural attributes instead.
|
||||||
pub trait PluginFunction {
|
pub trait PluginFunction {
|
||||||
/// Call the plugin function with the arguments provided.
|
/// Call the plugin function with the arguments provided.
|
||||||
#[must_use]
|
|
||||||
fn call(&self, context: NativeCallContext, args: &mut FnCallArgs) -> RhaiResult;
|
fn call(&self, context: NativeCallContext, args: &mut FnCallArgs) -> RhaiResult;
|
||||||
|
|
||||||
/// Is this plugin function a method?
|
/// Is this plugin function a method?
|
||||||
|
@ -245,7 +245,7 @@ impl<'a> Scope<'a> {
|
|||||||
) -> &mut Self {
|
) -> &mut Self {
|
||||||
self.names.push((name.into(), Default::default()));
|
self.names.push((name.into(), Default::default()));
|
||||||
value.set_access_mode(access);
|
value.set_access_mode(access);
|
||||||
self.values.push(value.into());
|
self.values.push(value);
|
||||||
self
|
self
|
||||||
}
|
}
|
||||||
/// Truncate (rewind) the [`Scope`] to a previous size.
|
/// Truncate (rewind) the [`Scope`] to a previous size.
|
||||||
@ -465,7 +465,6 @@ impl<'a> Scope<'a> {
|
|||||||
/// Get an iterator to entries in the [`Scope`].
|
/// Get an iterator to entries in the [`Scope`].
|
||||||
#[inline(always)]
|
#[inline(always)]
|
||||||
#[allow(dead_code)]
|
#[allow(dead_code)]
|
||||||
#[must_use]
|
|
||||||
pub(crate) fn into_iter(
|
pub(crate) fn into_iter(
|
||||||
self,
|
self,
|
||||||
) -> impl Iterator<Item = (Cow<'a, str>, Dynamic, Vec<Identifier>)> {
|
) -> impl Iterator<Item = (Cow<'a, str>, Dynamic, Vec<Identifier>)> {
|
||||||
@ -502,7 +501,6 @@ impl<'a> Scope<'a> {
|
|||||||
/// assert_eq!(value.cast::<String>(), "hello");
|
/// assert_eq!(value.cast::<String>(), "hello");
|
||||||
/// ```
|
/// ```
|
||||||
#[inline(always)]
|
#[inline(always)]
|
||||||
#[must_use]
|
|
||||||
pub fn iter(&self) -> impl Iterator<Item = (&str, bool, Dynamic)> {
|
pub fn iter(&self) -> impl Iterator<Item = (&str, bool, Dynamic)> {
|
||||||
self.iter_raw()
|
self.iter_raw()
|
||||||
.map(|(name, constant, value)| (name, constant, value.flatten_clone()))
|
.map(|(name, constant, value)| (name, constant, value.flatten_clone()))
|
||||||
@ -510,7 +508,6 @@ impl<'a> Scope<'a> {
|
|||||||
/// Get an iterator to entries in the [`Scope`].
|
/// Get an iterator to entries in the [`Scope`].
|
||||||
/// Shared values are not expanded.
|
/// Shared values are not expanded.
|
||||||
#[inline(always)]
|
#[inline(always)]
|
||||||
#[must_use]
|
|
||||||
pub fn iter_raw(&self) -> impl Iterator<Item = (&str, bool, &Dynamic)> {
|
pub fn iter_raw(&self) -> impl Iterator<Item = (&str, bool, &Dynamic)> {
|
||||||
self.names
|
self.names
|
||||||
.iter()
|
.iter()
|
||||||
|
70
src/token.rs
70
src/token.rs
@ -142,9 +142,7 @@ impl Position {
|
|||||||
#[must_use]
|
#[must_use]
|
||||||
pub const fn position(self) -> Option<usize> {
|
pub const fn position(self) -> Option<usize> {
|
||||||
#[cfg(not(feature = "no_position"))]
|
#[cfg(not(feature = "no_position"))]
|
||||||
return if self.is_none() {
|
return if self.is_none() || self.pos == 0 {
|
||||||
None
|
|
||||||
} else if self.pos == 0 {
|
|
||||||
None
|
None
|
||||||
} else {
|
} else {
|
||||||
Some(self.pos as usize)
|
Some(self.pos as usize)
|
||||||
@ -214,7 +212,6 @@ impl Position {
|
|||||||
}
|
}
|
||||||
/// Print this [`Position`] for debug purposes.
|
/// Print this [`Position`] for debug purposes.
|
||||||
#[inline(always)]
|
#[inline(always)]
|
||||||
#[must_use]
|
|
||||||
pub(crate) fn debug_print(&self, _f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
pub(crate) fn debug_print(&self, _f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||||
#[cfg(not(feature = "no_position"))]
|
#[cfg(not(feature = "no_position"))]
|
||||||
if !self.is_none() {
|
if !self.is_none() {
|
||||||
@ -606,7 +603,8 @@ impl Token {
|
|||||||
#[inline]
|
#[inline]
|
||||||
#[must_use]
|
#[must_use]
|
||||||
pub const fn is_op_assignment(&self) -> bool {
|
pub const fn is_op_assignment(&self) -> bool {
|
||||||
match self {
|
matches!(
|
||||||
|
self,
|
||||||
Self::PlusAssign
|
Self::PlusAssign
|
||||||
| Self::MinusAssign
|
| Self::MinusAssign
|
||||||
| Self::MultiplyAssign
|
| Self::MultiplyAssign
|
||||||
@ -617,9 +615,8 @@ impl Token {
|
|||||||
| Self::PowerOfAssign
|
| Self::PowerOfAssign
|
||||||
| Self::AndAssign
|
| Self::AndAssign
|
||||||
| Self::OrAssign
|
| Self::OrAssign
|
||||||
| Self::XOrAssign => true,
|
| Self::XOrAssign
|
||||||
_ => false,
|
)
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Get the corresponding operator of the token if it is an op-assignment operator.
|
/// Get the corresponding operator of the token if it is an op-assignment operator.
|
||||||
@ -645,7 +642,8 @@ impl Token {
|
|||||||
#[inline]
|
#[inline]
|
||||||
#[must_use]
|
#[must_use]
|
||||||
pub const fn has_op_assignment(&self) -> bool {
|
pub const fn has_op_assignment(&self) -> bool {
|
||||||
match self {
|
matches!(
|
||||||
|
self,
|
||||||
Self::Plus
|
Self::Plus
|
||||||
| Self::Minus
|
| Self::Minus
|
||||||
| Self::Multiply
|
| Self::Multiply
|
||||||
@ -656,9 +654,8 @@ impl Token {
|
|||||||
| Self::PowerOf
|
| Self::PowerOf
|
||||||
| Self::Ampersand
|
| Self::Ampersand
|
||||||
| Self::Pipe
|
| Self::Pipe
|
||||||
| Self::XOr => true,
|
| Self::XOr
|
||||||
_ => false,
|
)
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Get the corresponding op-assignment operator of the token.
|
/// Get the corresponding op-assignment operator of the token.
|
||||||
@ -792,10 +789,7 @@ impl Token {
|
|||||||
#[inline(always)]
|
#[inline(always)]
|
||||||
#[must_use]
|
#[must_use]
|
||||||
pub const fn is_eof(&self) -> bool {
|
pub const fn is_eof(&self) -> bool {
|
||||||
match self {
|
matches!(self, Self::EOF)
|
||||||
Self::EOF => true,
|
|
||||||
_ => false,
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// If another operator is after these, it's probably an unary operator
|
// If another operator is after these, it's probably an unary operator
|
||||||
@ -958,16 +952,12 @@ impl Token {
|
|||||||
#[inline(always)]
|
#[inline(always)]
|
||||||
#[must_use]
|
#[must_use]
|
||||||
pub const fn is_reserved(&self) -> bool {
|
pub const fn is_reserved(&self) -> bool {
|
||||||
match self {
|
matches!(self, Self::Reserved(_))
|
||||||
Self::Reserved(_) => true,
|
|
||||||
_ => false,
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Convert a token into a function name, if possible.
|
/// Convert a token into a function name, if possible.
|
||||||
#[cfg(not(feature = "no_function"))]
|
#[cfg(not(feature = "no_function"))]
|
||||||
#[inline]
|
#[inline]
|
||||||
#[must_use]
|
|
||||||
pub(crate) fn into_function_name_for_override(self) -> Result<String, Self> {
|
pub(crate) fn into_function_name_for_override(self) -> Result<String, Self> {
|
||||||
match self {
|
match self {
|
||||||
Self::Custom(s) | Self::Identifier(s) if is_valid_identifier(s.chars()) => Ok(s),
|
Self::Custom(s) | Self::Identifier(s) if is_valid_identifier(s.chars()) => Ok(s),
|
||||||
@ -979,10 +969,7 @@ impl Token {
|
|||||||
#[inline(always)]
|
#[inline(always)]
|
||||||
#[must_use]
|
#[must_use]
|
||||||
pub const fn is_custom(&self) -> bool {
|
pub const fn is_custom(&self) -> bool {
|
||||||
match self {
|
matches!(self, Self::Custom(_))
|
||||||
Self::Custom(_) => true,
|
|
||||||
_ => false,
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -1065,7 +1052,6 @@ pub trait InputStream {
|
|||||||
/// # Volatile API
|
/// # Volatile API
|
||||||
///
|
///
|
||||||
/// This function is volatile and may change.
|
/// This function is volatile and may change.
|
||||||
#[must_use]
|
|
||||||
pub fn parse_string_literal(
|
pub fn parse_string_literal(
|
||||||
stream: &mut impl InputStream,
|
stream: &mut impl InputStream,
|
||||||
state: &mut TokenizeState,
|
state: &mut TokenizeState,
|
||||||
@ -1289,20 +1275,26 @@ fn scan_block_comment(
|
|||||||
while let Some(c) = stream.get_next() {
|
while let Some(c) = stream.get_next() {
|
||||||
pos.advance();
|
pos.advance();
|
||||||
|
|
||||||
comment.as_mut().map(|comment| comment.push(c));
|
if let Some(comment) = comment.as_mut() {
|
||||||
|
comment.push(c);
|
||||||
|
}
|
||||||
|
|
||||||
match c {
|
match c {
|
||||||
'/' => {
|
'/' => {
|
||||||
stream.peek_next().filter(|&c2| c2 == '*').map(|c2| {
|
stream.peek_next().filter(|&c2| c2 == '*').map(|c2| {
|
||||||
eat_next(stream, pos);
|
eat_next(stream, pos);
|
||||||
comment.as_mut().map(|comment| comment.push(c2));
|
if let Some(comment) = comment.as_mut() {
|
||||||
|
comment.push(c2);
|
||||||
|
}
|
||||||
level += 1;
|
level += 1;
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
'*' => {
|
'*' => {
|
||||||
stream.peek_next().filter(|&c2| c2 == '/').map(|c2| {
|
stream.peek_next().filter(|&c2| c2 == '/').map(|c2| {
|
||||||
eat_next(stream, pos);
|
eat_next(stream, pos);
|
||||||
comment.as_mut().map(|comment| comment.push(c2));
|
if let Some(comment) = comment.as_mut() {
|
||||||
|
comment.push(c2);
|
||||||
|
}
|
||||||
level -= 1;
|
level -= 1;
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
@ -1344,21 +1336,13 @@ pub fn get_next_token(
|
|||||||
/// Test if the given character is a hex character.
|
/// Test if the given character is a hex character.
|
||||||
#[inline(always)]
|
#[inline(always)]
|
||||||
fn is_hex_digit(c: char) -> bool {
|
fn is_hex_digit(c: char) -> bool {
|
||||||
match c {
|
matches!(c, 'a'..='f' | 'A'..='F' | '0'..='9')
|
||||||
'a'..='f' => true,
|
|
||||||
'A'..='F' => true,
|
|
||||||
'0'..='9' => true,
|
|
||||||
_ => false,
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Test if the given character is a numeric digit.
|
/// Test if the given character is a numeric digit.
|
||||||
#[inline(always)]
|
#[inline(always)]
|
||||||
fn is_numeric_digit(c: char) -> bool {
|
fn is_numeric_digit(c: char) -> bool {
|
||||||
match c {
|
matches!(c, '0'..='9')
|
||||||
'0'..='9' => true,
|
|
||||||
_ => false,
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Test if the comment block is a doc-comment.
|
/// Test if the comment block is a doc-comment.
|
||||||
@ -1475,7 +1459,7 @@ fn get_next_token_inner(
|
|||||||
break;
|
break;
|
||||||
}
|
}
|
||||||
// symbol after period - probably a float
|
// symbol after period - probably a float
|
||||||
ch @ _ if !is_id_first_alphabetic(ch) => {
|
ch if !is_id_first_alphabetic(ch) => {
|
||||||
result.push(next_char);
|
result.push(next_char);
|
||||||
pos.advance();
|
pos.advance();
|
||||||
result.push('0');
|
result.push('0');
|
||||||
@ -1770,7 +1754,9 @@ fn get_next_token_inner(
|
|||||||
pos.new_line();
|
pos.new_line();
|
||||||
break;
|
break;
|
||||||
}
|
}
|
||||||
comment.as_mut().map(|comment| comment.push(c));
|
if let Some(comment) = comment.as_mut() {
|
||||||
|
comment.push(c);
|
||||||
|
}
|
||||||
pos.advance();
|
pos.advance();
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -2002,7 +1988,7 @@ fn get_identifier(
|
|||||||
));
|
));
|
||||||
}
|
}
|
||||||
|
|
||||||
return Some((Token::Identifier(identifier), start_pos));
|
Some((Token::Identifier(identifier), start_pos))
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Is this keyword allowed as a function?
|
/// Is this keyword allowed as a function?
|
||||||
|
@ -9,7 +9,6 @@ use std::{
|
|||||||
|
|
||||||
/// Cast a type into another type.
|
/// Cast a type into another type.
|
||||||
#[inline(always)]
|
#[inline(always)]
|
||||||
#[must_use]
|
|
||||||
pub fn unsafe_try_cast<A: Any, B: Any>(a: A) -> Result<B, A> {
|
pub fn unsafe_try_cast<A: Any, B: Any>(a: A) -> Result<B, A> {
|
||||||
if TypeId::of::<B>() == a.type_id() {
|
if TypeId::of::<B>() == a.type_id() {
|
||||||
// SAFETY: Just checked we have the right type. We explicitly forget the
|
// SAFETY: Just checked we have the right type. We explicitly forget the
|
||||||
@ -27,7 +26,6 @@ pub fn unsafe_try_cast<A: Any, B: Any>(a: A) -> Result<B, A> {
|
|||||||
|
|
||||||
/// Cast a Boxed type into another type.
|
/// Cast a Boxed type into another type.
|
||||||
#[inline(always)]
|
#[inline(always)]
|
||||||
#[must_use]
|
|
||||||
pub fn unsafe_cast_box<X: Any, T: Any>(item: Box<X>) -> Result<Box<T>, Box<X>> {
|
pub fn unsafe_cast_box<X: Any, T: Any>(item: Box<X>) -> Result<Box<T>, Box<X>> {
|
||||||
// Only allow casting to the exact same type
|
// Only allow casting to the exact same type
|
||||||
if TypeId::of::<X>() == TypeId::of::<T>() {
|
if TypeId::of::<X>() == TypeId::of::<T>() {
|
||||||
|
Loading…
Reference in New Issue
Block a user