diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml index bed9d2dee..b0ff35b15 100644 --- a/.github/workflows/build.yml +++ b/.github/workflows/build.yml @@ -32,6 +32,7 @@ jobs: - uses: actions-rs/cargo@v1 with: command: check + args: "--features decimal,metadata,serde,debugging" # typical build with various feature combinations build: diff --git a/codegen/Cargo.toml b/codegen/Cargo.toml index e0c6faf21..097a6a496 100644 --- a/codegen/Cargo.toml +++ b/codegen/Cargo.toml @@ -20,7 +20,7 @@ metadata = [] [dependencies] proc-macro2 = "1.0.0" -syn = { version = "1.0.0", features = ["full", "parsing", "printing", "proc-macro", "extra-traits"] } +syn = { version = "2.0.0", features = ["full", "parsing", "printing", "proc-macro", "extra-traits"] } quote = "1.0.0" [dev-dependencies] diff --git a/codegen/src/attrs.rs b/codegen/src/attrs.rs index 8e232a762..92ac08ea4 100644 --- a/codegen/src/attrs.rs +++ b/codegen/src/attrs.rs @@ -12,8 +12,8 @@ pub enum ExportScope { } impl Default for ExportScope { - fn default() -> ExportScope { - ExportScope::PubOnly + fn default() -> Self { + Self::PubOnly } } @@ -118,17 +118,11 @@ pub fn inner_item_attributes( attr_name: &str, ) -> syn::Result { // Find the #[rhai_fn] attribute which will turn be read for function parameters. - if let Some(index) = attrs - .iter() - .position(|a| a.path.get_ident().map_or(false, |i| *i == attr_name)) - { + if let Some(index) = attrs.iter().position(|a| a.path().is_ident(attr_name)) { let rhai_fn_attr = attrs.remove(index); // Cannot have more than one #[rhai_fn] - if let Some(duplicate) = attrs - .iter() - .find(|a| a.path.get_ident().map_or(false, |i| *i == attr_name)) - { + if let Some(duplicate) = attrs.iter().find(|&a| a.path().is_ident(attr_name)) { return Err(syn::Error::new( duplicate.span(), format!("duplicated attribute '{attr_name}'"), @@ -148,33 +142,37 @@ pub fn doc_attributes(attrs: &[syn::Attribute]) -> syn::Result> { let mut buf = String::new(); for attr in attrs { - if let Some(i) = attr.path.get_ident() { - if *i == "doc" { - if let syn::Meta::NameValue(syn::MetaNameValue { - lit: syn::Lit::Str(s), + if !attr.path().is_ident("doc") { + continue; + } + + if let syn::Meta::NameValue(syn::MetaNameValue { + value: + syn::Expr::Lit(syn::ExprLit { + lit: syn::Lit::Str(ref s), .. - }) = attr.parse_meta()? - { - let mut line = s.value(); - - if line.contains('\n') { - // Must be a block comment `/** ... */` - if !buf.is_empty() { - comments.push(buf.clone()); - buf.clear(); - } - line.insert_str(0, "/**"); - line.push_str("*/"); - comments.push(line); - } else { - // Single line - assume it is `///` - if !buf.is_empty() { - buf.push('\n'); - } - buf.push_str("///"); - buf.push_str(&line); - } + }), + .. + }) = attr.meta + { + let mut line = s.value(); + + if line.contains('\n') { + // Must be a block comment `/** ... */` + if !buf.is_empty() { + comments.push(buf.clone()); + buf.clear(); + } + line.insert_str(0, "/**"); + line.push_str("*/"); + comments.push(line); + } else { + // Single line - assume it is `///` + if !buf.is_empty() { + buf.push('\n'); } + buf.push_str("///"); + buf.push_str(&line); } } } @@ -189,7 +187,7 @@ pub fn doc_attributes(attrs: &[syn::Attribute]) -> syn::Result> { pub fn collect_cfg_attr(attrs: &[syn::Attribute]) -> Vec { attrs .iter() - .filter(|&a| a.path.get_ident().map_or(false, |i| *i == "cfg")) + .filter(|&a| a.path().is_ident("cfg")) .cloned() .collect() } diff --git a/codegen/src/function.rs b/codegen/src/function.rs index 27ec31c12..1be04f42d 100644 --- a/codegen/src/function.rs +++ b/codegen/src/function.rs @@ -47,8 +47,8 @@ pub enum FnSpecialAccess { } impl Default for FnSpecialAccess { - fn default() -> FnSpecialAccess { - FnSpecialAccess::None + fn default() -> Self { + Self::None } } @@ -309,7 +309,7 @@ impl Parse for ExportedFn { { pass_context = true; } - _ => {} + _ => (), } } @@ -389,7 +389,7 @@ impl Parse for ExportedFn { "Rhai functions cannot return references", )) } - _ => {} + _ => (), } } Ok(ExportedFn { @@ -597,7 +597,7 @@ impl ExportedFn { "index setter cannot return any value", )) } - _ => {} + _ => (), } self.params = params; diff --git a/codegen/src/register.rs b/codegen/src/register.rs index 773711c9f..0512e3953 100644 --- a/codegen/src/register.rs +++ b/codegen/src/register.rs @@ -37,13 +37,14 @@ pub fn parse_register_macro( syn::Expr::Lit(lit_str) => quote_spanned!(items[1].span() => #lit_str), expr => quote! { #expr }, }; - let rust_mod_path = if let syn::Expr::Path(ref path) = &items[2] { - path.path.clone() - } else { - return Err(syn::Error::new( - items[2].span(), - "third argument must be a function name", - )); + let rust_mod_path = match &items[2] { + syn::Expr::Path(ref path) => path.path.clone(), + _ => { + return Err(syn::Error::new( + items[2].span(), + "third argument must be a function name", + )) + } }; let module = items.remove(0); Ok((module, export_name, rust_mod_path)) diff --git a/codegen/ui_tests/export_mod_cfg.stderr b/codegen/ui_tests/export_mod_cfg.stderr index dc0145f0b..5a730000f 100644 --- a/codegen/ui_tests/export_mod_cfg.stderr +++ b/codegen/ui_tests/export_mod_cfg.stderr @@ -1,8 +1,8 @@ error: expected attribute arguments in parentheses: #[rhai_fn(...)] - --> ui_tests/export_mod_cfg.rs:12:1 + --> ui_tests/export_mod_cfg.rs:12:3 | 12 | #[rhai_fn] - | ^^^^^^^^^^ + | ^^^^^^^ error[E0433]: failed to resolve: use of undeclared crate or module `test_mod` --> ui_tests/export_mod_cfg.rs:23:8 diff --git a/src/api/build_type.rs b/src/api/build_type.rs index 1edce75b4..fca82193f 100644 --- a/src/api/build_type.rs +++ b/src/api/build_type.rs @@ -262,10 +262,9 @@ impl<'a, T: Variant + Clone> TypeBuilder<'a, T> { impl<'a, T: Variant + Clone> Drop for TypeBuilder<'a, T> { #[inline] fn drop(&mut self) { - if let Some(name) = self.name { - self.engine.register_type_with_name::(name); - } else { - self.engine.register_type::(); - } + match self.name { + Some(name) => self.engine.register_type_with_name::(name), + None => self.engine.register_type::(), + }; } } diff --git a/src/api/compile.rs b/src/api/compile.rs index 6d506b412..45b61fa46 100644 --- a/src/api/compile.rs +++ b/src/api/compile.rs @@ -227,12 +227,15 @@ impl Engine { let mut interner; let mut guard; - let interned_strings = if let Some(ref interner) = self.interned_strings { - guard = locked_write(interner); - &mut *guard - } else { - interner = StringsInterner::new(); - &mut interner + let interned_strings = match self.interned_strings { + Some(ref interner) => { + guard = locked_write(interner); + &mut *guard + } + None => { + interner = StringsInterner::new(); + &mut interner + } }; let state = &mut ParseState::new(scope, interned_strings, tc); @@ -308,12 +311,15 @@ impl Engine { let mut interner; let mut guard; - let interned_strings = if let Some(ref interner) = self.interned_strings { - guard = locked_write(interner); - &mut *guard - } else { - interner = StringsInterner::new(); - &mut interner + let interned_strings = match self.interned_strings { + Some(ref interner) => { + guard = locked_write(interner); + &mut *guard + } + None => { + interner = StringsInterner::new(); + &mut interner + } }; let state = &mut ParseState::new(Some(scope), interned_strings, t); diff --git a/src/api/eval.rs b/src/api/eval.rs index 7ac42d167..941c8dae0 100644 --- a/src/api/eval.rs +++ b/src/api/eval.rs @@ -122,12 +122,15 @@ impl Engine { let ast = { let mut interner; let mut guard; - let interned_strings = if let Some(ref interner) = self.interned_strings { - guard = locked_write(interner); - &mut *guard - } else { - interner = StringsInterner::new(); - &mut interner + let interned_strings = match self.interned_strings { + Some(ref interner) => { + guard = locked_write(interner); + &mut *guard + } + None => { + interner = StringsInterner::new(); + &mut interner + } }; let (stream, tc) = self.lex_raw(&scripts, self.token_mapper.as_deref()); diff --git a/src/api/files.rs b/src/api/files.rs index 9dec04a08..00f17550f 100644 --- a/src/api/files.rs +++ b/src/api/files.rs @@ -35,10 +35,11 @@ impl Engine { if contents.starts_with("#!") { // Remove shebang - if let Some(n) = contents.find('\n') { - contents.drain(0..n).count(); - } else { - contents.clear(); + match contents.find('\n') { + Some(n) => { + contents.drain(0..n).count(); + } + None => contents.clear(), } }; diff --git a/src/api/formatting.rs b/src/api/formatting.rs index 7fb7a376a..d4e729f01 100644 --- a/src/api/formatting.rs +++ b/src/api/formatting.rs @@ -227,12 +227,9 @@ impl Engine { #[must_use] pub(crate) fn format_type_name<'a>(&'a self, name: &'a str) -> std::borrow::Cow<'a, str> { if let Some(x) = name.strip_prefix("&mut ") { - let r = self.format_type_name(x); - - return if x == r { - name.into() - } else { - format!("&mut {r}").into() + return match self.format_type_name(x) { + r if r == x => name.into(), + r => format!("&mut {r}").into(), }; } diff --git a/src/api/json.rs b/src/api/json.rs index ee266d248..295c0cb4a 100644 --- a/src/api/json.rs +++ b/src/api/json.rs @@ -118,12 +118,15 @@ impl Engine { let ast = { let mut interner; let mut guard; - let interned_strings = if let Some(ref interner) = self.interned_strings { - guard = locked_write(interner); - &mut *guard - } else { - interner = StringsInterner::new(); - &mut interner + let interned_strings = match self.interned_strings { + Some(ref interner) => { + guard = locked_write(interner); + &mut *guard + } + None => { + interner = StringsInterner::new(); + &mut interner + } }; let state = &mut ParseState::new(None, interned_strings, tokenizer_control); @@ -174,12 +177,10 @@ pub fn format_map_as_json(map: &Map) -> String { write!(result, "{key:?}").unwrap(); result.push(':'); - if let Some(val) = value.read_lock::() { - result.push_str(&format_map_as_json(&val)); - } else if value.is_unit() { - result.push_str("null"); - } else { - write!(result, "{value:?}").unwrap(); + match value.read_lock::() { + Some(val) => result.push_str(&format_map_as_json(&val)), + None if value.is_unit() => result.push_str("null"), + None => write!(result, "{value:?}").unwrap(), } } diff --git a/src/api/optimize.rs b/src/api/optimize.rs index 32927c0fb..25a24b76d 100644 --- a/src/api/optimize.rs +++ b/src/api/optimize.rs @@ -63,10 +63,11 @@ impl Engine { ); #[cfg(feature = "metadata")] - if let Some(doc) = ast.doc_mut() { - _new_ast.set_doc(std::mem::take(doc)); - } else { - _new_ast.clear_doc(); + match ast.doc_mut() { + Some(doc) => _new_ast.set_doc(std::mem::take(doc)), + None => { + _new_ast.clear_doc(); + } } _new_ast diff --git a/src/api/run.rs b/src/api/run.rs index 1fe1e4769..2b9d0332a 100644 --- a/src/api/run.rs +++ b/src/api/run.rs @@ -63,12 +63,15 @@ impl Engine { let mut interner; let mut guard; - let interned_strings = if let Some(ref interner) = self.interned_strings { - guard = locked_write(interner); - &mut *guard - } else { - interner = StringsInterner::new(); - &mut interner + let interned_strings = match self.interned_strings { + Some(ref interner) => { + guard = locked_write(interner); + &mut *guard + } + None => { + interner = StringsInterner::new(); + &mut interner + } }; let state = &mut ParseState::new(Some(scope), interned_strings, tc); diff --git a/src/ast/ast.rs b/src/ast/ast.rs index 6734a446f..a348c3147 100644 --- a/src/ast/ast.rs +++ b/src/ast/ast.rs @@ -577,19 +577,18 @@ impl AST { lib }; - let mut _ast = if let Some(ref source) = other.source { - Self::new_with_source( + let mut _ast = match other.source { + Some(ref source) => Self::new_with_source( merged, #[cfg(not(feature = "no_function"))] lib, source.clone(), - ) - } else { - Self::new( + ), + None => Self::new( merged, #[cfg(not(feature = "no_function"))] lib, - ) + ), }; #[cfg(not(feature = "no_module"))] @@ -615,13 +614,13 @@ impl AST { } #[cfg(feature = "metadata")] - if let Some(ref other_doc) = other.doc { - if let Some(ref mut ast_doc) = _ast.doc { + match (&other.doc, &mut _ast.doc) { + (Some(other_doc), Some(ast_doc)) => { ast_doc.push('\n'); ast_doc.push_str(other_doc); - } else { - _ast.doc = Some(other_doc.clone()); } + (Some(other_doc), None) => _ast.doc = Some(other_doc.clone()), + _ => (), } _ast @@ -722,13 +721,13 @@ impl AST { } #[cfg(feature = "metadata")] - if let Some(other_doc) = other.doc { - if let Some(ref mut self_doc) = self.doc { + match (other.doc, &mut self.doc) { + (Some(ref other_doc), Some(self_doc)) => { self_doc.push('\n'); - self_doc.push_str(&other_doc); - } else { - self.doc = Some(other_doc); + self_doc.push_str(other_doc); } + (Some(other_doc), None) => self.doc = Some(other_doc), + _ => (), } self diff --git a/src/ast/expr.rs b/src/ast/expr.rs index 371ade11f..1387ccebe 100644 --- a/src/ast/expr.rs +++ b/src/ast/expr.rs @@ -113,15 +113,14 @@ impl fmt::Debug for FnCallHashes { #[inline(never)] fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { #[cfg(not(feature = "no_function"))] - if let Some(script) = self.script { - return if script == self.native { - fmt::Debug::fmt(&self.native, f) - } else { - write!(f, "({script}, {})", self.native) - }; - } + return match self.script { + Some(script) if script == self.native => fmt::Debug::fmt(&self.native, f), + Some(script) => write!(f, "({script}, {})", self.native), + None => write!(f, "{} (native only)", self.native), + }; - write!(f, "{} (native only)", self.native) + #[cfg(feature = "no_function")] + return write!(f, "{}", self.native); } } @@ -510,10 +509,9 @@ impl Expr { Self::FnCall(ref x, ..) if !x.is_qualified() && x.args.len() == 1 && x.name == KEYWORD_FN_PTR => { - if let Self::StringConstant(ref s, ..) = x.args[0] { - FnPtr::new(s.clone()).ok()?.into() - } else { - return None; + match x.args[0] { + Self::StringConstant(ref s, ..) => FnPtr::new(s.clone()).ok()?.into(), + _ => return None, } } @@ -521,29 +519,21 @@ impl Expr { Self::FnCall(x, ..) if !x.is_qualified() && x.args.len() == 2 => { match x.name.as_str() { // x..y - OP_EXCLUSIVE_RANGE => { - if let Self::IntegerConstant(ref start, ..) = x.args[0] { - if let Self::IntegerConstant(ref end, ..) = x.args[1] { - (*start..*end).into() - } else { - return None; - } - } else { - return None; - } - } + OP_EXCLUSIVE_RANGE => match (&x.args[0], &x.args[1]) { + ( + Self::IntegerConstant(ref start, ..), + Self::IntegerConstant(ref end, ..), + ) => (*start..*end).into(), + _ => return None, + }, // x..=y - OP_INCLUSIVE_RANGE => { - if let Self::IntegerConstant(ref start, ..) = x.args[0] { - if let Self::IntegerConstant(ref end, ..) = x.args[1] { - (*start..=*end).into() - } else { - return None; - } - } else { - return None; - } - } + OP_INCLUSIVE_RANGE => match (&x.args[0], &x.args[1]) { + ( + Self::IntegerConstant(ref start, ..), + Self::IntegerConstant(ref end, ..), + ) => (*start..=*end).into(), + _ => return None, + }, _ => return None, } } diff --git a/src/config/hashing.rs b/src/config/hashing.rs index 97340eae1..992b91c5e 100644 --- a/src/config/hashing.rs +++ b/src/config/hashing.rs @@ -71,9 +71,8 @@ pub fn set_ahash_seed(new_seed: Option<[u64; 4]>) -> Result<(), Option<[u64; 4]> #[inline] #[must_use] pub fn get_ahash_seed() -> &'static Option<[u64; 4]> { - if let Some(seed) = AHASH_SEED.get() { - seed - } else { - &hashing_env::AHASH_SEED + match AHASH_SEED.get() { + Some(seed) => seed, + None => &hashing_env::AHASH_SEED, } } diff --git a/src/engine.rs b/src/engine.rs index fd64723fc..85e3668f8 100644 --- a/src/engine.rs +++ b/src/engine.rs @@ -326,10 +326,9 @@ impl Engine { &self, string: impl AsRef + Into, ) -> ImmutableString { - if let Some(ref interner) = self.interned_strings { - locked_write(interner).get(string) - } else { - string.into() + match self.interned_strings { + Some(ref interner) => locked_write(interner).get(string), + _ => string.into(), } } @@ -345,10 +344,9 @@ impl Engine { &self, string: impl AsRef + Into, ) -> ImmutableString { - if let Some(ref interner) = self.interned_strings { - locked_write(interner).get(string) - } else { - string.into() + match self.interned_strings { + Some(ref interner) => locked_write(interner).get(string), + None => string.into(), } } diff --git a/src/eval/chaining.rs b/src/eval/chaining.rs index 04562b752..cd6e1c1e8 100644 --- a/src/eval/chaining.rs +++ b/src/eval/chaining.rs @@ -392,14 +392,16 @@ impl Engine { #[cfg(feature = "debugging")] self.run_debugger(global, caches, scope, this_ptr.as_deref_mut(), lhs)?; - if let Some(this_ptr) = this_ptr { - let target = &mut this_ptr.into(); + match this_ptr { + Some(this_ptr) => { + let target = &mut this_ptr.into(); - self.eval_dot_index_chain_raw( - global, caches, scope2, None, lhs, expr, target, rhs, idx_values, new_val, - ) - } else { - Err(ERR::ErrorUnboundThis(*var_pos).into()) + self.eval_dot_index_chain_raw( + global, caches, scope2, None, lhs, expr, target, rhs, idx_values, + new_val, + ) + } + None => Err(ERR::ErrorUnboundThis(*var_pos).into()), } } // id.??? or id[???] diff --git a/src/eval/debugger.rs b/src/eval/debugger.rs index de0bdd64a..ade8cbbb4 100644 --- a/src/eval/debugger.rs +++ b/src/eval/debugger.rs @@ -48,7 +48,6 @@ pub enum DebuggerCommand { impl Default for DebuggerCommand { #[inline(always)] - #[must_use] fn default() -> Self { Self::Continue } @@ -465,27 +464,28 @@ impl Engine { _ => (), } - if let Some(ref dbg) = global.debugger { - let event = match dbg.status { - DebuggerStatus::Init => Some(DebuggerEvent::Start), - DebuggerStatus::NEXT if node.is_stmt() => Some(DebuggerEvent::Step), - DebuggerStatus::INTO if node.is_expr() => Some(DebuggerEvent::Step), - DebuggerStatus::STEP => Some(DebuggerEvent::Step), - DebuggerStatus::Terminate => Some(DebuggerEvent::End), - _ => None, - }; + match global.debugger { + Some(ref dbg) => { + let event = match dbg.status { + DebuggerStatus::Init => Some(DebuggerEvent::Start), + DebuggerStatus::NEXT if node.is_stmt() => Some(DebuggerEvent::Step), + DebuggerStatus::INTO if node.is_expr() => Some(DebuggerEvent::Step), + DebuggerStatus::STEP => Some(DebuggerEvent::Step), + DebuggerStatus::Terminate => Some(DebuggerEvent::End), + _ => None, + }; - let event = match event { - Some(e) => e, - None => match dbg.is_break_point(global.source(), node) { - Some(bp) => DebuggerEvent::BreakPoint(bp), - None => return Ok(None), - }, - }; + let event = match event { + Some(e) => e, + None => match dbg.is_break_point(global.source(), node) { + Some(bp) => DebuggerEvent::BreakPoint(bp), + None => return Ok(None), + }, + }; - self.run_debugger_raw(global, caches, scope, this_ptr, node, event) - } else { - Ok(None) + self.run_debugger_raw(global, caches, scope, this_ptr, node, event) + } + None => Ok(None), } } /// Run the debugger callback unconditionally. @@ -504,55 +504,56 @@ impl Engine { node: ASTNode, event: DebuggerEvent, ) -> Result, Box> { - if let Some(ref x) = self.debugger_interface { - let orig_scope_len = scope.len(); - - let src = global.source_raw().cloned(); - let src = src.as_ref().map(|s| s.as_str()); - let context = EvalContext::new(self, global, caches, scope, this_ptr); - let (.., ref on_debugger) = *x; + match self.debugger_interface { + Some(ref x) => { + let orig_scope_len = scope.len(); - let command = on_debugger(context, event, node, src, node.position()); + let src = global.source_raw().cloned(); + let src = src.as_ref().map(|s| s.as_str()); + let context = EvalContext::new(self, global, caches, scope, this_ptr); + let (.., ref on_debugger) = *x; - if orig_scope_len != scope.len() { - // The scope is changed, always search from now on - global.always_search_scope = true; - } + let command = on_debugger(context, event, node, src, node.position()); - match command? { - DebuggerCommand::Continue => { - global.debugger_mut().status = DebuggerStatus::CONTINUE; - Ok(None) - } - DebuggerCommand::Next => { - global.debugger_mut().status = DebuggerStatus::CONTINUE; - Ok(Some(DebuggerStatus::NEXT)) - } - DebuggerCommand::StepOver => { - global.debugger_mut().status = DebuggerStatus::CONTINUE; - Ok(Some(DebuggerStatus::STEP)) + if orig_scope_len != scope.len() { + // The scope is changed, always search from now on + global.always_search_scope = true; } - DebuggerCommand::StepInto => { - global.debugger_mut().status = DebuggerStatus::STEP; - Ok(None) - } - DebuggerCommand::FunctionExit => { - // Bump a level if it is a function call - let level = match node { - ASTNode::Expr(Expr::FnCall(..)) | ASTNode::Stmt(Stmt::FnCall(..)) => { - global.level + 1 - } - ASTNode::Stmt(Stmt::Expr(e)) if matches!(**e, Expr::FnCall(..)) => { - global.level + 1 - } - _ => global.level, - }; - global.debugger_mut().status = DebuggerStatus::FunctionExit(level); - Ok(None) + + match command? { + DebuggerCommand::Continue => { + global.debugger_mut().status = DebuggerStatus::CONTINUE; + Ok(None) + } + DebuggerCommand::Next => { + global.debugger_mut().status = DebuggerStatus::CONTINUE; + Ok(Some(DebuggerStatus::NEXT)) + } + DebuggerCommand::StepOver => { + global.debugger_mut().status = DebuggerStatus::CONTINUE; + Ok(Some(DebuggerStatus::STEP)) + } + DebuggerCommand::StepInto => { + global.debugger_mut().status = DebuggerStatus::STEP; + Ok(None) + } + DebuggerCommand::FunctionExit => { + // Bump a level if it is a function call + let level = match node { + ASTNode::Expr(Expr::FnCall(..)) | ASTNode::Stmt(Stmt::FnCall(..)) => { + global.level + 1 + } + ASTNode::Stmt(Stmt::Expr(e)) if matches!(**e, Expr::FnCall(..)) => { + global.level + 1 + } + _ => global.level, + }; + global.debugger_mut().status = DebuggerStatus::FunctionExit(level); + Ok(None) + } } } - } else { - Ok(None) + None => Ok(None), } } } diff --git a/src/eval/stmt.rs b/src/eval/stmt.rs index 91fb5a683..b76b7536f 100644 --- a/src/eval/stmt.rs +++ b/src/eval/stmt.rs @@ -469,11 +469,14 @@ impl Engine { None }; - if let Some(index) = index { - value.set_access_mode(access); - *scope.get_mut_by_index(scope.len() - index.get()) = value; - } else { - scope.push_entry(var_name.name.clone(), access, value); + match index { + Some(index) => { + value.set_access_mode(access); + *scope.get_mut_by_index(scope.len() - index.get()) = value; + } + _ => { + scope.push_entry(var_name.name.clone(), access, value); + } } #[cfg(not(feature = "no_module"))] @@ -782,10 +785,9 @@ impl Engine { Stmt::BreakLoop(expr, options, pos) => { let is_break = options.contains(ASTFlags::BREAK); - let value = if let Some(ref expr) = expr { - self.eval_expr(global, caches, scope, this_ptr, expr)? - } else { - Dynamic::UNIT + let value = match expr { + Some(ref expr) => self.eval_expr(global, caches, scope, this_ptr, expr)?, + None => Dynamic::UNIT, }; Err(ERR::LoopBreak(is_break, value, *pos).into()) diff --git a/src/func/call.rs b/src/func/call.rs index e4926284e..21ad7f315 100644 --- a/src/func/call.rs +++ b/src/func/call.rs @@ -109,20 +109,19 @@ impl Drop for ArgBackup<'_> { #[cfg(not(feature = "no_closure"))] #[inline] pub fn ensure_no_data_race(fn_name: &str, args: &FnCallArgs, is_ref_mut: bool) -> RhaiResultOf<()> { - if let Some((n, ..)) = args + match args .iter() .enumerate() .skip(usize::from(is_ref_mut)) .find(|(.., a)| a.is_locked()) { - return Err(ERR::ErrorDataRace( + Some((n, ..)) => Err(ERR::ErrorDataRace( format!("argument #{} of function '{fn_name}'", n + 1), Position::NONE, ) - .into()); + .into()), + _ => Ok(()), } - - Ok(()) } /// Is a function name an anonymous function? @@ -457,28 +456,26 @@ impl Engine { // See if the function match print/debug (which requires special processing) return Ok(match name { - KEYWORD_PRINT => { - if let Some(ref print) = self.print { + KEYWORD_PRINT => match self.print { + Some(ref print) => { let text = result.into_immutable_string().map_err(|typ| { let t = self.map_type_name(type_name::()).into(); ERR::ErrorMismatchOutputType(t, typ.into(), pos) })?; (print(&text).into(), false) - } else { - (Dynamic::UNIT, false) } - } - KEYWORD_DEBUG => { - if let Some(ref debug) = self.debug { + None => (Dynamic::UNIT, false), + }, + KEYWORD_DEBUG => match self.debug { + Some(ref debug) => { let text = result.into_immutable_string().map_err(|typ| { let t = self.map_type_name(type_name::()).into(); ERR::ErrorMismatchOutputType(t, typ.into(), pos) })?; (debug(&text, global.source(), pos).into(), false) - } else { - (Dynamic::UNIT, false) } - } + None => (Dynamic::UNIT, false), + }, _ => (result, is_method), }); } @@ -642,11 +639,12 @@ impl Engine { } let mut empty_scope; - let scope = if let Some(scope) = _scope { - scope - } else { - empty_scope = Scope::new(); - &mut empty_scope + let scope = match _scope { + Some(scope) => scope, + None => { + empty_scope = Scope::new(); + &mut empty_scope + } }; let orig_source = mem::replace(&mut global.source, source); diff --git a/src/module/mod.rs b/src/module/mod.rs index 84c6b40ef..11df49377 100644 --- a/src/module/mod.rs +++ b/src/module/mod.rs @@ -736,11 +736,12 @@ impl Module { let num_params = fn_def.params.len(); let hash_script = crate::calc_fn_hash(None, &fn_def.name, num_params); #[cfg(not(feature = "no_object"))] - let (hash_script, namespace) = if let Some(ref this_type) = fn_def.this_type { - let hash = crate::calc_typed_method_hash(hash_script, this_type); - (hash, FnNamespace::Global) - } else { - (hash_script, namespace) + let (hash_script, namespace) = match fn_def.this_type { + Some(ref this_type) => { + let hash = crate::calc_typed_method_hash(hash_script, this_type); + (hash, FnNamespace::Global) + } + None => (hash_script, namespace), }; // Catch hash collisions in testing environment only. @@ -2404,12 +2405,12 @@ impl Module { f.metadata.num_params, ); #[cfg(not(feature = "no_object"))] - let hash_qualified_script = - if let Some(ref this_type) = f.metadata.this_type { + let hash_qualified_script = match f.metadata.this_type { + Some(ref this_type) => { crate::calc_typed_method_hash(hash_qualified_script, this_type) - } else { - hash_qualified_script - }; + } + None => hash_qualified_script, + }; // Catch hash collisions in testing environment only. #[cfg(feature = "testing-environ")] diff --git a/src/optimizer.rs b/src/optimizer.rs index 9bfe52399..940c58046 100644 --- a/src/optimizer.rs +++ b/src/optimizer.rs @@ -44,7 +44,6 @@ pub enum OptimizationLevel { impl Default for OptimizationLevel { #[inline(always)] - #[must_use] fn default() -> Self { Self::Simple } @@ -439,11 +438,12 @@ fn optimize_stmt(stmt: &mut Stmt, state: &mut OptimizerState, preserve_result: b Stmt::If(x, ..) if matches!(x.expr, Expr::BoolConstant(false, ..)) && x.branch.is_empty() => { - if let Expr::BoolConstant(false, pos) = x.expr { - state.set_dirty(); - *stmt = Stmt::Noop(pos); - } else { - unreachable!("`Expr::BoolConstant`"); + match x.expr { + Expr::BoolConstant(false, pos) => { + state.set_dirty(); + *stmt = Stmt::Noop(pos); + } + _ => unreachable!("`Expr::BoolConstant`"), } } // if false { if_block } else { else_block } -> else_block @@ -810,18 +810,17 @@ fn optimize_stmt(stmt: &mut Stmt, state: &mut OptimizerState, preserve_result: b Stmt::Expr(expr) => optimize_expr(expr, state, false), // func(...) - Stmt::FnCall(..) => { - if let Stmt::FnCall(x, pos) = stmt.take() { + Stmt::FnCall(..) => match stmt.take() { + Stmt::FnCall(x, pos) => { let mut expr = Expr::FnCall(x, pos); optimize_expr(&mut expr, state, false); *stmt = match expr { Expr::FnCall(x, pos) => Stmt::FnCall(x, pos), _ => Stmt::Expr(expr.into()), } - } else { - unreachable!(); } - } + _ => unreachable!(), + }, // break expr; Stmt::BreakLoop(Some(ref mut expr), ..) => optimize_expr(expr, state, false), @@ -1083,10 +1082,9 @@ fn optimize_expr(expr: &mut Expr, state: &mut OptimizerState, _chaining: bool) { && matches!(x.args[0], Expr::BoolConstant(..)) => { state.set_dirty(); - if let Expr::BoolConstant(b, pos) = x.args[0] { - *expr = Expr::BoolConstant(!b, pos) - } else { - unreachable!() + match x.args[0] { + Expr::BoolConstant(b, pos) => *expr = Expr::BoolConstant(!b, pos), + _ => unreachable!(), } } @@ -1156,16 +1154,16 @@ fn optimize_expr(expr: &mut Expr, state: &mut OptimizerState, _chaining: bool) { } // Overloaded operators can override built-in. _ if x.args.len() == 2 && x.op_token.is_some() && (state.engine.fast_operators() || !state.engine.has_native_fn_override(x.hashes.native(), &arg_types)) => { - if let Some(result) = get_builtin_binary_op_fn(x.op_token.as_ref().unwrap(), &arg_values[0], &arg_values[1]) - .and_then(|(f, ctx)| { - let context = ctx.then(|| (state.engine, x.name.as_str(), None, &state.global, *pos).into()); - let (first, second) = arg_values.split_first_mut().unwrap(); - f(context, &mut [ first, &mut second[0] ]).ok() - }) { + if let Some((f, ctx)) = get_builtin_binary_op_fn(x.op_token.as_ref().unwrap(), &arg_values[0], &arg_values[1]) { + let context = ctx.then(|| (state.engine, x.name.as_str(), None, &state.global, *pos).into()); + let (first, second) = arg_values.split_first_mut().unwrap(); + + if let Ok(result) = f(context, &mut [ first, &mut second[0] ]) { state.set_dirty(); *expr = Expr::from_dynamic(result, *pos); return; } + } } _ => () } diff --git a/src/packages/array_basic.rs b/src/packages/array_basic.rs index 1f2a32cf8..95070f991 100644 --- a/src/packages/array_basic.rs +++ b/src/packages/array_basic.rs @@ -315,10 +315,9 @@ pub mod array_functions { /// print(x); // prints "[3]" /// ``` pub fn remove(array: &mut Array, index: INT) -> Dynamic { - let index = if let Ok(n) = calc_index(array.len(), index, true, || Err(())) { - n - } else { - return Dynamic::UNIT; + let index = match calc_index(array.len(), index, true, || Err(())) { + Ok(n) => n, + _ => return Dynamic::UNIT, }; array.remove(index) diff --git a/src/packages/blob_basic.rs b/src/packages/blob_basic.rs index c5b2c7902..666414e3a 100644 --- a/src/packages/blob_basic.rs +++ b/src/packages/blob_basic.rs @@ -452,10 +452,9 @@ pub mod blob_functions { /// print(x); // prints "[010305]" /// ``` pub fn remove(blob: &mut Blob, index: INT) -> INT { - let index = if let Ok(n) = calc_index(blob.len(), index, true, || Err(())) { - n - } else { - return 0; + let index = match calc_index(blob.len(), index, true, || Err(())) { + Ok(n) => n, + _ => return 0, }; blob.remove(index) as INT diff --git a/src/packages/map_basic.rs b/src/packages/map_basic.rs index 23c97a493..fdd514636 100644 --- a/src/packages/map_basic.rs +++ b/src/packages/map_basic.rs @@ -219,17 +219,18 @@ mod map_functions { let mut map2 = map2; for (m1, v1) in map1 { - if let Some(v2) = map2.get_mut(m1) { - let equals = ctx - .call_native_fn_raw(OP_EQUALS, true, &mut [v1, v2])? - .as_bool() - .unwrap_or(false); + match map2.get_mut(m1) { + Some(v2) => { + let equals = ctx + .call_native_fn_raw(OP_EQUALS, true, &mut [v1, v2])? + .as_bool() + .unwrap_or(false); - if !equals { - return Ok(false); + if !equals { + return Ok(false); + } } - } else { - return Ok(false); + _ => return Ok(false), } } } diff --git a/src/packages/string_more.rs b/src/packages/string_more.rs index 3fc11f555..26d8c4bd0 100644 --- a/src/packages/string_more.rs +++ b/src/packages/string_more.rs @@ -251,10 +251,9 @@ mod string_functions { return; } - if let Some(s) = string.get_mut() { - s.clear(); - } else { - *string = ImmutableString::new(); + match string.get_mut() { + Some(s) => s.clear(), + _ => *string = ImmutableString::new(), } } /// Cut off the string at the specified number of characters. @@ -300,17 +299,20 @@ mod string_functions { /// print(text); // prints "hello" /// ``` pub fn trim(string: &mut ImmutableString) { - if let Some(s) = string.get_mut() { - let trimmed = s.trim(); + match string.get_mut() { + Some(s) => { + let trimmed = s.trim(); - if trimmed != s { - *s = trimmed.into(); + if trimmed != s { + *s = trimmed.into(); + } } - } else { - let trimmed = string.trim(); + None => { + let trimmed = string.trim(); - if trimmed != string { - *string = trimmed.into(); + if trimmed != string { + *string = trimmed.into(); + } } } } diff --git a/src/parser.rs b/src/parser.rs index c78be9cf0..8b6cfce7d 100644 --- a/src/parser.rs +++ b/src/parser.rs @@ -1299,8 +1299,7 @@ impl Engine { let mut range_value: Option = None; - let guard = value.read_lock::(); - if let Some(range) = guard { + if let Some(range) = value.read_lock::() { range_value = Some(range.clone().into()); } else if let Some(range) = value.read_lock::() { range_value = Some(range.clone().into()); @@ -2140,10 +2139,9 @@ impl Engine { } } - let op_info = if let Some(op) = op { - OpAssignment::new_op_assignment_from_token(op, op_pos) - } else { - OpAssignment::new_assignment(op_pos) + let op_info = match op { + Some(op) => OpAssignment::new_op_assignment_from_token(op, op_pos), + None => OpAssignment::new_assignment(op_pos), }; match lhs { @@ -2781,12 +2779,11 @@ impl Engine { // if guard { if_body } else ... let branch = if match_token(input, Token::Else).0 { - if let (Token::If, ..) = input.peek().expect(NEVER_ENDS) { + match input.peek().expect(NEVER_ENDS) { // if guard { if_body } else if ... - self.parse_if(input, state, lib, settings)? - } else { + (Token::If, ..) => self.parse_if(input, state, lib, settings)?, // if guard { if_body } else { else-body } - self.parse_block(input, state, lib, settings)? + _ => self.parse_block(input, state, lib, settings)?, } } else { Stmt::Noop(Position::NONE) @@ -3029,10 +3026,12 @@ impl Engine { match filter(false, info, context) { Ok(true) => (), Ok(false) => return Err(PERR::ForbiddenVariable(name.into()).into_err(pos)), - Err(err) => match *err { - EvalAltResult::ErrorParsing(e, pos) => return Err(e.into_err(pos)), - _ => return Err(PERR::ForbiddenVariable(name.into()).into_err(pos)), - }, + Err(err) => { + return Err(match *err { + EvalAltResult::ErrorParsing(e, pos) => e.into_err(pos), + _ => PERR::ForbiddenVariable(name.into()).into_err(pos), + }) + } } } } @@ -3070,12 +3069,15 @@ impl Engine { None }; - let idx = if let Some(n) = existing { - stack.get_mut_by_index(n).set_access_mode(access); - Some(NonZeroUsize::new(stack.len() - n).unwrap()) - } else { - stack.push_entry(name.as_str(), access, Dynamic::UNIT); - None + let idx = match existing { + Some(n) => { + stack.get_mut_by_index(n).set_access_mode(access); + Some(NonZeroUsize::new(stack.len() - n).unwrap()) + } + None => { + stack.push_entry(name.as_str(), access, Dynamic::UNIT); + None + } }; #[cfg(not(feature = "no_module"))] @@ -3492,10 +3494,9 @@ impl Engine { let hash = calc_fn_hash(None, &f.name, f.params.len()); #[cfg(not(feature = "no_object"))] - let hash = if let Some(ref this_type) = f.this_type { - crate::calc_typed_method_hash(hash, this_type) - } else { - hash + let hash = match f.this_type { + Some(ref this_type) => crate::calc_typed_method_hash(hash, this_type), + None => hash, }; if !lib.is_empty() && lib.contains_key(&hash) { @@ -3951,18 +3952,20 @@ impl Engine { // External variables may need to be processed in a consistent order, // so extract them into a list. #[cfg(not(feature = "no_closure"))] - let (mut params, externals) = if let Some(ref external_vars) = state.external_vars { - let externals: crate::FnArgsVec<_> = external_vars.iter().cloned().collect(); + let (mut params, externals) = match state.external_vars { + Some(ref external_vars) => { + let externals: crate::FnArgsVec<_> = external_vars.iter().cloned().collect(); - let mut params = crate::FnArgsVec::with_capacity(params_list.len() + externals.len()); - params.extend(externals.iter().map(|Ident { name, .. }| name.clone())); + let mut params = + crate::FnArgsVec::with_capacity(params_list.len() + externals.len()); + params.extend(externals.iter().map(|Ident { name, .. }| name.clone())); - (params, externals) - } else { - ( + (params, externals) + } + None => ( crate::FnArgsVec::with_capacity(params_list.len()), crate::FnArgsVec::new_const(), - ) + ), }; #[cfg(feature = "no_closure")] let mut params = crate::FnArgsVec::with_capacity(params_list.len()); diff --git a/src/serde/de.rs b/src/serde/de.rs index 681a68174..af3b00b6d 100644 --- a/src/serde/de.rs +++ b/src/serde/de.rs @@ -186,108 +186,105 @@ impl<'de> Deserializer<'de> for DynamicDeserializer<'de> { } fn deserialize_i8>(self, visitor: V) -> RhaiResultOf { - if let Ok(v) = self.0.as_int() { - Self::deserialize_int(v, visitor) - } else { - self.0 + match self.0.as_int() { + Ok(v) => Self::deserialize_int(v, visitor), + Err(_) => self + .0 .downcast_ref::() - .map_or_else(|| self.type_error(), |&x| visitor.visit_i8(x)) + .map_or_else(|| self.type_error(), |&x| visitor.visit_i8(x)), } } fn deserialize_i16>(self, visitor: V) -> RhaiResultOf { - if let Ok(v) = self.0.as_int() { - Self::deserialize_int(v, visitor) - } else { - self.0 + match self.0.as_int() { + Ok(v) => Self::deserialize_int(v, visitor), + Err(_) => self + .0 .downcast_ref::() - .map_or_else(|| self.type_error(), |&x| visitor.visit_i16(x)) + .map_or_else(|| self.type_error(), |&x| visitor.visit_i16(x)), } } fn deserialize_i32>(self, visitor: V) -> RhaiResultOf { - if let Ok(v) = self.0.as_int() { - Self::deserialize_int(v, visitor) - } else if cfg!(feature = "only_i32") { - self.type_error() - } else { - self.0 + match self.0.as_int() { + Ok(v) => Self::deserialize_int(v, visitor), + _ if cfg!(feature = "only_i32") => self.type_error(), + _ => self + .0 .downcast_ref::() - .map_or_else(|| self.type_error(), |&x| visitor.visit_i32(x)) + .map_or_else(|| self.type_error(), |&x| visitor.visit_i32(x)), } } fn deserialize_i64>(self, visitor: V) -> RhaiResultOf { - if let Ok(v) = self.0.as_int() { - Self::deserialize_int(v, visitor) - } else if cfg!(not(feature = "only_i32")) { - self.type_error() - } else { - self.0 + match self.0.as_int() { + Ok(v) => Self::deserialize_int(v, visitor), + _ if cfg!(not(feature = "only_i32")) => self.type_error(), + _ => self + .0 .downcast_ref::() - .map_or_else(|| self.type_error(), |&x| visitor.visit_i64(x)) + .map_or_else(|| self.type_error(), |&x| visitor.visit_i64(x)), } } fn deserialize_i128>(self, visitor: V) -> RhaiResultOf { - if let Ok(v) = self.0.as_int() { - Self::deserialize_int(v, visitor) - } else if cfg!(not(feature = "only_i32")) { - self.type_error() - } else { - self.0 + match self.0.as_int() { + Ok(v) => Self::deserialize_int(v, visitor), + _ if cfg!(not(feature = "only_i32")) => self.type_error(), + _ => self + .0 .downcast_ref::() - .map_or_else(|| self.type_error(), |&x| visitor.visit_i128(x)) + .map_or_else(|| self.type_error(), |&x| visitor.visit_i128(x)), } } fn deserialize_u8>(self, visitor: V) -> RhaiResultOf { - if let Ok(v) = self.0.as_int() { - Self::deserialize_int(v, visitor) - } else { - self.0 + match self.0.as_int() { + Ok(v) => Self::deserialize_int(v, visitor), + Err(_) => self + .0 .downcast_ref::() - .map_or_else(|| self.type_error(), |&x| visitor.visit_u8(x)) + .map_or_else(|| self.type_error(), |&x| visitor.visit_u8(x)), } } fn deserialize_u16>(self, visitor: V) -> RhaiResultOf { - if let Ok(v) = self.0.as_int() { - Self::deserialize_int(v, visitor) - } else { - self.0 + match self.0.as_int() { + Ok(v) => Self::deserialize_int(v, visitor), + Err(_) => self + .0 .downcast_ref::() - .map_or_else(|| self.type_error(), |&x| visitor.visit_u16(x)) + .map_or_else(|| self.type_error(), |&x| visitor.visit_u16(x)), } } fn deserialize_u32>(self, visitor: V) -> RhaiResultOf { - if let Ok(v) = self.0.as_int() { - Self::deserialize_int(v, visitor) - } else { - self.0 + match self.0.as_int() { + Ok(v) => Self::deserialize_int(v, visitor), + Err(_) => self + .0 .downcast_ref::() - .map_or_else(|| self.type_error(), |&x| visitor.visit_u32(x)) + .map_or_else(|| self.type_error(), |&x| visitor.visit_u32(x)), } } fn deserialize_u64>(self, visitor: V) -> RhaiResultOf { - if let Ok(v) = self.0.as_int() { - Self::deserialize_int(v, visitor) - } else { - self.0 + match self.0.as_int() { + Ok(v) => Self::deserialize_int(v, visitor), + Err(_) => self + .0 .downcast_ref::() - .map_or_else(|| self.type_error(), |&x| visitor.visit_u64(x)) + .map_or_else(|| self.type_error(), |&x| visitor.visit_u64(x)), } } fn deserialize_u128>(self, visitor: V) -> RhaiResultOf { - if let Ok(v) = self.0.as_int() { - Self::deserialize_int(v, visitor) - } else { - self.0 + match self.0.as_int() { + Ok(v) => Self::deserialize_int(v, visitor), + Err(_) => self + .0 .downcast_ref::() - .map_or_else(|| self.type_error(), |&x| visitor.visit_u128(x)) + .map_or_else(|| self.type_error(), |&x| visitor.visit_u128(x)), } } @@ -456,28 +453,28 @@ impl<'de> Deserializer<'de> for DynamicDeserializer<'de> { _variants: &'static [&'static str], visitor: V, ) -> RhaiResultOf { - if let Some(s) = self.0.read_lock::() { - visitor.visit_enum(s.as_str().into_deserializer()) - } else { - #[cfg(not(feature = "no_object"))] - return self.0.downcast_ref::().map_or_else( - || self.type_error(), - |map| { - let mut iter = map.iter(); - let first = iter.next(); - let second = iter.next(); - if let (Some((key, value)), None) = (first, second) { - visitor.visit_enum(EnumDeserializer { - tag: key, - content: DynamicDeserializer::new(value), - }) - } else { - self.type_error() - } - }, - ); - #[cfg(feature = "no_object")] - return self.type_error(); + match self.0.read_lock::() { + Some(s) => visitor.visit_enum(s.as_str().into_deserializer()), + None => { + #[cfg(not(feature = "no_object"))] + return self.0.downcast_ref::().map_or_else( + || self.type_error(), + |map| { + let mut iter = map.iter(); + let first = iter.next(); + let second = iter.next(); + match (first, second) { + (Some((key, value)), None) => visitor.visit_enum(EnumDeserializer { + tag: key, + content: DynamicDeserializer::new(value), + }), + _ => self.type_error(), + } + }, + ); + #[cfg(feature = "no_object")] + return self.type_error(); + } } } diff --git a/src/tokenizer.rs b/src/tokenizer.rs index f13c48015..b675a13ff 100644 --- a/src/tokenizer.rs +++ b/src/tokenizer.rs @@ -1182,13 +1182,10 @@ pub trait InputStream { /// Return error if the string is longer than the maximum length. #[inline] fn ensure_string_len_within_limit(max: Option, value: &str) -> Result<(), LexError> { - if let Some(max) = max { - if value.len() > max.get() { - return Err(LexError::StringTooLong(max.get())); - } + match max { + Some(max) if value.len() > max.get() => Err(LexError::StringTooLong(max.get())), + _ => Ok(()), } - - Ok(()) } /// _(internals)_ Parse a string literal ended by a specified termination character. @@ -1415,7 +1412,7 @@ pub fn parse_string_literal( // Whitespace to skip #[cfg(not(feature = "no_position"))] - _ if next_char.is_whitespace() && pos.position().unwrap() < skip_whitespace_until => {} + _ if next_char.is_whitespace() && pos.position().unwrap() < skip_whitespace_until => (), // All other characters _ => { @@ -1963,18 +1960,17 @@ fn get_next_token_inner( pos.advance(); } - if let Some(comment) = comment { - match comment { - #[cfg(feature = "metadata")] - _ if comment.starts_with("//!") => { - let g = &mut state.tokenizer_control.borrow_mut().global_comments; - if !g.is_empty() { - g.push('\n'); - } - g.push_str(&comment); + match comment { + #[cfg(feature = "metadata")] + Some(comment) if comment.starts_with("//!") => { + let g = &mut state.tokenizer_control.borrow_mut().global_comments; + if !g.is_empty() { + g.push('\n'); } - _ => return Some((Token::Comment(comment.into()), start_pos)), + g.push_str(&comment); } + Some(comment) => return Some((Token::Comment(comment.into()), start_pos)), + None => (), } } ('/', '*') => { @@ -2561,18 +2557,17 @@ impl<'a> Iterator for TokenIterator<'a> { }; // Run the mapper, if any - let token = if let Some(func) = self.token_mapper { - func(token, pos, &self.state) - } else { - token + let token = match self.token_mapper { + Some(func) => func(token, pos, &self.state), + None => token, }; // Collect the compressed script, if needed if compress_script { let control = &mut *self.state.tokenizer_control.borrow_mut(); - if let Some(ref mut compressed) = control.compressed { - if token != Token::EOF { + if token != Token::EOF { + if let Some(ref mut compressed) = control.compressed { use std::fmt::Write; let last_token = self.state.last_token.as_ref().unwrap(); diff --git a/src/types/dynamic.rs b/src/types/dynamic.rs index ae8fff847..c09a98b99 100644 --- a/src/types/dynamic.rs +++ b/src/types/dynamic.rs @@ -501,13 +501,10 @@ impl fmt::Display for Dynamic { #[cfg(not(feature = "no_closure"))] #[cfg(not(feature = "sync"))] - Union::Shared(ref cell, ..) => { - if let Ok(v) = cell.try_borrow() { - fmt::Display::fmt(&*v, f) - } else { - f.write_str("") - } - } + Union::Shared(ref cell, ..) => match cell.try_borrow() { + Ok(v) => fmt::Display::fmt(&*v, f), + Err(_) => f.write_str(""), + }, #[cfg(not(feature = "no_closure"))] #[cfg(feature = "sync")] Union::Shared(ref cell, ..) => fmt::Display::fmt(&*cell.read().unwrap(), f), @@ -606,13 +603,10 @@ impl fmt::Debug for Dynamic { #[cfg(not(feature = "no_closure"))] #[cfg(not(feature = "sync"))] - Union::Shared(ref cell, ..) => { - if let Ok(v) = cell.try_borrow() { - write!(f, "{:?} (shared)", *v) - } else { - f.write_str("") - } - } + Union::Shared(ref cell, ..) => match cell.try_borrow() { + Ok(v) => write!(f, "{:?} (shared)", *v), + Err(_) => f.write_str(""), + }, #[cfg(not(feature = "no_closure"))] #[cfg(feature = "sync")] Union::Shared(ref cell, ..) => fmt::Debug::fmt(&*cell.read().unwrap(), f), diff --git a/src/types/fn_ptr.rs b/src/types/fn_ptr.rs index ba13ab9dd..98e3d1736 100644 --- a/src/types/fn_ptr.rs +++ b/src/types/fn_ptr.rs @@ -297,8 +297,8 @@ impl FnPtr { // Linked to scripted function? #[cfg(not(feature = "no_function"))] - if let Some(ref fn_def) = self.fn_def { - if fn_def.params.len() == args.len() { + match self.fn_def { + Some(ref fn_def) if fn_def.params.len() == args.len() => { let global = &mut context.global_runtime_state().clone(); global.level += 1; @@ -316,6 +316,7 @@ impl FnPtr { context.position(), ); } + _ => (), } let is_method = this_ptr.is_some(); @@ -381,7 +382,14 @@ impl FnPtr { extras: [Dynamic; E], move_this_ptr_to_args: Option, ) -> RhaiResult { - self._call_with_extra_args(fn_name, ctx, this_ptr, args, extras, move_this_ptr_to_args) + match move_this_ptr_to_args { + Some(m) => { + self._call_with_extra_args::(fn_name, ctx, this_ptr, args, extras, m) + } + None => { + self._call_with_extra_args::(fn_name, ctx, this_ptr, args, extras, 0) + } + } } /// _(internals)_ Make a call to a function pointer with either a specified number of arguments, /// or with extra arguments attached. Exported under the `internals` feature only. @@ -407,46 +415,53 @@ impl FnPtr { extras: [Dynamic; E], move_this_ptr_to_args: Option, ) -> RhaiResult { - self._call_with_extra_args(fn_name, ctx, this_ptr, args, extras, move_this_ptr_to_args) + match move_this_ptr_to_args { + Some(m) => { + self._call_with_extra_args::(fn_name, ctx, this_ptr, args, extras, m) + } + None => { + self._call_with_extra_args::(fn_name, ctx, this_ptr, args, extras, 0) + } + } } /// Make a call to a function pointer with either a specified number of arguments, or with extra /// arguments attached. - fn _call_with_extra_args( + fn _call_with_extra_args( &self, fn_name: &str, ctx: &NativeCallContext, mut this_ptr: Option<&mut Dynamic>, args: [Dynamic; N], extras: [Dynamic; E], - move_this_ptr_to_args: Option, + move_this_ptr_to_args: usize, ) -> RhaiResult { #[cfg(not(feature = "no_function"))] if let Some(arity) = self.fn_def().map(|f| f.params.len()) { if arity == N + self.curry().len() { return self.call_raw(ctx, this_ptr, args); } - if let Some(move_to_args) = move_this_ptr_to_args { + if MOVE_PTR { if this_ptr.is_some() { if arity == N + 1 + self.curry().len() { let mut args2 = FnArgsVec::with_capacity(args.len() + 1); - if move_to_args == 0 { + if move_this_ptr_to_args == 0 { args2.push(this_ptr.as_mut().unwrap().clone()); args2.extend(args); } else { args2.extend(args); - args2.insert(move_to_args, this_ptr.as_mut().unwrap().clone()); + args2.insert(move_this_ptr_to_args, this_ptr.as_mut().unwrap().clone()); } return self.call_raw(ctx, None, args2); } if arity == N + E + 1 + self.curry().len() { let mut args2 = FnArgsVec::with_capacity(args.len() + extras.len() + 1); - if move_to_args == 0 { + if move_this_ptr_to_args == 0 { args2.push(this_ptr.as_mut().unwrap().clone()); args2.extend(args); args2.extend(extras); } else { args2.extend(args); - args2.insert(move_to_args, this_ptr.as_mut().unwrap().clone()); + args2.insert(move_this_ptr_to_args, this_ptr.as_mut().unwrap().clone()); args2.extend(extras); } return self.call_raw(ctx, None, args2); @@ -464,18 +479,15 @@ impl FnPtr { self.call_raw(ctx, this_ptr.as_deref_mut(), args.clone()) .or_else(|err| match *err { ERR::ErrorFunctionNotFound(sig, ..) - if move_this_ptr_to_args.is_some() - && this_ptr.is_some() - && sig.starts_with(self.fn_name()) => + if MOVE_PTR && this_ptr.is_some() && sig.starts_with(self.fn_name()) => { let mut args2 = FnArgsVec::with_capacity(args.len() + 1); - let move_to_args = move_this_ptr_to_args.unwrap(); - if move_to_args == 0 { + if move_this_ptr_to_args == 0 { args2.push(this_ptr.as_mut().unwrap().clone()); args2.extend(args.clone()); } else { args2.extend(args.clone()); - args2.insert(move_to_args, this_ptr.as_mut().unwrap().clone()); + args2.insert(move_this_ptr_to_args, this_ptr.as_mut().unwrap().clone()); } self.call_raw(ctx, None, args2) } @@ -483,17 +495,17 @@ impl FnPtr { }) .or_else(|err| match *err { ERR::ErrorFunctionNotFound(sig, ..) if sig.starts_with(self.fn_name()) => { - if let Some(move_to_args) = move_this_ptr_to_args { + if MOVE_PTR { if let Some(ref mut this_ptr) = this_ptr { let mut args2 = FnArgsVec::with_capacity(args.len() + extras.len() + 1); - if move_to_args == 0 { + if move_this_ptr_to_args == 0 { args2.push(this_ptr.clone()); args2.extend(args); args2.extend(extras); } else { args2.extend(args); args2.extend(extras); - args2.insert(move_to_args, this_ptr.clone()); + args2.insert(move_this_ptr_to_args, this_ptr.clone()); } return self.call_raw(ctx, None, args2); }