Merge pull request #459 from schungx/master

Fix error templates.
This commit is contained in:
Stephen Chung 2021-10-23 12:49:35 +08:00 committed by GitHub
commit 6459ff9c69
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
120 changed files with 1551 additions and 1100 deletions

View File

@ -1,6 +1,31 @@
Rhai Release Notes
==================
Version 1.2.0
=============
New features
------------
* `#[cfg(...)]` attributes can now be put directly on plugin functions or function defined in a plugin module.
Enhancements
------------
* Array methods now avoid cloning as much as possible (although most predicates will involve cloning anyway if passed a closure).
* Array methods that take function pointers (e.g. closures) now optionally take the function name as a string.
* Array adds the `dedup` method.
* Array adds a `sort` method with no parameters which sorts homogeneous arrays of built-in comparable types (e.g. `INT`).
* Inlining is disabled for error-path functions because errors are exceptional and scripts usually fail completely when an error is encountered.
* The `optimize` module is completely eliminated under `no_optimize`, which should yield smaller code size.
Deprecated API's
----------------
* `NativeCallContext::call_fn_dynamic_raw` is deprecated and `NativeCallContext::call_fn_raw` is added.
* `From<EvalAltResult>` for `Result<T, Box<EvalAltResult>>` is deprecated so it will no longer be possible to do `EvalAltResult::ErrorXXXXX.into()` to convert to a `Result`; instead, `Err(EvalAltResult:ErrorXXXXX.into())` must be used. Code is clearer if errors are explicitly wrapped in `Err`.
Version 1.1.0
=============
@ -60,10 +85,6 @@ Enhancements
* `StaticVec` is changed to keep three items inline instead of four.
Version 1.0.7
=============
Version 1.0.6
=============

View File

@ -3,7 +3,7 @@ members = [".", "codegen"]
[package]
name = "rhai"
version = "1.1.0"
version = "1.2.0"
edition = "2018"
authors = ["Jonathan Turner", "Lukáš Hozda", "Stephen Chung", "jhwgh1968"]
description = "Embedded scripting for Rust"
@ -20,7 +20,7 @@ smallvec = { version = "1.6", default-features = false, features = ["union"] }
ahash = { version = "0.7", default-features = false }
num-traits = { version = "0.2", default-features = false }
smartstring = { version = "0.2.7", default-features = false }
rhai_codegen = { version = "1.0", path = "codegen", default-features = false }
rhai_codegen = { version = "1.1", path = "codegen", default-features = false }
[features]
default = ["ahash/std", "num-traits/std"]

View File

@ -1,6 +1,6 @@
[package]
name = "rhai_codegen"
version = "1.1.0"
version = "1.2.0"
edition = "2018"
authors = ["jhwgh1968", "Stephen Chung"]
description = "Procedural macros support package for Rhai, a scripting language and engine for Rust"
@ -16,7 +16,7 @@ default = []
metadata = []
[dev-dependencies]
rhai = { path = "..", version = "1" }
rhai = { path = "..", version = "1.1" }
trybuild = "1"
[dependencies]

View File

@ -1,3 +1,4 @@
use proc_macro2::{Ident, Span, TokenStream};
use syn::{
parse::{ParseStream, Parser},
spanned::Spanned,
@ -24,14 +25,14 @@ pub trait ExportedParams: Sized {
#[derive(Debug, Clone)]
pub struct AttrItem {
pub key: proc_macro2::Ident,
pub key: Ident,
pub value: Option<syn::LitStr>,
pub span: proc_macro2::Span,
pub span: Span,
}
#[derive(Debug, Clone)]
pub struct ExportInfo {
pub item_span: proc_macro2::Span,
pub item_span: Span,
pub items: Vec<AttrItem>,
}
@ -42,8 +43,7 @@ pub fn parse_attr_items(args: ParseStream) -> syn::Result<ExportInfo> {
items: Vec::new(),
});
}
let arg_list = args
.call(syn::punctuated::Punctuated::<syn::Expr, syn::Token![,]>::parse_separated_nonempty)?;
let arg_list = args.call(syn::punctuated::Punctuated::parse_separated_nonempty)?;
parse_punctuated_items(arg_list)
}
@ -53,7 +53,8 @@ pub fn parse_punctuated_items(
) -> syn::Result<ExportInfo> {
let list_span = arg_list.span();
let mut attrs: Vec<AttrItem> = Vec::new();
let mut attrs = Vec::new();
for arg in arg_list {
let arg_span = arg.span();
let (key, value) = match arg {
@ -62,7 +63,7 @@ pub fn parse_punctuated_items(
ref right,
..
}) => {
let attr_name: syn::Ident = match left.as_ref() {
let attr_name = match left.as_ref() {
syn::Expr::Path(syn::ExprPath {
path: attr_path, ..
}) => attr_path.get_ident().cloned().ok_or_else(|| {
@ -79,13 +80,11 @@ pub fn parse_punctuated_items(
};
(attr_name, Some(attr_value))
}
syn::Expr::Path(syn::ExprPath {
path: attr_path, ..
}) => attr_path
syn::Expr::Path(syn::ExprPath { path, .. }) => path
.get_ident()
.cloned()
.map(|a| (a, None))
.ok_or_else(|| syn::Error::new(attr_path.span(), "expecting attribute name"))?,
.ok_or_else(|| syn::Error::new(path.span(), "expecting attribute name"))?,
x => return Err(syn::Error::new(x.span(), "expecting identifier")),
};
attrs.push(AttrItem {
@ -102,18 +101,16 @@ pub fn parse_punctuated_items(
}
pub fn outer_item_attributes<T: ExportedParams>(
args: proc_macro2::TokenStream,
args: TokenStream,
_attr_name: &str,
) -> syn::Result<T> {
if args.is_empty() {
return Ok(T::no_attrs());
}
let parser = syn::punctuated::Punctuated::<syn::Expr, syn::Token![,]>::parse_separated_nonempty;
let arg_list = parser.parse2(args)?;
let arg_list = syn::punctuated::Punctuated::parse_separated_nonempty.parse2(args)?;
let export_info = parse_punctuated_items(arg_list)?;
T::from_info(export_info)
T::from_info(parse_punctuated_items(arg_list)?)
}
pub fn inner_item_attributes<T: ExportedParams>(
@ -132,16 +129,10 @@ pub fn inner_item_attributes<T: ExportedParams>(
}
}
pub fn deny_cfg_attr(attrs: &[syn::Attribute]) -> syn::Result<()> {
if let Some(cfg_attr) = attrs
pub fn collect_cfg_attr(attrs: &[syn::Attribute]) -> Vec<syn::Attribute> {
attrs
.iter()
.find(|a| a.path.get_ident().map(|i| *i == "cfg").unwrap_or(false))
{
Err(syn::Error::new(
cfg_attr.span(),
"cfg attributes not allowed on this item",
))
} else {
Ok(())
}
.filter(|&a| a.path.get_ident().map(|i| *i == "cfg").unwrap_or(false))
.cloned()
.collect()
}

View File

@ -1,3 +1,10 @@
use proc_macro2::{Span, TokenStream};
use quote::{quote, quote_spanned, ToTokens};
use syn::{
parse::{Parse, ParseStream},
spanned::Spanned,
};
#[cfg(no_std)]
use alloc::format;
#[cfg(not(no_std))]
@ -5,12 +12,6 @@ use std::format;
use std::borrow::Cow;
use quote::{quote, quote_spanned, ToTokens};
use syn::{
parse::{Parse, ParseStream},
spanned::Spanned,
};
use crate::attrs::{ExportInfo, ExportScope, ExportedParams};
#[derive(Clone, Debug, Eq, PartialEq, Copy, Hash)]
@ -52,7 +53,7 @@ impl Default for FnSpecialAccess {
}
impl FnSpecialAccess {
pub fn get_fn_name(&self) -> Option<(String, String, proc_macro2::Span)> {
pub fn get_fn_name(&self) -> Option<(String, String, Span)> {
match self {
FnSpecialAccess::None => None,
FnSpecialAccess::Property(Property::Get(ref g)) => {
@ -64,12 +65,12 @@ impl FnSpecialAccess {
FnSpecialAccess::Index(Index::Get) => Some((
FN_IDX_GET.to_string(),
"index_get".to_string(),
proc_macro2::Span::call_site(),
Span::call_site(),
)),
FnSpecialAccess::Index(Index::Set) => Some((
FN_IDX_SET.to_string(),
"index_set".to_string(),
proc_macro2::Span::call_site(),
Span::call_site(),
)),
}
}
@ -98,12 +99,12 @@ pub fn print_type(ty: &syn::Type) -> String {
#[derive(Debug, Default)]
pub struct ExportedFnParams {
pub name: Vec<String>,
pub return_raw: Option<proc_macro2::Span>,
pub pure: Option<proc_macro2::Span>,
pub return_raw: Option<Span>,
pub pure: Option<Span>,
pub skip: bool,
pub special: FnSpecialAccess,
pub namespace: FnNamespaceAccess,
pub span: Option<proc_macro2::Span>,
pub span: Option<Span>,
}
pub const FN_GET: &str = "get$";
@ -274,12 +275,13 @@ impl ExportedParams for ExportedFnParams {
#[derive(Debug)]
pub struct ExportedFn {
entire_span: proc_macro2::Span,
entire_span: Span,
signature: syn::Signature,
visibility: syn::Visibility,
pass_context: bool,
mut_receiver: bool,
params: ExportedFnParams,
cfg_attrs: Vec<syn::Attribute>,
}
impl Parse for ExportedFn {
@ -293,8 +295,7 @@ impl Parse for ExportedFn {
syn::parse2::<syn::Path>(quote! { rhai::NativeCallContext }).unwrap();
let mut pass_context = false;
// #[cfg] attributes are not allowed on functions due to what is generated for them
crate::attrs::deny_cfg_attr(&fn_all.attrs)?;
let cfg_attrs = crate::attrs::collect_cfg_attr(&fn_all.attrs);
let visibility = fn_all.vis;
@ -369,7 +370,7 @@ impl Parse for ExportedFn {
if !is_ok {
return Err(syn::Error::new(
ty.span(),
"this type in this position passes from Rhai by value",
"function parameters other than the first one cannot be passed by reference",
));
}
}
@ -402,6 +403,7 @@ impl Parse for ExportedFn {
pass_context,
mut_receiver,
params: Default::default(),
cfg_attrs,
})
}
}
@ -413,6 +415,10 @@ impl ExportedFn {
&self.params
}
pub fn cfg_attrs(&self) -> &[syn::Attribute] {
&self.cfg_attrs
}
pub fn update_scope(&mut self, parent_scope: &ExportScope) {
let keep = match (self.params.skip, parent_scope) {
(true, _) => false,
@ -443,7 +449,7 @@ impl ExportedFn {
!matches!(self.visibility, syn::Visibility::Inherited)
}
pub fn span(&self) -> &proc_macro2::Span {
pub fn span(&self) -> &Span {
&self.entire_span
}
@ -456,7 +462,7 @@ impl ExportedFn {
.params
.name
.iter()
.map(|s| syn::LitStr::new(s, proc_macro2::Span::call_site()))
.map(|s| syn::LitStr::new(s, Span::call_site()))
.collect();
if let Some((s, _, span)) = self.params.special.get_fn_name() {
@ -497,6 +503,10 @@ impl ExportedFn {
}
}
pub fn set_cfg_attrs(&mut self, cfg_attrs: Vec<syn::Attribute>) {
self.cfg_attrs = cfg_attrs
}
pub fn set_params(&mut self, mut params: ExportedFnParams) -> syn::Result<()> {
// Several issues are checked here to avoid issues with diagnostics caused by raising them later.
//
@ -586,7 +596,7 @@ impl ExportedFn {
Ok(())
}
pub fn generate(self) -> proc_macro2::TokenStream {
pub fn generate(self) -> TokenStream {
let name: syn::Ident =
syn::Ident::new(&format!("rhai_fn_{}", self.name()), self.name().span());
let impl_block = self.generate_impl("Token");
@ -603,17 +613,16 @@ impl ExportedFn {
}
}
pub fn generate_dynamic_fn(&self) -> proc_macro2::TokenStream {
pub fn generate_dynamic_fn(&self) -> TokenStream {
let name = self.name().clone();
let mut dynamic_signature = self.signature.clone();
dynamic_signature.ident =
syn::Ident::new("dynamic_result_fn", proc_macro2::Span::call_site());
dynamic_signature.ident = syn::Ident::new("dynamic_result_fn", Span::call_site());
dynamic_signature.output = syn::parse2::<syn::ReturnType>(quote! {
-> RhaiResult
})
.unwrap();
let arguments: Vec<syn::Ident> = dynamic_signature
let arguments: Vec<_> = dynamic_signature
.inputs
.iter()
.filter_map(|fn_arg| match fn_arg {
@ -628,7 +637,7 @@ impl ExportedFn {
let return_span = self
.return_type()
.map(|r| r.span())
.unwrap_or_else(proc_macro2::Span::call_site);
.unwrap_or_else(Span::call_site);
if self.params.return_raw.is_some() {
quote_spanned! { return_span =>
pub #dynamic_signature {
@ -646,16 +655,16 @@ impl ExportedFn {
}
}
pub fn generate_impl(&self, on_type_name: &str) -> proc_macro2::TokenStream {
pub fn generate_impl(&self, on_type_name: &str) -> TokenStream {
let sig_name = self.name().clone();
let arg_count = self.arg_count();
let is_method_call = self.mutable_receiver();
let mut unpack_statements: Vec<syn::Stmt> = Vec::new();
let mut unpack_exprs: Vec<syn::Expr> = Vec::new();
let mut unpack_statements = Vec::new();
let mut unpack_exprs = Vec::new();
#[cfg(feature = "metadata")]
let mut input_type_names: Vec<String> = Vec::new();
let mut input_type_exprs: Vec<syn::Expr> = Vec::new();
let mut input_type_names = Vec::new();
let mut input_type_exprs = Vec::new();
let return_type = self
.return_type()
@ -672,7 +681,7 @@ impl ExportedFn {
if is_method_call {
skip_first_arg = true;
let first_arg = self.arg_list().next().unwrap();
let var = syn::Ident::new("arg0", proc_macro2::Span::call_site());
let var = syn::Ident::new("arg0", Span::call_site());
match first_arg {
syn::FnArg::Typed(syn::PatType { pat, ty, .. }) => {
#[cfg(feature = "metadata")]
@ -696,7 +705,7 @@ impl ExportedFn {
unpack_statements.push(
syn::parse2::<syn::Stmt>(quote! {
if args[0usize].is_read_only() {
return EvalAltResult::ErrorAssignmentToConstant(#arg_lit_str.to_string(), Position::NONE).into();
return Err(EvalAltResult::ErrorAssignmentToConstant(#arg_lit_str.to_string(), Position::NONE).into());
}
})
.unwrap(),
@ -725,7 +734,7 @@ impl ExportedFn {
let str_type_path = syn::parse2::<syn::Path>(quote! { str }).unwrap();
let string_type_path = syn::parse2::<syn::Path>(quote! { String }).unwrap();
for (i, arg) in self.arg_list().enumerate().skip(skip_first_arg as usize) {
let var = syn::Ident::new(&format!("arg{}", i), proc_macro2::Span::call_site());
let var = syn::Ident::new(&format!("arg{}", i), Span::call_site());
let is_string;
let is_ref;
match arg {
@ -811,7 +820,7 @@ impl ExportedFn {
let return_span = self
.return_type()
.map(|r| r.span())
.unwrap_or_else(proc_macro2::Span::call_site);
.unwrap_or_else(Span::call_site);
let return_expr = if self.params.return_raw.is_none() {
quote_spanned! { return_span =>
Ok(Dynamic::from(#sig_name(#(#unpack_exprs),*)))
@ -822,7 +831,7 @@ impl ExportedFn {
}
};
let type_name = syn::Ident::new(on_type_name, proc_macro2::Span::call_site());
let type_name = syn::Ident::new(on_type_name, Span::call_site());
#[cfg(feature = "metadata")]
let param_names = quote! {
@ -831,11 +840,19 @@ impl ExportedFn {
#[cfg(not(feature = "metadata"))]
let param_names = quote! {};
let cfg_attrs: Vec<_> = self
.cfg_attrs()
.iter()
.map(syn::Attribute::to_token_stream)
.collect();
quote! {
#(#cfg_attrs)*
impl #type_name {
#param_names
#[inline(always)] pub fn param_types() -> [TypeId; #arg_count] { [#(#input_type_exprs),*] }
}
#(#cfg_attrs)*
impl PluginFunction for #type_name {
#[inline(always)]
fn call(&self, context: NativeCallContext, args: &mut [&mut Dynamic]) -> RhaiResult {

View File

@ -88,7 +88,7 @@
//!
use quote::quote;
use syn::parse_macro_input;
use syn::{parse_macro_input, spanned::Spanned};
mod attrs;
mod function;
@ -130,9 +130,19 @@ pub fn export_fn(
let parsed_params = match crate::attrs::outer_item_attributes(args.into(), "export_fn") {
Ok(args) => args,
Err(err) => return proc_macro::TokenStream::from(err.to_compile_error()),
Err(err) => return err.to_compile_error().into(),
};
let mut function_def = parse_macro_input!(input as function::ExportedFn);
if !function_def.cfg_attrs().is_empty() {
return syn::Error::new(
function_def.cfg_attrs()[0].span(),
"`cfg` attributes are not allowed for `export_fn`",
)
.to_compile_error()
.into();
}
if let Err(e) = function_def.set_params(parsed_params) {
return e.to_compile_error().into();
}
@ -173,7 +183,7 @@ pub fn export_module(
) -> proc_macro::TokenStream {
let parsed_params = match crate::attrs::outer_item_attributes(args.into(), "export_module") {
Ok(args) => args,
Err(err) => return proc_macro::TokenStream::from(err.to_compile_error()),
Err(err) => return err.to_compile_error().into(),
};
let mut module_def = parse_macro_input!(input as module::Module);
if let Err(e) = module_def.set_params(parsed_params) {

View File

@ -1,14 +1,6 @@
use quote::{quote, ToTokens};
use syn::{parse::Parse, parse::ParseStream};
use crate::function::ExportedFn;
use crate::rhai_module::ExportedConst;
#[cfg(no_std)]
use alloc::vec as new_vec;
#[cfg(not(no_std))]
use std::vec as new_vec;
#[cfg(no_std)]
use core::mem;
#[cfg(not(no_std))]
@ -17,7 +9,8 @@ use std::mem;
use std::borrow::Cow;
use crate::attrs::{AttrItem, ExportInfo, ExportScope, ExportedParams};
use crate::function::ExportedFnParams;
use crate::function::ExportedFn;
use crate::rhai_module::ExportedConst;
#[derive(Debug, Clone, Eq, PartialEq, Hash, Default)]
pub struct ExportedModParams {
@ -32,9 +25,7 @@ impl Parse for ExportedModParams {
return Ok(ExportedModParams::default());
}
let info = crate::attrs::parse_attr_items(args)?;
Self::from_info(info)
Self::from_info(crate::attrs::parse_attr_items(args)?)
}
}
@ -115,8 +106,9 @@ impl Parse for Module {
fn parse(input: ParseStream) -> syn::Result<Self> {
let mut mod_all: syn::ItemMod = input.parse()?;
let fns: Vec<_>;
let mut consts: Vec<_> = new_vec![];
let mut sub_modules: Vec<_> = Vec::new();
let mut consts = Vec::new();
let mut sub_modules = Vec::new();
if let Some((_, ref mut content)) = mod_all.content {
// Gather and parse functions.
fns = content
@ -126,17 +118,13 @@ impl Parse for Module {
_ => None,
})
.try_fold(Vec::new(), |mut vec, item_fn| {
// #[cfg] attributes are not allowed on functions
crate::attrs::deny_cfg_attr(&item_fn.attrs)?;
let params =
crate::attrs::inner_item_attributes(&mut item_fn.attrs, "rhai_fn")?;
let params: ExportedFnParams =
match crate::attrs::inner_item_attributes(&mut item_fn.attrs, "rhai_fn") {
Ok(p) => p,
Err(e) => return Err(e),
};
syn::parse2::<ExportedFn>(item_fn.to_token_stream())
.and_then(|mut f| {
f.set_params(params)?;
f.set_cfg_attrs(crate::attrs::collect_cfg_attr(&item_fn.attrs));
Ok(f)
})
.map(|f| vec.push(f))
@ -152,16 +140,12 @@ impl Parse for Module {
attrs,
ty,
..
}) => {
// #[cfg] attributes are not allowed on const declarations
crate::attrs::deny_cfg_attr(&attrs)?;
match vis {
syn::Visibility::Public(_) => {
consts.push((ident.to_string(), ty.clone(), expr.as_ref().clone()))
}
_ => {}
}
}
}) if matches!(vis, syn::Visibility::Public(_)) => consts.push((
ident.to_string(),
ty.clone(),
expr.as_ref().clone(),
crate::attrs::collect_cfg_attr(&attrs),
)),
_ => {}
}
}
@ -192,7 +176,7 @@ impl Parse for Module {
}
}
} else {
fns = new_vec![];
fns = Vec::new();
}
Ok(Module {
mod_all,
@ -205,7 +189,7 @@ impl Parse for Module {
}
impl Module {
pub fn attrs(&self) -> &Vec<syn::Attribute> {
pub fn attrs(&self) -> &[syn::Attribute] {
&self.mod_all.attrs
}
@ -273,10 +257,12 @@ impl Module {
// NB: sub-modules must have their new items for exporting generated in depth-first order
// to avoid issues caused by re-parsing them
let inner_modules: Vec<proc_macro2::TokenStream> = sub_modules.drain(..)
.try_fold::<Vec<proc_macro2::TokenStream>, _,
Result<Vec<proc_macro2::TokenStream>, syn::Error>>(
Vec::new(), |mut acc, m| { acc.push(m.generate_inner()?); Ok(acc) })?;
let inner_modules = sub_modules
.drain(..)
.try_fold::<_, _, Result<_, syn::Error>>(Vec::new(), |mut acc, m| {
acc.push(m.generate_inner()?);
Ok(acc)
})?;
// Regenerate the module with the new content added.
Ok(quote! {
@ -319,7 +305,7 @@ impl Module {
}
#[allow(dead_code)]
pub fn content(&self) -> Option<&Vec<syn::Item>> {
pub fn content(&self) -> Option<&[syn::Item]> {
match self.mod_all {
syn::ItemMod {
content: Some((_, ref vec)),

View File

@ -22,10 +22,11 @@ type RegisterMacroInput = (syn::Expr, proc_macro2::TokenStream, syn::Path);
pub fn parse_register_macro(
args: proc_macro::TokenStream,
) -> Result<RegisterMacroInput, syn::Error> {
let parser = syn::punctuated::Punctuated::<syn::Expr, syn::Token![,]>::parse_separated_nonempty;
let args = parser.parse(args).unwrap();
let args = syn::punctuated::Punctuated::<_, syn::Token![,]>::parse_separated_nonempty
.parse(args)
.unwrap();
let arg_span = args.span();
let mut items: Vec<syn::Expr> = args.into_iter().collect();
let mut items: Vec<_> = args.into_iter().collect();
if items.len() != 3 {
return Err(syn::Error::new(
arg_span,

View File

@ -1,6 +1,7 @@
use std::collections::BTreeMap;
use proc_macro2::{Span, TokenStream};
use quote::{quote, ToTokens};
use quote::quote;
use std::collections::BTreeMap;
use crate::attrs::ExportScope;
use crate::function::{
@ -9,26 +10,33 @@ use crate::function::{
};
use crate::module::Module;
pub type ExportedConst = (String, Box<syn::Type>, syn::Expr);
pub type ExportedConst = (String, Box<syn::Type>, syn::Expr, Vec<syn::Attribute>);
pub fn generate_body(
fns: &mut [ExportedFn],
consts: &[ExportedConst],
sub_modules: &mut [Module],
parent_scope: &ExportScope,
) -> proc_macro2::TokenStream {
let mut set_fn_statements: Vec<syn::Stmt> = Vec::new();
let mut set_const_statements: Vec<syn::Stmt> = Vec::new();
let mut add_mod_blocks: Vec<syn::ExprBlock> = Vec::new();
let mut set_flattened_mod_blocks: Vec<syn::ExprBlock> = Vec::new();
) -> TokenStream {
let mut set_fn_statements = Vec::new();
let mut set_const_statements = Vec::new();
let mut add_mod_blocks = Vec::new();
let mut set_flattened_mod_blocks = Vec::new();
let str_type_path = syn::parse2::<syn::Path>(quote! { str }).unwrap();
let string_type_path = syn::parse2::<syn::Path>(quote! { String }).unwrap();
for (const_name, _, _) in consts {
let const_literal = syn::LitStr::new(&const_name, proc_macro2::Span::call_site());
let const_ref = syn::Ident::new(&const_name, proc_macro2::Span::call_site());
for (const_name, _, _, cfg_attrs) in consts {
let const_literal = syn::LitStr::new(&const_name, Span::call_site());
let const_ref = syn::Ident::new(&const_name, Span::call_site());
let cfg_attrs: Vec<_> = cfg_attrs
.iter()
.map(syn::Attribute::to_token_stream)
.collect();
set_const_statements.push(
syn::parse2::<syn::Stmt>(quote! {
#(#cfg_attrs)*
m.set_var(#const_literal, #const_ref);
})
.unwrap(),
@ -41,15 +49,8 @@ pub fn generate_body(
continue;
}
let module_name = item_mod.module_name();
let exported_name: syn::LitStr = syn::LitStr::new(
item_mod.exported_name().as_ref(),
proc_macro2::Span::call_site(),
);
let cfg_attrs: Vec<&syn::Attribute> = item_mod
.attrs()
.iter()
.filter(|&a| a.path.get_ident().map(|i| *i == "cfg").unwrap_or(false))
.collect();
let exported_name = syn::LitStr::new(item_mod.exported_name().as_ref(), Span::call_site());
let cfg_attrs = crate::attrs::collect_cfg_attr(item_mod.attrs());
add_mod_blocks.push(
syn::parse2::<syn::ExprBlock>(quote! {
{
@ -71,19 +72,20 @@ pub fn generate_body(
}
// NB: these are token streams, because re-parsing messes up "> >" vs ">>"
let mut gen_fn_tokens: Vec<proc_macro2::TokenStream> = Vec::new();
let mut gen_fn_tokens = Vec::new();
for function in fns {
function.update_scope(&parent_scope);
if function.skipped() {
continue;
}
let fn_token_name = syn::Ident::new(
&format!("{}_token", function.name().to_string()),
&format!("{}_token", function.name()),
function.name().span(),
);
let reg_names = function.exported_names();
let fn_input_types: Vec<syn::Expr> = function
let fn_input_types: Vec<_> = function
.arg_list()
.map(|fn_arg| match fn_arg {
syn::FnArg::Receiver(_) => panic!("internal error: receiver fn outside impl!?"),
@ -126,6 +128,12 @@ pub fn generate_body(
})
.collect();
let cfg_attrs: Vec<_> = function
.cfg_attrs()
.iter()
.map(syn::Attribute::to_token_stream)
.collect();
for fn_literal in reg_names {
let mut namespace = FnNamespaceAccess::Internal;
@ -166,6 +174,7 @@ pub fn generate_body(
set_fn_statements.push(
syn::parse2::<syn::Stmt>(quote! {
#(#cfg_attrs)*
m.set_fn(#fn_literal, FnNamespace::#ns_str, FnAccess::Public,
#param_names, &[#(#fn_input_types),*], #fn_token_name().into());
})
@ -174,9 +183,11 @@ pub fn generate_body(
}
gen_fn_tokens.push(quote! {
#(#cfg_attrs)*
#[allow(non_camel_case_types)]
pub struct #fn_token_name();
});
gen_fn_tokens.push(function.generate_impl(&fn_token_name.to_string()));
}
@ -229,8 +240,8 @@ pub fn check_rename_collisions(fns: &[ExportedFn]) -> Result<(), syn::Error> {
})
}
let mut renames = BTreeMap::<String, proc_macro2::Span>::new();
let mut fn_defs = BTreeMap::<String, proc_macro2::Span>::new();
let mut renames = BTreeMap::new();
let mut fn_defs = BTreeMap::new();
for item_fn in fns.iter() {
if !item_fn.params().name.is_empty() || item_fn.params().special != FnSpecialAccess::None {
@ -251,11 +262,11 @@ pub fn check_rename_collisions(fns: &[ExportedFn]) -> Result<(), syn::Error> {
if let Some(other_span) = renames.insert(key, current_span) {
let mut err = syn::Error::new(
current_span,
format!("duplicate Rhai signature for '{}'", &fn_name),
format!("duplicate Rhai signature for '{}'", fn_name),
);
err.combine(syn::Error::new(
other_span,
format!("duplicated function renamed '{}'", &fn_name),
format!("duplicated function renamed '{}'", fn_name),
));
return Err(err);
}
@ -263,13 +274,11 @@ pub fn check_rename_collisions(fns: &[ExportedFn]) -> Result<(), syn::Error> {
} else {
let ident = item_fn.name();
if let Some(other_span) = fn_defs.insert(ident.to_string(), ident.span()) {
let mut err = syn::Error::new(
ident.span(),
format!("duplicate function '{}'", ident.to_string()),
);
let mut err =
syn::Error::new(ident.span(), format!("duplicate function '{}'", ident));
err.combine(syn::Error::new(
other_span,
format!("duplicated function '{}'", ident.to_string()),
format!("duplicated function '{}'", ident),
));
return Err(err);
}
@ -277,11 +286,11 @@ pub fn check_rename_collisions(fns: &[ExportedFn]) -> Result<(), syn::Error> {
if let Some(fn_span) = renames.get(&key) {
let mut err = syn::Error::new(
ident.span(),
format!("duplicate Rhai signature for '{}'", &ident),
format!("duplicate Rhai signature for '{}'", ident),
);
err.combine(syn::Error::new(
*fn_span,
format!("duplicated function '{}'", &ident),
format!("duplicated function '{}'", ident),
));
return Err(err);
}

View File

@ -126,7 +126,7 @@ mod function_tests {
let err = syn::parse2::<ExportedFn>(input_tokens).unwrap_err();
assert_eq!(
format!("{}", err),
"this type in this position passes from Rhai by value"
"function parameters other than the first one cannot be passed by reference"
);
}
@ -139,7 +139,7 @@ mod function_tests {
let err = syn::parse2::<ExportedFn>(input_tokens).unwrap_err();
assert_eq!(
format!("{}", err),
"this type in this position passes from Rhai by value"
"function parameters other than the first one cannot be passed by reference"
);
}
@ -486,7 +486,7 @@ mod generate_tests {
#[inline(always)]
fn call(&self, context: NativeCallContext, args: &mut [&mut Dynamic]) -> RhaiResult {
if args[0usize].is_read_only() {
return EvalAltResult::ErrorAssignmentToConstant("x".to_string(), Position::NONE).into();
return Err(EvalAltResult::ErrorAssignmentToConstant("x".to_string(), Position::NONE).into());
}
let arg1 = mem::take(args[1usize]).cast::<usize>();
let arg0 = &mut args[0usize].write_lock::<usize>().unwrap();

View File

@ -1096,7 +1096,7 @@ mod generate_tests {
#[inline(always)]
fn call(&self, context: NativeCallContext, args: &mut [&mut Dynamic]) -> RhaiResult {
if args[0usize].is_read_only() {
return EvalAltResult::ErrorAssignmentToConstant("x".to_string(), Position::NONE).into();
return Err(EvalAltResult::ErrorAssignmentToConstant("x".to_string(), Position::NONE).into());
}
let arg0 = &mut args[0usize].write_lock::<FLOAT>().unwrap();
Ok(Dynamic::from(increment(arg0)))
@ -1155,7 +1155,7 @@ mod generate_tests {
#[inline(always)]
fn call(&self, context: NativeCallContext, args: &mut [&mut Dynamic]) -> RhaiResult {
if args[0usize].is_read_only() {
return EvalAltResult::ErrorAssignmentToConstant("x".to_string(), Position::NONE).into();
return Err(EvalAltResult::ErrorAssignmentToConstant("x".to_string(), Position::NONE).into());
}
let arg0 = &mut args[0usize].write_lock::<FLOAT>().unwrap();
Ok(Dynamic::from(increment(arg0)))
@ -1235,7 +1235,7 @@ mod generate_tests {
#[inline(always)]
fn call(&self, context: NativeCallContext, args: &mut [&mut Dynamic]) -> RhaiResult {
if args[0usize].is_read_only() {
return EvalAltResult::ErrorAssignmentToConstant("x".to_string(), Position::NONE).into();
return Err(EvalAltResult::ErrorAssignmentToConstant("x".to_string(), Position::NONE).into());
}
let arg0 = &mut args[0usize].write_lock::<FLOAT>().unwrap();
Ok(Dynamic::from(increment(arg0)))
@ -1316,7 +1316,7 @@ mod generate_tests {
#[inline(always)]
fn call(&self, context: NativeCallContext, args: &mut [&mut Dynamic]) -> RhaiResult {
if args[0usize].is_read_only() {
return EvalAltResult::ErrorAssignmentToConstant("x".to_string(), Position::NONE).into();
return Err(EvalAltResult::ErrorAssignmentToConstant("x".to_string(), Position::NONE).into());
}
let arg0 = &mut args[0usize].write_lock::<u64>().unwrap();
Ok(Dynamic::from(int_foo(arg0)))
@ -1376,7 +1376,7 @@ mod generate_tests {
#[inline(always)]
fn call(&self, context: NativeCallContext, args: &mut [&mut Dynamic]) -> RhaiResult {
if args[0usize].is_read_only() {
return EvalAltResult::ErrorAssignmentToConstant("x".to_string(), Position::NONE).into();
return Err(EvalAltResult::ErrorAssignmentToConstant("x".to_string(), Position::NONE).into());
}
let arg0 = &mut args[0usize].write_lock::<u64>().unwrap();
Ok(Dynamic::from(int_foo(arg0)))
@ -1433,7 +1433,7 @@ mod generate_tests {
#[inline(always)]
fn call(&self, context: NativeCallContext, args: &mut [&mut Dynamic]) -> RhaiResult {
if args[0usize].is_read_only() {
return EvalAltResult::ErrorAssignmentToConstant("x".to_string(), Position::NONE).into();
return Err(EvalAltResult::ErrorAssignmentToConstant("x".to_string(), Position::NONE).into());
}
let arg1 = mem::take(args[1usize]).cast::<u64>();
let arg0 = &mut args[0usize].write_lock::<u64>().unwrap();
@ -1494,7 +1494,7 @@ mod generate_tests {
#[inline(always)]
fn call(&self, context: NativeCallContext, args: &mut [&mut Dynamic]) -> RhaiResult {
if args[0usize].is_read_only() {
return EvalAltResult::ErrorAssignmentToConstant("x".to_string(), Position::NONE).into();
return Err(EvalAltResult::ErrorAssignmentToConstant("x".to_string(), Position::NONE).into());
}
let arg1 = mem::take(args[1usize]).cast::<u64>();
let arg0 = &mut args[0usize].write_lock::<u64>().unwrap();
@ -1552,7 +1552,73 @@ mod generate_tests {
#[inline(always)]
fn call(&self, context: NativeCallContext, args: &mut [&mut Dynamic]) -> RhaiResult {
if args[0usize].is_read_only() {
return EvalAltResult::ErrorAssignmentToConstant("x".to_string(), Position::NONE).into();
return Err(EvalAltResult::ErrorAssignmentToConstant("x".to_string(), Position::NONE).into());
}
let arg1 = mem::take(args[1usize]).cast::<u64>();
let arg0 = &mut args[0usize].write_lock::<MyCollection>().unwrap();
Ok(Dynamic::from(get_by_index(arg0, arg1)))
}
#[inline(always)] fn is_method_call(&self) -> bool { true }
}
}
};
let item_mod = syn::parse2::<Module>(input_tokens).unwrap();
assert_streams_eq(item_mod.generate(), expected_tokens);
}
#[test]
fn one_index_getter_fn_with_cfg_attr_module() {
let input_tokens: TokenStream = quote! {
pub mod one_index_fn {
#[cfg(hello)]
#[rhai_fn(index_get)]
#[some_other_attr]
pub fn get_by_index(x: &mut MyCollection, i: u64) -> FLOAT {
x.get(i)
}
}
};
let expected_tokens = quote! {
pub mod one_index_fn {
#[cfg(hello)]
#[some_other_attr]
pub fn get_by_index(x: &mut MyCollection, i: u64) -> FLOAT {
x.get(i)
}
#[allow(unused_imports)]
use super::*;
pub fn rhai_module_generate() -> Module {
let mut m = Module::new();
rhai_generate_into_module(&mut m, false);
m.build_index();
m
}
#[allow(unused_mut)]
pub fn rhai_generate_into_module(m: &mut Module, flatten: bool) {
#[cfg(hello)]
m.set_fn("index$get$", FnNamespace::Global, FnAccess::Public, Some(get_by_index_token::PARAM_NAMES),
&[TypeId::of::<MyCollection>(), TypeId::of::<u64>()],
get_by_index_token().into());
if flatten {} else {}
}
#[cfg(hello)]
#[allow(non_camel_case_types)]
pub struct get_by_index_token();
#[cfg(hello)]
impl get_by_index_token {
pub const PARAM_NAMES: &'static [&'static str] = &["x: &mut MyCollection", "i: u64", "FLOAT"];
#[inline(always)] pub fn param_types() -> [TypeId; 2usize] { [TypeId::of::<MyCollection>(), TypeId::of::<u64>()] }
}
#[cfg(hello)]
impl PluginFunction for get_by_index_token {
#[inline(always)]
fn call(&self, context: NativeCallContext, args: &mut [&mut Dynamic]) -> RhaiResult {
if args[0usize].is_read_only() {
return Err(EvalAltResult::ErrorAssignmentToConstant("x".to_string(), Position::NONE).into());
}
let arg1 = mem::take(args[1usize]).cast::<u64>();
let arg0 = &mut args[0usize].write_lock::<MyCollection>().unwrap();
@ -1613,7 +1679,7 @@ mod generate_tests {
#[inline(always)]
fn call(&self, context: NativeCallContext, args: &mut [&mut Dynamic]) -> RhaiResult {
if args[0usize].is_read_only() {
return EvalAltResult::ErrorAssignmentToConstant("x".to_string(), Position::NONE).into();
return Err(EvalAltResult::ErrorAssignmentToConstant("x".to_string(), Position::NONE).into());
}
let arg1 = mem::take(args[1usize]).cast::<u64>();
let arg0 = &mut args[0usize].write_lock::<MyCollection>().unwrap();
@ -1671,7 +1737,7 @@ mod generate_tests {
#[inline(always)]
fn call(&self, context: NativeCallContext, args: &mut [&mut Dynamic]) -> RhaiResult {
if args[0usize].is_read_only() {
return EvalAltResult::ErrorAssignmentToConstant("x".to_string(), Position::NONE).into();
return Err(EvalAltResult::ErrorAssignmentToConstant("x".to_string(), Position::NONE).into());
}
let arg1 = mem::take(args[1usize]).cast::<u64>();
let arg2 = mem::take(args[2usize]).cast::<FLOAT>();
@ -1733,7 +1799,7 @@ mod generate_tests {
#[inline(always)]
fn call(&self, context: NativeCallContext, args: &mut [&mut Dynamic]) -> RhaiResult {
if args[0usize].is_read_only() {
return EvalAltResult::ErrorAssignmentToConstant("x".to_string(), Position::NONE).into();
return Err(EvalAltResult::ErrorAssignmentToConstant("x".to_string(), Position::NONE).into());
}
let arg1 = mem::take(args[1usize]).cast::<u64>();
let arg2 = mem::take(args[2usize]).cast::<FLOAT>();
@ -1811,6 +1877,7 @@ mod generate_tests {
pub const MYSTIC_NUMBER: INT = 42;
}
pub mod second_is {
#[cfg(hello)]
pub const SPECIAL_CPU_NUMBER: INT = 68000;
}
}
@ -1836,6 +1903,7 @@ mod generate_tests {
}
}
pub mod second_is {
#[cfg(hello)]
pub const SPECIAL_CPU_NUMBER: INT = 68000;
#[allow(unused_imports)]
use super::*;
@ -1848,6 +1916,7 @@ mod generate_tests {
}
#[allow(unused_mut)]
pub fn rhai_generate_into_module(m: &mut Module, flatten: bool) {
#[cfg(hello)]
m.set_var("SPECIAL_CPU_NUMBER", SPECIAL_CPU_NUMBER);
if flatten {} else {}
}

View File

@ -1,11 +1,11 @@
error: unknown attribute 'unknown'
--> $DIR/export_fn_bad_attr.rs:9:13
--> ui_tests/export_fn_bad_attr.rs:9:13
|
9 | #[export_fn(unknown = "thing")]
| ^^^^^^^
error[E0425]: cannot find function `test_fn` in this scope
--> $DIR/export_fn_bad_attr.rs:19:8
--> ui_tests/export_fn_bad_attr.rs:19:8
|
19 | if test_fn(n) {
| ^^^^^^^ not found in this scope

View File

@ -1,11 +1,11 @@
error: expecting string literal
--> $DIR/export_fn_bad_value.rs:9:20
--> ui_tests/export_fn_bad_value.rs:9:20
|
9 | #[export_fn(name = true)]
| ^^^^
error[E0425]: cannot find function `test_fn` in this scope
--> $DIR/export_fn_bad_value.rs:19:8
--> ui_tests/export_fn_bad_value.rs:19:8
|
19 | if test_fn(n) {
| ^^^^^^^ not found in this scope

View File

@ -1,11 +1,11 @@
error: cfg attributes not allowed on this item
--> $DIR/export_fn_cfg.rs:9:1
error: `cfg` attributes are not allowed for `export_fn`
--> ui_tests/export_fn_cfg.rs:9:1
|
9 | #[cfg(not(feature = "foo"))]
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^
error[E0425]: cannot find function `test_fn` in this scope
--> $DIR/export_fn_cfg.rs:20:8
--> ui_tests/export_fn_cfg.rs:20:8
|
20 | if test_fn(n) {
| ^^^^^^^ not found in this scope

View File

@ -1,11 +1,11 @@
error: extraneous value
--> $DIR/export_fn_extra_value.rs:9:26
--> ui_tests/export_fn_extra_value.rs:9:26
|
9 | #[export_fn(return_raw = "yes")]
| ^^^^^
error[E0425]: cannot find function `test_fn` in this scope
--> $DIR/export_fn_extra_value.rs:19:8
--> ui_tests/export_fn_extra_value.rs:19:8
|
19 | if test_fn(n) {
| ^^^^^^^ not found in this scope

View File

@ -1,11 +1,11 @@
error: expecting identifier
--> $DIR/export_fn_junk_arg.rs:9:13
--> ui_tests/export_fn_junk_arg.rs:9:13
|
9 | #[export_fn("wheeeee")]
| ^^^^^^^^^
error[E0425]: cannot find function `test_fn` in this scope
--> $DIR/export_fn_junk_arg.rs:19:8
--> ui_tests/export_fn_junk_arg.rs:19:8
|
19 | if test_fn(n) {
| ^^^^^^^ not found in this scope

View File

@ -1,11 +1,11 @@
error: requires value
--> $DIR/export_fn_missing_value.rs:9:13
--> ui_tests/export_fn_missing_value.rs:9:13
|
9 | #[export_fn(name)]
| ^^^^
error[E0425]: cannot find function `test_fn` in this scope
--> $DIR/export_fn_missing_value.rs:19:8
--> ui_tests/export_fn_missing_value.rs:19:8
|
19 | if test_fn(n) {
| ^^^^^^^ not found in this scope

View File

@ -1,11 +1,11 @@
error: expecting attribute name
--> $DIR/export_fn_path_attr.rs:9:13
--> ui_tests/export_fn_path_attr.rs:9:13
|
9 | #[export_fn(rhai::name = "thing")]
| ^^^^^^^^^^
error[E0425]: cannot find function `test_fn` in this scope
--> $DIR/export_fn_path_attr.rs:19:8
--> ui_tests/export_fn_path_attr.rs:19:8
|
19 | if test_fn(n) {
| ^^^^^^^ not found in this scope

View File

@ -1,11 +1,11 @@
error: functions marked with 'return_raw' must return Result<T, Box<EvalAltResult>>
--> $DIR/export_fn_raw_noreturn.rs:9:13
--> ui_tests/export_fn_raw_noreturn.rs:9:13
|
9 | #[export_fn(return_raw)]
| ^^^^^^^^^^
error[E0425]: cannot find function `test_fn` in this scope
--> $DIR/export_fn_raw_noreturn.rs:19:5
--> ui_tests/export_fn_raw_noreturn.rs:19:5
|
19 | test_fn(&mut n);
| ^^^^^^^ not found in this scope

View File

@ -1,5 +1,5 @@
error[E0599]: the method `map` exists for type `bool`, but its trait bounds were not satisfied
--> $DIR/export_fn_raw_return.rs:10:33
--> ui_tests/export_fn_raw_return.rs:10:33
|
10 | pub fn test_fn(input: Point) -> bool {
| ^^^^ method cannot be called on `bool` due to unsatisfied trait bounds

View File

@ -1,11 +1,11 @@
error: unknown attribute 'unknown'
--> $DIR/export_mod_bad_attr.rs:11:11
--> ui_tests/export_mod_bad_attr.rs:11:11
|
11 | #[rhai_fn(unknown = "thing")]
| ^^^^^^^
error[E0433]: failed to resolve: use of undeclared crate or module `test_mod`
--> $DIR/export_mod_bad_attr.rs:22:8
--> ui_tests/export_mod_bad_attr.rs:22:8
|
22 | if test_mod::test_fn(n) {
| ^^^^^^^^ use of undeclared crate or module `test_mod`

View File

@ -1,11 +1,11 @@
error: expecting string literal
--> $DIR/export_mod_bad_value.rs:11:18
--> ui_tests/export_mod_bad_value.rs:11:18
|
11 | #[rhai_fn(name = true)]
| ^^^^
error[E0433]: failed to resolve: use of undeclared crate or module `test_mod`
--> $DIR/export_mod_bad_value.rs:22:8
--> ui_tests/export_mod_bad_value.rs:22:8
|
22 | if test_mod::test_fn(n) {
| ^^^^^^^^ use of undeclared crate or module `test_mod`

View File

@ -1,11 +1,11 @@
error: cfg attributes not allowed on this item
--> $DIR/export_mod_cfg.rs:11:1
error: expected attribute arguments in parentheses: #[rhai_fn(...)]
--> ui_tests/export_mod_cfg.rs:12:1
|
11 | #[cfg(not(feature = "foo"))]
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^
12 | #[rhai_fn]
| ^^^^^^^^^^
error[E0433]: failed to resolve: use of undeclared crate or module `test_mod`
--> $DIR/export_mod_cfg.rs:23:8
--> ui_tests/export_mod_cfg.rs:23:8
|
23 | if test_mod::test_fn(n) {
| ^^^^^^^^ use of undeclared crate or module `test_mod`

View File

@ -1,11 +1,11 @@
error: extraneous value
--> $DIR/export_mod_extra_value.rs:11:24
--> ui_tests/export_mod_extra_value.rs:11:24
|
11 | #[rhai_fn(return_raw = "yes")]
| ^^^^^
error[E0433]: failed to resolve: use of undeclared crate or module `test_mod`
--> $DIR/export_mod_extra_value.rs:22:8
--> ui_tests/export_mod_extra_value.rs:22:8
|
22 | if test_mod::test_fn(n) {
| ^^^^^^^^ use of undeclared crate or module `test_mod`

View File

@ -1,11 +1,11 @@
error: expecting identifier
--> $DIR/export_mod_junk_arg.rs:11:11
--> ui_tests/export_mod_junk_arg.rs:11:11
|
11 | #[rhai_fn("wheeeee")]
| ^^^^^^^^^
error[E0433]: failed to resolve: use of undeclared crate or module `test_mod`
--> $DIR/export_mod_junk_arg.rs:22:8
--> ui_tests/export_mod_junk_arg.rs:22:8
|
22 | if test_mod::test_fn(n) {
| ^^^^^^^^ use of undeclared crate or module `test_mod`

View File

@ -1,11 +1,11 @@
error: requires value
--> $DIR/export_mod_missing_value.rs:11:11
--> ui_tests/export_mod_missing_value.rs:11:11
|
11 | #[rhai_fn(name)]
| ^^^^
error[E0433]: failed to resolve: use of undeclared crate or module `test_mod`
--> $DIR/export_mod_missing_value.rs:22:8
--> ui_tests/export_mod_missing_value.rs:22:8
|
22 | if test_mod::test_fn(n) {
| ^^^^^^^^ use of undeclared crate or module `test_mod`

View File

@ -1,11 +1,11 @@
error: expecting attribute name
--> $DIR/export_mod_path_attr.rs:11:11
--> ui_tests/export_mod_path_attr.rs:11:11
|
11 | #[rhai_fn(rhai::name = "thing")]
| ^^^^^^^^^^
error[E0433]: failed to resolve: use of undeclared crate or module `test_mod`
--> $DIR/export_mod_path_attr.rs:22:8
--> ui_tests/export_mod_path_attr.rs:22:8
|
22 | if test_mod::test_fn(n) {
| ^^^^^^^^ use of undeclared crate or module `test_mod`

View File

@ -1,11 +1,11 @@
error: functions marked with 'return_raw' must return Result<T, Box<EvalAltResult>>
--> $DIR/export_mod_raw_noreturn.rs:11:11
--> ui_tests/export_mod_raw_noreturn.rs:11:11
|
11 | #[rhai_fn(return_raw)]
| ^^^^^^^^^^
error[E0433]: failed to resolve: use of undeclared crate or module `test_mod`
--> $DIR/export_mod_raw_noreturn.rs:22:5
--> ui_tests/export_mod_raw_noreturn.rs:22:5
|
22 | test_mod::test_fn(&mut n);
| ^^^^^^^^ use of undeclared crate or module `test_mod`

View File

@ -1,5 +1,5 @@
error[E0599]: the method `map` exists for type `bool`, but its trait bounds were not satisfied
--> $DIR/export_mod_raw_return.rs:12:33
--> ui_tests/export_mod_raw_return.rs:12:33
|
12 | pub fn test_fn(input: Point) -> bool {
| ^^^^ method cannot be called on `bool` due to unsatisfied trait bounds

View File

@ -1,11 +1,11 @@
error: references from Rhai in this position must be mutable
--> $DIR/first_shared_ref.rs:11:23
--> ui_tests/first_shared_ref.rs:11:23
|
11 | pub fn test_fn(input: &NonClonable) -> bool {
| ^^^^^^^^^^^^
error[E0425]: cannot find function `test_fn` in this scope
--> $DIR/first_shared_ref.rs:22:8
--> ui_tests/first_shared_ref.rs:22:8
|
22 | if test_fn(n) {
| ^^^^^^^ not found in this scope

View File

@ -1,31 +0,0 @@
use rhai::plugin::*;
#[derive(Clone)]
pub struct Point {
x: f32,
y: f32,
}
#[export_module]
pub mod test_module {
use rhai::FLOAT;
#[cfg(feature = "foo")]
pub const MAGIC: FLOAT = 42.0 as FLOAT;
pub fn test_fn(input: Point) -> bool {
input.x > input.y
}
}
fn main() {
let n = Point {
x: 0.0,
y: 10.0,
};
if test_module::test_fn(n) {
println!("yes");
} else {
println!("no");
}
}

View File

@ -1,11 +0,0 @@
error: cfg attributes not allowed on this item
--> $DIR/module_cfg_const.rs:13:5
|
13 | #[cfg(feature = "foo")]
| ^^^^^^^^^^^^^^^^^^^^^^^
error[E0433]: failed to resolve: use of undeclared crate or module `test_module`
--> $DIR/module_cfg_const.rs:26:8
|
26 | if test_module::test_fn(n) {
| ^^^^^^^^^^^ use of undeclared crate or module `test_module`

View File

@ -1,27 +0,0 @@
use rhai::plugin::*;
#[derive(Clone)]
pub struct Point {
x: f32,
y: f32,
}
#[export_module]
pub mod test_module {
#[cfg(not(feature = "foo"))]
pub fn test_fn(input: Point) -> bool {
input.x > input.y
}
}
fn main() {
let n = Point {
x: 0.0,
y: 10.0,
};
if test_module::test_fn(n) {
println!("yes");
} else {
println!("no");
}
}

View File

@ -1,11 +0,0 @@
error: cfg attributes not allowed on this item
--> $DIR/module_cfg_fn.rs:11:5
|
11 | #[cfg(not(feature = "foo"))]
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^
error[E0433]: failed to resolve: use of undeclared crate or module `test_module`
--> $DIR/module_cfg_fn.rs:22:8
|
22 | if test_module::test_fn(n) {
| ^^^^^^^^^^^ use of undeclared crate or module `test_module`

View File

@ -1,5 +1,5 @@
error[E0277]: the trait bound `NonClonable: Clone` is not satisfied
--> $DIR/non_clonable.rs:11:23
--> ui_tests/non_clonable.rs:11:23
|
11 | pub fn test_fn(input: NonClonable) -> bool {
| ^^^^^^^^^^^ the trait `Clone` is not implemented for `NonClonable`

View File

@ -1,5 +1,5 @@
error[E0277]: the trait bound `NonClonable: Clone` is not satisfied
--> $DIR/non_clonable_second.rs:11:27
--> ui_tests/non_clonable_second.rs:11:27
|
11 | pub fn test_fn(a: u32, b: NonClonable) -> bool {
| ^^^^^^^^^^^ the trait `Clone` is not implemented for `NonClonable`

View File

@ -1,11 +1,11 @@
error: Rhai functions cannot return references
--> $DIR/return_mut_ref.rs:12:38
--> ui_tests/return_mut_ref.rs:12:38
|
12 | pub fn test_fn(input: &mut Clonable) -> &mut bool {
| ^^^^^^^^^^^^
error[E0425]: cannot find function `test_fn` in this scope
--> $DIR/return_mut_ref.rs:23:8
--> ui_tests/return_mut_ref.rs:23:8
|
23 | if test_fn(n) {
| ^^^^^^^ not found in this scope

View File

@ -1,11 +1,11 @@
error: Rhai functions cannot return pointers
--> $DIR/return_pointer.rs:12:33
--> ui_tests/return_pointer.rs:12:33
|
12 | pub fn test_fn(input: Clonable) -> *const str {
| ^^^^^^^^^^^^^
error[E0425]: cannot find function `test_fn` in this scope
--> $DIR/return_pointer.rs:24:19
--> ui_tests/return_pointer.rs:24:19
|
24 | let ptr = test_fn(n);
| ^^^^^^^ not found in this scope

View File

@ -1,11 +1,11 @@
error: Rhai functions cannot return references
--> $DIR/return_shared_ref.rs:12:33
--> ui_tests/return_shared_ref.rs:12:33
|
12 | pub fn test_fn(input: Clonable) -> &'static str {
| ^^^^^^^^^^^^^^^
error[E0425]: cannot find function `test_fn` in this scope
--> $DIR/return_shared_ref.rs:23:20
--> ui_tests/return_shared_ref.rs:23:20
|
23 | println!("{}", test_fn(n));
| ^^^^^^^ not found in this scope

View File

@ -1,11 +1,11 @@
error: unknown attribute 'unknown'
--> $DIR/rhai_fn_bad_attr.rs:11:11
--> ui_tests/rhai_fn_bad_attr.rs:11:11
|
11 | #[rhai_fn(unknown = "thing")]
| ^^^^^^^
error[E0433]: failed to resolve: use of undeclared crate or module `test_module`
--> $DIR/rhai_fn_bad_attr.rs:22:8
--> ui_tests/rhai_fn_bad_attr.rs:22:8
|
22 | if test_module::test_fn(n) {
| ^^^^^^^^^^^ use of undeclared crate or module `test_module`

View File

@ -1,11 +1,11 @@
error: expecting string literal
--> $DIR/rhai_fn_bad_value.rs:11:18
--> ui_tests/rhai_fn_bad_value.rs:11:18
|
11 | #[rhai_fn(name = true)]
| ^^^^
error[E0433]: failed to resolve: use of undeclared crate or module `test_module`
--> $DIR/rhai_fn_bad_value.rs:22:8
--> ui_tests/rhai_fn_bad_value.rs:22:8
|
22 | if test_module::test_fn(n) {
| ^^^^^^^^^^^ use of undeclared crate or module `test_module`

View File

@ -1,11 +1,11 @@
error: extraneous value
--> $DIR/rhai_fn_extra_value.rs:11:24
--> ui_tests/rhai_fn_extra_value.rs:11:24
|
11 | #[rhai_fn(return_raw = "yes")]
| ^^^^^
error[E0433]: failed to resolve: use of undeclared crate or module `test_module`
--> $DIR/rhai_fn_extra_value.rs:22:8
--> ui_tests/rhai_fn_extra_value.rs:22:8
|
22 | if test_module::test_fn(n) {
| ^^^^^^^^^^^ use of undeclared crate or module `test_module`

View File

@ -1,11 +1,11 @@
error: conflicting setter
--> $DIR/rhai_fn_getter_conflict.rs:12:42
--> ui_tests/rhai_fn_getter_conflict.rs:12:42
|
12 | #[rhai_fn(name = "foo", get = "foo", set = "bar")]
| ^^^^^^^^^^^
error[E0433]: failed to resolve: use of undeclared crate or module `test_module`
--> $DIR/rhai_fn_getter_conflict.rs:23:8
--> ui_tests/rhai_fn_getter_conflict.rs:23:8
|
23 | if test_module::test_fn(n) {
| ^^^^^^^^^^^ use of undeclared crate or module `test_module`

View File

@ -1,11 +1,11 @@
error: conflicting getter
--> $DIR/rhai_fn_getter_multiple.rs:12:42
--> ui_tests/rhai_fn_getter_multiple.rs:12:42
|
12 | #[rhai_fn(name = "foo", get = "foo", get = "bar")]
| ^^^^^^^^^^^
error[E0433]: failed to resolve: use of undeclared crate or module `test_module`
--> $DIR/rhai_fn_getter_multiple.rs:23:8
--> ui_tests/rhai_fn_getter_multiple.rs:23:8
|
23 | if test_module::test_fn(n) {
| ^^^^^^^^^^^ use of undeclared crate or module `test_module`

View File

@ -1,11 +1,11 @@
error: property getter must return a value
--> $DIR/rhai_fn_getter_return.rs:13:9
--> ui_tests/rhai_fn_getter_return.rs:13:9
|
13 | pub fn test_fn(input: &mut Point) {
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
error[E0433]: failed to resolve: use of undeclared crate or module `test_module`
--> $DIR/rhai_fn_getter_return.rs:23:5
--> ui_tests/rhai_fn_getter_return.rs:23:5
|
23 | test_module::test_fn(&mut n);
| ^^^^^^^^^^^ use of undeclared crate or module `test_module`

View File

@ -1,11 +1,11 @@
error: property getter requires exactly 1 parameter
--> $DIR/rhai_fn_getter_signature.rs:13:20
--> ui_tests/rhai_fn_getter_signature.rs:13:20
|
13 | pub fn test_fn(input: Point, value: bool) -> bool {
| ^^^^^^^^^^^^^^^^^^^^^^^^^
error[E0433]: failed to resolve: use of undeclared crate or module `test_module`
--> $DIR/rhai_fn_getter_signature.rs:23:8
--> ui_tests/rhai_fn_getter_signature.rs:23:8
|
23 | if test_module::test_fn(n, true) {
| ^^^^^^^^^^^ use of undeclared crate or module `test_module`

View File

@ -1,11 +1,11 @@
error: namespace is already set to 'global'
--> $DIR/rhai_fn_global_multiple.rs:12:23
--> ui_tests/rhai_fn_global_multiple.rs:12:23
|
12 | #[rhai_fn(global, internal)]
| ^^^^^^^^
error[E0433]: failed to resolve: use of undeclared crate or module `test_module`
--> $DIR/rhai_fn_global_multiple.rs:23:8
--> ui_tests/rhai_fn_global_multiple.rs:23:8
|
23 | if test_module::test_fn(n) {
| ^^^^^^^^^^^ use of undeclared crate or module `test_module`

View File

@ -1,11 +1,11 @@
error: conflicting index_get
--> $DIR/rhai_fn_index_getter_multiple.rs:12:40
--> ui_tests/rhai_fn_index_getter_multiple.rs:12:40
|
12 | #[rhai_fn(name = "foo", index_get, index_get)]
| ^^^^^^^^^
error[E0433]: failed to resolve: use of undeclared crate or module `test_module`
--> $DIR/rhai_fn_index_getter_multiple.rs:23:8
--> ui_tests/rhai_fn_index_getter_multiple.rs:23:8
|
23 | if test_module::test_fn(n) {
| ^^^^^^^^^^^ use of undeclared crate or module `test_module`

View File

@ -1,11 +1,11 @@
error: index getter must return a value
--> $DIR/rhai_fn_index_getter_return.rs:13:9
--> ui_tests/rhai_fn_index_getter_return.rs:13:9
|
13 | pub fn test_fn(input: &mut Point, i: f32) {
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
error[E0433]: failed to resolve: use of undeclared crate or module `test_module`
--> $DIR/rhai_fn_index_getter_return.rs:23:8
--> ui_tests/rhai_fn_index_getter_return.rs:23:8
|
23 | if test_module::test_fn(&mut n, 5.0) {
| ^^^^^^^^^^^ use of undeclared crate or module `test_module`

View File

@ -1,11 +1,11 @@
error: index getter requires exactly 2 parameters
--> $DIR/rhai_fn_index_getter_signature.rs:13:20
--> ui_tests/rhai_fn_index_getter_signature.rs:13:20
|
13 | pub fn test_fn(input: Point) -> bool {
| ^^^^^^^^^^^^
error[E0433]: failed to resolve: use of undeclared crate or module `test_module`
--> $DIR/rhai_fn_index_getter_signature.rs:23:8
--> ui_tests/rhai_fn_index_getter_signature.rs:23:8
|
23 | if test_module::test_fn(n) {
| ^^^^^^^^^^^ use of undeclared crate or module `test_module`

View File

@ -1,11 +1,11 @@
error: conflicting index_set
--> $DIR/rhai_fn_index_setter_multiple.rs:12:40
--> ui_tests/rhai_fn_index_setter_multiple.rs:12:40
|
12 | #[rhai_fn(name = "foo", index_set, index_set)]
| ^^^^^^^^^
error[E0433]: failed to resolve: use of undeclared crate or module `test_module`
--> $DIR/rhai_fn_index_setter_multiple.rs:23:8
--> ui_tests/rhai_fn_index_setter_multiple.rs:23:8
|
23 | if test_module::test_fn(n) {
| ^^^^^^^^^^^ use of undeclared crate or module `test_module`

View File

@ -1,11 +1,11 @@
error: expecting identifier
--> $DIR/rhai_fn_junk_arg.rs:11:11
--> ui_tests/rhai_fn_junk_arg.rs:11:11
|
11 | #[rhai_fn("wheeeee")]
| ^^^^^^^^^
error[E0433]: failed to resolve: use of undeclared crate or module `test_module`
--> $DIR/rhai_fn_junk_arg.rs:22:8
--> ui_tests/rhai_fn_junk_arg.rs:22:8
|
22 | if test_module::test_fn(n) {
| ^^^^^^^^^^^ use of undeclared crate or module `test_module`

View File

@ -1,11 +1,11 @@
error: requires value
--> $DIR/rhai_fn_missing_value.rs:11:11
--> ui_tests/rhai_fn_missing_value.rs:11:11
|
11 | #[rhai_fn(name)]
| ^^^^
error[E0433]: failed to resolve: use of undeclared crate or module `test_module`
--> $DIR/rhai_fn_missing_value.rs:22:8
--> ui_tests/rhai_fn_missing_value.rs:22:8
|
22 | if test_module::test_fn(n) {
| ^^^^^^^^^^^ use of undeclared crate or module `test_module`

View File

@ -1,5 +1,5 @@
error[E0277]: the trait bound `NonClonable: Clone` is not satisfied
--> $DIR/rhai_fn_non_clonable_return.rs:11:8
--> ui_tests/rhai_fn_non_clonable_return.rs:11:8
|
11 | pub fn test_fn(input: f32) -> NonClonable {
| ^^^^^^^^^^^^^^^^^^^^^^^-----------
@ -8,7 +8,7 @@ error[E0277]: the trait bound `NonClonable: Clone` is not satisfied
| the trait `Clone` is not implemented for `NonClonable`
|
note: required by a bound in `rhai::Dynamic::from`
--> $DIR/dynamic.rs:1122:30
--> $WORKSPACE/src/dynamic.rs
|
1122 | pub fn from<T: Variant + Clone>(mut value: T) -> Self {
| pub fn from<T: Variant + Clone>(mut value: T) -> Self {
| ^^^^^ required by this bound in `rhai::Dynamic::from`

View File

@ -1,11 +1,11 @@
error: expecting attribute name
--> $DIR/rhai_fn_path_attr.rs:11:11
--> ui_tests/rhai_fn_path_attr.rs:11:11
|
11 | #[rhai_fn(rhai::name = "thing")]
| ^^^^^^^^^^
error[E0433]: failed to resolve: use of undeclared crate or module `test_module`
--> $DIR/rhai_fn_path_attr.rs:22:8
--> ui_tests/rhai_fn_path_attr.rs:22:8
|
22 | if test_module::test_fn(n) {
| ^^^^^^^^^^^ use of undeclared crate or module `test_module`

View File

@ -1,17 +1,17 @@
error: duplicate Rhai signature for 'foo'
--> $DIR/rhai_fn_rename_collision.rs:17:15
--> ui_tests/rhai_fn_rename_collision.rs:17:15
|
17 | #[rhai_fn(name = "foo")]
| ^^^^^^^^^^^^
error: duplicated function renamed 'foo'
--> $DIR/rhai_fn_rename_collision.rs:12:15
--> ui_tests/rhai_fn_rename_collision.rs:12:15
|
12 | #[rhai_fn(name = "foo")]
| ^^^^^^^^^^^^
error[E0433]: failed to resolve: use of undeclared crate or module `test_module`
--> $DIR/rhai_fn_rename_collision.rs:28:8
--> ui_tests/rhai_fn_rename_collision.rs:28:8
|
28 | if test_module::test_fn(n) {
| ^^^^^^^^^^^ use of undeclared crate or module `test_module`

View File

@ -1,17 +1,17 @@
error: duplicate Rhai signature for 'foo'
--> $DIR/rhai_fn_rename_collision_oneattr.rs:17:12
--> ui_tests/rhai_fn_rename_collision_oneattr.rs:17:12
|
17 | pub fn foo(input: Point) -> bool {
| ^^^
error: duplicated function 'foo'
--> $DIR/rhai_fn_rename_collision_oneattr.rs:12:15
--> ui_tests/rhai_fn_rename_collision_oneattr.rs:12:15
|
12 | #[rhai_fn(name = "foo")]
| ^^^^^^^^^^^^
error[E0433]: failed to resolve: use of undeclared crate or module `test_module`
--> $DIR/rhai_fn_rename_collision_oneattr.rs:27:8
--> ui_tests/rhai_fn_rename_collision_oneattr.rs:27:8
|
27 | if test_module::test_fn(n) {
| ^^^^^^^^^^^ use of undeclared crate or module `test_module`

View File

@ -1,17 +1,17 @@
error: duplicate Rhai signature for 'bar'
--> $DIR/rhai_fn_rename_collision_oneattr_multiple.rs:17:15
--> ui_tests/rhai_fn_rename_collision_oneattr_multiple.rs:17:15
|
17 | #[rhai_fn(get = "bar")]
| ^^^^^^^^^^^
error: duplicated function renamed 'bar'
--> $DIR/rhai_fn_rename_collision_oneattr_multiple.rs:12:15
--> ui_tests/rhai_fn_rename_collision_oneattr_multiple.rs:12:15
|
12 | #[rhai_fn(name = "foo", get = "bar")]
| ^^^^^^^^^^^^^^^^^^^^^^^^^
error[E0433]: failed to resolve: use of undeclared crate or module `test_module`
--> $DIR/rhai_fn_rename_collision_oneattr_multiple.rs:25:8
--> ui_tests/rhai_fn_rename_collision_oneattr_multiple.rs:25:8
|
25 | if test_module::test_fn(n) {
| ^^^^^^^^^^^ use of undeclared crate or module `test_module`

View File

@ -1,17 +1,17 @@
error: duplicate Rhai signature for 'foo'
--> $DIR/rhai_fn_rename_collision_with_itself.rs:12:15
--> ui_tests/rhai_fn_rename_collision_with_itself.rs:12:15
|
12 | #[rhai_fn(name = "foo", name = "bar", name = "foo")]
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
error: duplicated function renamed 'foo'
--> $DIR/rhai_fn_rename_collision_with_itself.rs:12:15
--> ui_tests/rhai_fn_rename_collision_with_itself.rs:12:15
|
12 | #[rhai_fn(name = "foo", name = "bar", name = "foo")]
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
error[E0433]: failed to resolve: use of undeclared crate or module `test_module`
--> $DIR/rhai_fn_rename_collision_with_itself.rs:20:8
--> ui_tests/rhai_fn_rename_collision_with_itself.rs:20:8
|
20 | if test_module::test_fn(n) {
| ^^^^^^^^^^^ use of undeclared crate or module `test_module`

View File

@ -1,11 +1,11 @@
error: use attribute 'index_get' instead
--> $DIR/rhai_fn_rename_to_index_getter.rs:12:15
--> ui_tests/rhai_fn_rename_to_index_getter.rs:12:15
|
12 | #[rhai_fn(name = "index$get$")]
| ^^^^^^^^^^^^^^^^^^^
error[E0433]: failed to resolve: use of undeclared crate or module `test_module`
--> $DIR/rhai_fn_rename_to_index_getter.rs:23:8
--> ui_tests/rhai_fn_rename_to_index_getter.rs:23:8
|
23 | if test_module::test_fn(n) {
| ^^^^^^^^^^^ use of undeclared crate or module `test_module`

View File

@ -1,11 +1,11 @@
error: use attribute 'index_set' instead
--> $DIR/rhai_fn_rename_to_index_setter.rs:12:15
--> ui_tests/rhai_fn_rename_to_index_setter.rs:12:15
|
12 | #[rhai_fn(name = "index$set$")]
| ^^^^^^^^^^^^^^^^^^^
error[E0433]: failed to resolve: use of undeclared crate or module `test_module`
--> $DIR/rhai_fn_rename_to_index_setter.rs:23:8
--> ui_tests/rhai_fn_rename_to_index_setter.rs:23:8
|
23 | if test_module::test_fn(n) {
| ^^^^^^^^^^^ use of undeclared crate or module `test_module`

View File

@ -1,11 +1,11 @@
error: use attribute 'getter = "foo"' instead
--> $DIR/rhai_fn_rename_to_prop_getter.rs:12:15
--> ui_tests/rhai_fn_rename_to_prop_getter.rs:12:15
|
12 | #[rhai_fn(name = "get$foo")]
| ^^^^^^^^^^^^^^^^
error[E0433]: failed to resolve: use of undeclared crate or module `test_module`
--> $DIR/rhai_fn_rename_to_prop_getter.rs:23:8
--> ui_tests/rhai_fn_rename_to_prop_getter.rs:23:8
|
23 | if test_module::test_fn(n) {
| ^^^^^^^^^^^ use of undeclared crate or module `test_module`

View File

@ -1,11 +1,11 @@
error: use attribute 'getter = "foo"' instead
--> $DIR/rhai_fn_rename_to_prop_setter.rs:12:15
--> ui_tests/rhai_fn_rename_to_prop_setter.rs:12:15
|
12 | #[rhai_fn(name = "get$foo")]
| ^^^^^^^^^^^^^^^^
error[E0433]: failed to resolve: use of undeclared crate or module `test_module`
--> $DIR/rhai_fn_rename_to_prop_setter.rs:23:8
--> ui_tests/rhai_fn_rename_to_prop_setter.rs:23:8
|
23 | if test_module::test_fn(n) {
| ^^^^^^^^^^^ use of undeclared crate or module `test_module`

View File

@ -1,11 +1,11 @@
error: index setter requires exactly 3 parameters
--> $DIR/rhai_fn_setter_index_signature.rs:13:20
--> ui_tests/rhai_fn_setter_index_signature.rs:13:20
|
13 | pub fn test_fn(input: Point) -> bool {
| ^^^^^^^^^^^^
error[E0433]: failed to resolve: use of undeclared crate or module `test_module`
--> $DIR/rhai_fn_setter_index_signature.rs:23:8
--> ui_tests/rhai_fn_setter_index_signature.rs:23:8
|
23 | if test_module::test_fn(n) {
| ^^^^^^^^^^^ use of undeclared crate or module `test_module`

View File

@ -1,11 +1,11 @@
error: conflicting setter
--> $DIR/rhai_fn_setter_multiple.rs:12:42
--> ui_tests/rhai_fn_setter_multiple.rs:12:42
|
12 | #[rhai_fn(name = "foo", set = "foo", set = "bar")]
| ^^^^^^^^^^^
error[E0433]: failed to resolve: use of undeclared crate or module `test_module`
--> $DIR/rhai_fn_setter_multiple.rs:23:8
--> ui_tests/rhai_fn_setter_multiple.rs:23:8
|
23 | if test_module::test_fn(n) {
| ^^^^^^^^^^^ use of undeclared crate or module `test_module`

View File

@ -1,11 +1,11 @@
error: property setter cannot return any value
--> $DIR/rhai_fn_setter_return.rs:13:51
--> ui_tests/rhai_fn_setter_return.rs:13:51
|
13 | pub fn test_fn(input: &mut Point, value: f32) -> bool {
| ^^^^^^^
error[E0433]: failed to resolve: use of undeclared crate or module `test_module`
--> $DIR/rhai_fn_setter_return.rs:24:8
--> ui_tests/rhai_fn_setter_return.rs:24:8
|
24 | if test_module::test_fn(&mut n, 5.0) {
| ^^^^^^^^^^^ use of undeclared crate or module `test_module`

View File

@ -1,11 +1,11 @@
error: property setter requires exactly 2 parameters
--> $DIR/rhai_fn_setter_signature.rs:13:20
--> ui_tests/rhai_fn_setter_signature.rs:13:20
|
13 | pub fn test_fn(input: Point) -> bool {
| ^^^^^^^^^^^^
error[E0433]: failed to resolve: use of undeclared crate or module `test_module`
--> $DIR/rhai_fn_setter_signature.rs:23:8
--> ui_tests/rhai_fn_setter_signature.rs:23:8
|
23 | if test_module::test_fn(n) {
| ^^^^^^^^^^^ use of undeclared crate or module `test_module`

View File

@ -1,11 +1,11 @@
error: unknown attribute 'unknown'
--> $DIR/rhai_mod_bad_attr.rs:11:12
--> ui_tests/rhai_mod_bad_attr.rs:11:12
|
11 | #[rhai_mod(unknown = "thing")]
| ^^^^^^^
error[E0433]: failed to resolve: use of undeclared crate or module `test_module`
--> $DIR/rhai_mod_bad_attr.rs:24:8
--> ui_tests/rhai_mod_bad_attr.rs:24:8
|
24 | if test_module::test_fn(n) {
| ^^^^^^^^^^^ use of undeclared crate or module `test_module`

View File

@ -1,11 +1,11 @@
error: expecting string literal
--> $DIR/rhai_mod_bad_value.rs:11:19
--> ui_tests/rhai_mod_bad_value.rs:11:19
|
11 | #[rhai_mod(name = true)]
| ^^^^
error[E0433]: failed to resolve: use of undeclared crate or module `test_module`
--> $DIR/rhai_mod_bad_value.rs:24:8
--> ui_tests/rhai_mod_bad_value.rs:24:8
|
24 | if test_module::test_fn(n) {
| ^^^^^^^^^^^ use of undeclared crate or module `test_module`

View File

@ -1,5 +1,5 @@
error[E0433]: failed to resolve: could not find `test_mod` in `test_module`
--> $DIR/rhai_mod_inner_cfg_false.rs:24:21
--> ui_tests/rhai_mod_inner_cfg_false.rs:24:21
|
24 | if test_module::test_mod::test_fn(n) {
| ^^^^^^^^ could not find `test_mod` in `test_module`

View File

@ -1,11 +1,11 @@
error: expecting identifier
--> $DIR/rhai_mod_junk_arg.rs:11:12
--> ui_tests/rhai_mod_junk_arg.rs:11:12
|
11 | #[rhai_mod("wheeeee")]
| ^^^^^^^^^
error[E0433]: failed to resolve: use of undeclared crate or module `test_module`
--> $DIR/rhai_mod_junk_arg.rs:24:8
--> ui_tests/rhai_mod_junk_arg.rs:24:8
|
24 | if test_module::test_fn(n) {
| ^^^^^^^^^^^ use of undeclared crate or module `test_module`

View File

@ -1,11 +1,11 @@
error: requires value
--> $DIR/rhai_mod_missing_value.rs:11:12
--> ui_tests/rhai_mod_missing_value.rs:11:12
|
11 | #[rhai_mod(name)]
| ^^^^
error[E0433]: failed to resolve: use of undeclared crate or module `test_module`
--> $DIR/rhai_mod_missing_value.rs:24:8
--> ui_tests/rhai_mod_missing_value.rs:24:8
|
24 | if test_module::test_fn(n) {
| ^^^^^^^^^^^ use of undeclared crate or module `test_module`

View File

@ -1,17 +1,17 @@
error: duplicate function 'test_fn'
--> $DIR/rhai_mod_name_collisions.rs:16:12
--> ui_tests/rhai_mod_name_collisions.rs:16:12
|
16 | pub fn test_fn(input: Point) -> bool {
| ^^^^^^^
error: duplicated function 'test_fn'
--> $DIR/rhai_mod_name_collisions.rs:12:12
--> ui_tests/rhai_mod_name_collisions.rs:12:12
|
12 | pub fn test_fn(input: Point) -> bool {
| ^^^^^^^
error[E0433]: failed to resolve: use of undeclared crate or module `test_module`
--> $DIR/rhai_mod_name_collisions.rs:26:8
--> ui_tests/rhai_mod_name_collisions.rs:26:8
|
26 | if test_module::test_fn(n) {
| ^^^^^^^^^^^ use of undeclared crate or module `test_module`

View File

@ -1,5 +1,5 @@
error[E0277]: the trait bound `NonClonable: Clone` is not satisfied
--> $DIR/rhai_mod_non_clonable_return.rs:12:12
--> ui_tests/rhai_mod_non_clonable_return.rs:12:12
|
12 | pub fn test_fn(input: f32) -> NonClonable {
| ^^^^^^^^^^^^^^^^^^^^^^^-----------
@ -8,7 +8,7 @@ error[E0277]: the trait bound `NonClonable: Clone` is not satisfied
| the trait `Clone` is not implemented for `NonClonable`
|
note: required by a bound in `rhai::Dynamic::from`
--> $DIR/dynamic.rs:1122:30
--> $WORKSPACE/src/dynamic.rs
|
1122 | pub fn from<T: Variant + Clone>(mut value: T) -> Self {
| pub fn from<T: Variant + Clone>(mut value: T) -> Self {
| ^^^^^ required by this bound in `rhai::Dynamic::from`

View File

@ -1,11 +1,11 @@
error: expecting attribute name
--> $DIR/rhai_mod_path_attr.rs:11:12
--> ui_tests/rhai_mod_path_attr.rs:11:12
|
11 | #[rhai_mod(rhai::name = "thing")]
| ^^^^^^^^^^
error[E0433]: failed to resolve: use of undeclared crate or module `test_module`
--> $DIR/rhai_mod_path_attr.rs:24:8
--> ui_tests/rhai_mod_path_attr.rs:24:8
|
24 | if test_module::test_fn(n) {
| ^^^^^^^^^^^ use of undeclared crate or module `test_module`

View File

@ -1,11 +1,11 @@
error: unknown attribute 'return_raw'
--> $DIR/rhai_mod_return_raw.rs:11:12
--> ui_tests/rhai_mod_return_raw.rs:11:12
|
11 | #[rhai_mod(return_raw = "yes")]
| ^^^^^^^^^^
error[E0433]: failed to resolve: use of undeclared crate or module `test_module`
--> $DIR/rhai_mod_return_raw.rs:24:8
--> ui_tests/rhai_mod_return_raw.rs:24:8
|
24 | if test_module::test_fn(n) {
| ^^^^^^^^^^^ use of undeclared crate or module `test_module`

View File

@ -1,5 +1,5 @@
error[E0412]: cannot find type `Pointer` in this scope
--> $DIR/rhai_mod_unknown_type.rs:12:27
--> ui_tests/rhai_mod_unknown_type.rs:12:27
|
4 | pub struct Point {
| ---------------- similarly named struct `Point` defined here

View File

@ -1,5 +1,5 @@
error[E0412]: cannot find type `boool` in this scope
--> $DIR/rhai_mod_unknown_type_return.rs:12:37
--> ui_tests/rhai_mod_unknown_type_return.rs:12:37
|
12 | pub fn test_fn(input: Point) -> boool {
| ^^^^^ help: a builtin type with a similar name exists: `bool`

View File

@ -1,11 +1,11 @@
error: this type in this position passes from Rhai by value
--> $DIR/second_shared_ref.rs:12:41
error: function parameters other than the first one cannot be passed by reference
--> ui_tests/second_shared_ref.rs:12:41
|
12 | pub fn test_fn(input: Clonable, factor: &bool) -> bool {
| ^^^^^
error[E0425]: cannot find function `test_fn` in this scope
--> $DIR/second_shared_ref.rs:23:8
--> ui_tests/second_shared_ref.rs:23:8
|
23 | if test_fn(n, &true) {
| ^^^^^^^ not found in this scope

View File

@ -718,7 +718,7 @@ impl AST {
/// Not available under `no_function`.
#[cfg(not(feature = "no_function"))]
#[cfg(not(feature = "no_module"))]
#[inline(always)]
#[inline]
pub(crate) fn iter_fn_def(&self) -> impl Iterator<Item = &ScriptFnDef> {
self.functions
.iter_script_fn()
@ -728,7 +728,7 @@ impl AST {
///
/// Not available under `no_function`.
#[cfg(not(feature = "no_function"))]
#[inline(always)]
#[inline]
pub fn iter_functions<'a>(&'a self) -> impl Iterator<Item = ScriptFnMetadata> + 'a {
self.functions
.iter_script_fn()
@ -944,7 +944,7 @@ impl fmt::Debug for StmtBlock {
}
impl From<StmtBlock> for Stmt {
#[inline(always)]
#[inline]
fn from(block: StmtBlock) -> Self {
let block_pos = block.position();
Self::Block(block.0.into_boxed_slice(), block_pos)
@ -1852,7 +1852,7 @@ impl<F: Float> From<F> for FloatWrapper<F> {
impl<F: Float + FromStr> FromStr for FloatWrapper<F> {
type Err = <F as FromStr>::Err;
#[inline(always)]
#[inline]
fn from_str(s: &str) -> Result<Self, Self::Err> {
F::from_str(s).map(Into::<Self>::into)
}
@ -2003,14 +2003,12 @@ impl fmt::Debug for Expr {
}
Self::Variable(i, _, x) => {
f.write_str("Variable(")?;
match x.1 {
Some((_, ref namespace)) => write!(f, "{}", namespace)?,
_ => (),
if let Some((_, ref namespace)) = x.1 {
write!(f, "{}", namespace)?
}
f.write_str(&x.2)?;
match i.map_or_else(|| x.0, |n| NonZeroUsize::new(n.get() as usize)) {
Some(n) => write!(f, " #{}", n)?,
_ => (),
if let Some(n) = i.map_or_else(|| x.0, |n| NonZeroUsize::new(n.get() as usize)) {
write!(f, " #{}", n)?
}
f.write_str(")")
}
@ -2134,7 +2132,7 @@ impl Expr {
}
}
/// Is the expression a simple variable access?
#[inline(always)]
#[inline]
#[must_use]
pub(crate) const fn is_variable_access(&self, non_qualified: bool) -> bool {
match self {
@ -2143,7 +2141,7 @@ impl Expr {
}
}
/// Return the variable name if the expression a simple variable access.
#[inline(always)]
#[inline]
#[must_use]
pub(crate) fn get_variable_name(&self, non_qualified: bool) -> Option<&str> {
match self {

View File

@ -1,6 +1,8 @@
//! Module containing all deprecated API that will be removed in the next major version.
use crate::{Dynamic, Engine, EvalAltResult, ImmutableString, Scope, AST};
use crate::{
Dynamic, Engine, EvalAltResult, ImmutableString, NativeCallContext, RhaiResult, Scope, AST,
};
#[cfg(feature = "no_std")]
use std::prelude::v1::*;
@ -141,3 +143,37 @@ impl Dynamic {
self.into_immutable_string()
}
}
impl NativeCallContext<'_> {
/// Call a function inside the call context.
///
/// # WARNING
///
/// All arguments may be _consumed_, meaning that they may be replaced by `()`.
/// This is to avoid unnecessarily cloning the arguments.
///
/// Do not use the arguments after this call. If they are needed afterwards,
/// clone them _before_ calling this function.
///
/// If `is_method` is [`true`], the first argument is assumed to be passed
/// by reference and is not consumed.
#[deprecated(since = "1.2.0", note = "use `call_fn_raw` instead")]
#[inline(always)]
pub fn call_fn_dynamic_raw(
&self,
fn_name: impl AsRef<str>,
is_method_call: bool,
args: &mut [&mut Dynamic],
) -> RhaiResult {
self.call_fn_raw(fn_name.as_ref(), is_method_call, is_method_call, args)
}
}
#[allow(useless_deprecated)]
#[deprecated(since = "1.2.0", note = "explicitly wrap `EvalAltResult` in `Err`")]
impl<T> From<EvalAltResult> for Result<T, Box<EvalAltResult>> {
#[inline(always)]
fn from(err: EvalAltResult) -> Self {
Err(err.into())
}
}

View File

@ -255,7 +255,7 @@ enum DynamicReadLockInner<'d, T: Clone> {
impl<'d, T: Any + Clone> Deref for DynamicReadLock<'d, T> {
type Target = T;
#[inline(always)]
#[inline]
fn deref(&self) -> &Self::Target {
match self.0 {
DynamicReadLockInner::Reference(ref reference) => *reference,
@ -296,7 +296,7 @@ enum DynamicWriteLockInner<'d, T: Clone> {
impl<'d, T: Any + Clone> Deref for DynamicWriteLock<'d, T> {
type Target = T;
#[inline(always)]
#[inline]
fn deref(&self) -> &Self::Target {
match self.0 {
DynamicWriteLockInner::Reference(ref reference) => *reference,
@ -307,7 +307,7 @@ impl<'d, T: Any + Clone> Deref for DynamicWriteLock<'d, T> {
}
impl<'d, T: Any + Clone> DerefMut for DynamicWriteLock<'d, T> {
#[inline(always)]
#[inline]
fn deref_mut(&mut self) -> &mut Self::Target {
match self.0 {
DynamicWriteLockInner::Reference(ref mut reference) => *reference,
@ -384,17 +384,16 @@ impl Dynamic {
#[inline(always)]
#[must_use]
pub const fn is_shared(&self) -> bool {
match self.0 {
#[cfg(not(feature = "no_closure"))]
Union::Shared(_, _, _) => true,
_ => false,
}
return matches!(self.0, Union::Shared(_, _, _));
#[cfg(feature = "no_closure")]
return false;
}
/// Is the value held by this [`Dynamic`] a particular type?
///
/// If the [`Dynamic`] is a shared variant checking is performed on
/// top of its internal value.
#[inline(always)]
#[inline]
#[must_use]
pub fn is<T: Any + Clone>(&self) -> bool {
if TypeId::of::<T>() == TypeId::of::<String>() {
@ -1221,7 +1220,7 @@ impl Dynamic {
///
/// If the [`Dynamic`] value is already shared, this method returns itself.
#[cfg(not(feature = "no_closure"))]
#[inline(always)]
#[inline]
#[must_use]
pub fn into_shared(self) -> Self {
let _access = self.access_mode();
@ -1452,7 +1451,7 @@ impl Dynamic {
/// If the [`Dynamic`] is not a shared value, it returns a cloned copy.
///
/// If the [`Dynamic`] is a shared value, it returns a cloned copy of the shared value.
#[inline(always)]
#[inline]
#[must_use]
pub fn flatten_clone(&self) -> Self {
match self.0 {
@ -1471,7 +1470,7 @@ impl Dynamic {
///
/// If the [`Dynamic`] is a shared value, it returns the shared value if there are no
/// outstanding references, or a cloned copy.
#[inline(always)]
#[inline]
#[must_use]
pub fn flatten(self) -> Self {
match self.0 {
@ -1495,7 +1494,7 @@ impl Dynamic {
///
/// If the [`Dynamic`] is a shared value, it is set to the shared value if there are no
/// outstanding references, or a cloned copy otherwise.
#[inline(always)]
#[inline]
pub(crate) fn flatten_in_place(&mut self) -> &mut Self {
match self.0 {
#[cfg(not(feature = "no_closure"))]
@ -1528,7 +1527,7 @@ impl Dynamic {
/// Access just waits until the [`RwLock`][std::sync::RwLock] is released.
/// So this method always returns [`false`] under [`Sync`].
#[cfg(not(feature = "no_closure"))]
#[inline(always)]
#[inline]
#[must_use]
pub fn is_locked(&self) -> bool {
#[cfg(not(feature = "no_closure"))]
@ -1895,7 +1894,7 @@ impl Dynamic {
/// Convert the [`Dynamic`] into a [`String`] and return it.
/// 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.
#[inline(always)]
#[inline]
pub fn into_string(self) -> Result<String, &'static str> {
self.into_immutable_string()
.map(ImmutableString::into_owned)
@ -1997,7 +1996,7 @@ impl Dynamic {
}
#[cfg(not(feature = "no_index"))]
impl<T: Variant + Clone> From<Vec<T>> for Dynamic {
#[inline(always)]
#[inline]
fn from(value: Vec<T>) -> Self {
Self(Union::Array(
Box::new(value.into_iter().map(Dynamic::from).collect()),
@ -2008,7 +2007,7 @@ impl<T: Variant + Clone> From<Vec<T>> for Dynamic {
}
#[cfg(not(feature = "no_index"))]
impl<T: Variant + Clone> From<&[T]> for Dynamic {
#[inline(always)]
#[inline]
fn from(value: &[T]) -> Self {
Self(Union::Array(
Box::new(value.iter().cloned().map(Dynamic::from).collect()),
@ -2019,7 +2018,7 @@ impl<T: Variant + Clone> From<&[T]> for Dynamic {
}
#[cfg(not(feature = "no_index"))]
impl<T: Variant + Clone> std::iter::FromIterator<T> for Dynamic {
#[inline(always)]
#[inline]
fn from_iter<X: IntoIterator<Item = T>>(iter: X) -> Self {
Self(Union::Array(
Box::new(iter.into_iter().map(Dynamic::from).collect()),

View File

@ -9,7 +9,6 @@ use crate::fn_native::{
OnVarCallback,
};
use crate::module::NamespaceRef;
use crate::optimize::OptimizationLevel;
use crate::packages::{Package, StandardPackage};
use crate::r#unsafe::unsafe_cast_var_name_to_lifetime;
use crate::token::Token;
@ -144,7 +143,7 @@ impl Imports {
}
/// Does the specified function hash key exist in this stack of imported [modules][Module]?
#[allow(dead_code)]
#[inline(always)]
#[inline]
#[must_use]
pub fn contains_fn(&self, hash: u64) -> bool {
self.modules.iter().any(|m| m.contains_qualified_fn(hash))
@ -161,7 +160,7 @@ impl Imports {
/// Does the specified [`TypeId`][std::any::TypeId] iterator exist in this stack of
/// imported [modules][Module]?
#[allow(dead_code)]
#[inline(always)]
#[inline]
#[must_use]
pub fn contains_iter(&self, id: TypeId) -> bool {
self.modules.iter().any(|m| m.contains_qualified_iter(id))
@ -888,7 +887,7 @@ impl<'x, 'px, 'pt> EvalContext<'_, 'x, 'px, '_, '_, '_, '_, 'pt> {
self.mods
}
/// Get an iterator over the namespaces containing definition of all script-defined functions.
#[inline(always)]
#[inline]
pub fn iter_namespaces(&self) -> impl Iterator<Item = &Module> {
self.lib.iter().cloned()
}
@ -979,7 +978,8 @@ pub struct Engine {
pub(crate) progress: Option<crate::fn_native::OnProgressCallback>,
/// Optimize the AST after compilation.
pub(crate) optimization_level: OptimizationLevel,
#[cfg(not(feature = "no_optimize"))]
pub(crate) optimization_level: crate::OptimizationLevel,
/// Max limits.
#[cfg(not(feature = "unchecked"))]
@ -1101,6 +1101,7 @@ impl Engine {
#[cfg(not(feature = "unchecked"))]
progress: None,
#[cfg(not(feature = "no_optimize"))]
optimization_level: Default::default(),
#[cfg(not(feature = "unchecked"))]
@ -1221,7 +1222,7 @@ impl Engine {
return if let Some(val) = this_ptr {
Ok(((*val).into(), *pos))
} else {
EvalAltResult::ErrorUnboundThis(*pos).into()
Err(EvalAltResult::ErrorUnboundThis(*pos).into())
}
}
_ if state.always_search_scope => (0, expr.position()),
@ -1723,7 +1724,7 @@ impl Engine {
}
}
// Syntax error
_ => EvalAltResult::ErrorDotExpr("".into(), rhs.position()).into(),
_ => Err(EvalAltResult::ErrorDotExpr("".into(), rhs.position()).into()),
}
}
}
@ -1958,12 +1959,11 @@ impl Engine {
arr_len
- index
.checked_abs()
.ok_or_else(|| {
EvalAltResult::ErrorArrayBounds(arr_len, index, idx_pos).into()
})
.ok_or_else(|| EvalAltResult::ErrorArrayBounds(arr_len, index, idx_pos))
.and_then(|n| {
if n as usize > arr_len {
EvalAltResult::ErrorArrayBounds(arr_len, index, idx_pos).into()
Err(EvalAltResult::ErrorArrayBounds(arr_len, index, idx_pos)
.into())
} else {
Ok(n as usize)
}
@ -2014,7 +2014,9 @@ impl Engine {
let offset = index as usize;
(
if offset >= bits {
return EvalAltResult::ErrorBitFieldBounds(bits, index, idx_pos).into();
return Err(
EvalAltResult::ErrorBitFieldBounds(bits, index, idx_pos).into()
);
} else {
(*value & (1 << offset)) != 0
},
@ -2025,14 +2027,16 @@ impl Engine {
(
// Count from end if negative
if offset > bits {
return EvalAltResult::ErrorBitFieldBounds(bits, index, idx_pos).into();
return Err(
EvalAltResult::ErrorBitFieldBounds(bits, index, idx_pos).into()
);
} else {
(*value & (1 << (bits - offset))) != 0
},
offset,
)
} else {
return EvalAltResult::ErrorBitFieldBounds(bits, index, idx_pos).into();
return Err(EvalAltResult::ErrorBitFieldBounds(bits, index, idx_pos).into());
};
Ok(Target::BitField(target, offset, bit_value.into()))
@ -2066,7 +2070,7 @@ impl Engine {
)
} else {
let chars_len = s.chars().count();
return EvalAltResult::ErrorStringBounds(chars_len, index, idx_pos).into();
return Err(EvalAltResult::ErrorStringBounds(chars_len, index, idx_pos).into());
};
Ok(Target::StringChar(target, offset, ch.into()))
@ -2083,7 +2087,7 @@ impl Engine {
.map(|(v, _)| v.into())
}
_ => EvalAltResult::ErrorIndexingType(
_ => Err(EvalAltResult::ErrorIndexingType(
format!(
"{} [{}]",
self.map_type_name(target.type_name()),
@ -2091,7 +2095,7 @@ impl Engine {
),
Position::NONE,
)
.into(),
.into()),
}
}
@ -2386,7 +2390,9 @@ impl Engine {
) -> Result<(), Box<EvalAltResult>> {
if target.is_read_only() {
// Assignment to constant variable
return EvalAltResult::ErrorAssignmentToConstant(root.0.to_string(), root.1).into();
return Err(
EvalAltResult::ErrorAssignmentToConstant(root.0.to_string(), root.1).into(),
);
}
let mut new_val = new_val;
@ -2482,8 +2488,11 @@ impl Engine {
.expect("`lhs_ptr` is `Variable`");
if !lhs_ptr.is_ref() {
return EvalAltResult::ErrorAssignmentToConstant(var_name.to_string(), pos)
.into();
return Err(EvalAltResult::ErrorAssignmentToConstant(
var_name.to_string(),
pos,
)
.into());
}
#[cfg(not(feature = "unchecked"))]
@ -2722,12 +2731,10 @@ impl Engine {
if let Some(func) = func {
// Add the loop variables
let orig_scope_len = scope.len();
let counter_index = if let Some(Ident { name, .. }) = counter {
let counter_index = counter.as_ref().map(|Ident { name, .. }| {
scope.push(unsafe_cast_var_name_to_lifetime(name), 0 as INT);
Some(scope.len() - 1)
} else {
None
};
scope.len() - 1
});
scope.push(unsafe_cast_var_name_to_lifetime(name), ());
let index = scope.len() - 1;
state.scope_level += 1;
@ -2737,11 +2744,11 @@ impl Engine {
if let Some(c) = counter_index {
#[cfg(not(feature = "unchecked"))]
if x > INT::MAX as usize {
return EvalAltResult::ErrorArithmetic(
return Err(EvalAltResult::ErrorArithmetic(
format!("for-loop counter overflow: {}", x),
counter.as_ref().expect("`counter` is `Some`").pos,
)
.into();
.into());
}
let mut counter_var = scope
@ -2791,13 +2798,13 @@ impl Engine {
scope.rewind(orig_scope_len);
Ok(Dynamic::UNIT)
} else {
EvalAltResult::ErrorFor(expr.position()).into()
Err(EvalAltResult::ErrorFor(expr.position()).into())
}
}
// Continue/Break statement
Stmt::BreakLoop(options, pos) => {
EvalAltResult::LoopBreak(options.contains(AST_OPTION_BREAK_OUT), *pos).into()
Err(EvalAltResult::LoopBreak(options.contains(AST_OPTION_BREAK_OUT), *pos).into())
}
// Namespace-qualified function call
@ -2920,29 +2927,29 @@ impl Engine {
// Throw value
Stmt::Return(options, Some(expr), pos) if options.contains(AST_OPTION_BREAK_OUT) => {
EvalAltResult::ErrorRuntime(
Err(EvalAltResult::ErrorRuntime(
self.eval_expr(scope, mods, state, lib, this_ptr, expr, level)?
.flatten(),
*pos,
)
.into()
.into())
}
// Empty throw
Stmt::Return(options, None, pos) if options.contains(AST_OPTION_BREAK_OUT) => {
EvalAltResult::ErrorRuntime(Dynamic::UNIT, *pos).into()
Err(EvalAltResult::ErrorRuntime(Dynamic::UNIT, *pos).into())
}
// Return value
Stmt::Return(_, Some(expr), pos) => EvalAltResult::Return(
Stmt::Return(_, Some(expr), pos) => Err(EvalAltResult::Return(
self.eval_expr(scope, mods, state, lib, this_ptr, expr, level)?
.flatten(),
*pos,
)
.into(),
.into()),
// Empty return
Stmt::Return(_, None, pos) => EvalAltResult::Return(Dynamic::UNIT, *pos).into(),
Stmt::Return(_, None, pos) => Err(EvalAltResult::Return(Dynamic::UNIT, *pos).into()),
// Let/const statement
Stmt::Var(expr, x, options, _) => {
@ -3005,7 +3012,7 @@ impl Engine {
// Guard against too many modules
#[cfg(not(feature = "unchecked"))]
if state.num_modules >= self.max_modules() {
return EvalAltResult::ErrorTooManyModules(*_pos).into();
return Err(EvalAltResult::ErrorTooManyModules(*_pos).into());
}
if let Some(path) = self
@ -3034,7 +3041,10 @@ impl Engine {
.map(|r| r.resolve(self, source, &path, path_pos))
})
.unwrap_or_else(|| {
EvalAltResult::ErrorModuleNotFound(path.to_string(), path_pos).into()
Err(
EvalAltResult::ErrorModuleNotFound(path.to_string(), path_pos)
.into(),
)
})?;
if let Some(name) = export.as_ref().map(|x| x.name.clone()) {
@ -3067,7 +3077,9 @@ impl Engine {
if rename.is_empty() { name } else { rename }.clone(),
);
} else {
return EvalAltResult::ErrorVariableNotFound(name.to_string(), *pos).into();
return Err(
EvalAltResult::ErrorVariableNotFound(name.to_string(), *pos).into()
);
}
}
Ok(Dynamic::UNIT)
@ -3184,11 +3196,11 @@ impl Engine {
.max_string_size
.map_or(usize::MAX, NonZeroUsize::get)
{
return EvalAltResult::ErrorDataTooLarge(
return Err(EvalAltResult::ErrorDataTooLarge(
"Length of string".to_string(),
Position::NONE,
)
.into();
.into());
}
#[cfg(not(feature = "no_index"))]
@ -3198,8 +3210,11 @@ impl Engine {
.max_array_size
.map_or(usize::MAX, NonZeroUsize::get)
{
return EvalAltResult::ErrorDataTooLarge("Size of array".to_string(), Position::NONE)
.into();
return Err(EvalAltResult::ErrorDataTooLarge(
"Size of array".to_string(),
Position::NONE,
)
.into());
}
#[cfg(not(feature = "no_object"))]
@ -3209,11 +3224,11 @@ impl Engine {
.max_map_size
.map_or(usize::MAX, NonZeroUsize::get)
{
return EvalAltResult::ErrorDataTooLarge(
return Err(EvalAltResult::ErrorDataTooLarge(
"Size of object map".to_string(),
Position::NONE,
)
.into();
.into());
}
Ok(())
@ -3230,14 +3245,14 @@ impl Engine {
// Guard against too many operations
if self.max_operations() > 0 && state.num_operations > self.max_operations() {
return EvalAltResult::ErrorTooManyOperations(pos).into();
return Err(EvalAltResult::ErrorTooManyOperations(pos).into());
}
// Report progress - only in steps
if let Some(ref progress) = self.progress {
if let Some(token) = progress(state.num_operations) {
// Terminate script if progress returns a termination token
return EvalAltResult::ErrorTerminated(token, pos).into();
return Err(EvalAltResult::ErrorTerminated(token, pos).into());
}
}
@ -3248,7 +3263,7 @@ impl Engine {
///
/// If a type is registered via [`register_type_with_name`][Engine::register_type_with_name],
/// the type name provided for the registration will be used.
#[inline(always)]
#[inline]
#[must_use]
pub fn map_type_name<'a>(&'a self, name: &'a str) -> &'a str {
self.type_names
@ -3258,7 +3273,7 @@ impl Engine {
}
/// Make a `Box<`[`EvalAltResult<ErrorMismatchDataType>`][EvalAltResult::ErrorMismatchDataType]`>`.
#[inline(always)]
#[inline]
#[must_use]
pub(crate) fn make_type_mismatch_err<T>(&self, typ: &str, pos: Position) -> Box<EvalAltResult> {
EvalAltResult::ErrorMismatchDataType(

View File

@ -5,7 +5,6 @@ use crate::engine::{EvalContext, EvalState, Imports};
use crate::fn_call::FnCallArgs;
use crate::fn_native::SendSync;
use crate::fn_register::RegisterNativeFunction;
use crate::optimize::OptimizationLevel;
use crate::parse::ParseState;
use crate::{
scope::Scope, Dynamic, Engine, EvalAltResult, FnAccess, FnNamespace, Identifier, Module,
@ -1171,7 +1170,12 @@ impl Engine {
scope: &Scope,
scripts: &[&str],
) -> Result<AST, ParseError> {
self.compile_with_scope_and_optimization_level(scope, scripts, self.optimization_level)
self.compile_with_scope_and_optimization_level(
scope,
scripts,
#[cfg(not(feature = "no_optimize"))]
self.optimization_level,
)
}
/// Join a list of strings and compile into an [`AST`] using own scope at a specific optimization level.
#[inline]
@ -1179,7 +1183,7 @@ impl Engine {
&self,
scope: &Scope,
scripts: &[&str],
optimization_level: OptimizationLevel,
#[cfg(not(feature = "no_optimize"))] optimization_level: crate::OptimizationLevel,
) -> Result<AST, ParseError> {
let (stream, tokenizer_control) =
self.lex_raw(scripts, self.token_mapper.as_ref().map(Box::as_ref));
@ -1188,6 +1192,7 @@ impl Engine {
&mut stream.peekable(),
&mut state,
scope,
#[cfg(not(feature = "no_optimize"))]
optimization_level,
)
}
@ -1287,7 +1292,7 @@ impl Engine {
/// ```
#[cfg(not(feature = "no_std"))]
#[cfg(not(any(target_arch = "wasm32", target_arch = "wasm64")))]
#[inline(always)]
#[inline]
pub fn compile_file_with_scope(
&self,
scope: &Scope,
@ -1385,7 +1390,8 @@ impl Engine {
&mut stream.peekable(),
&mut state,
&scope,
OptimizationLevel::None,
#[cfg(not(feature = "no_optimize"))]
crate::OptimizationLevel::None,
)?;
if has_null {
scope.push_constant("null", ());
@ -1470,7 +1476,13 @@ impl Engine {
let mut peekable = stream.peekable();
let mut state = ParseState::new(self, tokenizer_control);
self.parse_global_expr(&mut peekable, &mut state, scope, self.optimization_level)
self.parse_global_expr(
&mut peekable,
&mut state,
scope,
#[cfg(not(feature = "no_optimize"))]
self.optimization_level,
)
}
/// Evaluate a script file.
///
@ -1491,7 +1503,7 @@ impl Engine {
/// ```
#[cfg(not(feature = "no_std"))]
#[cfg(not(any(target_arch = "wasm32", target_arch = "wasm64")))]
#[inline(always)]
#[inline]
pub fn eval_file<T: Variant + Clone>(
&self,
path: std::path::PathBuf,
@ -1521,7 +1533,7 @@ impl Engine {
/// ```
#[cfg(not(feature = "no_std"))]
#[cfg(not(any(target_arch = "wasm32", target_arch = "wasm64")))]
#[inline(always)]
#[inline]
pub fn eval_file_with_scope<T: Variant + Clone>(
&self,
scope: &mut Scope,
@ -1569,7 +1581,7 @@ impl Engine {
/// # Ok(())
/// # }
/// ```
#[inline(always)]
#[inline]
pub fn eval_with_scope<T: Variant + Clone>(
&self,
scope: &mut Scope,
@ -1578,6 +1590,7 @@ impl Engine {
let ast = self.compile_with_scope_and_optimization_level(
scope,
&[script],
#[cfg(not(feature = "no_optimize"))]
self.optimization_level,
)?;
self.eval_ast_with_scope(scope, &ast)
@ -1637,7 +1650,8 @@ impl Engine {
&mut stream.peekable(),
&mut state,
scope,
OptimizationLevel::None,
#[cfg(not(feature = "no_optimize"))]
crate::OptimizationLevel::None,
)?;
self.eval_ast_with_scope(scope, &ast)
@ -1744,7 +1758,7 @@ impl Engine {
/// Not available under `no_std` or `WASM`.
#[cfg(not(feature = "no_std"))]
#[cfg(not(any(target_arch = "wasm32", target_arch = "wasm64")))]
#[inline(always)]
#[inline]
pub fn run_file(&self, path: std::path::PathBuf) -> Result<(), Box<EvalAltResult>> {
Self::read_file(path).and_then(|contents| self.run(&contents))
}
@ -1753,7 +1767,7 @@ impl Engine {
/// Not available under `no_std` or `WASM`.
#[cfg(not(feature = "no_std"))]
#[cfg(not(any(target_arch = "wasm32", target_arch = "wasm64")))]
#[inline(always)]
#[inline]
pub fn run_file_with_scope(
&self,
scope: &mut Scope,
@ -1782,6 +1796,7 @@ impl Engine {
&mut stream.peekable(),
&mut state,
scope,
#[cfg(not(feature = "no_optimize"))]
self.optimization_level,
)?;
@ -2027,7 +2042,7 @@ impl Engine {
&self,
scope: &Scope,
mut ast: AST,
optimization_level: OptimizationLevel,
optimization_level: crate::OptimizationLevel,
) -> AST {
#[cfg(not(feature = "no_function"))]
let lib = ast

View File

@ -67,7 +67,7 @@ impl Engine {
///
/// Not available under `unchecked`.
#[cfg(not(feature = "unchecked"))]
#[inline(always)]
#[inline]
#[must_use]
pub const fn max_operations(&self) -> u64 {
if let Some(n) = self.limits.max_operations {
@ -117,7 +117,7 @@ impl Engine {
///
/// Not available under `unchecked`.
#[cfg(not(feature = "unchecked"))]
#[inline(always)]
#[inline]
#[must_use]
pub const fn max_expr_depth(&self) -> usize {
if let Some(n) = self.limits.max_expr_depth {
@ -131,7 +131,7 @@ impl Engine {
/// Not available under `unchecked` or `no_function`.
#[cfg(not(feature = "unchecked"))]
#[cfg(not(feature = "no_function"))]
#[inline(always)]
#[inline]
#[must_use]
pub const fn max_function_expr_depth(&self) -> usize {
if let Some(n) = self.limits.max_function_expr_depth {
@ -153,7 +153,7 @@ impl Engine {
///
/// Not available under `unchecked`.
#[cfg(not(feature = "unchecked"))]
#[inline(always)]
#[inline]
#[must_use]
pub const fn max_string_size(&self) -> usize {
if let Some(n) = self.limits.max_string_size {
@ -177,7 +177,7 @@ impl Engine {
/// Not available under `unchecked` or `no_index`.
#[cfg(not(feature = "unchecked"))]
#[cfg(not(feature = "no_index"))]
#[inline(always)]
#[inline]
#[must_use]
pub const fn max_array_size(&self) -> usize {
if let Some(n) = self.limits.max_array_size {
@ -201,7 +201,7 @@ impl Engine {
/// Not available under `unchecked` or `no_object`.
#[cfg(not(feature = "unchecked"))]
#[cfg(not(feature = "no_object"))]
#[inline(always)]
#[inline]
#[must_use]
pub const fn max_map_size(&self) -> usize {
if let Some(n) = self.limits.max_map_size {

View File

@ -216,14 +216,14 @@ impl fmt::Display for EvalAltResult {
}
impl<T: AsRef<str>> From<T> for EvalAltResult {
#[inline(always)]
#[inline(never)]
fn from(err: T) -> Self {
Self::ErrorRuntime(err.as_ref().to_string().into(), Position::NONE)
}
}
impl<T: AsRef<str>> From<T> for Box<EvalAltResult> {
#[inline(always)]
#[inline(never)]
fn from(err: T) -> Self {
EvalAltResult::ErrorRuntime(err.as_ref().to_string().into(), Position::NONE).into()
}
@ -444,7 +444,7 @@ impl EvalAltResult {
}
/// Consume the current [`EvalAltResult`] and return a new one with the specified [`Position`]
/// if the current position is [`Position::None`].
#[inline]
#[inline(never)]
#[must_use]
pub(crate) fn fill_position(mut self: Box<Self>, new_position: Position) -> Box<Self> {
if self.position().is_none() {
@ -453,10 +453,3 @@ impl EvalAltResult {
self
}
}
impl<T> From<EvalAltResult> for Result<T, Box<EvalAltResult>> {
#[inline(always)]
fn from(err: EvalAltResult) -> Self {
Err(err.into())
}
}

View File

@ -266,7 +266,7 @@ impl fmt::Display for ParseErrorType {
}
impl From<LexError> for ParseErrorType {
#[inline(always)]
#[inline(never)]
fn from(err: LexError) -> Self {
match err {
LexError::StringTooLong(max) => {

View File

@ -57,7 +57,7 @@ pub trait FuncArgs {
}
impl<T: Variant + Clone> FuncArgs for Vec<T> {
#[inline(always)]
#[inline]
fn parse<CONTAINER: Extend<Dynamic>>(self, container: &mut CONTAINER) {
container.extend(self.into_iter().map(Variant::into_dynamic));
}
@ -69,7 +69,7 @@ macro_rules! impl_args {
($($p:ident),*) => {
impl<$($p: Variant + Clone),*> FuncArgs for ($($p,)*)
{
#[inline(always)]
#[inline]
#[allow(unused_variables)]
fn parse<CONTAINER: Extend<Dynamic>>(self, container: &mut CONTAINER) {
let ($($p,)*) = self;

View File

@ -9,7 +9,6 @@ use crate::engine::{
use crate::fn_builtin::{get_builtin_binary_op_fn, get_builtin_op_assignment_fn};
use crate::fn_native::FnAny;
use crate::module::NamespaceRef;
use crate::optimize::OptimizationLevel;
use crate::{
ast::{Expr, Stmt},
fn_native::CallableFunction,
@ -57,7 +56,7 @@ impl<'a> ArgBackup<'a> {
/// # Panics
///
/// Panics when `args` is empty.
#[inline(always)]
#[inline]
fn change_first_arg_to_copy(&mut self, args: &mut FnCallArgs<'a>) {
// Clone the original value.
self.value_copy = args[0].clone();
@ -91,7 +90,7 @@ impl<'a> ArgBackup<'a> {
}
impl Drop for ArgBackup<'_> {
#[inline(always)]
#[inline]
fn drop(&mut self) {
// Panic if the shorter lifetime leaks.
assert!(
@ -115,11 +114,11 @@ pub fn ensure_no_data_race(
.skip(if is_method_call { 1 } else { 0 })
.find(|(_, a)| a.is_locked())
{
return EvalAltResult::ErrorDataRace(
return Err(EvalAltResult::ErrorDataRace(
format!("argument #{} of function '{}'", n + 1, fn_name),
Position::NONE,
)
.into();
.into());
}
Ok(())
@ -392,7 +391,7 @@ impl Engine {
crate::engine::FN_IDX_GET => {
assert!(args.len() == 2);
EvalAltResult::ErrorIndexingType(
Err(EvalAltResult::ErrorIndexingType(
format!(
"{} [{}]",
self.map_type_name(args[0].type_name()),
@ -400,7 +399,7 @@ impl Engine {
),
pos,
)
.into()
.into())
}
// index setter function not found?
@ -408,7 +407,7 @@ impl Engine {
crate::engine::FN_IDX_SET => {
assert!(args.len() == 3);
EvalAltResult::ErrorIndexingType(
Err(EvalAltResult::ErrorIndexingType(
format!(
"{} [{}] = {}",
self.map_type_name(args[0].type_name()),
@ -417,7 +416,7 @@ impl Engine {
),
pos,
)
.into()
.into())
}
// Getter function not found?
@ -425,7 +424,7 @@ impl Engine {
_ if name.starts_with(crate::engine::FN_GET) => {
assert!(args.len() == 1);
EvalAltResult::ErrorDotExpr(
Err(EvalAltResult::ErrorDotExpr(
format!(
"Unknown property '{}' - a getter is not registered for type '{}'",
&name[crate::engine::FN_GET.len()..],
@ -433,7 +432,7 @@ impl Engine {
),
pos,
)
.into()
.into())
}
// Setter function not found?
@ -441,7 +440,7 @@ impl Engine {
_ if name.starts_with(crate::engine::FN_SET) => {
assert!(args.len() == 2);
EvalAltResult::ErrorDotExpr(
Err(EvalAltResult::ErrorDotExpr(
format!(
"No writable property '{}' - a setter is not registered for type '{}' to handle '{}'",
&name[crate::engine::FN_SET.len()..],
@ -450,14 +449,15 @@ impl Engine {
),
pos,
)
.into()
.into())
}
// Raise error
_ => {
EvalAltResult::ErrorFunctionNotFound(self.gen_call_signature(None, name, args), pos)
.into()
}
_ => Err(EvalAltResult::ErrorFunctionNotFound(
self.gen_call_signature(None, name, args),
pos,
)
.into()),
}
}
@ -481,6 +481,7 @@ impl Engine {
pos: Position,
level: usize,
) -> RhaiResult {
#[inline(never)]
fn make_error(
name: String,
fn_def: &crate::ast::ScriptFnDef,
@ -488,7 +489,7 @@ impl Engine {
err: Box<EvalAltResult>,
pos: Position,
) -> RhaiResult {
EvalAltResult::ErrorInFunctionCall(
Err(EvalAltResult::ErrorInFunctionCall(
name,
fn_def
.lib
@ -499,7 +500,7 @@ impl Engine {
err,
pos,
)
.into()
.into())
}
#[cfg(not(feature = "unchecked"))]
@ -513,7 +514,7 @@ impl Engine {
#[cfg(not(feature = "no_function"))]
#[cfg(not(feature = "unchecked"))]
if level > self.max_call_levels() {
return EvalAltResult::ErrorStackOverflow(pos).into();
return Err(EvalAltResult::ErrorStackOverflow(pos).into());
}
let orig_scope_level = state.scope_level;
@ -577,7 +578,7 @@ impl Engine {
// System errors are passed straight-through
mut err if err.is_system_exception() => {
err.set_position(pos);
err.into()
Err(err.into())
}
// Other errors are wrapped in `ErrorInFunctionCall`
_ => make_error(fn_def.name.to_string(), fn_def, state, err, pos),
@ -650,7 +651,7 @@ impl Engine {
) -> Result<(Dynamic, bool), Box<EvalAltResult>> {
fn no_method_err(name: &str, pos: Position) -> Result<(Dynamic, bool), Box<EvalAltResult>> {
let msg = format!("'{0}' should not be called this way. Try {0}(...);", name);
EvalAltResult::ErrorRuntime(msg.into(), pos).into()
Err(EvalAltResult::ErrorRuntime(msg.into(), pos).into())
}
// Check for data race.
@ -857,7 +858,8 @@ impl Engine {
let ast = self.compile_with_scope_and_optimization_level(
&Default::default(),
&[script],
OptimizationLevel::None,
#[cfg(not(feature = "no_optimize"))]
crate::OptimizationLevel::None,
)?;
// If new functions are defined within the eval string, it is an error
@ -1457,11 +1459,11 @@ impl Engine {
Some(f) => unreachable!("unknown function type: {:?}", f),
None => EvalAltResult::ErrorFunctionNotFound(
None => Err(EvalAltResult::ErrorFunctionNotFound(
self.gen_call_signature(Some(namespace), fn_name, &args),
pos,
)
.into(),
.into()),
}
}
}

View File

@ -96,13 +96,13 @@ macro_rules! def_anonymous_fn {
#[cfg(not(feature = "sync"))]
type Output = Box<dyn Fn($($par),*) -> Result<RET, Box<EvalAltResult>>>;
#[inline(always)]
#[inline]
fn create_from_ast(self, ast: AST, entry_point: &str) -> Self::Output {
let fn_name: SmartString = entry_point.into();
Box::new(move |$($par),*| self.call_fn(&mut Scope::new(), &ast, &fn_name, ($($par,)*)))
}
#[inline(always)]
#[inline]
fn create_from_script(self, script: &str, entry_point: &str) -> Result<Self::Output, ParseError> {
let ast = self.compile(script)?;
Ok(Func::<($($par,)*), RET>::create_from_ast(self, ast, entry_point))

View File

@ -144,14 +144,14 @@ impl<'a> NativeCallContext<'a> {
///
/// Not available under `no_module`.
#[cfg(not(feature = "no_module"))]
#[inline(always)]
#[inline]
pub fn iter_imports(&self) -> impl Iterator<Item = (&str, &Module)> {
self.mods.iter().flat_map(|&m| m.iter())
}
/// Get an iterator over the current set of modules imported via `import` statements.
#[cfg(not(feature = "no_module"))]
#[allow(dead_code)]
#[inline(always)]
#[inline]
pub(crate) fn iter_imports_raw(
&self,
) -> impl Iterator<Item = (&crate::Identifier, &Shared<Module>)> {
@ -169,7 +169,7 @@ impl<'a> NativeCallContext<'a> {
self.mods
}
/// Get an iterator over the namespaces containing definitions of all script-defined functions.
#[inline(always)]
#[inline]
pub fn iter_namespaces(&self) -> impl Iterator<Item = &Module> {
self.lib.iter().cloned()
}
@ -183,6 +183,9 @@ impl<'a> NativeCallContext<'a> {
}
/// Call a function inside the call context.
///
/// If `is_method_call` is [`true`], the first argument is assumed to be the
/// `this` pointer for a script-defined function (or the object of a method call).
///
/// # WARNING
///
/// All arguments may be _consumed_, meaning that they may be replaced by `()`.
@ -191,19 +194,13 @@ impl<'a> NativeCallContext<'a> {
/// Do not use the arguments after this call. If they are needed afterwards,
/// clone them _before_ calling this function.
///
/// If `is_method` is [`true`], the first argument is assumed to be passed
/// If `is_ref_mut` is [`true`], the first argument is assumed to be passed
/// by reference and is not consumed.
#[inline(always)]
pub fn call_fn_dynamic_raw(
pub fn call_fn_raw(
&self,
fn_name: impl AsRef<str>,
is_method_call: bool,
args: &mut [&mut Dynamic],
) -> RhaiResult {
fn call_fn_dynamic_inner(
context: &NativeCallContext,
is_method_call: bool,
fn_name: &str,
is_ref_mut: bool,
is_method_call: bool,
args: &mut [&mut Dynamic],
) -> Result<Dynamic, Box<EvalAltResult>> {
let hash = if is_method_call {
@ -214,16 +211,16 @@ impl<'a> NativeCallContext<'a> {
} else {
FnCallHashes::from_script(calc_fn_hash(fn_name, args.len()))
};
context
.engine()
self.engine()
.exec_fn_call(
&mut context.mods.cloned().unwrap_or_default(),
&mut self.mods.cloned().unwrap_or_default(),
&mut Default::default(),
context.lib,
self.lib,
fn_name,
hash,
args,
is_method_call,
is_ref_mut,
is_method_call,
Position::NONE,
None,
@ -231,9 +228,6 @@ impl<'a> NativeCallContext<'a> {
)
.map(|(r, _)| r)
}
call_fn_dynamic_inner(self, is_method_call, fn_name.as_ref(), args)
}
}
/// Consume a [`Shared`] resource and return a mutable reference to the wrapped value.
@ -245,7 +239,7 @@ pub fn shared_make_mut<T: Clone>(value: &mut Shared<T>) -> &mut T {
}
/// Consume a [`Shared`] resource if is unique (i.e. not shared), or clone it otherwise.
#[inline(always)]
#[inline]
#[must_use]
pub fn shared_take_or_clone<T: Clone>(value: Shared<T>) -> T {
shared_try_take(value).unwrap_or_else(|v| v.as_ref().clone())
@ -262,7 +256,7 @@ pub fn shared_try_take<T>(value: Shared<T>) -> Result<T, Shared<T>> {
/// # Panics
///
/// Panics if the resource is shared (i.e. has other outstanding references).
#[inline(always)]
#[inline]
#[must_use]
pub fn shared_take<T>(value: Shared<T>) -> T {
shared_try_take(value)

View File

@ -69,7 +69,7 @@ impl FnPtr {
self
}
/// Set curried arguments to the function pointer.
#[inline(always)]
#[inline]
pub fn set_curry(&mut self, values: impl IntoIterator<Item = Dynamic>) -> &mut Self {
self.1 = values.into_iter().collect();
self
@ -130,7 +130,7 @@ impl FnPtr {
}
args.extend(arg_values.iter_mut());
ctx.call_fn_dynamic_raw(self.fn_name(), is_method, &mut args)
ctx.call_fn_raw(self.fn_name(), is_method, is_method, &mut args)
}
}
@ -148,7 +148,7 @@ impl TryFrom<Identifier> for FnPtr {
if is_valid_identifier(value.chars()) {
Ok(Self(value, Default::default()))
} else {
EvalAltResult::ErrorFunctionNotFound(value.to_string(), Position::NONE).into()
Err(EvalAltResult::ErrorFunctionNotFound(value.to_string(), Position::NONE).into())
}
}
}

View File

@ -123,7 +123,7 @@ macro_rules! def_register {
#[inline(always)] fn into_callable_function(self) -> CallableFunction {
CallableFunction::$abi(Box::new(move |ctx: NativeCallContext, args: &mut FnCallArgs| {
if args.len() == 2 && args[0].is_read_only() && is_setter(ctx.fn_name()) {
return EvalAltResult::ErrorAssignmentToConstant(Default::default(), Position::NONE).into();
return Err(EvalAltResult::ErrorAssignmentToConstant(Default::default(), Position::NONE).into());
}
// The arguments are assumed to be of the correct number and types!
@ -151,7 +151,7 @@ macro_rules! def_register {
#[inline(always)] fn into_callable_function(self) -> CallableFunction {
CallableFunction::$abi(Box::new(move |ctx: NativeCallContext, args: &mut FnCallArgs| {
if args.len() == 2 && args[0].is_read_only() && is_setter(ctx.fn_name()) {
return EvalAltResult::ErrorAssignmentToConstant(Default::default(), Position::NONE).into();
return Err(EvalAltResult::ErrorAssignmentToConstant(Default::default(), Position::NONE).into());
}
// The arguments are assumed to be of the correct number and types!
@ -179,7 +179,7 @@ macro_rules! def_register {
#[inline(always)] fn into_callable_function(self) -> CallableFunction {
CallableFunction::$abi(Box::new(move |ctx: NativeCallContext, args: &mut FnCallArgs| {
if args.len() == 2 && args[0].is_read_only() && is_setter(ctx.fn_name()) {
return EvalAltResult::ErrorAssignmentToConstant(Default::default(), Position::NONE).into();
return Err(EvalAltResult::ErrorAssignmentToConstant(Default::default(), Position::NONE).into());
}
// The arguments are assumed to be of the correct number and types!
@ -204,7 +204,7 @@ macro_rules! def_register {
#[inline(always)] fn into_callable_function(self) -> CallableFunction {
CallableFunction::$abi(Box::new(move |ctx: NativeCallContext, args: &mut FnCallArgs| {
if args.len() == 2 && args[0].is_read_only() && is_setter(ctx.fn_name()) {
return EvalAltResult::ErrorAssignmentToConstant(Default::default(), Position::NONE).into();
return Err(EvalAltResult::ErrorAssignmentToConstant(Default::default(), Position::NONE).into());
}
// The arguments are assumed to be of the correct number and types!

View File

@ -90,26 +90,29 @@ impl Borrow<str> for ImmutableString {
impl From<&str> for ImmutableString {
#[inline(always)]
fn from(value: &str) -> Self {
Self(Into::<SmartString>::into(value).into())
let value: SmartString = value.into();
Self(value.into())
}
}
impl From<&String> for ImmutableString {
#[inline(always)]
fn from(value: &String) -> Self {
Self(Into::<SmartString>::into(value).into())
let value: SmartString = value.into();
Self(value.into())
}
}
impl From<String> for ImmutableString {
#[inline(always)]
fn from(value: String) -> Self {
Self(Into::<SmartString>::into(value).into())
let value: SmartString = value.into();
Self(value.into())
}
}
#[cfg(not(feature = "no_smartstring"))]
impl From<&SmartString> for ImmutableString {
#[inline(always)]
fn from(value: &SmartString) -> Self {
Self(Into::<SmartString>::into(value.as_str()).into())
Self(value.clone().into())
}
}
#[cfg(not(feature = "no_smartstring"))]
@ -137,33 +140,34 @@ impl FromStr for ImmutableString {
#[inline(always)]
fn from_str(s: &str) -> Result<Self, Self::Err> {
Ok(Self(Into::<SmartString>::into(s).into()))
let s: SmartString = s.into();
Ok(Self(s.into()))
}
}
impl FromIterator<char> for ImmutableString {
#[inline(always)]
#[inline]
fn from_iter<T: IntoIterator<Item = char>>(iter: T) -> Self {
Self(iter.into_iter().collect::<SmartString>().into())
}
}
impl<'a> FromIterator<&'a char> for ImmutableString {
#[inline(always)]
#[inline]
fn from_iter<T: IntoIterator<Item = &'a char>>(iter: T) -> Self {
Self(iter.into_iter().cloned().collect::<SmartString>().into())
}
}
impl<'a> FromIterator<&'a str> for ImmutableString {
#[inline(always)]
#[inline]
fn from_iter<T: IntoIterator<Item = &'a str>>(iter: T) -> Self {
Self(iter.into_iter().collect::<SmartString>().into())
}
}
impl<'a> FromIterator<String> for ImmutableString {
#[inline(always)]
#[inline]
fn from_iter<T: IntoIterator<Item = String>>(iter: T) -> Self {
Self(iter.into_iter().collect::<SmartString>().into())
}
@ -171,7 +175,7 @@ impl<'a> FromIterator<String> for ImmutableString {
#[cfg(not(feature = "no_smartstring"))]
impl<'a> FromIterator<SmartString> for ImmutableString {
#[inline(always)]
#[inline]
fn from_iter<T: IntoIterator<Item = SmartString>>(iter: T) -> Self {
Self(iter.into_iter().collect::<SmartString>().into())
}
@ -278,7 +282,7 @@ impl Add<&str> for &ImmutableString {
}
impl AddAssign<&str> for ImmutableString {
#[inline(always)]
#[inline]
fn add_assign(&mut self, rhs: &str) {
if !rhs.is_empty() {
self.make_mut().push_str(rhs);
@ -324,7 +328,8 @@ impl AddAssign<String> for ImmutableString {
fn add_assign(&mut self, rhs: String) {
if !rhs.is_empty() {
if self.is_empty() {
self.0 = Into::<SmartString>::into(rhs).into();
let rhs: SmartString = rhs.into();
self.0 = rhs.into();
} else {
self.make_mut().push_str(&rhs);
}
@ -335,7 +340,7 @@ impl AddAssign<String> for ImmutableString {
impl Add<char> for ImmutableString {
type Output = Self;
#[inline(always)]
#[inline]
fn add(mut self, rhs: char) -> Self::Output {
self.make_mut().push(rhs);
self
@ -345,7 +350,7 @@ impl Add<char> for ImmutableString {
impl Add<char> for &ImmutableString {
type Output = ImmutableString;
#[inline(always)]
#[inline]
fn add(self, rhs: char) -> Self::Output {
let mut s = self.clone();
s.make_mut().push(rhs);
@ -354,7 +359,7 @@ impl Add<char> for &ImmutableString {
}
impl AddAssign<char> for ImmutableString {
#[inline(always)]
#[inline]
fn add_assign(&mut self, rhs: char) {
self.make_mut().push(rhs);
}
@ -397,7 +402,8 @@ impl SubAssign<&ImmutableString> for ImmutableString {
if self.is_empty() {
self.0 = rhs.0.clone();
} else {
self.0 = Into::<SmartString>::into(self.replace(rhs.as_str(), "")).into();
let rhs: SmartString = self.replace(rhs.as_str(), "").into();
self.0 = rhs.into();
}
}
}
@ -410,7 +416,8 @@ impl SubAssign<ImmutableString> for ImmutableString {
if self.is_empty() {
self.0 = rhs.0;
} else {
self.0 = Into::<SmartString>::into(self.replace(rhs.as_str(), "")).into();
let rhs: SmartString = self.replace(rhs.as_str(), "").into();
self.0 = rhs.into();
}
}
}
@ -447,9 +454,10 @@ impl Sub<String> for &ImmutableString {
}
impl SubAssign<String> for ImmutableString {
#[inline(always)]
#[inline]
fn sub_assign(&mut self, rhs: String) {
self.0 = Into::<SmartString>::into(self.replace(&rhs, "")).into();
let rhs: SmartString = self.replace(&rhs, "").into();
self.0 = rhs.into();
}
}
@ -472,9 +480,10 @@ impl Sub<char> for &ImmutableString {
}
impl SubAssign<char> for ImmutableString {
#[inline(always)]
#[inline]
fn sub_assign(&mut self, rhs: char) {
self.0 = Into::<SmartString>::into(self.replace(rhs, "")).into();
let rhs: SmartString = self.replace(rhs, "").into();
self.0 = rhs.into();
}
}
@ -527,7 +536,7 @@ impl ImmutableString {
}
/// Consume the [`ImmutableString`] and convert it into a [`String`].
/// If there are other references to the same string, a cloned copy is returned.
#[inline(always)]
#[inline]
pub fn into_owned(mut self) -> String {
self.make_mut(); // Make sure it is unique reference
shared_take(self.0).into() // Should succeed

View File

@ -88,6 +88,7 @@ mod fn_ptr;
mod fn_register;
mod immutable_string;
mod module;
#[cfg(not(feature = "no_optimize"))]
mod optimize;
pub mod packages;
mod parse;

View File

@ -204,7 +204,7 @@ impl AsRef<Module> for Module {
impl<M: AsRef<Module>> Add<M> for &Module {
type Output = Module;
#[inline(always)]
#[inline]
fn add(self, rhs: M) -> Self::Output {
let mut module = self.clone();
module.merge(rhs.as_ref());
@ -240,7 +240,7 @@ impl Module {
/// module.set_var("answer", 42_i64);
/// assert_eq!(module.get_var_value::<i64>("answer").expect("answer should exist"), 42);
/// ```
#[inline(always)]
#[inline]
#[must_use]
pub fn new() -> Self {
Self {
@ -269,7 +269,7 @@ impl Module {
/// module.set_id("hello");
/// assert_eq!(module.id(), Some("hello"));
/// ```
#[inline(always)]
#[inline]
#[must_use]
pub fn id(&self) -> Option<&str> {
self.id_raw().map(|s| s.as_str())
@ -365,7 +365,7 @@ impl Module {
/// Generate signatures for all the non-private functions in the [`Module`].
/// Exported under the `metadata` feature only.
#[cfg(feature = "metadata")]
#[inline(always)]
#[inline]
pub fn gen_fn_signatures(&self) -> impl Iterator<Item = String> + '_ {
self.functions
.values()
@ -402,7 +402,7 @@ impl Module {
/// module.set_var("answer", 42_i64);
/// assert_eq!(module.get_var_value::<i64>("answer").expect("answer should exist"), 42);
/// ```
#[inline(always)]
#[inline]
#[must_use]
pub fn get_var_value<T: Variant + Clone>(&self, name: &str) -> Option<T> {
self.get_var(name).and_then(Dynamic::try_cast::<T>)
@ -559,7 +559,7 @@ impl Module {
/// module.set_sub_module("question", sub_module);
/// assert!(module.get_sub_module("question").is_some());
/// ```
#[inline(always)]
#[inline]
#[must_use]
pub fn get_sub_module(&self, name: &str) -> Option<&Module> {
self.modules.get(name).map(|m| m.as_ref())
@ -1113,7 +1113,7 @@ impl Module {
/// Get a Rust function.
///
/// The [`u64`] hash is returned by the [`set_native_fn`][Module::set_native_fn] call.
#[inline(always)]
#[inline]
#[must_use]
pub(crate) fn get_fn(&self, hash_fn: u64) -> Option<&CallableFunction> {
self.functions.get(&hash_fn).map(|f| f.func.as_ref())
@ -1131,7 +1131,7 @@ impl Module {
/// Get a namespace-qualified function.
///
/// The [`u64`] hash is calculated by [`build_index`][Module::build_index].
#[inline(always)]
#[inline]
#[must_use]
pub(crate) fn get_qualified_fn(&self, hash_qualified_fn: u64) -> Option<&CallableFunction> {
self.all_functions
@ -1289,19 +1289,19 @@ impl Module {
}
/// Get an iterator to the sub-modules in the [`Module`].
#[inline(always)]
#[inline]
pub fn iter_sub_modules(&self) -> impl Iterator<Item = (&str, Shared<Module>)> {
self.modules.iter().map(|(k, m)| (k.as_str(), m.clone()))
}
/// Get an iterator to the variables in the [`Module`].
#[inline(always)]
#[inline]
pub fn iter_var(&self) -> impl Iterator<Item = (&str, &Dynamic)> {
self.variables.iter().map(|(k, v)| (k.as_str(), v))
}
/// Get an iterator to the functions in the [`Module`].
#[inline(always)]
#[inline]
#[allow(dead_code)]
pub(crate) fn iter_fn(&self) -> impl Iterator<Item = &FuncInfo> {
self.functions.values().map(Box::as_ref)
@ -1316,7 +1316,7 @@ impl Module {
/// 4) Number of parameters.
/// 5) Shared reference to function definition [`ScriptFnDef`][crate::ast::ScriptFnDef].
#[cfg(not(feature = "no_function"))]
#[inline(always)]
#[inline]
pub(crate) fn iter_script_fn(
&self,
) -> impl Iterator<
@ -1351,7 +1351,7 @@ impl Module {
/// 4) Number of parameters.
#[cfg(not(feature = "no_function"))]
#[cfg(not(feature = "internals"))]
#[inline(always)]
#[inline]
pub fn iter_script_fn_info(
&self,
) -> impl Iterator<Item = (FnNamespace, FnAccess, &str, usize)> {
@ -1610,7 +1610,7 @@ impl Module {
}
/// Set a type iterator into the [`Module`].
#[inline(always)]
#[inline]
pub fn set_iterable<T>(&mut self) -> &mut Self
where
T: Variant + Clone + IntoIterator,
@ -1622,7 +1622,7 @@ impl Module {
}
/// Set an iterator type into the [`Module`] as a type iterator.
#[inline(always)]
#[inline]
pub fn set_iterator<T>(&mut self) -> &mut Self
where
T: Variant + Clone + Iterator,
@ -1634,14 +1634,14 @@ impl Module {
}
/// Get the specified type iterator.
#[inline(always)]
#[inline]
#[must_use]
pub(crate) fn get_qualified_iter(&self, id: TypeId) -> Option<IteratorFn> {
self.all_type_iterators.get(&id).cloned()
}
/// Get the specified type iterator.
#[inline(always)]
#[inline]
#[must_use]
pub(crate) fn get_iter(&self, id: TypeId) -> Option<IteratorFn> {
self.type_iterators.get(&id).cloned()
@ -1709,8 +1709,7 @@ impl DerefMut for NamespaceRef {
impl From<StaticVec<Ident>> for NamespaceRef {
#[inline(always)]
fn from(path: StaticVec<Ident>) -> Self {
let mut path = path;
fn from(mut path: StaticVec<Ident>) -> Self {
path.shrink_to_fit();
Self { index: None, path }
}

View File

@ -76,7 +76,7 @@ impl ModuleResolversCollection {
self.0.remove(index)
}
/// Get an iterator of all the [module resolvers][ModuleResolver].
#[inline(always)]
#[inline]
pub fn iter(&self) -> impl Iterator<Item = &dyn ModuleResolver> {
self.0.iter().map(|v| v.as_ref())
}
@ -100,7 +100,7 @@ impl ModuleResolversCollection {
}
/// Add another [`ModuleResolversCollection`] to the end of this collection.
/// The other [`ModuleResolversCollection`] is consumed.
#[inline(always)]
#[inline]
pub fn append(&mut self, other: Self) -> &mut Self {
self.0.extend(other.0.into_iter());
self
@ -136,7 +136,7 @@ impl ModuleResolver for ModuleResolversCollection {
}
}
EvalAltResult::ErrorModuleNotFound(path.into(), pos).into()
Err(EvalAltResult::ErrorModuleNotFound(path.into(), pos).into())
}
}

View File

@ -45,6 +45,6 @@ impl ModuleResolver for DummyModuleResolver {
path: &str,
pos: Position,
) -> Result<Shared<Module>, Box<EvalAltResult>> {
EvalAltResult::ErrorModuleNotFound(path.into(), pos).into()
Err(EvalAltResult::ErrorModuleNotFound(path.into(), pos).into())
}
}

View File

@ -215,7 +215,7 @@ impl FileModuleResolver {
return self.cache.write().unwrap().contains_key(&file_path);
}
/// Empty the internal cache.
#[inline(always)]
#[inline]
pub fn clear_cache(&mut self) -> &mut Self {
#[cfg(not(feature = "sync"))]
self.cache.borrow_mut().clear();

View File

@ -48,7 +48,7 @@ impl StaticModuleResolver {
Default::default()
}
/// Add a [module][Module] keyed by its path.
#[inline(always)]
#[inline]
pub fn insert(&mut self, path: impl Into<Identifier>, mut module: Module) {
module.build_index();
self.0.insert(path.into(), module.into());
@ -65,17 +65,17 @@ impl StaticModuleResolver {
self.0.contains_key(path)
}
/// Get an iterator of all the [modules][Module].
#[inline(always)]
#[inline]
pub fn iter(&self) -> impl Iterator<Item = (&str, &Shared<Module>)> {
self.0.iter().map(|(k, v)| (k.as_str(), v))
}
/// Get a mutable iterator of all the [modules][Module].
#[inline(always)]
#[inline]
pub fn iter_mut(&mut self) -> impl Iterator<Item = (&str, &mut Shared<Module>)> {
self.0.iter_mut().map(|(k, v)| (k.as_str(), v))
}
/// Get an iterator of all the [module][Module] paths.
#[inline(always)]
#[inline]
pub fn paths(&self) -> impl Iterator<Item = &str> {
self.0.keys().map(|s| s.as_str())
}
@ -105,7 +105,7 @@ impl StaticModuleResolver {
/// The other [`StaticModuleResolver`] is consumed.
///
/// Existing modules of the same path name are overwritten.
#[inline(always)]
#[inline]
pub fn merge(&mut self, other: Self) -> &mut Self {
if !other.is_empty() {
self.0.extend(other.0.into_iter());
@ -124,7 +124,7 @@ impl IntoIterator for StaticModuleResolver {
}
impl ModuleResolver for StaticModuleResolver {
#[inline(always)]
#[inline]
fn resolve(
&self,
_: &Engine,

Some files were not shown because too many files have changed in this diff Show More