From be448dfe4d7919d2a543820497a3b5e75f4ab8db Mon Sep 17 00:00:00 2001 From: Stephen Chung Date: Thu, 11 Aug 2022 19:01:23 +0800 Subject: [PATCH] Use identifiers in format! --- codegen/src/attrs.rs | 2 +- codegen/src/function.rs | 8 ++--- codegen/src/module.rs | 2 +- codegen/src/rhai_module.rs | 12 +++---- codegen/src/test/function.rs | 13 +++----- codegen/tests/test_functions.rs | 2 +- codegen/tests/test_modules.rs | 2 +- src/api/custom_syntax.rs | 6 ++-- src/api/mod.rs | 6 ++-- src/api/register.rs | 2 +- src/api/type_names.rs | 2 +- src/ast/expr.rs | 10 +++--- src/bin/rhai-dbg.rs | 2 +- src/bin/rhai-repl.rs | 2 +- src/bin/rhai-run.rs | 2 +- src/eval/expr.rs | 6 ++-- src/eval/stmt.rs | 2 +- src/func/builtin.rs | 8 ++--- src/func/call.rs | 19 ++++------- src/func/script.rs | 4 +-- src/module/mod.rs | 11 +++---- src/packages/arithmetic.rs | 57 +++++++++++++++------------------ src/packages/lang_core.rs | 23 ++++++------- src/packages/math_basic.rs | 49 ++++++++++++---------------- src/packages/string_basic.rs | 22 +++++++------ src/packages/string_more.rs | 6 ++-- src/packages/time_basic.rs | 27 ++++++---------- src/parser.rs | 21 +++++------- src/tokenizer.rs | 2 +- src/types/error.rs | 2 +- tests/custom_syntax.rs | 6 ++-- tests/native.rs | 4 +-- tests/optimizer.rs | 12 +++---- tests/plugins.rs | 2 +- tests/print.rs | 12 +++---- tests/serde.rs | 2 +- 36 files changed, 164 insertions(+), 206 deletions(-) diff --git a/codegen/src/attrs.rs b/codegen/src/attrs.rs index da376cf2..044252df 100644 --- a/codegen/src/attrs.rs +++ b/codegen/src/attrs.rs @@ -131,7 +131,7 @@ pub fn inner_item_attributes( { return Err(syn::Error::new( duplicate.span(), - format!("duplicated attribute '{}'", attr_name), + format!("duplicated attribute '{attr_name}'"), )); } diff --git a/codegen/src/function.rs b/codegen/src/function.rs index 078c1c2a..d356645e 100644 --- a/codegen/src/function.rs +++ b/codegen/src/function.rs @@ -57,10 +57,10 @@ impl FnSpecialAccess { match self { FnSpecialAccess::None => None, FnSpecialAccess::Property(Property::Get(ref g)) => { - Some((format!("{}{}", FN_GET, g), g.to_string(), g.span())) + Some((format!("{FN_GET}{g}"), g.to_string(), g.span())) } FnSpecialAccess::Property(Property::Set(ref s)) => { - Some((format!("{}{}", FN_SET, s), s.to_string(), s.span())) + Some((format!("{FN_SET}{s}"), s.to_string(), s.span())) } FnSpecialAccess::Index(Index::Get) => Some(( FN_IDX_GET.to_string(), @@ -255,7 +255,7 @@ impl ExportedParams for ExportedFnParams { (attr, ..) => { return Err(syn::Error::new( key.span(), - format!("unknown attribute '{}'", attr), + format!("unknown attribute '{attr}'"), )) } } @@ -748,7 +748,7 @@ impl ExportedFn { let str_type_path = syn::parse2::(quote! { str }).unwrap(); let string_type_path = syn::parse2::(quote! { String }).unwrap(); for (i, arg) in self.arg_list().enumerate().skip(skip_first_arg as usize) { - let var = syn::Ident::new(&format!("arg{}", i), Span::call_site()); + let var = syn::Ident::new(&format!("arg{i}"), Span::call_site()); let is_string; let is_ref; match arg { diff --git a/codegen/src/module.rs b/codegen/src/module.rs index bd6a4c1f..9206be78 100644 --- a/codegen/src/module.rs +++ b/codegen/src/module.rs @@ -72,7 +72,7 @@ impl ExportedParams for ExportedModParams { (attr, ..) => { return Err(syn::Error::new( key.span(), - format!("unknown attribute '{}'", attr), + format!("unknown attribute '{attr}'"), )) } } diff --git a/codegen/src/rhai_module.rs b/codegen/src/rhai_module.rs index b5c8df4a..4e52d83d 100644 --- a/codegen/src/rhai_module.rs +++ b/codegen/src/rhai_module.rs @@ -319,11 +319,11 @@ pub fn check_rename_collisions(fns: &[ExportedFn]) -> Result<(), syn::Error> { if let Some(other_span) = renames.insert(key, current_span) { let mut err = syn::Error::new( current_span, - format!("duplicate Rhai signature for '{}'", fn_name), + format!("duplicate Rhai signature for '{fn_name}'"), ); err.combine(syn::Error::new( other_span, - format!("duplicated function renamed '{}'", fn_name), + format!("duplicated function renamed '{fn_name}'"), )); return Err(err); } @@ -332,10 +332,10 @@ pub fn check_rename_collisions(fns: &[ExportedFn]) -> Result<(), syn::Error> { let ident = item_fn.name(); if let Some(other_span) = fn_defs.insert(ident.to_string(), ident.span()) { let mut err = - syn::Error::new(ident.span(), format!("duplicate function '{}'", ident)); + syn::Error::new(ident.span(), format!("duplicate function '{ident}'")); err.combine(syn::Error::new( other_span, - format!("duplicated function '{}'", ident), + format!("duplicated function '{ident}'"), )); return Err(err); } @@ -343,11 +343,11 @@ pub fn check_rename_collisions(fns: &[ExportedFn]) -> Result<(), syn::Error> { if let Some(fn_span) = renames.get(&key) { let mut err = syn::Error::new( ident.span(), - format!("duplicate Rhai signature for '{}'", ident), + format!("duplicate Rhai signature for '{ident}'"), ); err.combine(syn::Error::new( *fn_span, - format!("duplicated function '{}'", ident), + format!("duplicated function '{ident}'"), )); return Err(err); } diff --git a/codegen/src/test/function.rs b/codegen/src/test/function.rs index f187c5ed..8465cd61 100644 --- a/codegen/src/test/function.rs +++ b/codegen/src/test/function.rs @@ -88,10 +88,7 @@ mod function_tests { }; let err = syn::parse2::(input_tokens).unwrap_err(); - assert_eq!( - format!("{}", err), - "Rhai functions cannot return references" - ); + assert_eq!(format!("{err}"), "Rhai functions cannot return references"); } #[test] @@ -101,7 +98,7 @@ mod function_tests { }; let err = syn::parse2::(input_tokens).unwrap_err(); - assert_eq!(format!("{}", err), "Rhai functions cannot return pointers"); + assert_eq!(format!("{err}"), "Rhai functions cannot return pointers"); } #[test] @@ -112,7 +109,7 @@ mod function_tests { let err = syn::parse2::(input_tokens).unwrap_err(); assert_eq!( - format!("{}", err), + format!("{err}"), "references from Rhai in this position must be mutable" ); } @@ -125,7 +122,7 @@ mod function_tests { let err = syn::parse2::(input_tokens).unwrap_err(); assert_eq!( - format!("{}", err), + format!("{err}"), "function parameters other than the first one cannot be passed by reference" ); } @@ -138,7 +135,7 @@ mod function_tests { let err = syn::parse2::(input_tokens).unwrap_err(); assert_eq!( - format!("{}", err), + format!("{err}"), "function parameters other than the first one cannot be passed by reference" ); } diff --git a/codegen/tests/test_functions.rs b/codegen/tests/test_functions.rs index 9becd777..cc665678 100644 --- a/codegen/tests/test_functions.rs +++ b/codegen/tests/test_functions.rs @@ -107,7 +107,7 @@ mod mut_opaque_ref { StatusMessage { is_ok, os_code: Some(os_code), - message: format!("OS Code {}", os_code), + message: format!("OS Code {os_code}"), } } diff --git a/codegen/tests/test_modules.rs b/codegen/tests/test_modules.rs index a4657871..4be606a7 100644 --- a/codegen/tests/test_modules.rs +++ b/codegen/tests/test_modules.rs @@ -127,7 +127,7 @@ pub mod mut_opaque_ref_module { StatusMessage { is_ok, os_code: Some(os_code), - message: format!("OS Code {}", os_code), + message: format!("OS Code {os_code}"), } } diff --git a/src/api/custom_syntax.rs b/src/api/custom_syntax.rs index b84a0c26..64954d27 100644 --- a/src/api/custom_syntax.rs +++ b/src/api/custom_syntax.rs @@ -258,9 +258,8 @@ impl Engine { return Err(LexError::ImproperSymbol( s.to_string(), format!( - "Improper symbol for custom syntax at position #{}: '{}'", + "Improper symbol for custom syntax at position #{}: '{s}'", segments.len() + 1, - s ), ) .into_err(Position::NONE)); @@ -282,9 +281,8 @@ impl Engine { return Err(LexError::ImproperSymbol( s.to_string(), format!( - "Improper symbol for custom syntax at position #{}: '{}'", + "Improper symbol for custom syntax at position #{}: '{s}'", segments.len() + 1, - s ), ) .into_err(Position::NONE)); diff --git a/src/api/mod.rs b/src/api/mod.rs index 635082dd..b5120787 100644 --- a/src/api/mod.rs +++ b/src/api/mod.rs @@ -181,7 +181,7 @@ impl Engine { if self.disabled_symbols.is_empty() || !self.disabled_symbols.contains(&*token.syntax()) { - return Err(format!("'{}' is a reserved keyword", keyword)); + return Err(format!("'{keyword}' is a reserved keyword")); } } // Active standard symbols cannot be made custom @@ -189,7 +189,7 @@ impl Engine { if self.disabled_symbols.is_empty() || !self.disabled_symbols.contains(&*token.syntax()) { - return Err(format!("'{}' is a reserved operator", keyword)); + return Err(format!("'{keyword}' is a reserved operator")); } } // Active standard symbols cannot be made custom @@ -197,7 +197,7 @@ impl Engine { if self.disabled_symbols.is_empty() || !self.disabled_symbols.contains(&*token.syntax()) => { - return Err(format!("'{}' is a reserved symbol", keyword)) + return Err(format!("'{keyword}' is a reserved symbol")) } // Disabled symbols are OK Some(_) => (), diff --git a/src/api/register.rs b/src/api/register.rs index 7a782229..3ebb8695 100644 --- a/src/api/register.rs +++ b/src/api/register.rs @@ -1037,7 +1037,7 @@ impl Engine { #[cfg(not(feature = "no_module"))] for (name, m) in &self.global_sub_modules { - signatures.extend(m.gen_fn_signatures().map(|f| format!("{}::{}", name, f))); + signatures.extend(m.gen_fn_signatures().map(|f| format!("{name}::{f}"))); } signatures.extend( diff --git a/src/api/type_names.rs b/src/api/type_names.rs index db63ffbd..7d802376 100644 --- a/src/api/type_names.rs +++ b/src/api/type_names.rs @@ -150,7 +150,7 @@ impl Engine { return if x == r { name.into() } else { - format!("&mut {}", r).into() + format!("&mut {r}").into() }; } diff --git a/src/ast/expr.rs b/src/ast/expr.rs index 193324fa..16269430 100644 --- a/src/ast/expr.rs +++ b/src/ast/expr.rs @@ -476,7 +476,7 @@ impl fmt::Debug for Expr { write!(f, "{}{}", x.1, Token::DoubleColon.literal_syntax())?; let pos = x.1.position(); if !pos.is_none() { - display_pos = format!(" @ {:?}", pos); + display_pos = format!(" @ {pos:?}"); } } f.write_str(&x.3)?; @@ -490,7 +490,7 @@ impl fmt::Debug for Expr { Self::Stmt(x) => { let pos = x.span(); if !pos.is_none() { - display_pos = format!(" @ {:?}", pos); + display_pos = format!(" @ {pos:?}"); } f.write_str("ExprStmtBlock")?; f.debug_list().entries(x.iter()).finish() @@ -498,7 +498,7 @@ impl fmt::Debug for Expr { Self::FnCall(x, ..) => fmt::Debug::fmt(x, f), Self::Index(x, options, pos) => { if !pos.is_none() { - display_pos = format!(" @ {:?}", pos); + display_pos = format!(" @ {pos:?}"); } let mut f = f.debug_struct("Index"); @@ -511,7 +511,7 @@ impl fmt::Debug for Expr { } Self::Dot(x, options, pos) => { if !pos.is_none() { - display_pos = format!(" @ {:?}", pos); + display_pos = format!(" @ {pos:?}"); } let mut f = f.debug_struct("Dot"); @@ -531,7 +531,7 @@ impl fmt::Debug for Expr { }; if !pos.is_none() { - display_pos = format!(" @ {:?}", pos); + display_pos = format!(" @ {pos:?}"); } f.debug_struct(op_name) diff --git a/src/bin/rhai-dbg.rs b/src/bin/rhai-dbg.rs index 56ed34c8..d51d877d 100644 --- a/src/bin/rhai-dbg.rs +++ b/src/bin/rhai-dbg.rs @@ -20,7 +20,7 @@ fn print_source(lines: &[String], pos: Position, offset: usize, window: (usize, let line = pos.line().unwrap() - 1; let start = if line >= window.0 { line - window.0 } else { 0 }; let end = usize::min(line + window.1, lines.len() - 1); - let line_no_len = format!("{}", end).len(); + let line_no_len = end.to_string().len(); // Print error position if start >= end { diff --git a/src/bin/rhai-repl.rs b/src/bin/rhai-repl.rs index 43118f42..932bcf30 100644 --- a/src/bin/rhai-repl.rs +++ b/src/bin/rhai-repl.rs @@ -260,7 +260,7 @@ mod sample_functions { /// print(result); // prints "42 123" /// ``` pub fn test(x: INT, y: INT) -> String { - format!("{} {}", x, y) + format!("{x} {y}") } /// This is a sample method for integers. diff --git a/src/bin/rhai-run.rs b/src/bin/rhai-run.rs index 0ccc6006..ec4816d6 100644 --- a/src/bin/rhai-run.rs +++ b/src/bin/rhai-run.rs @@ -5,7 +5,7 @@ use std::{env, fs::File, io::Read, path::Path, process::exit}; fn eprint_error(input: &str, mut err: EvalAltResult) { fn eprint_line(lines: &[&str], pos: Position, err_msg: &str) { let line = pos.line().unwrap(); - let line_no = format!("{}: ", line); + let line_no = format!("{line}: "); eprintln!("{}{}", line_no, lines[line - 1]); eprintln!( diff --git a/src/eval/expr.rs b/src/eval/expr.rs index 071aa45b..9b338b78 100644 --- a/src/eval/expr.rs +++ b/src/eval/expr.rs @@ -82,7 +82,7 @@ impl Engine { let sep = crate::tokenizer::Token::DoubleColon.literal_syntax(); Err(ERR::ErrorVariableNotFound( - format!("{}{}{}", namespace, sep, var_name), + format!("{namespace}{sep}{var_name}"), namespace.position(), ) .into()) @@ -106,7 +106,7 @@ impl Engine { let sep = crate::tokenizer::Token::DoubleColon.literal_syntax(); return Err(ERR::ErrorVariableNotFound( - format!("{}{}{}", namespace, sep, var_name), + format!("{namespace}{sep}{var_name}"), namespace.position(), ) .into()); @@ -496,7 +496,7 @@ impl Engine { // The key should exist, unless the AST is compiled in a different Engine let custom_def = self.custom_syntax.get(key_token).ok_or_else(|| { Box::new(ERR::ErrorCustomSyntax( - format!("Invalid custom syntax prefix: {}", key_token), + format!("Invalid custom syntax prefix: {key_token}"), custom.tokens.iter().map(<_>::to_string).collect(), *pos, )) diff --git a/src/eval/stmt.rs b/src/eval/stmt.rs index 86a3d0a9..fb2b1a2c 100644 --- a/src/eval/stmt.rs +++ b/src/eval/stmt.rs @@ -642,7 +642,7 @@ impl Engine { #[cfg(not(feature = "unchecked"))] if x > INT::MAX as usize { loop_result = Err(ERR::ErrorArithmetic( - format!("for-loop counter overflow: {}", x), + format!("for-loop counter overflow: {x}"), counter.pos, ) .into()); diff --git a/src/func/builtin.rs b/src/func/builtin.rs index 2214cfda..8304567f 100644 --- a/src/func/builtin.rs +++ b/src/func/builtin.rs @@ -212,7 +212,7 @@ pub fn get_builtin_binary_op_fn(op: &str, x: &Dynamic, y: &Dynamic) -> Option Some(|_, args| { let x = args[0].as_char().expect(BUILTIN); let y = &*args[1].read_lock::().expect(BUILTIN); - Ok(format!("{}{}", x, y).into()) + Ok(format!("{x}{y}").into()) }), "==" => Some(impl_op!(get_s1s2(==))), "!=" => Some(impl_op!(get_s1s2(!=))), @@ -496,7 +496,7 @@ pub fn get_builtin_binary_op_fn(op: &str, x: &Dynamic, y: &Dynamic) -> Option Some(|_, args| { let x = args[0].as_char().expect(BUILTIN); let y = args[1].as_char().expect(BUILTIN); - Ok(format!("{}{}", x, y).into()) + Ok(format!("{x}{y}").into()) }), "==" => Some(impl_op!(char => as_char == as_char)), "!=" => Some(impl_op!(char => as_char != as_char)), @@ -809,8 +809,8 @@ pub fn get_builtin_op_assignment_fn(op: &str, x: &Dynamic, y: &Dynamic) -> Optio return match op { "+=" => Some(|_, args| { let y = args[1].as_char().expect(BUILTIN); - let mut x = args[0].write_lock::().expect(BUILTIN); - Ok((*x = format!("{}{}", *x, y).into()).into()) + let x = &mut *args[0].write_lock::().expect(BUILTIN); + Ok((*x = format!("{x}{y}").into()).into()) }), _ => None, }; diff --git a/src/func/call.rs b/src/func/call.rs index c6ff25c0..eb1bffda 100644 --- a/src/func/call.rs +++ b/src/func/call.rs @@ -118,7 +118,7 @@ pub fn ensure_no_data_race( .find(|(.., a)| a.is_locked()) { return Err(ERR::ErrorDataRace( - format!("argument #{} of function '{}'", n + 1, fn_name), + format!("argument #{} of function '{fn_name}'", n + 1), Position::NONE, ) .into()); @@ -150,10 +150,7 @@ impl Engine { let (ns, sep) = ("", ""); format!( - "{}{}{} ({})", - ns, - sep, - fn_name, + "{ns}{sep}{fn_name} ({})", args.iter() .map(|a| if a.is::() { "&str | ImmutableString | String" @@ -493,7 +490,7 @@ impl Engine { let t0 = self.map_type_name(args[0].type_name()); let t1 = self.map_type_name(args[1].type_name()); - Err(ERR::ErrorIndexingType(format!("{} [{}]", t0, t1), pos).into()) + Err(ERR::ErrorIndexingType(format!("{t0} [{t1}]"), pos).into()) } // index setter function not found? @@ -505,7 +502,7 @@ impl Engine { let t1 = self.map_type_name(args[1].type_name()); let t2 = self.map_type_name(args[2].type_name()); - Err(ERR::ErrorIndexingType(format!("{} [{}] = {}", t0, t1, t2), pos).into()) + Err(ERR::ErrorIndexingType(format!("{t0} [{t1}] = {t2}"), pos).into()) } // Getter function not found? @@ -518,8 +515,7 @@ impl Engine { Err(ERR::ErrorDotExpr( format!( - "Unknown property '{}' - a getter is not registered for type '{}'", - prop, t0 + "Unknown property '{prop}' - a getter is not registered for type '{t0}'" ), pos, ) @@ -537,8 +533,7 @@ impl Engine { Err(ERR::ErrorDotExpr( format!( - "No writable property '{}' - a setter is not registered for type '{}' to handle '{}'", - prop, t0, t1 + "No writable property '{prop}' - a setter is not registered for type '{t0}' to handle '{t1}'" ), pos, ) @@ -586,7 +581,7 @@ impl Engine { ) -> RhaiResultOf<(Dynamic, bool)> { fn no_method_err(name: &str, pos: Position) -> RhaiResultOf<(Dynamic, bool)> { Err(ERR::ErrorRuntime( - (format!("'{0}' should not be called this way. Try {0}(...);", name)).into(), + format!("'{name}' should not be called this way. Try {name}(...);").into(), pos, ) .into()) diff --git a/src/func/script.rs b/src/func/script.rs index 5202e61a..eeb41693 100644 --- a/src/func/script.rs +++ b/src/func/script.rs @@ -161,9 +161,9 @@ impl Engine { // Error in sub function call ERR::ErrorInFunctionCall(name, src, err, ..) => { let fn_name = if src.is_empty() { - format!("{} < {}", name, fn_def.name) + format!("{name} < {}", fn_def.name) } else { - format!("{} @ '{}' < {}", name, src, fn_def.name) + format!("{name} @ '{src}' < {}", fn_def.name) }; make_error(fn_name, fn_def, global, err, pos) } diff --git a/src/module/mod.rs b/src/module/mod.rs index 969d2d58..9507fc16 100644 --- a/src/module/mod.rs +++ b/src/module/mod.rs @@ -135,7 +135,7 @@ impl FuncInfo { return if r == x { typ.into() } else { - format!("&mut {}", r).into() + format!("&mut {r}").into() }; } @@ -202,7 +202,7 @@ impl FuncInfo { }; let result: std::borrow::Cow = match seg.next() { Some(typ) => { - format!("{}: {}", name, FuncInfo::format_type(typ, false)).into() + format!("{name}: {}", FuncInfo::format_type(typ, false)).into() } None => name.into(), }; @@ -2016,12 +2016,11 @@ impl Module { return Err(crate::ERR::ErrorMismatchDataType( "".to_string(), if fn_ptr.is_anonymous() { - format!("cannot export closure in variable {}", _name) + format!("cannot export closure in variable {_name}") } else { format!( - "cannot export function pointer to local function '{}' in variable {}", - fn_ptr.fn_name(), - _name + "cannot export function pointer to local function '{}' in variable {_name}", + fn_ptr.fn_name() ) }, crate::Position::NONE, diff --git a/src/packages/arithmetic.rs b/src/packages/arithmetic.rs index 883b29e3..2347f451 100644 --- a/src/packages/arithmetic.rs +++ b/src/packages/arithmetic.rs @@ -24,7 +24,7 @@ macro_rules! gen_arithmetic_functions { #[rhai_fn(name = "+", return_raw)] pub fn add(x: $arg_type, y: $arg_type) -> RhaiResultOf<$arg_type> { if cfg!(not(feature = "unchecked")) { - x.checked_add(y).ok_or_else(|| make_err(format!("Addition overflow: {} + {}", x, y))) + x.checked_add(y).ok_or_else(|| make_err(format!("Addition overflow: {x} + {y}"))) } else { Ok(x + y) } @@ -32,7 +32,7 @@ macro_rules! gen_arithmetic_functions { #[rhai_fn(name = "-", return_raw)] pub fn subtract(x: $arg_type, y: $arg_type) -> RhaiResultOf<$arg_type> { if cfg!(not(feature = "unchecked")) { - x.checked_sub(y).ok_or_else(|| make_err(format!("Subtraction overflow: {} - {}", x, y))) + x.checked_sub(y).ok_or_else(|| make_err(format!("Subtraction overflow: {x} - {y}"))) } else { Ok(x - y) } @@ -40,7 +40,7 @@ macro_rules! gen_arithmetic_functions { #[rhai_fn(name = "*", return_raw)] pub fn multiply(x: $arg_type, y: $arg_type) -> RhaiResultOf<$arg_type> { if cfg!(not(feature = "unchecked")) { - x.checked_mul(y).ok_or_else(|| make_err(format!("Multiplication overflow: {} * {}", x, y))) + x.checked_mul(y).ok_or_else(|| make_err(format!("Multiplication overflow: {x} * {y}"))) } else { Ok(x * y) } @@ -50,9 +50,9 @@ macro_rules! gen_arithmetic_functions { if cfg!(not(feature = "unchecked")) { // Detect division by zero if y == 0 { - Err(make_err(format!("Division by zero: {} / {}", x, y))) + Err(make_err(format!("Division by zero: {x} / {y}"))) } else { - x.checked_div(y).ok_or_else(|| make_err(format!("Division overflow: {} / {}", x, y))) + x.checked_div(y).ok_or_else(|| make_err(format!("Division overflow: {x} / {y}"))) } } else { Ok(x / y) @@ -61,7 +61,7 @@ macro_rules! gen_arithmetic_functions { #[rhai_fn(name = "%", return_raw)] pub fn modulo(x: $arg_type, y: $arg_type) -> RhaiResultOf<$arg_type> { if cfg!(not(feature = "unchecked")) { - x.checked_rem(y).ok_or_else(|| make_err(format!("Modulo division by zero or overflow: {} % {}", x, y))) + x.checked_rem(y).ok_or_else(|| make_err(format!("Modulo division by zero or overflow: {x} % {y}"))) } else { Ok(x % y) } @@ -70,11 +70,11 @@ macro_rules! gen_arithmetic_functions { pub fn power(x: $arg_type, y: INT) -> RhaiResultOf<$arg_type> { if cfg!(not(feature = "unchecked")) { if cfg!(not(feature = "only_i32")) && y > (u32::MAX as INT) { - Err(make_err(format!("Integer raised to too large an index: {} ~ {}", x, y))) + Err(make_err(format!("Integer raised to too large an index: {x} ** {y}"))) } else if y < 0 { - Err(make_err(format!("Integer raised to a negative index: {} ~ {}", x, y))) + Err(make_err(format!("Integer raised to a negative index: {x} ** {y}"))) } else { - x.checked_pow(y as u32).ok_or_else(|| make_err(format!("Exponential overflow: {} ~ {}", x, y))) + x.checked_pow(y as u32).ok_or_else(|| make_err(format!("Exponential overflow: {x} ** {y}"))) } } else { Ok(x.pow(y as u32)) @@ -85,11 +85,11 @@ macro_rules! gen_arithmetic_functions { pub fn shift_left(x: $arg_type, y: INT) -> RhaiResultOf<$arg_type> { if cfg!(not(feature = "unchecked")) { if cfg!(not(feature = "only_i32")) && y > (u32::MAX as INT) { - Err(make_err(format!("Left-shift by too many bits: {} << {}", x, y))) + Err(make_err(format!("Left-shift by too many bits: {x} << {y}"))) } else if y < 0 { - Err(make_err(format!("Left-shift by a negative number: {} << {}", x, y))) + Err(make_err(format!("Left-shift by a negative number: {x} << {y}"))) } else { - x.checked_shl(y as u32).ok_or_else(|| make_err(format!("Left-shift by too many bits: {} << {}", x, y))) + x.checked_shl(y as u32).ok_or_else(|| make_err(format!("Left-shift by too many bits: {x} << {y}"))) } } else { Ok(x << y) @@ -99,11 +99,11 @@ macro_rules! gen_arithmetic_functions { pub fn shift_right(x: $arg_type, y: INT) -> RhaiResultOf<$arg_type> { if cfg!(not(feature = "unchecked")) { if cfg!(not(feature = "only_i32")) && y > (u32::MAX as INT) { - Err(make_err(format!("Right-shift by too many bits: {} >> {}", x, y))) + Err(make_err(format!("Right-shift by too many bits: {x} >> {y}"))) } else if y < 0 { - Err(make_err(format!("Right-shift by a negative number: {} >> {}", x, y))) + Err(make_err(format!("Right-shift by a negative number: {x} >> {y}"))) } else { - x.checked_shr(y as u32).ok_or_else(|| make_err(format!("Right-shift by too many bits: {} >> {}", x, y))) + x.checked_shr(y as u32).ok_or_else(|| make_err(format!("Right-shift by too many bits: {x} >> {y}"))) } } else { Ok(x >> y) @@ -151,7 +151,7 @@ macro_rules! gen_signed_functions { #[rhai_fn(name = "-", return_raw)] pub fn neg(x: $arg_type) -> RhaiResultOf<$arg_type> { if cfg!(not(feature = "unchecked")) { - x.checked_neg().ok_or_else(|| make_err(format!("Negation overflow: -{}", x))) + x.checked_neg().ok_or_else(|| make_err(format!("Negation overflow: -{x}"))) } else { Ok(-x) } @@ -164,7 +164,7 @@ macro_rules! gen_signed_functions { #[rhai_fn(return_raw)] pub fn abs(x: $arg_type) -> RhaiResultOf<$arg_type> { if cfg!(not(feature = "unchecked")) { - x.checked_abs().ok_or_else(|| make_err(format!("Negation overflow: -{}", x))) + x.checked_abs().ok_or_else(|| make_err(format!("Negation overflow: -{x}"))) } else { Ok(x.abs()) } @@ -372,8 +372,7 @@ mod f32_functions { pub fn pow_f_i(x: f32, y: INT) -> RhaiResultOf { if cfg!(not(feature = "unchecked")) && y > (i32::MAX as INT) { Err(make_err(format!( - "Number raised to too large an index: {} ~ {}", - x, y + "Number raised to too large an index: {x} ** {y}" ))) } else { Ok(x.powi(y as i32)) @@ -495,7 +494,7 @@ pub mod decimal_functions { pub fn add(x: Decimal, y: Decimal) -> RhaiResultOf { if cfg!(not(feature = "unchecked")) { x.checked_add(y) - .ok_or_else(|| make_err(format!("Addition overflow: {} + {}", x, y))) + .ok_or_else(|| make_err(format!("Addition overflow: {x} + {y}"))) } else { Ok(x + y) } @@ -504,7 +503,7 @@ pub mod decimal_functions { pub fn subtract(x: Decimal, y: Decimal) -> RhaiResultOf { if cfg!(not(feature = "unchecked")) { x.checked_sub(y) - .ok_or_else(|| make_err(format!("Subtraction overflow: {} - {}", x, y))) + .ok_or_else(|| make_err(format!("Subtraction overflow: {x} - {y}"))) } else { Ok(x - y) } @@ -513,7 +512,7 @@ pub mod decimal_functions { pub fn multiply(x: Decimal, y: Decimal) -> RhaiResultOf { if cfg!(not(feature = "unchecked")) { x.checked_mul(y) - .ok_or_else(|| make_err(format!("Multiplication overflow: {} * {}", x, y))) + .ok_or_else(|| make_err(format!("Multiplication overflow: {x} * {y}"))) } else { Ok(x * y) } @@ -523,10 +522,10 @@ pub mod decimal_functions { if cfg!(not(feature = "unchecked")) { // Detect division by zero if y == Decimal::zero() { - Err(make_err(format!("Division by zero: {} / {}", x, y))) + Err(make_err(format!("Division by zero: {x} / {y}"))) } else { x.checked_div(y) - .ok_or_else(|| make_err(format!("Division overflow: {} / {}", x, y))) + .ok_or_else(|| make_err(format!("Division overflow: {x} / {y}"))) } } else { Ok(x / y) @@ -535,12 +534,8 @@ pub mod decimal_functions { #[rhai_fn(skip, return_raw)] pub fn modulo(x: Decimal, y: Decimal) -> RhaiResultOf { if cfg!(not(feature = "unchecked")) { - x.checked_rem(y).ok_or_else(|| { - make_err(format!( - "Modulo division by zero or overflow: {} % {}", - x, y - )) - }) + x.checked_rem(y) + .ok_or_else(|| make_err(format!("Modulo division by zero or overflow: {x} % {y}"))) } else { Ok(x % y) } @@ -549,7 +544,7 @@ pub mod decimal_functions { pub fn power(x: Decimal, y: Decimal) -> RhaiResultOf { if cfg!(not(feature = "unchecked")) { x.checked_powd(y) - .ok_or_else(|| make_err(format!("Exponential overflow: {} + {}", x, y))) + .ok_or_else(|| make_err(format!("Exponential overflow: {x} ** {y}"))) } else { Ok(x.pow(y)) } diff --git a/src/packages/lang_core.rs b/src/packages/lang_core.rs index 72aca603..36a5486e 100644 --- a/src/packages/lang_core.rs +++ b/src/packages/lang_core.rs @@ -49,24 +49,21 @@ mod core_functions { /// ``` #[rhai_fn(name = "set_tag", set = "tag", return_raw)] pub fn set_tag(value: &mut Dynamic, tag: INT) -> RhaiResultOf<()> { - if tag < Tag::MIN as INT { + const TAG_MIN: Tag = Tag::MIN; + const TAG_MAX: Tag = Tag::MAX; + + if tag < TAG_MIN as INT { Err(ERR::ErrorArithmetic( format!( - "{} is too small to fit into a tag (must be between {} and {})", - tag, - Tag::MIN, - Tag::MAX + "{tag} is too small to fit into a tag (must be between {TAG_MIN} and {TAG_MAX})" ), Position::NONE, ) .into()) - } else if tag > Tag::MAX as INT { + } else if tag > TAG_MAX as INT { Err(ERR::ErrorArithmetic( format!( - "{} is too large to fit into a tag (must be between {} and {})", - tag, - Tag::MIN, - Tag::MAX + "{tag} is too large to fit into a tag (must be between {TAG_MIN} and {TAG_MAX})" ), Position::NONE, ) @@ -281,10 +278,8 @@ fn collect_fn_metadata( .for_each(|(.., f)| list.push(make_metadata(dict, namespace.into(), f).into())); for (ns, m) in module.iter_sub_modules() { let ns = format!( - "{}{}{}", - namespace, - crate::tokenizer::Token::DoubleColon.literal_syntax(), - ns + "{namespace}{}{ns}", + crate::tokenizer::Token::DoubleColon.literal_syntax() ); scan_module(list, dict, &ns, &**m, filter); } diff --git a/src/packages/math_basic.rs b/src/packages/math_basic.rs index 604ef992..f7c3c40f 100644 --- a/src/packages/math_basic.rs +++ b/src/packages/math_basic.rs @@ -139,16 +139,14 @@ mod int_functions { #[rhai_fn(name = "parse_int", return_raw)] pub fn parse_int_radix(string: &str, radix: INT) -> RhaiResultOf { if !(2..=36).contains(&radix) { - return Err(ERR::ErrorArithmetic( - format!("Invalid radix: '{}'", radix), - Position::NONE, - ) - .into()); + return Err( + ERR::ErrorArithmetic(format!("Invalid radix: '{radix}'"), Position::NONE).into(), + ); } INT::from_str_radix(string.trim(), radix as u32).map_err(|err| { ERR::ErrorArithmetic( - format!("Error parsing integer number '{}': {}", string, err), + format!("Error parsing integer number '{string}': {err}"), Position::NONE, ) .into() @@ -316,7 +314,7 @@ mod float_functions { pub fn f32_to_int(x: f32) -> RhaiResultOf { if cfg!(not(feature = "unchecked")) && (x > (INT::MAX as f32) || x < (INT::MIN as f32)) { Err( - ERR::ErrorArithmetic(format!("Integer overflow: to_int({})", x), Position::NONE) + ERR::ErrorArithmetic(format!("Integer overflow: to_int({x})"), Position::NONE) .into(), ) } else { @@ -328,7 +326,7 @@ mod float_functions { pub fn f64_to_int(x: f64) -> RhaiResultOf { if cfg!(not(feature = "unchecked")) && (x > (INT::MAX as f64) || x < (INT::MIN as f64)) { Err( - ERR::ErrorArithmetic(format!("Integer overflow: to_int({})", x), Position::NONE) + ERR::ErrorArithmetic(format!("Integer overflow: to_int({x})"), Position::NONE) .into(), ) } else { @@ -348,7 +346,7 @@ mod float_functions { pub fn parse_float(string: &str) -> RhaiResultOf { string.trim().parse::().map_err(|err| { ERR::ErrorArithmetic( - format!("Error parsing floating-point number '{}': {}", string, err), + format!("Error parsing floating-point number '{string}': {err}"), Position::NONE, ) .into() @@ -416,14 +414,14 @@ mod decimal_functions { #[rhai_fn(return_raw)] pub fn sqrt(x: Decimal) -> RhaiResultOf { x.sqrt() - .ok_or_else(|| make_err(format!("Error taking the square root of {}", x,))) + .ok_or_else(|| make_err(format!("Error taking the square root of {x}"))) } /// Return the exponential of the decimal number. #[rhai_fn(return_raw)] pub fn exp(x: Decimal) -> RhaiResultOf { if cfg!(not(feature = "unchecked")) { x.checked_exp() - .ok_or_else(|| make_err(format!("Exponential overflow: e ** {}", x,))) + .ok_or_else(|| make_err(format!("Exponential overflow: e ** {x}"))) } else { Ok(x.exp()) } @@ -433,7 +431,7 @@ mod decimal_functions { pub fn ln(x: Decimal) -> RhaiResultOf { if cfg!(not(feature = "unchecked")) { x.checked_ln() - .ok_or_else(|| make_err(format!("Error taking the natural log of {}", x))) + .ok_or_else(|| make_err(format!("Error taking the natural log of {x}"))) } else { Ok(x.ln()) } @@ -443,7 +441,7 @@ mod decimal_functions { pub fn log10(x: Decimal) -> RhaiResultOf { if cfg!(not(feature = "unchecked")) { x.checked_log10() - .ok_or_else(|| make_err(format!("Error taking the log of {}", x))) + .ok_or_else(|| make_err(format!("Error taking the log of {x}"))) } else { Ok(x.log10()) } @@ -471,8 +469,7 @@ mod decimal_functions { if cfg!(not(feature = "unchecked")) { if digits < 0 { return Err(make_err(format!( - "Invalid number of digits for rounding: {}", - digits + "Invalid number of digits for rounding: {digits}" ))); } if cfg!(not(feature = "only_i32")) && digits > (u32::MAX as INT) { @@ -489,8 +486,7 @@ mod decimal_functions { if cfg!(not(feature = "unchecked")) { if digits < 0 { return Err(make_err(format!( - "Invalid number of digits for rounding: {}", - digits + "Invalid number of digits for rounding: {digits}" ))); } if cfg!(not(feature = "only_i32")) && digits > (u32::MAX as INT) { @@ -507,8 +503,7 @@ mod decimal_functions { if cfg!(not(feature = "unchecked")) { if digits < 0 { return Err(make_err(format!( - "Invalid number of digits for rounding: {}", - digits + "Invalid number of digits for rounding: {digits}" ))); } if cfg!(not(feature = "only_i32")) && digits > (u32::MAX as INT) { @@ -525,8 +520,7 @@ mod decimal_functions { if cfg!(not(feature = "unchecked")) { if digits < 0 { return Err(make_err(format!( - "Invalid number of digits for rounding: {}", - digits + "Invalid number of digits for rounding: {digits}" ))); } if cfg!(not(feature = "only_i32")) && digits > (u32::MAX as INT) { @@ -543,8 +537,7 @@ mod decimal_functions { if cfg!(not(feature = "unchecked")) { if digits < 0 { return Err(make_err(format!( - "Invalid number of digits for rounding: {}", - digits + "Invalid number of digits for rounding: {digits}" ))); } if cfg!(not(feature = "only_i32")) && digits > (u32::MAX as INT) { @@ -572,7 +565,7 @@ mod decimal_functions { match n { Some(n) => Ok(n), _ => Err(ERR::ErrorArithmetic( - format!("Integer overflow: to_int({})", x), + format!("Integer overflow: to_int({x})"), Position::NONE, ) .into()), @@ -603,7 +596,7 @@ mod decimal_functions { .or_else(|_| Decimal::from_scientific(string)) .map_err(|err| { ERR::ErrorArithmetic( - format!("Error parsing decimal number '{}': {}", string, err), + format!("Error parsing decimal number '{string}': {err}"), Position::NONE, ) .into() @@ -616,7 +609,7 @@ mod decimal_functions { pub fn f32_to_decimal(x: f32) -> RhaiResultOf { Decimal::try_from(x).map_err(|_| { ERR::ErrorArithmetic( - format!("Cannot convert to Decimal: to_decimal({})", x), + format!("Cannot convert to Decimal: to_decimal({x})"), Position::NONE, ) .into() @@ -628,7 +621,7 @@ mod decimal_functions { pub fn f64_to_decimal(x: f64) -> RhaiResultOf { Decimal::try_from(x).map_err(|_| { ERR::ErrorArithmetic( - format!("Cannot convert to Decimal: to_decimal({})", x), + format!("Cannot convert to Decimal: to_decimal({x})"), Position::NONE, ) .into() @@ -640,7 +633,7 @@ mod decimal_functions { pub fn to_float(x: Decimal) -> RhaiResultOf { FLOAT::try_from(x).map_err(|_| { ERR::ErrorArithmetic( - format!("Cannot convert to floating-point: to_float({})", x), + format!("Cannot convert to floating-point: to_float({x})"), Position::NONE, ) .into() diff --git a/src/packages/string_basic.rs b/src/packages/string_basic.rs index a64317b2..6f8af72c 100644 --- a/src/packages/string_basic.rs +++ b/src/packages/string_basic.rs @@ -69,7 +69,7 @@ mod print_debug_functions { /// Convert the value of the `item` into a string in debug format. #[rhai_fn(name = "to_debug", pure)] pub fn to_debug_generic(ctx: NativeCallContext, item: &mut Dynamic) -> ImmutableString { - ctx.engine().map_type_name(&format!("{:?}", item)).into() + ctx.engine().map_type_name(&format!("{item:?}")).into() } /// Return the empty string. @@ -86,7 +86,7 @@ mod print_debug_functions { /// Convert the string into debug format. #[rhai_fn(name = "debug", name = "to_debug", pure)] pub fn debug_string(string: &mut ImmutableString) -> ImmutableString { - format!("{:?}", string).into() + format!("{string:?}").into() } /// Return the character into a string. @@ -97,7 +97,7 @@ mod print_debug_functions { /// Convert the string into debug format. #[rhai_fn(name = "debug", name = "to_debug")] pub fn debug_char(character: char) -> ImmutableString { - format!("{:?}", character).into() + format!("{character:?}").into() } /// Convert the function pointer into a string in debug format. @@ -109,12 +109,12 @@ mod print_debug_functions { /// Return the boolean value into a string. #[rhai_fn(name = "print", name = "to_string")] pub fn print_bool(value: bool) -> ImmutableString { - format!("{}", value).into() + value.to_string().into() } /// Convert the boolean value into a string in debug format. #[rhai_fn(name = "debug", name = "to_debug")] pub fn debug_bool(value: bool) -> ImmutableString { - format!("{:?}", value).into() + format!("{value:?}").into() } /// Return the empty string. @@ -146,13 +146,15 @@ mod print_debug_functions { #[cfg(not(feature = "no_float"))] #[rhai_fn(name = "debug", name = "to_debug")] pub fn debug_f64(number: f64) -> ImmutableString { - format!("{:?}", crate::ast::FloatWrapper::new(number)).into() + let number = crate::ast::FloatWrapper::new(number); + format!("{number:?}").into() } /// Convert the value of `number` into a string. #[cfg(not(feature = "no_float"))] #[rhai_fn(name = "debug", name = "to_debug")] pub fn debug_f32(number: f32) -> ImmutableString { - format!("{:?}", crate::ast::FloatWrapper::new(number)).into() + let number = crate::ast::FloatWrapper::new(number); + format!("{number:?}").into() } /// Convert the array into a string. @@ -215,13 +217,13 @@ mod print_debug_functions { #[export_module] mod number_formatting { fn to_hex(value: T) -> ImmutableString { - format!("{:x}", value).into() + format!("{value:x}").into() } fn to_octal(value: T) -> ImmutableString { - format!("{:o}", value).into() + format!("{value:o}").into() } fn to_binary(value: T) -> ImmutableString { - format!("{:b}", value).into() + format!("{value:b}").into() } /// Convert the `value` into a string in hex format. diff --git a/src/packages/string_more.rs b/src/packages/string_more.rs index c1ceebb3..edbdb4a6 100644 --- a/src/packages/string_more.rs +++ b/src/packages/string_more.rs @@ -30,7 +30,7 @@ mod string_functions { if s.is_empty() { string.clone() } else { - format!("{}{}", string, s).into() + format!("{string}{s}").into() } } #[rhai_fn(name = "+=", name = "append")] @@ -38,7 +38,7 @@ mod string_functions { let s = print_with_func(FUNC_TO_STRING, &ctx, &mut item); if !s.is_empty() { - *string = format!("{}{}", string, s).into(); + *string = format!("{string}{s}").into(); } } #[rhai_fn(name = "+", pure)] @@ -68,7 +68,7 @@ mod string_functions { } #[rhai_fn(name = "+")] pub fn add_prepend_char(character: char, string: &str) -> ImmutableString { - format!("{}{}", character, string).into() + format!("{character}{string}").into() } #[rhai_fn(name = "+")] diff --git a/src/packages/time_basic.rs b/src/packages/time_basic.rs index b8bfa175..16ade536 100644 --- a/src/packages/time_basic.rs +++ b/src/packages/time_basic.rs @@ -66,8 +66,7 @@ mod time_functions { if cfg!(not(feature = "unchecked")) && seconds > (INT::MAX as u64) { Err(make_arithmetic_err(format!( - "Integer overflow for timestamp.elapsed: {}", - seconds + "Integer overflow for timestamp.elapsed: {seconds}" ))) } else if timestamp > Instant::now() { Err(make_arithmetic_err("Time-stamp is later than now")) @@ -94,8 +93,7 @@ mod time_functions { if cfg!(not(feature = "unchecked")) && seconds > (INT::MAX as u64) { Err(make_arithmetic_err(format!( - "Integer overflow for timestamp duration: -{}", - seconds + "Integer overflow for timestamp duration: -{seconds}" ))) } else { Ok((-(seconds as INT)).into()) @@ -105,8 +103,7 @@ mod time_functions { if cfg!(not(feature = "unchecked")) && seconds > (INT::MAX as u64) { Err(make_arithmetic_err(format!( - "Integer overflow for timestamp duration: {}", - seconds + "Integer overflow for timestamp duration: {seconds}" ))) } else { Ok((seconds as INT).into()) @@ -122,16 +119,14 @@ mod time_functions { } else if cfg!(not(feature = "unchecked")) { if seconds > (INT::MAX as FLOAT) { Err(make_arithmetic_err(format!( - "Integer overflow for timestamp add: {}", - seconds + "Integer overflow for timestamp add: {seconds}" ))) } else { timestamp .checked_add(Duration::from_millis((seconds * 1000.0) as u64)) .ok_or_else(|| { make_arithmetic_err(format!( - "Timestamp overflow when adding {} second(s)", - seconds + "Timestamp overflow when adding {seconds} second(s)" )) }) } @@ -145,16 +140,14 @@ mod time_functions { } else if cfg!(not(feature = "unchecked")) { if seconds > (INT::MAX as FLOAT) { Err(make_arithmetic_err(format!( - "Integer overflow for timestamp add: {}", - seconds + "Integer overflow for timestamp add: {seconds}" ))) } else { timestamp .checked_sub(Duration::from_millis((seconds * 1000.0) as u64)) .ok_or_else(|| { make_arithmetic_err(format!( - "Timestamp overflow when adding {} second(s)", - seconds + "Timestamp overflow when adding {seconds} second(s)" )) }) } @@ -195,8 +188,7 @@ mod time_functions { .checked_add(Duration::from_secs(seconds as u64)) .ok_or_else(|| { make_arithmetic_err(format!( - "Timestamp overflow when adding {} second(s)", - seconds + "Timestamp overflow when adding {seconds} second(s)" )) }) } else { @@ -211,8 +203,7 @@ mod time_functions { .checked_sub(Duration::from_secs(seconds as u64)) .ok_or_else(|| { make_arithmetic_err(format!( - "Timestamp overflow when adding {} second(s)", - seconds + "Timestamp overflow when adding {seconds} second(s)" )) }) } else { diff --git a/src/parser.rs b/src/parser.rs index 663cbed1..f6674cda 100644 --- a/src/parser.rs +++ b/src/parser.rs @@ -536,7 +536,7 @@ impl Engine { Token::EOF => { return Err(PERR::MissingToken( Token::RightParen.into(), - format!("to close the arguments list of this function call '{}'", id), + format!("to close the arguments list of this function call '{id}'"), ) .into_err(*token_pos)) } @@ -677,7 +677,7 @@ impl Engine { (Token::EOF, pos) => { return Err(PERR::MissingToken( Token::RightParen.into(), - format!("to close the arguments list of this function call '{}'", id), + format!("to close the arguments list of this function call '{id}'"), ) .into_err(*pos)) } @@ -687,7 +687,7 @@ impl Engine { (.., pos) => { return Err(PERR::MissingToken( Token::Comma.into(), - format!("to separate the arguments to function call '{}'", id), + format!("to separate the arguments to function call '{id}'"), ) .into_err(*pos)) } @@ -1011,10 +1011,7 @@ impl Engine { (.., pos) => { return Err(PERR::MissingToken( Token::Colon.into(), - format!( - "to follow the property '{}' in this object map literal", - name - ), + format!("to follow the property '{name}' in this object map literal"), ) .into_err(pos)) } @@ -1609,7 +1606,7 @@ impl Engine { ), // Cannot access to `this` as a variable not in a function scope _ if &*s == KEYWORD_THIS => { - let msg = format!("'{}' can only be used in functions", s); + let msg = format!("'{s}' can only be used in functions"); return Err( LexError::ImproperSymbol(s.to_string(), msg).into_err(settings.pos) ); @@ -1862,9 +1859,7 @@ impl Engine { #[cfg(feature = "no_float")] return None; }) - .ok_or_else(|| { - LexError::MalformedNumber(format!("-{}", num)).into_err(pos) - }), + .ok_or_else(|| LexError::MalformedNumber(format!("-{num}")).into_err(pos)), // Negative float #[cfg(not(feature = "no_float"))] @@ -3479,7 +3474,7 @@ impl Engine { let mut params = StaticVec::new_const(); if !no_params { - let sep_err = format!("to separate the parameters of function '{}'", name); + let sep_err = format!("to separate the parameters of function '{name}'"); loop { match input.next().expect(NEVER_ENDS) { @@ -3497,7 +3492,7 @@ impl Engine { (.., pos) => { return Err(PERR::MissingToken( Token::RightParen.into(), - format!("to close the parameters list of function '{}'", name), + format!("to close the parameters list of function '{name}'"), ) .into_err(pos)) } diff --git a/src/tokenizer.rs b/src/tokenizer.rs index 885960a9..a13de181 100644 --- a/src/tokenizer.rs +++ b/src/tokenizer.rs @@ -2406,7 +2406,7 @@ impl<'a> Iterator for TokenIterator<'a> { (.., true) => unreachable!("no custom operators"), // Reserved keyword that is not custom and disabled. (token, false) if !self.engine.disabled_symbols.is_empty() && self.engine.disabled_symbols.contains(token) => { - let msg = format!("reserved {} '{}' is disabled", if is_valid_identifier(token.chars()) { "keyword"} else {"symbol"}, token); + let msg = format!("reserved {} '{token}' is disabled", if is_valid_identifier(token.chars()) { "keyword"} else {"symbol"}); Token::LexError(LERR::ImproperSymbol(s.to_string(), msg).into()) }, // Reserved keyword/operator that is not custom. diff --git a/src/types/error.rs b/src/types/error.rs index 47fb8274..9c0133f4 100644 --- a/src/types/error.rs +++ b/src/types/error.rs @@ -341,7 +341,7 @@ impl EvalAltResult { pub(crate) fn dump_fields(&self, map: &mut crate::Map) { map.insert( "error".into(), - format!("{:?}", self) + format!("{self:?}") .split('(') .next() .expect("`ErrorXXX(...)`") diff --git a/tests/custom_syntax.rs b/tests/custom_syntax.rs index 5d4cb113..7ba2fc59 100644 --- a/tests/custom_syntax.rs +++ b/tests/custom_syntax.rs @@ -45,7 +45,7 @@ fn test_custom_syntax() -> Result<(), Box> { ">=" => count < max, "==" => count != max, "!=" => count == max, - _ => return Err(format!("Unsupported operator: {}", op).into()), + _ => return Err(format!("Unsupported operator: {op}").into()), }; if done { @@ -63,7 +63,7 @@ fn test_custom_syntax() -> Result<(), Box> { context .scope_mut() - .push(format!("{}{}", var_name, count), count); + .push(format!("{var_name}{count}"), count); let stop = !context .eval_expression_tree(condition)? @@ -189,7 +189,7 @@ fn test_custom_syntax() -> Result<(), Box> { context.scope_mut().set_value(var_name.to_string(), value); Ok(Dynamic::UNIT) } else { - Err(format!("variable {} is constant", var_name).into()) + Err(format!("variable {var_name} is constant").into()) } }, )?; diff --git a/tests/native.rs b/tests/native.rs index 22d005a1..ac5c75b1 100644 --- a/tests/native.rs +++ b/tests/native.rs @@ -68,11 +68,11 @@ fn test_native_overload() -> Result<(), Box> { .register_fn( "+", |s1: ImmutableString, s2: ImmutableString| -> ImmutableString { - format!("{}***{}", s1, s2).into() + format!("{s1}***{s2}").into() }, ) .register_fn("+", |s1: ImmutableString, _: ()| -> ImmutableString { - format!("{} Foo!", s1).into() + format!("{s1} Foo!").into() }); assert_eq!( diff --git a/tests/optimizer.rs b/tests/optimizer.rs index da8ecd68..d231540b 100644 --- a/tests/optimizer.rs +++ b/tests/optimizer.rs @@ -81,21 +81,21 @@ fn test_optimizer_parse() -> Result<(), Box> { let ast = engine.compile("{ const DECISION = false; if DECISION { 42 } else { 123 } }")?; assert_eq!( - format!("{:?}", ast), + format!("{ast:?}"), r#"AST { source: "", doc: "", resolver: None, body: [Expr(123 @ 1:53)] }"# ); let ast = engine.compile("const DECISION = false; if DECISION { 42 } else { 123 }")?; assert_eq!( - format!("{:?}", ast), + format!("{ast:?}"), r#"AST { source: "", doc: "", resolver: None, body: [Var(("DECISION" @ 1:7, false @ 1:18, None), CONSTANT, 1:1), Expr(123 @ 1:51)] }"# ); let ast = engine.compile("if 1 == 2 { 42 }")?; assert_eq!( - format!("{:?}", ast), + format!("{ast:?}"), r#"AST { source: "", doc: "", resolver: None, body: [] }"# ); @@ -104,14 +104,14 @@ fn test_optimizer_parse() -> Result<(), Box> { let ast = engine.compile("abs(-42)")?; assert_eq!( - format!("{:?}", ast), + format!("{ast:?}"), r#"AST { source: "", doc: "", resolver: None, body: [Expr(42 @ 1:1)] }"# ); let ast = engine.compile("NUMBER")?; assert_eq!( - format!("{:?}", ast), + format!("{ast:?}"), r#"AST { source: "", doc: "", resolver: None, body: [Expr(Variable(NUMBER) @ 1:1)] }"# ); @@ -123,7 +123,7 @@ fn test_optimizer_parse() -> Result<(), Box> { let ast = engine.compile("NUMBER")?; assert_eq!( - format!("{:?}", ast), + format!("{ast:?}"), r#"AST { source: "", doc: "", resolver: None, body: [Expr(42 @ 1:1)] }"# ); diff --git a/tests/plugins.rs b/tests/plugins.rs index 85833a54..a5355d07 100644 --- a/tests/plugins.rs +++ b/tests/plugins.rs @@ -70,7 +70,7 @@ macro_rules! reg_functions { } fn make_greeting(n: impl std::fmt::Display) -> String { - format!("{} kitties", n) + format!("{n} kitties") } gen_unary_functions!(greet = make_greeting(INT, bool, char) -> String); diff --git a/tests/print.rs b/tests/print.rs index ac7dbcef..820cce58 100644 --- a/tests/print.rs +++ b/tests/print.rs @@ -39,14 +39,12 @@ fn test_print_debug() -> Result<(), Box> { let mut engine = Engine::new(); engine - .on_print(move |s| log1.write().unwrap().push(format!("entry: {}", s))) + .on_print(move |s| log1.write().unwrap().push(format!("entry: {s}"))) .on_debug(move |s, src, pos| { - log2.write().unwrap().push(format!( - "DEBUG of {} at {:?}: {}", - src.unwrap_or("unknown"), - pos, - s - )) + let src = src.unwrap_or("unknown"); + log2.write() + .unwrap() + .push(format!("DEBUG of {src} at {pos:?}: {s}")) }); // Evaluate script diff --git a/tests/serde.rs b/tests/serde.rs index 2d32ed3d..5df11139 100644 --- a/tests/serde.rs +++ b/tests/serde.rs @@ -744,7 +744,7 @@ fn test_serde_json() -> serde_json::Result<()> { let a = m.remove("b").unwrap().cast::(); assert_eq!(a.len(), 3); - assert_eq!(format!("{:?}", a), "[1, 2, 3]"); + assert_eq!(format!("{a:?}"), "[1, 2, 3]"); Ok(()) }