Reduce usage of as_ref and as_mut.

This commit is contained in:
Stephen Chung 2022-07-05 16:26:38 +08:00
parent 9319f87a7b
commit b6528bd51d
33 changed files with 211 additions and 137 deletions

View File

@ -137,7 +137,7 @@ impl Parse for Module {
Ok(vec) Ok(vec)
})?; })?;
// Gather and parse constants definitions. // Gather and parse constants definitions.
for item in content.iter() { for item in &*content {
match item { match item {
syn::Item::Const(syn::ItemConst { syn::Item::Const(syn::ItemConst {
vis: syn::Visibility::Public(..), vis: syn::Visibility::Public(..),
@ -156,7 +156,7 @@ impl Parse for Module {
} }
} }
// Gather and parse type definitions. // Gather and parse type definitions.
for item in content.iter() { for item in &*content {
match item { match item {
syn::Item::Type(syn::ItemType { syn::Item::Type(syn::ItemType {
vis: syn::Visibility::Public(..), vis: syn::Visibility::Public(..),

View File

@ -300,7 +300,7 @@ pub fn check_rename_collisions(fns: &[ExportedFn]) -> Result<(), syn::Error> {
let mut renames = BTreeMap::new(); let mut renames = BTreeMap::new();
let mut fn_defs = BTreeMap::new(); let mut fn_defs = BTreeMap::new();
for item_fn in fns.iter() { for item_fn in fns {
if !item_fn.params().name.is_empty() || item_fn.params().special != FnSpecialAccess::None { if !item_fn.params().name.is_empty() || item_fn.params().special != FnSpecialAccess::None {
let mut names: Vec<_> = item_fn let mut names: Vec<_> = item_fn
.params() .params()

View File

@ -259,7 +259,7 @@ impl Engine {
} }
let mut this_ptr = this_ptr; let mut this_ptr = this_ptr;
let mut args: StaticVec<_> = arg_values.as_mut().iter_mut().collect(); let mut args: StaticVec<_> = arg_values.iter_mut().collect();
// Check for data race. // Check for data race.
#[cfg(not(feature = "no_closure"))] #[cfg(not(feature = "no_closure"))]

View File

@ -219,7 +219,7 @@ impl Engine {
) -> ParseResult<AST> { ) -> ParseResult<AST> {
let (stream, tokenizer_control) = self.lex_raw( let (stream, tokenizer_control) = self.lex_raw(
scripts.as_ref(), scripts.as_ref(),
self.token_mapper.as_ref().map(Box::as_ref), self.token_mapper.as_ref().map(<_>::as_ref),
); );
let mut state = ParseState::new(self, scope, tokenizer_control); let mut state = ParseState::new(self, scope, tokenizer_control);
self.parse(&mut stream.peekable(), &mut state, optimization_level) self.parse(&mut stream.peekable(), &mut state, optimization_level)
@ -288,7 +288,7 @@ impl Engine {
) -> ParseResult<AST> { ) -> ParseResult<AST> {
let scripts = [script]; let scripts = [script];
let (stream, tokenizer_control) = let (stream, tokenizer_control) =
self.lex_raw(&scripts, self.token_mapper.as_ref().map(Box::as_ref)); self.lex_raw(&scripts, self.token_mapper.as_ref().map(<_>::as_ref));
let mut peekable = stream.peekable(); let mut peekable = stream.peekable();
let mut state = ParseState::new(self, scope, tokenizer_control); let mut state = ParseState::new(self, scope, tokenizer_control);

View File

@ -115,7 +115,7 @@ impl Engine {
) -> RhaiResultOf<T> { ) -> RhaiResultOf<T> {
let scripts = [script]; let scripts = [script];
let (stream, tokenizer_control) = let (stream, tokenizer_control) =
self.lex_raw(&scripts, self.token_mapper.as_ref().map(Box::as_ref)); self.lex_raw(&scripts, self.token_mapper.as_ref().map(<_>::as_ref));
let mut state = ParseState::new(self, scope, tokenizer_control); let mut state = ParseState::new(self, scope, tokenizer_control);
// No need to optimize a lone expression // No need to optimize a lone expression

View File

@ -158,7 +158,9 @@ impl Engine {
return Err("precedence cannot be zero".into()); return Err("precedence cannot be zero".into());
} }
match Token::lookup_from_syntax(keyword.as_ref()) { let keyword = keyword.as_ref();
match Token::lookup_from_syntax(keyword) {
// Standard identifiers, reserved keywords and custom keywords are OK // Standard identifiers, reserved keywords and custom keywords are OK
None | Some(Token::Reserved(..)) | Some(Token::Custom(..)) => (), None | Some(Token::Reserved(..)) | Some(Token::Custom(..)) => (),
// Active standard keywords cannot be made custom // Active standard keywords cannot be made custom
@ -167,7 +169,7 @@ impl Engine {
if self.disabled_symbols.is_empty() if self.disabled_symbols.is_empty()
|| !self.disabled_symbols.contains(&*token.syntax()) || !self.disabled_symbols.contains(&*token.syntax())
{ {
return Err(format!("'{}' is a reserved keyword", keyword.as_ref())); return Err(format!("'{}' is a reserved keyword", keyword));
} }
} }
// Active standard symbols cannot be made custom // Active standard symbols cannot be made custom
@ -175,7 +177,7 @@ impl Engine {
if self.disabled_symbols.is_empty() if self.disabled_symbols.is_empty()
|| !self.disabled_symbols.contains(&*token.syntax()) || !self.disabled_symbols.contains(&*token.syntax())
{ {
return Err(format!("'{}' is a reserved operator", keyword.as_ref())); return Err(format!("'{}' is a reserved operator", keyword));
} }
} }
// Active standard symbols cannot be made custom // Active standard symbols cannot be made custom
@ -183,15 +185,14 @@ impl Engine {
if self.disabled_symbols.is_empty() if self.disabled_symbols.is_empty()
|| !self.disabled_symbols.contains(&*token.syntax()) => || !self.disabled_symbols.contains(&*token.syntax()) =>
{ {
return Err(format!("'{}' is a reserved symbol", keyword.as_ref())) return Err(format!("'{}' is a reserved symbol", keyword))
} }
// Disabled symbols are OK // Disabled symbols are OK
Some(_) => (), Some(_) => (),
} }
// Add to custom keywords // Add to custom keywords
self.custom_keywords self.custom_keywords.insert(keyword.into(), precedence);
.insert(keyword.as_ref().into(), precedence);
Ok(self) Ok(self)
} }

View File

@ -987,8 +987,9 @@ impl Engine {
module: Shared<Module>, module: Shared<Module>,
) { ) {
let separator = crate::tokenizer::Token::DoubleColon.syntax(); let separator = crate::tokenizer::Token::DoubleColon.syntax();
let separator = separator.as_ref();
if !name.contains(separator.as_ref()) { if !name.contains(separator) {
if !module.is_indexed() { if !module.is_indexed() {
// Index the module (making a clone copy if necessary) if it is not indexed // Index the module (making a clone copy if necessary) if it is not indexed
let mut module = crate::func::shared_take_or_clone(module); let mut module = crate::func::shared_take_or_clone(module);
@ -998,7 +999,7 @@ impl Engine {
root.insert(name.into(), module); root.insert(name.into(), module);
} }
} else { } else {
let mut iter = name.splitn(2, separator.as_ref()); let mut iter = name.splitn(2, separator);
let sub_module = iter.next().expect("contains separator").trim(); let sub_module = iter.next().expect("contains separator").trim();
let remainder = iter.next().expect("contains separator").trim(); let remainder = iter.next().expect("contains separator").trim();

View File

@ -23,7 +23,7 @@ impl Engine {
pub fn run_with_scope(&self, scope: &mut Scope, script: &str) -> RhaiResultOf<()> { pub fn run_with_scope(&self, scope: &mut Scope, script: &str) -> RhaiResultOf<()> {
let scripts = [script]; let scripts = [script];
let (stream, tokenizer_control) = let (stream, tokenizer_control) =
self.lex_raw(&scripts, self.token_mapper.as_ref().map(Box::as_ref)); self.lex_raw(&scripts, self.token_mapper.as_ref().map(<_>::as_ref));
let mut state = ParseState::new(self, scope, tokenizer_control); let mut state = ParseState::new(self, scope, tokenizer_control);
let ast = self.parse(&mut stream.peekable(), &mut state, self.optimization_level)?; let ast = self.parse(&mut stream.peekable(), &mut state, self.optimization_level)?;

View File

@ -54,7 +54,7 @@ impl fmt::Debug for AST {
#[cfg(not(feature = "no_function"))] #[cfg(not(feature = "no_function"))]
if !self.lib.is_empty() { if !self.lib.is_empty() {
for (.., ref fn_def) in self.lib.iter_script_fn() { for (.., fn_def) in self.lib.iter_script_fn() {
let sig = fn_def.to_string(); let sig = fn_def.to_string();
fp.field(&sig, &fn_def.body.as_slice()); fp.field(&sig, &fn_def.body.as_slice());
} }
@ -523,19 +523,19 @@ impl AST {
#[cfg(not(feature = "no_module"))] #[cfg(not(feature = "no_module"))]
match ( match (
self.resolver().map_or(0, |r| r.len()), self.resolver().map_or(true, |r| r.is_empty()),
other.resolver().map_or(0, |r| r.len()), other.resolver().map_or(true, |r| r.is_empty()),
) { ) {
(0, 0) => (), (true, true) => (),
(_, 0) => { (false, true) => {
_ast.set_resolver(self.resolver().unwrap().clone()); _ast.set_resolver(self.resolver().unwrap().clone());
} }
(0, _) => { (true, false) => {
_ast.set_resolver(other.resolver().unwrap().clone()); _ast.set_resolver(other.resolver().unwrap().clone());
} }
(_, _) => { (false, false) => {
let mut resolver = (**self.resolver().unwrap()).clone(); let mut resolver = self.resolver().unwrap().as_ref().clone();
let other_resolver = (**other.resolver().unwrap()).clone(); let other_resolver = other.resolver().unwrap().as_ref().clone();
for (k, v) in other_resolver { for (k, v) in other_resolver {
resolver.insert(k, crate::func::shared_take_or_clone(v)); resolver.insert(k, crate::func::shared_take_or_clone(v));
} }
@ -611,23 +611,16 @@ impl AST {
other: Self, other: Self,
_filter: impl Fn(FnNamespace, FnAccess, bool, &str, usize) -> bool, _filter: impl Fn(FnNamespace, FnAccess, bool, &str, usize) -> bool,
) -> &mut Self { ) -> &mut Self {
self.body.extend(other.body.into_iter());
#[cfg(not(feature = "no_function"))]
if !other.lib.is_empty() {
crate::func::shared_make_mut(&mut self.lib).merge_filtered(&other.lib, &_filter);
}
#[cfg(not(feature = "no_module"))] #[cfg(not(feature = "no_module"))]
match ( match (
self.resolver.as_ref().map_or(0, |r| r.len()), self.resolver().map_or(true, |r| r.is_empty()),
other.resolver.as_ref().map_or(0, |r| r.len()), other.resolver().map_or(true, |r| r.is_empty()),
) { ) {
(_, 0) => (), (_, true) => (),
(0, _) => { (true, false) => {
self.set_resolver(other.resolver.unwrap()); self.set_resolver(other.resolver.unwrap());
} }
(_, _) => { (false, false) => {
let resolver = crate::func::shared_make_mut(self.resolver.as_mut().unwrap()); let resolver = crate::func::shared_make_mut(self.resolver.as_mut().unwrap());
let other_resolver = crate::func::shared_take_or_clone(other.resolver.unwrap()); let other_resolver = crate::func::shared_take_or_clone(other.resolver.unwrap());
for (k, v) in other_resolver { for (k, v) in other_resolver {
@ -636,6 +629,13 @@ impl AST {
} }
} }
self.body.extend(other.body.into_iter());
#[cfg(not(feature = "no_function"))]
if !other.lib.is_empty() {
crate::func::shared_make_mut(&mut self.lib).merge_filtered(&other.lib, &_filter);
}
self self
} }
/// Filter out the functions, retaining only some based on a filter predicate. /// Filter out the functions, retaining only some based on a filter predicate.
@ -792,7 +792,7 @@ impl AST {
if options.contains(ASTFlags::CONSTANT) && include_constants if options.contains(ASTFlags::CONSTANT) && include_constants
|| !options.contains(ASTFlags::CONSTANT) && include_variables => || !options.contains(ASTFlags::CONSTANT) && include_variables =>
{ {
let (name, expr, ..) = x.as_ref(); let (name, expr, ..) = &**x;
if let Some(value) = expr.get_literal_value() { if let Some(value) = expr.get_literal_value() {
Some((name.as_str(), options.contains(ASTFlags::CONSTANT), value)) Some((name.as_str(), options.contains(ASTFlags::CONSTANT), value))
} else { } else {

View File

@ -886,14 +886,14 @@ impl Expr {
match self { match self {
Self::Stmt(x) => { Self::Stmt(x) => {
for s in x.iter() { for s in &**x {
if !s.walk(path, on_node) { if !s.walk(path, on_node) {
return false; return false;
} }
} }
} }
Self::InterpolatedString(x, ..) | Self::Array(x, ..) => { Self::InterpolatedString(x, ..) | Self::Array(x, ..) => {
for e in x.as_ref() { for e in &**x {
if !e.walk(path, on_node) { if !e.walk(path, on_node) {
return false; return false;
} }

View File

@ -123,7 +123,7 @@ impl<'a> From<&'a ScriptFnDef> for ScriptFnMetadata<'a> {
params: value.params.iter().map(|s| s.as_str()).collect(), params: value.params.iter().map(|s| s.as_str()).collect(),
access: value.access, access: value.access,
#[cfg(feature = "metadata")] #[cfg(feature = "metadata")]
comments: value.comments.iter().map(Box::as_ref).collect(), comments: value.comments.iter().map(<_>::as_ref).collect(),
} }
} }
} }

View File

@ -175,6 +175,7 @@ impl fmt::Debug for RangeCase {
impl From<Range<INT>> for RangeCase { impl From<Range<INT>> for RangeCase {
#[inline(always)] #[inline(always)]
#[must_use]
fn from(value: Range<INT>) -> Self { fn from(value: Range<INT>) -> Self {
Self::ExclusiveInt(value, 0) Self::ExclusiveInt(value, 0)
} }
@ -182,6 +183,7 @@ impl From<Range<INT>> for RangeCase {
impl From<RangeInclusive<INT>> for RangeCase { impl From<RangeInclusive<INT>> for RangeCase {
#[inline(always)] #[inline(always)]
#[must_use]
fn from(value: RangeInclusive<INT>) -> Self { fn from(value: RangeInclusive<INT>) -> Self {
Self::InclusiveInt(value, 0) Self::InclusiveInt(value, 0)
} }
@ -467,6 +469,17 @@ impl IntoIterator for StmtBlock {
} }
} }
impl<'a> IntoIterator for &'a StmtBlock {
type Item = &'a Stmt;
type IntoIter = std::slice::Iter<'a, Stmt>;
#[inline(always)]
fn into_iter(self) -> Self::IntoIter {
let x = self.block.iter();
x
}
}
impl Extend<Stmt> for StmtBlock { impl Extend<Stmt> for StmtBlock {
#[inline(always)] #[inline(always)]
fn extend<T: IntoIterator<Item = Stmt>>(&mut self, iter: T) { fn extend<T: IntoIterator<Item = Stmt>>(&mut self, iter: T) {
@ -730,7 +743,7 @@ impl Stmt {
x.0.is_pure() && x.1.iter().all(Stmt::is_pure) && x.2.iter().all(Stmt::is_pure) x.0.is_pure() && x.1.iter().all(Stmt::is_pure) && x.2.iter().all(Stmt::is_pure)
} }
Self::Switch(x, ..) => { Self::Switch(x, ..) => {
let (expr, sw) = x.as_ref(); let (expr, sw) = &**x;
expr.is_pure() expr.is_pure()
&& sw.cases.values().all(|&c| { && sw.cases.values().all(|&c| {
let block = &sw.blocks[c]; let block = &sw.blocks[c];
@ -814,7 +827,7 @@ impl Stmt {
match self { match self {
Self::Var(x, ..) => x.1.is_pure(), Self::Var(x, ..) => x.1.is_pure(),
Self::Expr(e) => match e.as_ref() { Self::Expr(e) => match &**e {
Expr::Stmt(s) => s.iter().all(Stmt::is_internally_pure), Expr::Stmt(s) => s.iter().all(Stmt::is_internally_pure),
_ => self.is_pure(), _ => self.is_pure(),
}, },
@ -864,48 +877,48 @@ impl Stmt {
if !x.0.walk(path, on_node) { if !x.0.walk(path, on_node) {
return false; return false;
} }
for s in x.1.iter() { for s in &x.1 {
if !s.walk(path, on_node) { if !s.walk(path, on_node) {
return false; return false;
} }
} }
for s in x.2.iter() { for s in &x.2 {
if !s.walk(path, on_node) { if !s.walk(path, on_node) {
return false; return false;
} }
} }
} }
Self::Switch(x, ..) => { Self::Switch(x, ..) => {
let (expr, sw) = x.as_ref(); let (expr, sw) = &**x;
if !expr.walk(path, on_node) { if !expr.walk(path, on_node) {
return false; return false;
} }
for (.., &b) in sw.cases.iter() { for (.., &b) in &sw.cases {
let block = &sw.blocks[b]; let block = &sw.blocks[b];
if !block.condition.walk(path, on_node) { if !block.condition.walk(path, on_node) {
return false; return false;
} }
for s in block.statements.iter() { for s in &block.statements {
if !s.walk(path, on_node) { if !s.walk(path, on_node) {
return false; return false;
} }
} }
} }
for r in sw.ranges.iter() { for r in &sw.ranges {
let block = &sw.blocks[r.index()]; let block = &sw.blocks[r.index()];
if !block.condition.walk(path, on_node) { if !block.condition.walk(path, on_node) {
return false; return false;
} }
for s in block.statements.iter() { for s in &block.statements {
if !s.walk(path, on_node) { if !s.walk(path, on_node) {
return false; return false;
} }
} }
} }
for s in sw.blocks[sw.def_case].statements.iter() { for s in &sw.blocks[sw.def_case].statements {
if !s.walk(path, on_node) { if !s.walk(path, on_node) {
return false; return false;
} }
@ -925,7 +938,7 @@ impl Stmt {
if !x.2.walk(path, on_node) { if !x.2.walk(path, on_node) {
return false; return false;
} }
for s in x.3.iter() { for s in &x.3 {
if !s.walk(path, on_node) { if !s.walk(path, on_node) {
return false; return false;
} }
@ -954,12 +967,12 @@ impl Stmt {
} }
} }
Self::TryCatch(x, ..) => { Self::TryCatch(x, ..) => {
for s in x.try_block.iter() { for s in &x.try_block {
if !s.walk(path, on_node) { if !s.walk(path, on_node) {
return false; return false;
} }
} }
for s in x.catch_block.iter() { for s in &x.catch_block {
if !s.walk(path, on_node) { if !s.walk(path, on_node) {
return false; return false;
} }

View File

@ -205,7 +205,7 @@ impl Engine {
let crate::ast::FnCallExpr { let crate::ast::FnCallExpr {
name, hashes, args, .. name, hashes, args, ..
} = x.as_ref(); } = &**x;
let offset = idx_values.len() - args.len(); let offset = idx_values.len() - args.len();
let call_args = &mut idx_values[offset..]; let call_args = &mut idx_values[offset..];
@ -266,7 +266,7 @@ impl Engine {
#[cfg(feature = "debugging")] #[cfg(feature = "debugging")]
self.run_debugger(scope, global, lib, this_ptr, rhs, level)?; self.run_debugger(scope, global, lib, this_ptr, rhs, level)?;
let ((getter, hash_get), (setter, hash_set), name) = x.as_ref(); let ((getter, hash_get), (setter, hash_set), name) = &**x;
let (mut new_val, op_info) = new_val.expect("`Some`"); let (mut new_val, op_info) = new_val.expect("`Some`");
if op_info.is_op_assignment() { if op_info.is_op_assignment() {
@ -331,7 +331,7 @@ impl Engine {
#[cfg(feature = "debugging")] #[cfg(feature = "debugging")]
self.run_debugger(scope, global, lib, this_ptr, rhs, level)?; self.run_debugger(scope, global, lib, this_ptr, rhs, level)?;
let ((getter, hash_get), _, name) = x.as_ref(); let ((getter, hash_get), _, name) = &**x;
let args = &mut [target.as_mut()]; let args = &mut [target.as_mut()];
self.call_native_fn( self.call_native_fn(
global, caches, lib, getter, *hash_get, args, is_ref_mut, false, *pos, global, caches, lib, getter, *hash_get, args, is_ref_mut, false, *pos,
@ -382,7 +382,7 @@ impl Engine {
let crate::ast::FnCallExpr { let crate::ast::FnCallExpr {
name, hashes, args, .. name, hashes, args, ..
} = x.as_ref(); } = &**x;
let offset = idx_values.len() - args.len(); let offset = idx_values.len() - args.len();
let call_args = &mut idx_values[offset..]; let call_args = &mut idx_values[offset..];
@ -425,7 +425,7 @@ impl Engine {
#[cfg(feature = "debugging")] #[cfg(feature = "debugging")]
self.run_debugger(scope, global, lib, this_ptr, _node, level)?; self.run_debugger(scope, global, lib, this_ptr, _node, level)?;
let ((getter, hash_get), (setter, hash_set), name) = p.as_ref(); let ((getter, hash_get), (setter, hash_set), name) = &**p;
let rhs_chain = rhs.into(); let rhs_chain = rhs.into();
let mut arg_values = [target.as_mut(), &mut Dynamic::UNIT.clone()]; let mut arg_values = [target.as_mut(), &mut Dynamic::UNIT.clone()];
let args = &mut arg_values[..1]; let args = &mut arg_values[..1];
@ -507,7 +507,7 @@ impl Engine {
let crate::ast::FnCallExpr { let crate::ast::FnCallExpr {
name, hashes, args, .. name, hashes, args, ..
} = f.as_ref(); } = &**f;
let rhs_chain = rhs.into(); let rhs_chain = rhs.into();
let offset = idx_values.len() - args.len(); let offset = idx_values.len() - args.len();
@ -563,9 +563,9 @@ impl Engine {
let chain_type = ChainType::from(expr); let chain_type = ChainType::from(expr);
let (crate::ast::BinaryExpr { lhs, rhs }, options, op_pos) = match expr { let (crate::ast::BinaryExpr { lhs, rhs }, options, op_pos) = match expr {
#[cfg(not(feature = "no_index"))] #[cfg(not(feature = "no_index"))]
Expr::Index(x, options, pos) => (x.as_ref(), *options, *pos), Expr::Index(x, options, pos) => (&**x, *options, *pos),
#[cfg(not(feature = "no_object"))] #[cfg(not(feature = "no_object"))]
Expr::Dot(x, options, pos) => (x.as_ref(), *options, *pos), Expr::Dot(x, options, pos) => (&**x, *options, *pos),
expr => unreachable!("Expr::Index or Expr::Dot expected but gets {:?}", expr), expr => unreachable!("Expr::Index or Expr::Dot expected but gets {:?}", expr),
}; };
@ -666,7 +666,7 @@ impl Engine {
Expr::MethodCall(x, ..) Expr::MethodCall(x, ..)
if _parent_chain_type == ChainType::Dotting && !x.is_qualified() => if _parent_chain_type == ChainType::Dotting && !x.is_qualified() =>
{ {
for arg_expr in x.args.as_ref() { for arg_expr in &x.args {
idx_values.push( idx_values.push(
self.get_arg_value(scope, global, caches, lib, this_ptr, arg_expr, level)? self.get_arg_value(scope, global, caches, lib, this_ptr, arg_expr, level)?
.0 .0
@ -686,7 +686,7 @@ impl Engine {
Expr::Index(x, options, ..) | Expr::Dot(x, options, ..) Expr::Index(x, options, ..) | Expr::Dot(x, options, ..)
if !parent_options.contains(ASTFlags::BREAK) => if !parent_options.contains(ASTFlags::BREAK) =>
{ {
let crate::ast::BinaryExpr { lhs, rhs, .. } = x.as_ref(); let crate::ast::BinaryExpr { lhs, rhs, .. } = &**x;
let mut _arg_values = FnArgsVec::new_const(); let mut _arg_values = FnArgsVec::new_const();
@ -700,7 +700,7 @@ impl Engine {
Expr::MethodCall(x, ..) Expr::MethodCall(x, ..)
if _parent_chain_type == ChainType::Dotting && !x.is_qualified() => if _parent_chain_type == ChainType::Dotting && !x.is_qualified() =>
{ {
for arg_expr in x.args.as_ref() { for arg_expr in &x.args {
_arg_values.push( _arg_values.push(
self.get_arg_value( self.get_arg_value(
scope, global, caches, lib, this_ptr, arg_expr, level, scope, global, caches, lib, this_ptr, arg_expr, level,

View File

@ -357,7 +357,7 @@ impl Debugger {
ASTNode::Expr(Expr::FnCall(x, ..)) | ASTNode::Stmt(Stmt::FnCall(x, ..)) => { ASTNode::Expr(Expr::FnCall(x, ..)) | ASTNode::Stmt(Stmt::FnCall(x, ..)) => {
x.name == *name x.name == *name
} }
ASTNode::Stmt(Stmt::Expr(e)) => match e.as_ref() { ASTNode::Stmt(Stmt::Expr(e)) => match &**e {
Expr::FnCall(x, ..) => x.name == *name, Expr::FnCall(x, ..) => x.name == *name,
_ => false, _ => false,
}, },
@ -367,7 +367,7 @@ impl Debugger {
ASTNode::Expr(Expr::FnCall(x, ..)) | ASTNode::Stmt(Stmt::FnCall(x, ..)) => { ASTNode::Expr(Expr::FnCall(x, ..)) | ASTNode::Stmt(Stmt::FnCall(x, ..)) => {
x.args.len() == *args && x.name == *name x.args.len() == *args && x.name == *name
} }
ASTNode::Stmt(Stmt::Expr(e)) => match e.as_ref() { ASTNode::Stmt(Stmt::Expr(e)) => match &**e {
Expr::FnCall(x, ..) => x.args.len() == *args && x.name == *name, Expr::FnCall(x, ..) => x.args.len() == *args && x.name == *name,
_ => false, _ => false,
}, },
@ -560,7 +560,7 @@ impl Engine {
ASTNode::Expr(Expr::FnCall(..)) | ASTNode::Stmt(Stmt::FnCall(..)) => { ASTNode::Expr(Expr::FnCall(..)) | ASTNode::Stmt(Stmt::FnCall(..)) => {
level + 1 level + 1
} }
ASTNode::Stmt(Stmt::Expr(e)) if matches!(e.as_ref(), Expr::FnCall(..)) => { ASTNode::Stmt(Stmt::Expr(e)) if matches!(**e, Expr::FnCall(..)) => {
level + 1 level + 1
} }
_ => level, _ => level,

View File

@ -60,7 +60,7 @@ impl Engine {
Expr::Variable(_, Some(_), _) => { Expr::Variable(_, Some(_), _) => {
self.search_scope_only(scope, global, lib, this_ptr, expr, level) self.search_scope_only(scope, global, lib, this_ptr, expr, level)
} }
Expr::Variable(v, None, _var_pos) => match v.as_ref() { Expr::Variable(v, None, _var_pos) => match &**v {
// Normal variable access // Normal variable access
#[cfg(not(feature = "no_module"))] #[cfg(not(feature = "no_module"))]
(_, ns, ..) if ns.is_empty() => { (_, ns, ..) if ns.is_empty() => {
@ -323,7 +323,7 @@ impl Engine {
let mut op_info = OpAssignment::new_op_assignment(OP_CONCAT, Position::NONE); let mut op_info = OpAssignment::new_op_assignment(OP_CONCAT, Position::NONE);
let root = ("", Position::NONE); let root = ("", Position::NONE);
for expr in x.iter() { for expr in &**x {
let item = let item =
match self.eval_expr(scope, global, caches, lib, this_ptr, expr, level) { match self.eval_expr(scope, global, caches, lib, this_ptr, expr, level) {
Ok(r) => r, Ok(r) => r,
@ -354,7 +354,7 @@ impl Engine {
#[cfg(not(feature = "unchecked"))] #[cfg(not(feature = "unchecked"))]
let mut sizes = (0, 0, 0); let mut sizes = (0, 0, 0);
for item_expr in x.iter() { for item_expr in &**x {
let value = match self let value = match self
.eval_expr(scope, global, caches, lib, this_ptr, item_expr, level) .eval_expr(scope, global, caches, lib, this_ptr, item_expr, level)
{ {
@ -392,7 +392,7 @@ impl Engine {
#[cfg(not(feature = "unchecked"))] #[cfg(not(feature = "unchecked"))]
let mut sizes = (0, 0, 0); let mut sizes = (0, 0, 0);
for (key, value_expr) in x.0.iter() { for (key, value_expr) in &x.0 {
let value = match self let value = match self
.eval_expr(scope, global, caches, lib, this_ptr, value_expr, level) .eval_expr(scope, global, caches, lib, this_ptr, value_expr, level)
{ {

View File

@ -197,7 +197,7 @@ impl GlobalRuntimeState<'_> {
.iter() .iter()
.rev() .rev()
.zip(self.modules.iter().rev()) .zip(self.modules.iter().rev())
.map(|(name, module)| (name.as_str(), module.as_ref())) .map(|(name, module)| (name.as_str(), &**module))
} }
/// Get an iterator to the stack of globally-imported [modules][crate::Module] in reverse order. /// Get an iterator to the stack of globally-imported [modules][crate::Module] in reverse order.
/// ///
@ -327,6 +327,21 @@ impl IntoIterator for GlobalRuntimeState<'_> {
} }
} }
#[cfg(not(feature = "no_module"))]
impl<'a> IntoIterator for &'a GlobalRuntimeState<'_> {
type Item = (&'a Identifier, &'a crate::Shared<crate::Module>);
type IntoIter = std::iter::Zip<
std::iter::Rev<std::slice::Iter<'a, Identifier>>,
std::iter::Rev<std::slice::Iter<'a, crate::Shared<crate::Module>>>,
>;
#[inline]
fn into_iter(self) -> Self::IntoIter {
let x = self.keys.iter().rev().zip(self.modules.iter().rev());
x
}
}
#[cfg(not(feature = "no_module"))] #[cfg(not(feature = "no_module"))]
impl<K: Into<Identifier>, M: Into<crate::Shared<crate::Module>>> Extend<(K, M)> impl<K: Into<Identifier>, M: Into<crate::Shared<crate::Module>>> Extend<(K, M)>
for GlobalRuntimeState<'_> for GlobalRuntimeState<'_>

View File

@ -248,7 +248,7 @@ impl Engine {
self.inc_operations(&mut global.num_operations, stmt.position())?; self.inc_operations(&mut global.num_operations, stmt.position())?;
let result = if x.1.lhs.is_variable_access(false) { let result = if x.1.lhs.is_variable_access(false) {
let (op_info, BinaryExpr { lhs, rhs }) = x.as_ref(); let (op_info, BinaryExpr { lhs, rhs }) = &**x;
let rhs_result = self let rhs_result = self
.eval_expr(scope, global, caches, lib, this_ptr, rhs, level) .eval_expr(scope, global, caches, lib, this_ptr, rhs, level)
@ -294,7 +294,7 @@ impl Engine {
rhs_result rhs_result
} }
} else { } else {
let (op_info, BinaryExpr { lhs, rhs }) = x.as_ref(); let (op_info, BinaryExpr { lhs, rhs }) = &**x;
let rhs_result = self let rhs_result = self
.eval_expr(scope, global, caches, lib, this_ptr, rhs, level) .eval_expr(scope, global, caches, lib, this_ptr, rhs, level)
@ -356,7 +356,7 @@ impl Engine {
// If statement // If statement
Stmt::If(x, ..) => { Stmt::If(x, ..) => {
let (expr, if_block, else_block) = x.as_ref(); let (expr, if_block, else_block) = &**x;
let guard_val = self let guard_val = self
.eval_expr(scope, global, caches, lib, this_ptr, expr, level) .eval_expr(scope, global, caches, lib, this_ptr, expr, level)
@ -399,7 +399,7 @@ impl Engine {
def_case, def_case,
ranges, ranges,
}, },
) = x.as_ref(); ) = &**x;
let value_result = let value_result =
self.eval_expr(scope, global, caches, lib, this_ptr, expr, level); self.eval_expr(scope, global, caches, lib, this_ptr, expr, level);
@ -500,7 +500,7 @@ impl Engine {
// Loop // Loop
Stmt::While(x, ..) if matches!(x.0, Expr::Unit(..)) => loop { Stmt::While(x, ..) if matches!(x.0, Expr::Unit(..)) => loop {
let (.., body) = x.as_ref(); let (.., body) = &**x;
if !body.is_empty() { if !body.is_empty() {
match self match self
@ -521,7 +521,7 @@ impl Engine {
// While loop // While loop
Stmt::While(x, ..) => loop { Stmt::While(x, ..) => loop {
let (expr, body) = x.as_ref(); let (expr, body) = &**x;
let condition = self let condition = self
.eval_expr(scope, global, caches, lib, this_ptr, expr, level) .eval_expr(scope, global, caches, lib, this_ptr, expr, level)
@ -552,7 +552,7 @@ impl Engine {
// Do loop // Do loop
Stmt::Do(x, options, ..) => loop { Stmt::Do(x, options, ..) => loop {
let (expr, body) = x.as_ref(); let (expr, body) = &**x;
let is_while = !options.contains(ASTFlags::NEGATED); let is_while = !options.contains(ASTFlags::NEGATED);
if !body.is_empty() { if !body.is_empty() {
@ -585,7 +585,7 @@ impl Engine {
// For loop // For loop
Stmt::For(x, ..) => { Stmt::For(x, ..) => {
let (var_name, counter, expr, statements) = x.as_ref(); let (var_name, counter, expr, statements) = &**x;
let iter_result = self let iter_result = self
.eval_expr(scope, global, caches, lib, this_ptr, expr, level) .eval_expr(scope, global, caches, lib, this_ptr, expr, level)
@ -728,7 +728,7 @@ impl Engine {
name: catch_var, .. name: catch_var, ..
}, },
catch_block, catch_block,
} = x.as_ref(); } = &**x;
let result = self let result = self
.eval_stmt_block(scope, global, caches, lib, this_ptr, try_block, true, level) .eval_stmt_block(scope, global, caches, lib, this_ptr, try_block, true, level)
@ -832,7 +832,7 @@ impl Engine {
} }
// Let/const statement // Let/const statement
Stmt::Var(x, options, pos) => { Stmt::Var(x, options, pos) => {
let (var_name, expr, index) = x.as_ref(); let (var_name, expr, index) = &**x;
let access = if options.contains(ASTFlags::CONSTANT) { let access = if options.contains(ASTFlags::CONSTANT) {
AccessMode::ReadOnly AccessMode::ReadOnly
@ -926,7 +926,7 @@ impl Engine {
// Import statement // Import statement
#[cfg(not(feature = "no_module"))] #[cfg(not(feature = "no_module"))]
Stmt::Import(x, _pos) => { Stmt::Import(x, _pos) => {
let (expr, export) = x.as_ref(); let (expr, export) = &**x;
// Guard against too many modules // Guard against too many modules
#[cfg(not(feature = "unchecked"))] #[cfg(not(feature = "unchecked"))]
@ -995,7 +995,7 @@ impl Engine {
// Export statement // Export statement
#[cfg(not(feature = "no_module"))] #[cfg(not(feature = "no_module"))]
Stmt::Export(x, ..) => { Stmt::Export(x, ..) => {
let (Ident { name, pos, .. }, alias) = x.as_ref(); let (Ident { name, pos, .. }, alias) = &**x;
// Mark scope variables as public // Mark scope variables as public
if let Some((index, ..)) = scope.get_index(name) { if let Some((index, ..)) = scope.get_index(name) {
let alias = if alias.is_empty() { name } else { alias }.clone(); let alias = if alias.is_empty() { name } else { alias }.clone();

View File

@ -178,7 +178,7 @@ impl CallableFunction {
#[must_use] #[must_use]
pub fn get_iter_fn(&self) -> Option<&IteratorFn> { pub fn get_iter_fn(&self) -> Option<&IteratorFn> {
match self { match self {
Self::Iterator(f) => Some(f.as_ref()), Self::Iterator(f) => Some(&**f),
Self::Pure(..) | Self::Method(..) | Self::Plugin(..) => None, Self::Pure(..) | Self::Method(..) | Self::Plugin(..) => None,
#[cfg(not(feature = "no_function"))] #[cfg(not(feature = "no_function"))]

View File

@ -110,7 +110,7 @@ impl<'a, M: AsRef<[&'a Module]> + ?Sized, S: AsRef<str> + 'a + ?Sized>
Self { Self {
engine: value.0, engine: value.0,
fn_name: value.1.as_ref(), fn_name: value.1.as_ref(),
source: value.2.map(S::as_ref), source: value.2.map(<_>::as_ref),
global: Some(value.3), global: Some(value.3),
lib: value.4.as_ref(), lib: value.4.as_ref(),
pos: value.5, pos: value.5,

View File

@ -131,7 +131,7 @@ impl Engine {
lib lib
} else { } else {
caches.push_fn_resolution_cache(); caches.push_fn_resolution_cache();
lib_merged.push(fn_lib.as_ref()); lib_merged.push(&**fn_lib);
lib_merged.extend(lib.iter().cloned()); lib_merged.extend(lib.iter().cloned());
&lib_merged &lib_merged
}, },

View File

@ -781,7 +781,7 @@ impl Module {
#[must_use] #[must_use]
pub fn get_sub_module(&self, name: &str) -> Option<&Module> { pub fn get_sub_module(&self, name: &str) -> Option<&Module> {
if !self.modules.is_empty() { if !self.modules.is_empty() {
self.modules.get(name).map(|m| m.as_ref()) self.modules.get(name).map(|m| &**m)
} else { } else {
None None
} }
@ -1006,18 +1006,19 @@ impl Module {
(names, return_type) (names, return_type)
}; };
let hash_fn = calc_native_fn_hash(None, name.as_ref(), &param_types); let name = name.as_ref();
let hash_fn = calc_native_fn_hash(None, name, &param_types);
if is_dynamic { if is_dynamic {
self.dynamic_functions self.dynamic_functions
.insert(calc_fn_hash(name.as_ref(), param_types.len())); .insert(calc_fn_hash(name, param_types.len()));
} }
self.functions.insert( self.functions.insert(
hash_fn, hash_fn,
FuncInfo { FuncInfo {
metadata: FnMetadata { metadata: FnMetadata {
name: name.as_ref().into(), name: name.into(),
namespace, namespace,
access, access,
params: param_types.len(), params: param_types.len(),
@ -1549,7 +1550,7 @@ impl Module {
/// Sub-modules are flattened onto the root [`Module`], with higher level overriding lower level. /// Sub-modules are flattened onto the root [`Module`], with higher level overriding lower level.
#[inline] #[inline]
pub fn combine_flatten(&mut self, other: Self) -> &mut Self { pub fn combine_flatten(&mut self, other: Self) -> &mut Self {
for (.., m) in other.modules.into_iter() { for (.., m) in other.modules {
self.combine_flatten(shared_take_or_clone(m)); self.combine_flatten(shared_take_or_clone(m));
} }
self.variables.extend(other.variables.into_iter()); self.variables.extend(other.variables.into_iter());
@ -1707,7 +1708,7 @@ impl Module {
#[inline] #[inline]
#[allow(dead_code)] #[allow(dead_code)]
pub(crate) fn iter_fn(&self) -> impl Iterator<Item = &FuncInfo> { pub(crate) fn iter_fn(&self) -> impl Iterator<Item = &FuncInfo> {
self.functions.values().map(Box::as_ref) self.functions.values().map(<_>::as_ref)
} }
/// Get an iterator over all script-defined functions in the [`Module`]. /// Get an iterator over all script-defined functions in the [`Module`].
@ -2154,7 +2155,7 @@ impl Module {
#[must_use] #[must_use]
pub(crate) fn get_qualified_iter(&self, id: TypeId) -> Option<&IteratorFn> { pub(crate) fn get_qualified_iter(&self, id: TypeId) -> Option<&IteratorFn> {
if !self.all_type_iterators.is_empty() { if !self.all_type_iterators.is_empty() {
self.all_type_iterators.get(&id).map(|f| f.as_ref()) self.all_type_iterators.get(&id).map(|f| &**f)
} else { } else {
None None
} }
@ -2165,7 +2166,7 @@ impl Module {
#[must_use] #[must_use]
pub(crate) fn get_iter(&self, id: TypeId) -> Option<&IteratorFn> { pub(crate) fn get_iter(&self, id: TypeId) -> Option<&IteratorFn> {
if !self.type_iterators.is_empty() { if !self.type_iterators.is_empty() {
self.type_iterators.get(&id).map(|f| f.as_ref()) self.type_iterators.get(&id).map(|f| &**f)
} else { } else {
None None
} }

View File

@ -1,7 +1,7 @@
use crate::{Engine, Module, ModuleResolver, Position, RhaiResultOf, Shared, ERR}; use crate::{Engine, Module, ModuleResolver, Position, RhaiResultOf, Shared, ERR};
#[cfg(feature = "no_std")] #[cfg(feature = "no_std")]
use std::prelude::v1::*; use std::prelude::v1::*;
use std::{ops::AddAssign, vec::IntoIter}; use std::{ops::AddAssign, slice::Iter, vec::IntoIter};
/// [Module] resolution service that holds a collection of module resolvers, /// [Module] resolution service that holds a collection of module resolvers,
/// to be searched in sequential order. /// to be searched in sequential order.
@ -116,6 +116,16 @@ impl IntoIterator for ModuleResolversCollection {
} }
} }
impl<'a> IntoIterator for &'a ModuleResolversCollection {
type Item = &'a Box<dyn ModuleResolver>;
type IntoIter = Iter<'a, Box<dyn ModuleResolver>>;
#[inline(always)]
fn into_iter(self) -> Self::IntoIter {
self.0.iter()
}
}
impl ModuleResolver for ModuleResolversCollection { impl ModuleResolver for ModuleResolversCollection {
fn resolve( fn resolve(
&self, &self,

View File

@ -172,7 +172,7 @@ impl FileModuleResolver {
#[inline(always)] #[inline(always)]
#[must_use] #[must_use]
pub fn base_path(&self) -> Option<&Path> { pub fn base_path(&self) -> Option<&Path> {
self.base_path.as_ref().map(PathBuf::as_ref) self.base_path.as_ref().map(<_>::as_ref)
} }
/// Set the base path for script files. /// Set the base path for script files.
#[inline(always)] #[inline(always)]

View File

@ -3,7 +3,11 @@ use crate::{
}; };
#[cfg(feature = "no_std")] #[cfg(feature = "no_std")]
use std::prelude::v1::*; use std::prelude::v1::*;
use std::{collections::btree_map::IntoIter, collections::BTreeMap, ops::AddAssign}; use std::{
collections::btree_map::{IntoIter, Iter},
collections::BTreeMap,
ops::AddAssign,
};
/// A static [module][Module] resolution service that serves [modules][Module] added into it. /// A static [module][Module] resolution service that serves [modules][Module] added into it.
/// ///
@ -122,11 +126,22 @@ impl IntoIterator for StaticModuleResolver {
type Item = (Identifier, Shared<Module>); type Item = (Identifier, Shared<Module>);
type IntoIter = IntoIter<SmartString, Shared<Module>>; type IntoIter = IntoIter<SmartString, Shared<Module>>;
#[inline(always)]
fn into_iter(self) -> Self::IntoIter { fn into_iter(self) -> Self::IntoIter {
self.0.into_iter() self.0.into_iter()
} }
} }
impl<'a> IntoIterator for &'a StaticModuleResolver {
type Item = (&'a Identifier, &'a Shared<Module>);
type IntoIter = Iter<'a, SmartString, Shared<Module>>;
#[inline(always)]
fn into_iter(self) -> Self::IntoIter {
self.0.iter()
}
}
impl ModuleResolver for StaticModuleResolver { impl ModuleResolver for StaticModuleResolver {
#[inline] #[inline]
fn resolve( fn resolve(

View File

@ -512,7 +512,7 @@ fn optimize_stmt(stmt: &mut Stmt, state: &mut OptimizerState, preserve_result: b
} }
// if expr { if_block } else { else_block } // if expr { if_block } else { else_block }
Stmt::If(x, ..) => { Stmt::If(x, ..) => {
let (condition, body, other) = x.as_mut(); let (condition, body, other) = &mut **x;
optimize_expr(condition, state, false); optimize_expr(condition, state, false);
**body = **body =
optimize_stmt_block(mem::take(&mut **body), state, preserve_result, true, false); optimize_stmt_block(mem::take(&mut **body), state, preserve_result, true, false);
@ -530,7 +530,7 @@ fn optimize_stmt(stmt: &mut Stmt, state: &mut OptimizerState, preserve_result: b
ranges, ranges,
def_case, def_case,
}, },
) = x.as_mut(); ) = &mut **x;
let value = match_expr.get_literal_value().unwrap(); let value = match_expr.get_literal_value().unwrap();
let hasher = &mut get_hasher(); let hasher = &mut get_hasher();
@ -640,7 +640,7 @@ fn optimize_stmt(stmt: &mut Stmt, state: &mut OptimizerState, preserve_result: b
state.set_dirty(); state.set_dirty();
} }
for r in ranges.iter() { for r in &*ranges {
let block = &mut blocks_list[r.index()]; let block = &mut blocks_list[r.index()];
let statements = mem::take(&mut *block.statements); let statements = mem::take(&mut *block.statements);
*block.statements = *block.statements =
@ -679,7 +679,7 @@ fn optimize_stmt(stmt: &mut Stmt, state: &mut OptimizerState, preserve_result: b
def_case, def_case,
.. ..
}, },
) = x.as_mut(); ) = &mut **x;
optimize_expr(match_expr, state, false); optimize_expr(match_expr, state, false);
@ -738,7 +738,7 @@ fn optimize_stmt(stmt: &mut Stmt, state: &mut OptimizerState, preserve_result: b
}, },
// while expr { block } // while expr { block }
Stmt::While(x, ..) => { Stmt::While(x, ..) => {
let (condition, body) = x.as_mut(); let (condition, body) = &mut **x;
optimize_expr(condition, state, false); optimize_expr(condition, state, false);
if let Expr::BoolConstant(true, pos) = condition { if let Expr::BoolConstant(true, pos) = condition {
*condition = Expr::Unit(*pos); *condition = Expr::Unit(*pos);
@ -846,7 +846,7 @@ fn optimize_stmt(stmt: &mut Stmt, state: &mut OptimizerState, preserve_result: b
Stmt::Expr(expr) => { Stmt::Expr(expr) => {
optimize_expr(expr, state, false); optimize_expr(expr, state, false);
match expr.as_mut() { match &mut **expr {
// func(...) // func(...)
Expr::FnCall(x, pos) => { Expr::FnCall(x, pos) => {
state.set_dirty(); state.set_dirty();
@ -892,7 +892,7 @@ fn optimize_expr(expr: &mut Expr, state: &mut OptimizerState, _chaining: bool) {
***x = optimize_stmt_block(mem::take(&mut **x), state, true, true, false); ***x = optimize_stmt_block(mem::take(&mut **x), state, true, true, false);
// { Stmt(Expr) } - promote // { Stmt(Expr) } - promote
match x.as_mut().as_mut() { match &mut ****x {
[ Stmt::Expr(e) ] => { state.set_dirty(); *expr = mem::take(e); } [ Stmt::Expr(e) ] => { state.set_dirty(); *expr = mem::take(e); }
_ => () _ => ()
} }
@ -1129,7 +1129,7 @@ fn optimize_expr(expr: &mut Expr, state: &mut OptimizerState, _chaining: bool) {
return; return;
} }
// Overloaded operators can override built-in. // Overloaded operators can override built-in.
_ if x.args.len() == 2 && !has_native_fn_override(state.engine, x.hashes.native, arg_types.as_ref()) => { _ if x.args.len() == 2 && !has_native_fn_override(state.engine, x.hashes.native, &arg_types) => {
if let Some(result) = get_builtin_binary_op_fn(&x.name, &arg_values[0], &arg_values[1]) if let Some(result) = get_builtin_binary_op_fn(&x.name, &arg_values[0], &arg_values[1])
.and_then(|f| { .and_then(|f| {
#[cfg(not(feature = "no_function"))] #[cfg(not(feature = "no_function"))]

View File

@ -273,12 +273,12 @@ fn collect_fn_metadata(
crate::tokenizer::Token::DoubleColon.literal_syntax(), crate::tokenizer::Token::DoubleColon.literal_syntax(),
ns ns
); );
scan_module(list, dict, ns.into(), m.as_ref(), filter) scan_module(list, dict, ns.into(), &**m, filter)
} }
} }
for (ns, m) in ctx.iter_imports_raw() { for (ns, m) in ctx.iter_imports_raw() {
scan_module(&mut list, &dict, ns.clone(), m.as_ref(), filter) scan_module(&mut list, &dict, ns.clone(), &**m, filter)
} }
} }

View File

@ -191,7 +191,7 @@ mod map_functions {
if !map1.is_empty() { if !map1.is_empty() {
let mut map2 = map2; let mut map2 = map2;
for (m1, v1) in map1.iter_mut() { for (m1, v1) in map1 {
if let Some(v2) = map2.get_mut(m1) { if let Some(v2) = map2.get_mut(m1) {
let equals = ctx let equals = ctx
.call_fn_raw(OP_EQUALS, true, false, &mut [v1, v2])? .call_fn_raw(OP_EQUALS, true, false, &mut [v1, v2])?

View File

@ -1729,9 +1729,9 @@ impl Engine {
// Cache the hash key for namespace-qualified variables // Cache the hash key for namespace-qualified variables
#[cfg(not(feature = "no_module"))] #[cfg(not(feature = "no_module"))]
let namespaced_variable = match lhs { let namespaced_variable = match lhs {
Expr::Variable(ref mut x, ..) if !x.1.is_empty() => Some(x.as_mut()), Expr::Variable(ref mut x, ..) if !x.1.is_empty() => Some(&mut **x),
Expr::Index(ref mut x, ..) | Expr::Dot(ref mut x, ..) => match x.lhs { Expr::Index(ref mut x, ..) | Expr::Dot(ref mut x, ..) => match x.lhs {
Expr::Variable(ref mut x, ..) if !x.1.is_empty() => Some(x.as_mut()), Expr::Variable(ref mut x, ..) if !x.1.is_empty() => Some(&mut **x),
_ => None, _ => None,
}, },
_ => None, _ => None,
@ -1933,7 +1933,7 @@ impl Engine {
} }
// var (indexed) = rhs // var (indexed) = rhs
Expr::Variable(ref x, i, var_pos) => { Expr::Variable(ref x, i, var_pos) => {
let (index, .., name) = x.as_ref(); let (index, .., name) = &**x;
let index = i.map_or_else( let index = i.map_or_else(
|| index.expect("either long or short index is `None`").get(), || index.expect("either long or short index is `None`").get(),
|n| n.get() as usize, |n| n.get() as usize,
@ -2067,7 +2067,7 @@ impl Engine {
(.., Expr::FnCall(func, func_pos)) (.., Expr::FnCall(func, func_pos))
if func.args.is_empty() if func.args.is_empty()
&& [crate::engine::KEYWORD_FN_PTR, crate::engine::KEYWORD_EVAL] && [crate::engine::KEYWORD_FN_PTR, crate::engine::KEYWORD_EVAL]
.contains(&func.name.as_ref()) => .contains(&func.name.as_str()) =>
{ {
let err_msg = format!( let err_msg = format!(
"'{}' should not be called in method style. Try {}(...);", "'{}' should not be called in method style. Try {}(...);",
@ -2370,7 +2370,7 @@ impl Engine {
state.stack.push(marker, ()); state.stack.push(marker, ());
} }
let parse_func = syntax.parse.as_ref(); let parse_func = &*syntax.parse;
let mut required_token: ImmutableString = key.into(); let mut required_token: ImmutableString = key.into();
tokens.push(required_token.clone().into()); tokens.push(required_token.clone().into());

View File

@ -146,10 +146,10 @@ impl<'a> From<&'a FuncInfo> for FnMetadata<'a> {
.expect("script-defined function") .expect("script-defined function")
.comments .comments
.iter() .iter()
.map(Box::as_ref) .map(<_>::as_ref)
.collect() .collect()
} else { } else {
info.metadata.comments.iter().map(Box::as_ref).collect() info.metadata.comments.iter().map(<_>::as_ref).collect()
}, },
} }
} }

View File

@ -329,20 +329,20 @@ impl Span {
impl fmt::Display for Span { impl fmt::Display for Span {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match (self.start().is_none(), self.end().is_none()) { match (self.start(), self.end()) {
(false, false) if self.start().line() != self.end().line() => { (Position::NONE, Position::NONE) => write!(f, "{:?}", Position::NONE),
write!(f, "{:?}-{:?}", self.start(), self.end()) (Position::NONE, end) => write!(f, "..{:?}", end),
(start, Position::NONE) => write!(f, "{:?}", start),
(start, end) if start.line() != end.line() => {
write!(f, "{:?}-{:?}", start, end)
} }
(false, false) => write!( (start, end) => write!(
f, f,
"{}:{}-{}", "{}:{}-{}",
self.start().line().unwrap(), start.line().unwrap(),
self.start().position().unwrap_or(0), start.position().unwrap_or(0),
self.end().position().unwrap_or(0) end.position().unwrap_or(0)
), ),
(true, false) => write!(f, "..{:?}", self.end()),
(false, true) => write!(f, "{:?}", self.start()),
(true, true) => write!(f, "{:?}", Position::NONE),
} }
} }
} }

View File

@ -56,7 +56,7 @@ impl FnPtr {
#[inline(always)] #[inline(always)]
#[must_use] #[must_use]
pub fn fn_name(&self) -> &str { pub fn fn_name(&self) -> &str {
self.fn_name_raw().as_ref() self.fn_name_raw().as_str()
} }
/// Get the name of the function. /// Get the name of the function.
#[inline(always)] #[inline(always)]
@ -223,7 +223,7 @@ impl FnPtr {
args_data = StaticVec::with_capacity(self.curry().len() + arg_values.len()); args_data = StaticVec::with_capacity(self.curry().len() + arg_values.len());
args_data.extend(self.curry().iter().cloned()); args_data.extend(self.curry().iter().cloned());
args_data.extend(arg_values.iter_mut().map(mem::take)); args_data.extend(arg_values.iter_mut().map(mem::take));
arg_values = args_data.as_mut(); arg_values = &mut *args_data;
}; };
let is_method = this_ptr.is_some(); let is_method = this_ptr.is_some();

View File

@ -51,7 +51,10 @@ impl StringsInterner<'_> {
#[inline] #[inline]
#[must_use] #[must_use]
pub fn get(&mut self, prefix: impl AsRef<str>, text: impl AsRef<str>) -> ImmutableString { pub fn get(&mut self, prefix: impl AsRef<str>, text: impl AsRef<str>) -> ImmutableString {
let (dict, mapper): (_, fn(&str) -> Identifier) = match prefix.as_ref() { let prefix = prefix.as_ref();
let text = text.as_ref();
let (dict, mapper): (_, fn(&str) -> Identifier) = match prefix {
"" => (&mut self.strings, |s| s.into()), "" => (&mut self.strings, |s| s.into()),
#[cfg(not(feature = "no_object"))] #[cfg(not(feature = "no_object"))]
@ -59,14 +62,14 @@ impl StringsInterner<'_> {
#[cfg(not(feature = "no_object"))] #[cfg(not(feature = "no_object"))]
crate::engine::FN_SET => (&mut self.setters, crate::engine::make_setter), crate::engine::FN_SET => (&mut self.setters, crate::engine::make_setter),
_ => unreachable!("unsupported prefix {}", prefix.as_ref()), _ => unreachable!("unsupported prefix {}", prefix),
}; };
if !dict.is_empty() && dict.contains_key(text.as_ref()) { if !dict.is_empty() && dict.contains_key(text) {
dict.get(text.as_ref()).unwrap().clone() dict.get(text).unwrap().clone()
} else { } else {
let value: ImmutableString = mapper(text.as_ref()).into(); let value: ImmutableString = mapper(text).into();
dict.insert(text.as_ref().into(), value.clone()); dict.insert(text.into(), value.clone());
value value
} }
} }

View File

@ -132,6 +132,21 @@ impl IntoIterator for Scope<'_> {
} }
} }
impl<'a> IntoIterator for &'a Scope<'_> {
type Item = (&'a Identifier, &'a Dynamic, &'a Vec<Identifier>);
type IntoIter = Box<dyn Iterator<Item = Self::Item> + 'a>;
#[inline]
fn into_iter(self) -> Self::IntoIter {
Box::new(
self.values
.iter()
.zip(self.names.iter().zip(self.aliases.iter()))
.map(|(value, (name, alias))| (name, value, alias)),
)
}
}
impl Scope<'_> { impl Scope<'_> {
/// Create a new [`Scope`]. /// Create a new [`Scope`].
/// ///
@ -686,7 +701,7 @@ impl Scope<'_> {
self.names self.names
.iter() .iter()
.zip(self.values.iter()) .zip(self.values.iter())
.map(|(name, value)| (name.as_ref(), value.is_read_only(), value)) .map(|(name, value)| (name.as_str(), value.is_read_only(), value))
} }
/// Get a reverse iterator to entries in the [`Scope`]. /// Get a reverse iterator to entries in the [`Scope`].
/// Shared values are not expanded. /// Shared values are not expanded.
@ -696,7 +711,7 @@ impl Scope<'_> {
.iter() .iter()
.rev() .rev()
.zip(self.values.iter().rev()) .zip(self.values.iter().rev())
.map(|(name, value)| (name.as_ref(), value.is_read_only(), value)) .map(|(name, value)| (name.as_str(), value.is_read_only(), value))
} }
/// Remove a range of entries within the [`Scope`]. /// Remove a range of entries within the [`Scope`].
/// ///