From b6528bd51d0d2447ec3f033ab8078f75573db115 Mon Sep 17 00:00:00 2001 From: Stephen Chung Date: Tue, 5 Jul 2022 16:26:38 +0800 Subject: [PATCH] Reduce usage of as_ref and as_mut. --- codegen/src/module.rs | 4 +-- codegen/src/rhai_module.rs | 2 +- src/api/call_fn.rs | 2 +- src/api/compile.rs | 4 +-- src/api/eval.rs | 2 +- src/api/mod.rs | 13 +++++---- src/api/register.rs | 5 ++-- src/api/run.rs | 2 +- src/ast/ast.rs | 44 +++++++++++++++--------------- src/ast/expr.rs | 4 +-- src/ast/script_fn.rs | 2 +- src/ast/stmt.rs | 39 +++++++++++++++++--------- src/eval/chaining.rs | 22 +++++++-------- src/eval/debugger.rs | 6 ++-- src/eval/expr.rs | 8 +++--- src/eval/global_state.rs | 17 +++++++++++- src/eval/stmt.rs | 24 ++++++++-------- src/func/callable_function.rs | 2 +- src/func/native.rs | 2 +- src/func/script.rs | 2 +- src/module/mod.rs | 17 ++++++------ src/module/resolvers/collection.rs | 12 +++++++- src/module/resolvers/file.rs | 2 +- src/module/resolvers/stat.rs | 17 +++++++++++- src/optimizer.rs | 16 +++++------ src/packages/lang_core.rs | 4 +-- src/packages/map_basic.rs | 2 +- src/parser.rs | 10 +++---- src/serde/metadata.rs | 4 +-- src/tokenizer.rs | 20 +++++++------- src/types/fn_ptr.rs | 4 +-- src/types/interner.rs | 15 ++++++---- src/types/scope.rs | 19 +++++++++++-- 33 files changed, 211 insertions(+), 137 deletions(-) diff --git a/codegen/src/module.rs b/codegen/src/module.rs index 52b9716c..c1d7d6a3 100644 --- a/codegen/src/module.rs +++ b/codegen/src/module.rs @@ -137,7 +137,7 @@ impl Parse for Module { Ok(vec) })?; // Gather and parse constants definitions. - for item in content.iter() { + for item in &*content { match item { syn::Item::Const(syn::ItemConst { vis: syn::Visibility::Public(..), @@ -156,7 +156,7 @@ impl Parse for Module { } } // Gather and parse type definitions. - for item in content.iter() { + for item in &*content { match item { syn::Item::Type(syn::ItemType { vis: syn::Visibility::Public(..), diff --git a/codegen/src/rhai_module.rs b/codegen/src/rhai_module.rs index 0e03917f..10b61e20 100644 --- a/codegen/src/rhai_module.rs +++ b/codegen/src/rhai_module.rs @@ -300,7 +300,7 @@ pub fn check_rename_collisions(fns: &[ExportedFn]) -> Result<(), syn::Error> { let mut renames = 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 { let mut names: Vec<_> = item_fn .params() diff --git a/src/api/call_fn.rs b/src/api/call_fn.rs index dcbfbf99..9ad2965d 100644 --- a/src/api/call_fn.rs +++ b/src/api/call_fn.rs @@ -259,7 +259,7 @@ impl Engine { } 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. #[cfg(not(feature = "no_closure"))] diff --git a/src/api/compile.rs b/src/api/compile.rs index 2250b641..9aed8eed 100644 --- a/src/api/compile.rs +++ b/src/api/compile.rs @@ -219,7 +219,7 @@ impl Engine { ) -> ParseResult { let (stream, tokenizer_control) = self.lex_raw( 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); self.parse(&mut stream.peekable(), &mut state, optimization_level) @@ -288,7 +288,7 @@ impl Engine { ) -> ParseResult { let scripts = [script]; 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 state = ParseState::new(self, scope, tokenizer_control); diff --git a/src/api/eval.rs b/src/api/eval.rs index a90d88bc..cb351301 100644 --- a/src/api/eval.rs +++ b/src/api/eval.rs @@ -115,7 +115,7 @@ impl Engine { ) -> RhaiResultOf { let scripts = [script]; 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); // No need to optimize a lone expression diff --git a/src/api/mod.rs b/src/api/mod.rs index b8e7084e..71a6527c 100644 --- a/src/api/mod.rs +++ b/src/api/mod.rs @@ -158,7 +158,9 @@ impl Engine { 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 None | Some(Token::Reserved(..)) | Some(Token::Custom(..)) => (), // Active standard keywords cannot be made custom @@ -167,7 +169,7 @@ impl Engine { if self.disabled_symbols.is_empty() || !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 @@ -175,7 +177,7 @@ impl Engine { if self.disabled_symbols.is_empty() || !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 @@ -183,15 +185,14 @@ impl Engine { if self.disabled_symbols.is_empty() || !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 Some(_) => (), } // Add to custom keywords - self.custom_keywords - .insert(keyword.as_ref().into(), precedence); + self.custom_keywords.insert(keyword.into(), precedence); Ok(self) } diff --git a/src/api/register.rs b/src/api/register.rs index 3ee7eb39..485cec44 100644 --- a/src/api/register.rs +++ b/src/api/register.rs @@ -987,8 +987,9 @@ impl Engine { module: Shared, ) { 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() { // Index the module (making a clone copy if necessary) if it is not indexed let mut module = crate::func::shared_take_or_clone(module); @@ -998,7 +999,7 @@ impl Engine { root.insert(name.into(), module); } } 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 remainder = iter.next().expect("contains separator").trim(); diff --git a/src/api/run.rs b/src/api/run.rs index 673fa19e..1c937956 100644 --- a/src/api/run.rs +++ b/src/api/run.rs @@ -23,7 +23,7 @@ impl Engine { pub fn run_with_scope(&self, scope: &mut Scope, script: &str) -> RhaiResultOf<()> { let scripts = [script]; 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 ast = self.parse(&mut stream.peekable(), &mut state, self.optimization_level)?; diff --git a/src/ast/ast.rs b/src/ast/ast.rs index 67237b95..e7dcddf9 100644 --- a/src/ast/ast.rs +++ b/src/ast/ast.rs @@ -54,7 +54,7 @@ impl fmt::Debug for AST { #[cfg(not(feature = "no_function"))] 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(); fp.field(&sig, &fn_def.body.as_slice()); } @@ -523,19 +523,19 @@ impl AST { #[cfg(not(feature = "no_module"))] match ( - self.resolver().map_or(0, |r| r.len()), - other.resolver().map_or(0, |r| r.len()), + self.resolver().map_or(true, |r| r.is_empty()), + other.resolver().map_or(true, |r| r.is_empty()), ) { - (0, 0) => (), - (_, 0) => { + (true, true) => (), + (false, true) => { _ast.set_resolver(self.resolver().unwrap().clone()); } - (0, _) => { + (true, false) => { _ast.set_resolver(other.resolver().unwrap().clone()); } - (_, _) => { - let mut resolver = (**self.resolver().unwrap()).clone(); - let other_resolver = (**other.resolver().unwrap()).clone(); + (false, false) => { + let mut resolver = self.resolver().unwrap().as_ref().clone(); + let other_resolver = other.resolver().unwrap().as_ref().clone(); for (k, v) in other_resolver { resolver.insert(k, crate::func::shared_take_or_clone(v)); } @@ -611,23 +611,16 @@ impl AST { other: Self, _filter: impl Fn(FnNamespace, FnAccess, bool, &str, usize) -> bool, ) -> &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"))] match ( - self.resolver.as_ref().map_or(0, |r| r.len()), - other.resolver.as_ref().map_or(0, |r| r.len()), + self.resolver().map_or(true, |r| r.is_empty()), + other.resolver().map_or(true, |r| r.is_empty()), ) { - (_, 0) => (), - (0, _) => { + (_, true) => (), + (true, false) => { self.set_resolver(other.resolver.unwrap()); } - (_, _) => { + (false, false) => { let resolver = crate::func::shared_make_mut(self.resolver.as_mut().unwrap()); let other_resolver = crate::func::shared_take_or_clone(other.resolver.unwrap()); 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 } /// 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 || !options.contains(ASTFlags::CONSTANT) && include_variables => { - let (name, expr, ..) = x.as_ref(); + let (name, expr, ..) = &**x; if let Some(value) = expr.get_literal_value() { Some((name.as_str(), options.contains(ASTFlags::CONSTANT), value)) } else { diff --git a/src/ast/expr.rs b/src/ast/expr.rs index a802e688..6251dd0a 100644 --- a/src/ast/expr.rs +++ b/src/ast/expr.rs @@ -886,14 +886,14 @@ impl Expr { match self { Self::Stmt(x) => { - for s in x.iter() { + for s in &**x { if !s.walk(path, on_node) { return false; } } } Self::InterpolatedString(x, ..) | Self::Array(x, ..) => { - for e in x.as_ref() { + for e in &**x { if !e.walk(path, on_node) { return false; } diff --git a/src/ast/script_fn.rs b/src/ast/script_fn.rs index 2ebbc9ed..38edeea1 100644 --- a/src/ast/script_fn.rs +++ b/src/ast/script_fn.rs @@ -123,7 +123,7 @@ impl<'a> From<&'a ScriptFnDef> for ScriptFnMetadata<'a> { params: value.params.iter().map(|s| s.as_str()).collect(), access: value.access, #[cfg(feature = "metadata")] - comments: value.comments.iter().map(Box::as_ref).collect(), + comments: value.comments.iter().map(<_>::as_ref).collect(), } } } diff --git a/src/ast/stmt.rs b/src/ast/stmt.rs index 7cab128f..d5c1069c 100644 --- a/src/ast/stmt.rs +++ b/src/ast/stmt.rs @@ -175,6 +175,7 @@ impl fmt::Debug for RangeCase { impl From> for RangeCase { #[inline(always)] + #[must_use] fn from(value: Range) -> Self { Self::ExclusiveInt(value, 0) } @@ -182,6 +183,7 @@ impl From> for RangeCase { impl From> for RangeCase { #[inline(always)] + #[must_use] fn from(value: RangeInclusive) -> Self { 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 for StmtBlock { #[inline(always)] fn extend>(&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) } Self::Switch(x, ..) => { - let (expr, sw) = x.as_ref(); + let (expr, sw) = &**x; expr.is_pure() && sw.cases.values().all(|&c| { let block = &sw.blocks[c]; @@ -814,7 +827,7 @@ impl Stmt { match self { 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), _ => self.is_pure(), }, @@ -864,48 +877,48 @@ impl Stmt { if !x.0.walk(path, on_node) { return false; } - for s in x.1.iter() { + for s in &x.1 { if !s.walk(path, on_node) { return false; } } - for s in x.2.iter() { + for s in &x.2 { if !s.walk(path, on_node) { return false; } } } Self::Switch(x, ..) => { - let (expr, sw) = x.as_ref(); + let (expr, sw) = &**x; if !expr.walk(path, on_node) { return false; } - for (.., &b) in sw.cases.iter() { + for (.., &b) in &sw.cases { let block = &sw.blocks[b]; if !block.condition.walk(path, on_node) { return false; } - for s in block.statements.iter() { + for s in &block.statements { if !s.walk(path, on_node) { return false; } } } - for r in sw.ranges.iter() { + for r in &sw.ranges { let block = &sw.blocks[r.index()]; if !block.condition.walk(path, on_node) { return false; } - for s in block.statements.iter() { + for s in &block.statements { if !s.walk(path, on_node) { 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) { return false; } @@ -925,7 +938,7 @@ impl Stmt { if !x.2.walk(path, on_node) { return false; } - for s in x.3.iter() { + for s in &x.3 { if !s.walk(path, on_node) { return false; } @@ -954,12 +967,12 @@ impl Stmt { } } Self::TryCatch(x, ..) => { - for s in x.try_block.iter() { + for s in &x.try_block { if !s.walk(path, on_node) { return false; } } - for s in x.catch_block.iter() { + for s in &x.catch_block { if !s.walk(path, on_node) { return false; } diff --git a/src/eval/chaining.rs b/src/eval/chaining.rs index 810486a9..a1e39da3 100644 --- a/src/eval/chaining.rs +++ b/src/eval/chaining.rs @@ -205,7 +205,7 @@ impl Engine { let crate::ast::FnCallExpr { name, hashes, args, .. - } = x.as_ref(); + } = &**x; let offset = idx_values.len() - args.len(); let call_args = &mut idx_values[offset..]; @@ -266,7 +266,7 @@ impl Engine { #[cfg(feature = "debugging")] 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`"); if op_info.is_op_assignment() { @@ -331,7 +331,7 @@ impl Engine { #[cfg(feature = "debugging")] 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()]; self.call_native_fn( global, caches, lib, getter, *hash_get, args, is_ref_mut, false, *pos, @@ -382,7 +382,7 @@ impl Engine { let crate::ast::FnCallExpr { name, hashes, args, .. - } = x.as_ref(); + } = &**x; let offset = idx_values.len() - args.len(); let call_args = &mut idx_values[offset..]; @@ -425,7 +425,7 @@ impl Engine { #[cfg(feature = "debugging")] 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 mut arg_values = [target.as_mut(), &mut Dynamic::UNIT.clone()]; let args = &mut arg_values[..1]; @@ -507,7 +507,7 @@ impl Engine { let crate::ast::FnCallExpr { name, hashes, args, .. - } = f.as_ref(); + } = &**f; let rhs_chain = rhs.into(); let offset = idx_values.len() - args.len(); @@ -563,9 +563,9 @@ impl Engine { let chain_type = ChainType::from(expr); let (crate::ast::BinaryExpr { lhs, rhs }, options, op_pos) = match expr { #[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"))] - 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), }; @@ -666,7 +666,7 @@ impl Engine { Expr::MethodCall(x, ..) 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( self.get_arg_value(scope, global, caches, lib, this_ptr, arg_expr, level)? .0 @@ -686,7 +686,7 @@ impl Engine { Expr::Index(x, options, ..) | Expr::Dot(x, options, ..) 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(); @@ -700,7 +700,7 @@ impl Engine { Expr::MethodCall(x, ..) 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( self.get_arg_value( scope, global, caches, lib, this_ptr, arg_expr, level, diff --git a/src/eval/debugger.rs b/src/eval/debugger.rs index 21f9e739..4954f923 100644 --- a/src/eval/debugger.rs +++ b/src/eval/debugger.rs @@ -357,7 +357,7 @@ impl Debugger { ASTNode::Expr(Expr::FnCall(x, ..)) | ASTNode::Stmt(Stmt::FnCall(x, ..)) => { 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, _ => false, }, @@ -367,7 +367,7 @@ impl Debugger { ASTNode::Expr(Expr::FnCall(x, ..)) | ASTNode::Stmt(Stmt::FnCall(x, ..)) => { 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, _ => false, }, @@ -560,7 +560,7 @@ impl Engine { ASTNode::Expr(Expr::FnCall(..)) | ASTNode::Stmt(Stmt::FnCall(..)) => { 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, diff --git a/src/eval/expr.rs b/src/eval/expr.rs index 9e9aa7be..94da70e5 100644 --- a/src/eval/expr.rs +++ b/src/eval/expr.rs @@ -60,7 +60,7 @@ impl Engine { Expr::Variable(_, Some(_), _) => { 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 #[cfg(not(feature = "no_module"))] (_, ns, ..) if ns.is_empty() => { @@ -323,7 +323,7 @@ impl Engine { let mut op_info = OpAssignment::new_op_assignment(OP_CONCAT, Position::NONE); let root = ("", Position::NONE); - for expr in x.iter() { + for expr in &**x { let item = match self.eval_expr(scope, global, caches, lib, this_ptr, expr, level) { Ok(r) => r, @@ -354,7 +354,7 @@ impl Engine { #[cfg(not(feature = "unchecked"))] let mut sizes = (0, 0, 0); - for item_expr in x.iter() { + for item_expr in &**x { let value = match self .eval_expr(scope, global, caches, lib, this_ptr, item_expr, level) { @@ -392,7 +392,7 @@ impl Engine { #[cfg(not(feature = "unchecked"))] 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 .eval_expr(scope, global, caches, lib, this_ptr, value_expr, level) { diff --git a/src/eval/global_state.rs b/src/eval/global_state.rs index 3c0a8c4a..1ed3b3af 100644 --- a/src/eval/global_state.rs +++ b/src/eval/global_state.rs @@ -197,7 +197,7 @@ impl GlobalRuntimeState<'_> { .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. /// @@ -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); + type IntoIter = std::iter::Zip< + std::iter::Rev>, + std::iter::Rev>>, + >; + + #[inline] + fn into_iter(self) -> Self::IntoIter { + let x = self.keys.iter().rev().zip(self.modules.iter().rev()); + x + } +} + #[cfg(not(feature = "no_module"))] impl, M: Into>> Extend<(K, M)> for GlobalRuntimeState<'_> diff --git a/src/eval/stmt.rs b/src/eval/stmt.rs index 7b2a485a..1fcef61f 100644 --- a/src/eval/stmt.rs +++ b/src/eval/stmt.rs @@ -248,7 +248,7 @@ impl Engine { self.inc_operations(&mut global.num_operations, stmt.position())?; 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 .eval_expr(scope, global, caches, lib, this_ptr, rhs, level) @@ -294,7 +294,7 @@ impl Engine { rhs_result } } else { - let (op_info, BinaryExpr { lhs, rhs }) = x.as_ref(); + let (op_info, BinaryExpr { lhs, rhs }) = &**x; let rhs_result = self .eval_expr(scope, global, caches, lib, this_ptr, rhs, level) @@ -356,7 +356,7 @@ impl Engine { // If statement Stmt::If(x, ..) => { - let (expr, if_block, else_block) = x.as_ref(); + let (expr, if_block, else_block) = &**x; let guard_val = self .eval_expr(scope, global, caches, lib, this_ptr, expr, level) @@ -399,7 +399,7 @@ impl Engine { def_case, ranges, }, - ) = x.as_ref(); + ) = &**x; let value_result = self.eval_expr(scope, global, caches, lib, this_ptr, expr, level); @@ -500,7 +500,7 @@ impl Engine { // Loop Stmt::While(x, ..) if matches!(x.0, Expr::Unit(..)) => loop { - let (.., body) = x.as_ref(); + let (.., body) = &**x; if !body.is_empty() { match self @@ -521,7 +521,7 @@ impl Engine { // While loop Stmt::While(x, ..) => loop { - let (expr, body) = x.as_ref(); + let (expr, body) = &**x; let condition = self .eval_expr(scope, global, caches, lib, this_ptr, expr, level) @@ -552,7 +552,7 @@ impl Engine { // Do loop Stmt::Do(x, options, ..) => loop { - let (expr, body) = x.as_ref(); + let (expr, body) = &**x; let is_while = !options.contains(ASTFlags::NEGATED); if !body.is_empty() { @@ -585,7 +585,7 @@ impl Engine { // For loop Stmt::For(x, ..) => { - let (var_name, counter, expr, statements) = x.as_ref(); + let (var_name, counter, expr, statements) = &**x; let iter_result = self .eval_expr(scope, global, caches, lib, this_ptr, expr, level) @@ -728,7 +728,7 @@ impl Engine { name: catch_var, .. }, catch_block, - } = x.as_ref(); + } = &**x; let result = self .eval_stmt_block(scope, global, caches, lib, this_ptr, try_block, true, level) @@ -832,7 +832,7 @@ impl Engine { } // Let/const statement 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) { AccessMode::ReadOnly @@ -926,7 +926,7 @@ impl Engine { // Import statement #[cfg(not(feature = "no_module"))] Stmt::Import(x, _pos) => { - let (expr, export) = x.as_ref(); + let (expr, export) = &**x; // Guard against too many modules #[cfg(not(feature = "unchecked"))] @@ -995,7 +995,7 @@ impl Engine { // Export statement #[cfg(not(feature = "no_module"))] Stmt::Export(x, ..) => { - let (Ident { name, pos, .. }, alias) = x.as_ref(); + let (Ident { name, pos, .. }, alias) = &**x; // Mark scope variables as public if let Some((index, ..)) = scope.get_index(name) { let alias = if alias.is_empty() { name } else { alias }.clone(); diff --git a/src/func/callable_function.rs b/src/func/callable_function.rs index 2b24b4a9..87691895 100644 --- a/src/func/callable_function.rs +++ b/src/func/callable_function.rs @@ -178,7 +178,7 @@ impl CallableFunction { #[must_use] pub fn get_iter_fn(&self) -> Option<&IteratorFn> { match self { - Self::Iterator(f) => Some(f.as_ref()), + Self::Iterator(f) => Some(&**f), Self::Pure(..) | Self::Method(..) | Self::Plugin(..) => None, #[cfg(not(feature = "no_function"))] diff --git a/src/func/native.rs b/src/func/native.rs index 64cd34dc..c88570ba 100644 --- a/src/func/native.rs +++ b/src/func/native.rs @@ -110,7 +110,7 @@ impl<'a, M: AsRef<[&'a Module]> + ?Sized, S: AsRef + 'a + ?Sized> Self { engine: value.0, fn_name: value.1.as_ref(), - source: value.2.map(S::as_ref), + source: value.2.map(<_>::as_ref), global: Some(value.3), lib: value.4.as_ref(), pos: value.5, diff --git a/src/func/script.rs b/src/func/script.rs index ce6c3d95..985070f0 100644 --- a/src/func/script.rs +++ b/src/func/script.rs @@ -131,7 +131,7 @@ impl Engine { lib } else { 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 }, diff --git a/src/module/mod.rs b/src/module/mod.rs index 9a5e8366..65c61253 100644 --- a/src/module/mod.rs +++ b/src/module/mod.rs @@ -781,7 +781,7 @@ impl Module { #[must_use] pub fn get_sub_module(&self, name: &str) -> Option<&Module> { if !self.modules.is_empty() { - self.modules.get(name).map(|m| m.as_ref()) + self.modules.get(name).map(|m| &**m) } else { None } @@ -1006,18 +1006,19 @@ impl Module { (names, return_type) }; - let hash_fn = calc_native_fn_hash(None, name.as_ref(), ¶m_types); + let name = name.as_ref(); + let hash_fn = calc_native_fn_hash(None, name, ¶m_types); if is_dynamic { self.dynamic_functions - .insert(calc_fn_hash(name.as_ref(), param_types.len())); + .insert(calc_fn_hash(name, param_types.len())); } self.functions.insert( hash_fn, FuncInfo { metadata: FnMetadata { - name: name.as_ref().into(), + name: name.into(), namespace, access, params: param_types.len(), @@ -1549,7 +1550,7 @@ impl Module { /// Sub-modules are flattened onto the root [`Module`], with higher level overriding lower level. #[inline] 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.variables.extend(other.variables.into_iter()); @@ -1707,7 +1708,7 @@ impl Module { #[inline] #[allow(dead_code)] pub(crate) fn iter_fn(&self) -> impl Iterator { - self.functions.values().map(Box::as_ref) + self.functions.values().map(<_>::as_ref) } /// Get an iterator over all script-defined functions in the [`Module`]. @@ -2154,7 +2155,7 @@ impl Module { #[must_use] pub(crate) fn get_qualified_iter(&self, id: TypeId) -> Option<&IteratorFn> { 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 { None } @@ -2165,7 +2166,7 @@ impl Module { #[must_use] pub(crate) fn get_iter(&self, id: TypeId) -> Option<&IteratorFn> { 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 { None } diff --git a/src/module/resolvers/collection.rs b/src/module/resolvers/collection.rs index fe03612f..ca815968 100644 --- a/src/module/resolvers/collection.rs +++ b/src/module/resolvers/collection.rs @@ -1,7 +1,7 @@ use crate::{Engine, Module, ModuleResolver, Position, RhaiResultOf, Shared, ERR}; #[cfg(feature = "no_std")] 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, /// to be searched in sequential order. @@ -116,6 +116,16 @@ impl IntoIterator for ModuleResolversCollection { } } +impl<'a> IntoIterator for &'a ModuleResolversCollection { + type Item = &'a Box; + type IntoIter = Iter<'a, Box>; + + #[inline(always)] + fn into_iter(self) -> Self::IntoIter { + self.0.iter() + } +} + impl ModuleResolver for ModuleResolversCollection { fn resolve( &self, diff --git a/src/module/resolvers/file.rs b/src/module/resolvers/file.rs index 054168b6..52a87a4d 100644 --- a/src/module/resolvers/file.rs +++ b/src/module/resolvers/file.rs @@ -172,7 +172,7 @@ impl FileModuleResolver { #[inline(always)] #[must_use] 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. #[inline(always)] diff --git a/src/module/resolvers/stat.rs b/src/module/resolvers/stat.rs index 3e2e9659..60a89950 100644 --- a/src/module/resolvers/stat.rs +++ b/src/module/resolvers/stat.rs @@ -3,7 +3,11 @@ use crate::{ }; #[cfg(feature = "no_std")] 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. /// @@ -122,11 +126,22 @@ impl IntoIterator for StaticModuleResolver { type Item = (Identifier, Shared); type IntoIter = IntoIter>; + #[inline(always)] fn into_iter(self) -> Self::IntoIter { self.0.into_iter() } } +impl<'a> IntoIterator for &'a StaticModuleResolver { + type Item = (&'a Identifier, &'a Shared); + type IntoIter = Iter<'a, SmartString, Shared>; + + #[inline(always)] + fn into_iter(self) -> Self::IntoIter { + self.0.iter() + } +} + impl ModuleResolver for StaticModuleResolver { #[inline] fn resolve( diff --git a/src/optimizer.rs b/src/optimizer.rs index d5f8c029..8e540cf7 100644 --- a/src/optimizer.rs +++ b/src/optimizer.rs @@ -512,7 +512,7 @@ fn optimize_stmt(stmt: &mut Stmt, state: &mut OptimizerState, preserve_result: b } // if expr { if_block } else { else_block } Stmt::If(x, ..) => { - let (condition, body, other) = x.as_mut(); + let (condition, body, other) = &mut **x; optimize_expr(condition, state, false); **body = 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, def_case, }, - ) = x.as_mut(); + ) = &mut **x; let value = match_expr.get_literal_value().unwrap(); let hasher = &mut get_hasher(); @@ -640,7 +640,7 @@ fn optimize_stmt(stmt: &mut Stmt, state: &mut OptimizerState, preserve_result: b state.set_dirty(); } - for r in ranges.iter() { + for r in &*ranges { let block = &mut blocks_list[r.index()]; let statements = mem::take(&mut *block.statements); *block.statements = @@ -679,7 +679,7 @@ fn optimize_stmt(stmt: &mut Stmt, state: &mut OptimizerState, preserve_result: b def_case, .. }, - ) = x.as_mut(); + ) = &mut **x; 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 } Stmt::While(x, ..) => { - let (condition, body) = x.as_mut(); + let (condition, body) = &mut **x; optimize_expr(condition, state, false); if let Expr::BoolConstant(true, pos) = condition { *condition = Expr::Unit(*pos); @@ -846,7 +846,7 @@ fn optimize_stmt(stmt: &mut Stmt, state: &mut OptimizerState, preserve_result: b Stmt::Expr(expr) => { optimize_expr(expr, state, false); - match expr.as_mut() { + match &mut **expr { // func(...) Expr::FnCall(x, pos) => { 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); // { Stmt(Expr) } - promote - match x.as_mut().as_mut() { + match &mut ****x { [ 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; } // 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]) .and_then(|f| { #[cfg(not(feature = "no_function"))] diff --git a/src/packages/lang_core.rs b/src/packages/lang_core.rs index 4126b5ae..a82a5fa4 100644 --- a/src/packages/lang_core.rs +++ b/src/packages/lang_core.rs @@ -273,12 +273,12 @@ fn collect_fn_metadata( crate::tokenizer::Token::DoubleColon.literal_syntax(), 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() { - scan_module(&mut list, &dict, ns.clone(), m.as_ref(), filter) + scan_module(&mut list, &dict, ns.clone(), &**m, filter) } } diff --git a/src/packages/map_basic.rs b/src/packages/map_basic.rs index 771bc7aa..427146b9 100644 --- a/src/packages/map_basic.rs +++ b/src/packages/map_basic.rs @@ -191,7 +191,7 @@ mod map_functions { if !map1.is_empty() { let mut map2 = map2; - for (m1, v1) in map1.iter_mut() { + for (m1, v1) in map1 { if let Some(v2) = map2.get_mut(m1) { let equals = ctx .call_fn_raw(OP_EQUALS, true, false, &mut [v1, v2])? diff --git a/src/parser.rs b/src/parser.rs index cfa594a5..3c8e6c9f 100644 --- a/src/parser.rs +++ b/src/parser.rs @@ -1729,9 +1729,9 @@ impl Engine { // Cache the hash key for namespace-qualified variables #[cfg(not(feature = "no_module"))] 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::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, @@ -1933,7 +1933,7 @@ impl Engine { } // var (indexed) = rhs Expr::Variable(ref x, i, var_pos) => { - let (index, .., name) = x.as_ref(); + let (index, .., name) = &**x; let index = i.map_or_else( || index.expect("either long or short index is `None`").get(), |n| n.get() as usize, @@ -2067,7 +2067,7 @@ impl Engine { (.., Expr::FnCall(func, func_pos)) if func.args.is_empty() && [crate::engine::KEYWORD_FN_PTR, crate::engine::KEYWORD_EVAL] - .contains(&func.name.as_ref()) => + .contains(&func.name.as_str()) => { let err_msg = format!( "'{}' should not be called in method style. Try {}(...);", @@ -2370,7 +2370,7 @@ impl Engine { state.stack.push(marker, ()); } - let parse_func = syntax.parse.as_ref(); + let parse_func = &*syntax.parse; let mut required_token: ImmutableString = key.into(); tokens.push(required_token.clone().into()); diff --git a/src/serde/metadata.rs b/src/serde/metadata.rs index 8cd30eaa..f430e484 100644 --- a/src/serde/metadata.rs +++ b/src/serde/metadata.rs @@ -146,10 +146,10 @@ impl<'a> From<&'a FuncInfo> for FnMetadata<'a> { .expect("script-defined function") .comments .iter() - .map(Box::as_ref) + .map(<_>::as_ref) .collect() } else { - info.metadata.comments.iter().map(Box::as_ref).collect() + info.metadata.comments.iter().map(<_>::as_ref).collect() }, } } diff --git a/src/tokenizer.rs b/src/tokenizer.rs index fa74a647..39bd7627 100644 --- a/src/tokenizer.rs +++ b/src/tokenizer.rs @@ -329,20 +329,20 @@ impl Span { impl fmt::Display for Span { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { - match (self.start().is_none(), self.end().is_none()) { - (false, false) if self.start().line() != self.end().line() => { - write!(f, "{:?}-{:?}", self.start(), self.end()) + match (self.start(), self.end()) { + (Position::NONE, Position::NONE) => write!(f, "{:?}", Position::NONE), + (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, "{}:{}-{}", - self.start().line().unwrap(), - self.start().position().unwrap_or(0), - self.end().position().unwrap_or(0) + start.line().unwrap(), + start.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), } } } diff --git a/src/types/fn_ptr.rs b/src/types/fn_ptr.rs index 8e80cb35..719e8b0f 100644 --- a/src/types/fn_ptr.rs +++ b/src/types/fn_ptr.rs @@ -56,7 +56,7 @@ impl FnPtr { #[inline(always)] #[must_use] pub fn fn_name(&self) -> &str { - self.fn_name_raw().as_ref() + self.fn_name_raw().as_str() } /// Get the name of the function. #[inline(always)] @@ -223,7 +223,7 @@ impl FnPtr { args_data = StaticVec::with_capacity(self.curry().len() + arg_values.len()); args_data.extend(self.curry().iter().cloned()); 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(); diff --git a/src/types/interner.rs b/src/types/interner.rs index a5277207..f9e85acc 100644 --- a/src/types/interner.rs +++ b/src/types/interner.rs @@ -51,7 +51,10 @@ impl StringsInterner<'_> { #[inline] #[must_use] pub fn get(&mut self, prefix: impl AsRef, text: impl AsRef) -> 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()), #[cfg(not(feature = "no_object"))] @@ -59,14 +62,14 @@ impl StringsInterner<'_> { #[cfg(not(feature = "no_object"))] 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()) { - dict.get(text.as_ref()).unwrap().clone() + if !dict.is_empty() && dict.contains_key(text) { + dict.get(text).unwrap().clone() } else { - let value: ImmutableString = mapper(text.as_ref()).into(); - dict.insert(text.as_ref().into(), value.clone()); + let value: ImmutableString = mapper(text).into(); + dict.insert(text.into(), value.clone()); value } } diff --git a/src/types/scope.rs b/src/types/scope.rs index 6b96013b..aaa76fa3 100644 --- a/src/types/scope.rs +++ b/src/types/scope.rs @@ -132,6 +132,21 @@ impl IntoIterator for Scope<'_> { } } +impl<'a> IntoIterator for &'a Scope<'_> { + type Item = (&'a Identifier, &'a Dynamic, &'a Vec); + type IntoIter = Box + '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<'_> { /// Create a new [`Scope`]. /// @@ -686,7 +701,7 @@ impl Scope<'_> { self.names .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`]. /// Shared values are not expanded. @@ -696,7 +711,7 @@ impl Scope<'_> { .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`]. ///