Use identifiers in format!

This commit is contained in:
Stephen Chung 2022-08-11 19:01:23 +08:00
parent ceaf9fab1b
commit be448dfe4d
36 changed files with 164 additions and 206 deletions

View File

@ -131,7 +131,7 @@ pub fn inner_item_attributes<T: ExportedParams>(
{ {
return Err(syn::Error::new( return Err(syn::Error::new(
duplicate.span(), duplicate.span(),
format!("duplicated attribute '{}'", attr_name), format!("duplicated attribute '{attr_name}'"),
)); ));
} }

View File

@ -57,10 +57,10 @@ impl FnSpecialAccess {
match self { match self {
FnSpecialAccess::None => None, FnSpecialAccess::None => None,
FnSpecialAccess::Property(Property::Get(ref g)) => { 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)) => { 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(( FnSpecialAccess::Index(Index::Get) => Some((
FN_IDX_GET.to_string(), FN_IDX_GET.to_string(),
@ -255,7 +255,7 @@ impl ExportedParams for ExportedFnParams {
(attr, ..) => { (attr, ..) => {
return Err(syn::Error::new( return Err(syn::Error::new(
key.span(), key.span(),
format!("unknown attribute '{}'", attr), format!("unknown attribute '{attr}'"),
)) ))
} }
} }
@ -748,7 +748,7 @@ impl ExportedFn {
let str_type_path = syn::parse2::<syn::Path>(quote! { str }).unwrap(); let str_type_path = syn::parse2::<syn::Path>(quote! { str }).unwrap();
let string_type_path = syn::parse2::<syn::Path>(quote! { String }).unwrap(); let string_type_path = syn::parse2::<syn::Path>(quote! { String }).unwrap();
for (i, arg) in self.arg_list().enumerate().skip(skip_first_arg as usize) { 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_string;
let is_ref; let is_ref;
match arg { match arg {

View File

@ -72,7 +72,7 @@ impl ExportedParams for ExportedModParams {
(attr, ..) => { (attr, ..) => {
return Err(syn::Error::new( return Err(syn::Error::new(
key.span(), key.span(),
format!("unknown attribute '{}'", attr), format!("unknown attribute '{attr}'"),
)) ))
} }
} }

View File

@ -319,11 +319,11 @@ pub fn check_rename_collisions(fns: &[ExportedFn]) -> Result<(), syn::Error> {
if let Some(other_span) = renames.insert(key, current_span) { if let Some(other_span) = renames.insert(key, current_span) {
let mut err = syn::Error::new( let mut err = syn::Error::new(
current_span, current_span,
format!("duplicate Rhai signature for '{}'", fn_name), format!("duplicate Rhai signature for '{fn_name}'"),
); );
err.combine(syn::Error::new( err.combine(syn::Error::new(
other_span, other_span,
format!("duplicated function renamed '{}'", fn_name), format!("duplicated function renamed '{fn_name}'"),
)); ));
return Err(err); return Err(err);
} }
@ -332,10 +332,10 @@ pub fn check_rename_collisions(fns: &[ExportedFn]) -> Result<(), syn::Error> {
let ident = item_fn.name(); let ident = item_fn.name();
if let Some(other_span) = fn_defs.insert(ident.to_string(), ident.span()) { if let Some(other_span) = fn_defs.insert(ident.to_string(), ident.span()) {
let mut err = 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( err.combine(syn::Error::new(
other_span, other_span,
format!("duplicated function '{}'", ident), format!("duplicated function '{ident}'"),
)); ));
return Err(err); 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) { if let Some(fn_span) = renames.get(&key) {
let mut err = syn::Error::new( let mut err = syn::Error::new(
ident.span(), ident.span(),
format!("duplicate Rhai signature for '{}'", ident), format!("duplicate Rhai signature for '{ident}'"),
); );
err.combine(syn::Error::new( err.combine(syn::Error::new(
*fn_span, *fn_span,
format!("duplicated function '{}'", ident), format!("duplicated function '{ident}'"),
)); ));
return Err(err); return Err(err);
} }

View File

@ -88,10 +88,7 @@ mod function_tests {
}; };
let err = syn::parse2::<ExportedFn>(input_tokens).unwrap_err(); let err = syn::parse2::<ExportedFn>(input_tokens).unwrap_err();
assert_eq!( assert_eq!(format!("{err}"), "Rhai functions cannot return references");
format!("{}", err),
"Rhai functions cannot return references"
);
} }
#[test] #[test]
@ -101,7 +98,7 @@ mod function_tests {
}; };
let err = syn::parse2::<ExportedFn>(input_tokens).unwrap_err(); let err = syn::parse2::<ExportedFn>(input_tokens).unwrap_err();
assert_eq!(format!("{}", err), "Rhai functions cannot return pointers"); assert_eq!(format!("{err}"), "Rhai functions cannot return pointers");
} }
#[test] #[test]
@ -112,7 +109,7 @@ mod function_tests {
let err = syn::parse2::<ExportedFn>(input_tokens).unwrap_err(); let err = syn::parse2::<ExportedFn>(input_tokens).unwrap_err();
assert_eq!( assert_eq!(
format!("{}", err), format!("{err}"),
"references from Rhai in this position must be mutable" "references from Rhai in this position must be mutable"
); );
} }
@ -125,7 +122,7 @@ mod function_tests {
let err = syn::parse2::<ExportedFn>(input_tokens).unwrap_err(); let err = syn::parse2::<ExportedFn>(input_tokens).unwrap_err();
assert_eq!( assert_eq!(
format!("{}", err), format!("{err}"),
"function parameters other than the first one cannot be passed by reference" "function parameters other than the first one cannot be passed by reference"
); );
} }
@ -138,7 +135,7 @@ mod function_tests {
let err = syn::parse2::<ExportedFn>(input_tokens).unwrap_err(); let err = syn::parse2::<ExportedFn>(input_tokens).unwrap_err();
assert_eq!( assert_eq!(
format!("{}", err), format!("{err}"),
"function parameters other than the first one cannot be passed by reference" "function parameters other than the first one cannot be passed by reference"
); );
} }

View File

@ -107,7 +107,7 @@ mod mut_opaque_ref {
StatusMessage { StatusMessage {
is_ok, is_ok,
os_code: Some(os_code), os_code: Some(os_code),
message: format!("OS Code {}", os_code), message: format!("OS Code {os_code}"),
} }
} }

View File

@ -127,7 +127,7 @@ pub mod mut_opaque_ref_module {
StatusMessage { StatusMessage {
is_ok, is_ok,
os_code: Some(os_code), os_code: Some(os_code),
message: format!("OS Code {}", os_code), message: format!("OS Code {os_code}"),
} }
} }

View File

@ -258,9 +258,8 @@ impl Engine {
return Err(LexError::ImproperSymbol( return Err(LexError::ImproperSymbol(
s.to_string(), s.to_string(),
format!( format!(
"Improper symbol for custom syntax at position #{}: '{}'", "Improper symbol for custom syntax at position #{}: '{s}'",
segments.len() + 1, segments.len() + 1,
s
), ),
) )
.into_err(Position::NONE)); .into_err(Position::NONE));
@ -282,9 +281,8 @@ impl Engine {
return Err(LexError::ImproperSymbol( return Err(LexError::ImproperSymbol(
s.to_string(), s.to_string(),
format!( format!(
"Improper symbol for custom syntax at position #{}: '{}'", "Improper symbol for custom syntax at position #{}: '{s}'",
segments.len() + 1, segments.len() + 1,
s
), ),
) )
.into_err(Position::NONE)); .into_err(Position::NONE));

View File

@ -181,7 +181,7 @@ impl Engine {
if self.disabled_symbols.is_empty() if self.disabled_symbols.is_empty()
|| !self.disabled_symbols.contains(&*token.syntax()) || !self.disabled_symbols.contains(&*token.syntax())
{ {
return Err(format!("'{}' is a reserved keyword", keyword)); return Err(format!("'{keyword}' is a reserved keyword"));
} }
} }
// Active standard symbols cannot be made custom // Active standard symbols cannot be made custom
@ -189,7 +189,7 @@ impl Engine {
if self.disabled_symbols.is_empty() if self.disabled_symbols.is_empty()
|| !self.disabled_symbols.contains(&*token.syntax()) || !self.disabled_symbols.contains(&*token.syntax())
{ {
return Err(format!("'{}' is a reserved operator", keyword)); return Err(format!("'{keyword}' is a reserved operator"));
} }
} }
// Active standard symbols cannot be made custom // Active standard symbols cannot be made custom
@ -197,7 +197,7 @@ impl Engine {
if self.disabled_symbols.is_empty() if self.disabled_symbols.is_empty()
|| !self.disabled_symbols.contains(&*token.syntax()) => || !self.disabled_symbols.contains(&*token.syntax()) =>
{ {
return Err(format!("'{}' is a reserved symbol", keyword)) return Err(format!("'{keyword}' is a reserved symbol"))
} }
// Disabled symbols are OK // Disabled symbols are OK
Some(_) => (), Some(_) => (),

View File

@ -1037,7 +1037,7 @@ impl Engine {
#[cfg(not(feature = "no_module"))] #[cfg(not(feature = "no_module"))]
for (name, m) in &self.global_sub_modules { 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( signatures.extend(

View File

@ -150,7 +150,7 @@ impl Engine {
return if x == r { return if x == r {
name.into() name.into()
} else { } else {
format!("&mut {}", r).into() format!("&mut {r}").into()
}; };
} }

View File

@ -476,7 +476,7 @@ impl fmt::Debug for Expr {
write!(f, "{}{}", x.1, Token::DoubleColon.literal_syntax())?; write!(f, "{}{}", x.1, Token::DoubleColon.literal_syntax())?;
let pos = x.1.position(); let pos = x.1.position();
if !pos.is_none() { if !pos.is_none() {
display_pos = format!(" @ {:?}", pos); display_pos = format!(" @ {pos:?}");
} }
} }
f.write_str(&x.3)?; f.write_str(&x.3)?;
@ -490,7 +490,7 @@ impl fmt::Debug for Expr {
Self::Stmt(x) => { Self::Stmt(x) => {
let pos = x.span(); let pos = x.span();
if !pos.is_none() { if !pos.is_none() {
display_pos = format!(" @ {:?}", pos); display_pos = format!(" @ {pos:?}");
} }
f.write_str("ExprStmtBlock")?; f.write_str("ExprStmtBlock")?;
f.debug_list().entries(x.iter()).finish() 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::FnCall(x, ..) => fmt::Debug::fmt(x, f),
Self::Index(x, options, pos) => { Self::Index(x, options, pos) => {
if !pos.is_none() { if !pos.is_none() {
display_pos = format!(" @ {:?}", pos); display_pos = format!(" @ {pos:?}");
} }
let mut f = f.debug_struct("Index"); let mut f = f.debug_struct("Index");
@ -511,7 +511,7 @@ impl fmt::Debug for Expr {
} }
Self::Dot(x, options, pos) => { Self::Dot(x, options, pos) => {
if !pos.is_none() { if !pos.is_none() {
display_pos = format!(" @ {:?}", pos); display_pos = format!(" @ {pos:?}");
} }
let mut f = f.debug_struct("Dot"); let mut f = f.debug_struct("Dot");
@ -531,7 +531,7 @@ impl fmt::Debug for Expr {
}; };
if !pos.is_none() { if !pos.is_none() {
display_pos = format!(" @ {:?}", pos); display_pos = format!(" @ {pos:?}");
} }
f.debug_struct(op_name) f.debug_struct(op_name)

View File

@ -20,7 +20,7 @@ fn print_source(lines: &[String], pos: Position, offset: usize, window: (usize,
let line = pos.line().unwrap() - 1; let line = pos.line().unwrap() - 1;
let start = if line >= window.0 { line - window.0 } else { 0 }; let start = if line >= window.0 { line - window.0 } else { 0 };
let end = usize::min(line + window.1, lines.len() - 1); 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 // Print error position
if start >= end { if start >= end {

View File

@ -260,7 +260,7 @@ mod sample_functions {
/// print(result); // prints "42 123" /// print(result); // prints "42 123"
/// ``` /// ```
pub fn test(x: INT, y: INT) -> String { pub fn test(x: INT, y: INT) -> String {
format!("{} {}", x, y) format!("{x} {y}")
} }
/// This is a sample method for integers. /// This is a sample method for integers.

View File

@ -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_error(input: &str, mut err: EvalAltResult) {
fn eprint_line(lines: &[&str], pos: Position, err_msg: &str) { fn eprint_line(lines: &[&str], pos: Position, err_msg: &str) {
let line = pos.line().unwrap(); let line = pos.line().unwrap();
let line_no = format!("{}: ", line); let line_no = format!("{line}: ");
eprintln!("{}{}", line_no, lines[line - 1]); eprintln!("{}{}", line_no, lines[line - 1]);
eprintln!( eprintln!(

View File

@ -82,7 +82,7 @@ impl Engine {
let sep = crate::tokenizer::Token::DoubleColon.literal_syntax(); let sep = crate::tokenizer::Token::DoubleColon.literal_syntax();
Err(ERR::ErrorVariableNotFound( Err(ERR::ErrorVariableNotFound(
format!("{}{}{}", namespace, sep, var_name), format!("{namespace}{sep}{var_name}"),
namespace.position(), namespace.position(),
) )
.into()) .into())
@ -106,7 +106,7 @@ impl Engine {
let sep = crate::tokenizer::Token::DoubleColon.literal_syntax(); let sep = crate::tokenizer::Token::DoubleColon.literal_syntax();
return Err(ERR::ErrorVariableNotFound( return Err(ERR::ErrorVariableNotFound(
format!("{}{}{}", namespace, sep, var_name), format!("{namespace}{sep}{var_name}"),
namespace.position(), namespace.position(),
) )
.into()); .into());
@ -496,7 +496,7 @@ impl Engine {
// The key should exist, unless the AST is compiled in a different 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(|| { let custom_def = self.custom_syntax.get(key_token).ok_or_else(|| {
Box::new(ERR::ErrorCustomSyntax( 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(), custom.tokens.iter().map(<_>::to_string).collect(),
*pos, *pos,
)) ))

View File

@ -642,7 +642,7 @@ impl Engine {
#[cfg(not(feature = "unchecked"))] #[cfg(not(feature = "unchecked"))]
if x > INT::MAX as usize { if x > INT::MAX as usize {
loop_result = Err(ERR::ErrorArithmetic( loop_result = Err(ERR::ErrorArithmetic(
format!("for-loop counter overflow: {}", x), format!("for-loop counter overflow: {x}"),
counter.pos, counter.pos,
) )
.into()); .into());

View File

@ -212,7 +212,7 @@ pub fn get_builtin_binary_op_fn(op: &str, x: &Dynamic, y: &Dynamic) -> Option<Fn
"+" => Some(|_, args| { "+" => Some(|_, args| {
let x = args[0].as_char().expect(BUILTIN); let x = args[0].as_char().expect(BUILTIN);
let y = &*args[1].read_lock::<ImmutableString>().expect(BUILTIN); let y = &*args[1].read_lock::<ImmutableString>().expect(BUILTIN);
Ok(format!("{}{}", x, y).into()) Ok(format!("{x}{y}").into())
}), }),
"==" => Some(impl_op!(get_s1s2(==))), "==" => Some(impl_op!(get_s1s2(==))),
"!=" => 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<Fn
"+" => Some(|_, args| { "+" => Some(|_, args| {
let x = args[0].as_char().expect(BUILTIN); let x = args[0].as_char().expect(BUILTIN);
let y = args[1].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)),
"!=" => 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 { return match op {
"+=" => Some(|_, args| { "+=" => Some(|_, args| {
let y = args[1].as_char().expect(BUILTIN); let y = args[1].as_char().expect(BUILTIN);
let mut x = args[0].write_lock::<Dynamic>().expect(BUILTIN); let x = &mut *args[0].write_lock::<Dynamic>().expect(BUILTIN);
Ok((*x = format!("{}{}", *x, y).into()).into()) Ok((*x = format!("{x}{y}").into()).into())
}), }),
_ => None, _ => None,
}; };

View File

@ -118,7 +118,7 @@ pub fn ensure_no_data_race(
.find(|(.., a)| a.is_locked()) .find(|(.., a)| a.is_locked())
{ {
return Err(ERR::ErrorDataRace( return Err(ERR::ErrorDataRace(
format!("argument #{} of function '{}'", n + 1, fn_name), format!("argument #{} of function '{fn_name}'", n + 1),
Position::NONE, Position::NONE,
) )
.into()); .into());
@ -150,10 +150,7 @@ impl Engine {
let (ns, sep) = ("", ""); let (ns, sep) = ("", "");
format!( format!(
"{}{}{} ({})", "{ns}{sep}{fn_name} ({})",
ns,
sep,
fn_name,
args.iter() args.iter()
.map(|a| if a.is::<ImmutableString>() { .map(|a| if a.is::<ImmutableString>() {
"&str | ImmutableString | String" "&str | ImmutableString | String"
@ -493,7 +490,7 @@ impl Engine {
let t0 = self.map_type_name(args[0].type_name()); let t0 = self.map_type_name(args[0].type_name());
let t1 = self.map_type_name(args[1].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? // index setter function not found?
@ -505,7 +502,7 @@ impl Engine {
let t1 = self.map_type_name(args[1].type_name()); let t1 = self.map_type_name(args[1].type_name());
let t2 = self.map_type_name(args[2].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? // Getter function not found?
@ -518,8 +515,7 @@ impl Engine {
Err(ERR::ErrorDotExpr( Err(ERR::ErrorDotExpr(
format!( format!(
"Unknown property '{}' - a getter is not registered for type '{}'", "Unknown property '{prop}' - a getter is not registered for type '{t0}'"
prop, t0
), ),
pos, pos,
) )
@ -537,8 +533,7 @@ impl Engine {
Err(ERR::ErrorDotExpr( Err(ERR::ErrorDotExpr(
format!( format!(
"No writable property '{}' - a setter is not registered for type '{}' to handle '{}'", "No writable property '{prop}' - a setter is not registered for type '{t0}' to handle '{t1}'"
prop, t0, t1
), ),
pos, pos,
) )
@ -586,7 +581,7 @@ impl Engine {
) -> RhaiResultOf<(Dynamic, bool)> { ) -> RhaiResultOf<(Dynamic, bool)> {
fn no_method_err(name: &str, pos: Position) -> RhaiResultOf<(Dynamic, bool)> { fn no_method_err(name: &str, pos: Position) -> RhaiResultOf<(Dynamic, bool)> {
Err(ERR::ErrorRuntime( 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, pos,
) )
.into()) .into())

View File

@ -161,9 +161,9 @@ impl Engine {
// Error in sub function call // Error in sub function call
ERR::ErrorInFunctionCall(name, src, err, ..) => { ERR::ErrorInFunctionCall(name, src, err, ..) => {
let fn_name = if src.is_empty() { let fn_name = if src.is_empty() {
format!("{} < {}", name, fn_def.name) format!("{name} < {}", fn_def.name)
} else { } else {
format!("{} @ '{}' < {}", name, src, fn_def.name) format!("{name} @ '{src}' < {}", fn_def.name)
}; };
make_error(fn_name, fn_def, global, err, pos) make_error(fn_name, fn_def, global, err, pos)
} }

View File

@ -135,7 +135,7 @@ impl FuncInfo {
return if r == x { return if r == x {
typ.into() typ.into()
} else { } else {
format!("&mut {}", r).into() format!("&mut {r}").into()
}; };
} }
@ -202,7 +202,7 @@ impl FuncInfo {
}; };
let result: std::borrow::Cow<str> = match seg.next() { let result: std::borrow::Cow<str> = match seg.next() {
Some(typ) => { Some(typ) => {
format!("{}: {}", name, FuncInfo::format_type(typ, false)).into() format!("{name}: {}", FuncInfo::format_type(typ, false)).into()
} }
None => name.into(), None => name.into(),
}; };
@ -2016,12 +2016,11 @@ impl Module {
return Err(crate::ERR::ErrorMismatchDataType( return Err(crate::ERR::ErrorMismatchDataType(
"".to_string(), "".to_string(),
if fn_ptr.is_anonymous() { if fn_ptr.is_anonymous() {
format!("cannot export closure in variable {}", _name) format!("cannot export closure in variable {_name}")
} else { } else {
format!( format!(
"cannot export function pointer to local function '{}' in variable {}", "cannot export function pointer to local function '{}' in variable {_name}",
fn_ptr.fn_name(), fn_ptr.fn_name()
_name
) )
}, },
crate::Position::NONE, crate::Position::NONE,

View File

@ -24,7 +24,7 @@ macro_rules! gen_arithmetic_functions {
#[rhai_fn(name = "+", return_raw)] #[rhai_fn(name = "+", return_raw)]
pub fn add(x: $arg_type, y: $arg_type) -> RhaiResultOf<$arg_type> { pub fn add(x: $arg_type, y: $arg_type) -> RhaiResultOf<$arg_type> {
if cfg!(not(feature = "unchecked")) { 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 { } else {
Ok(x + y) Ok(x + y)
} }
@ -32,7 +32,7 @@ macro_rules! gen_arithmetic_functions {
#[rhai_fn(name = "-", return_raw)] #[rhai_fn(name = "-", return_raw)]
pub fn subtract(x: $arg_type, y: $arg_type) -> RhaiResultOf<$arg_type> { pub fn subtract(x: $arg_type, y: $arg_type) -> RhaiResultOf<$arg_type> {
if cfg!(not(feature = "unchecked")) { 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 { } else {
Ok(x - y) Ok(x - y)
} }
@ -40,7 +40,7 @@ macro_rules! gen_arithmetic_functions {
#[rhai_fn(name = "*", return_raw)] #[rhai_fn(name = "*", return_raw)]
pub fn multiply(x: $arg_type, y: $arg_type) -> RhaiResultOf<$arg_type> { pub fn multiply(x: $arg_type, y: $arg_type) -> RhaiResultOf<$arg_type> {
if cfg!(not(feature = "unchecked")) { 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 { } else {
Ok(x * y) Ok(x * y)
} }
@ -50,9 +50,9 @@ macro_rules! gen_arithmetic_functions {
if cfg!(not(feature = "unchecked")) { if cfg!(not(feature = "unchecked")) {
// Detect division by zero // Detect division by zero
if y == 0 { if y == 0 {
Err(make_err(format!("Division by zero: {} / {}", x, y))) Err(make_err(format!("Division by zero: {x} / {y}")))
} else { } 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 { } else {
Ok(x / y) Ok(x / y)
@ -61,7 +61,7 @@ macro_rules! gen_arithmetic_functions {
#[rhai_fn(name = "%", return_raw)] #[rhai_fn(name = "%", return_raw)]
pub fn modulo(x: $arg_type, y: $arg_type) -> RhaiResultOf<$arg_type> { pub fn modulo(x: $arg_type, y: $arg_type) -> RhaiResultOf<$arg_type> {
if cfg!(not(feature = "unchecked")) { 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 { } else {
Ok(x % y) Ok(x % y)
} }
@ -70,11 +70,11 @@ macro_rules! gen_arithmetic_functions {
pub fn power(x: $arg_type, y: INT) -> RhaiResultOf<$arg_type> { pub fn power(x: $arg_type, y: INT) -> RhaiResultOf<$arg_type> {
if cfg!(not(feature = "unchecked")) { if cfg!(not(feature = "unchecked")) {
if cfg!(not(feature = "only_i32")) && y > (u32::MAX as INT) { 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 { } 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 { } 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 { } else {
Ok(x.pow(y as u32)) 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> { pub fn shift_left(x: $arg_type, y: INT) -> RhaiResultOf<$arg_type> {
if cfg!(not(feature = "unchecked")) { if cfg!(not(feature = "unchecked")) {
if cfg!(not(feature = "only_i32")) && y > (u32::MAX as INT) { 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 { } 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 { } 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 { } else {
Ok(x << y) Ok(x << y)
@ -99,11 +99,11 @@ macro_rules! gen_arithmetic_functions {
pub fn shift_right(x: $arg_type, y: INT) -> RhaiResultOf<$arg_type> { pub fn shift_right(x: $arg_type, y: INT) -> RhaiResultOf<$arg_type> {
if cfg!(not(feature = "unchecked")) { if cfg!(not(feature = "unchecked")) {
if cfg!(not(feature = "only_i32")) && y > (u32::MAX as INT) { 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 { } 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 { } 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 { } else {
Ok(x >> y) Ok(x >> y)
@ -151,7 +151,7 @@ macro_rules! gen_signed_functions {
#[rhai_fn(name = "-", return_raw)] #[rhai_fn(name = "-", return_raw)]
pub fn neg(x: $arg_type) -> RhaiResultOf<$arg_type> { pub fn neg(x: $arg_type) -> RhaiResultOf<$arg_type> {
if cfg!(not(feature = "unchecked")) { 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 { } else {
Ok(-x) Ok(-x)
} }
@ -164,7 +164,7 @@ macro_rules! gen_signed_functions {
#[rhai_fn(return_raw)] #[rhai_fn(return_raw)]
pub fn abs(x: $arg_type) -> RhaiResultOf<$arg_type> { pub fn abs(x: $arg_type) -> RhaiResultOf<$arg_type> {
if cfg!(not(feature = "unchecked")) { 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 { } else {
Ok(x.abs()) Ok(x.abs())
} }
@ -372,8 +372,7 @@ mod f32_functions {
pub fn pow_f_i(x: f32, y: INT) -> RhaiResultOf<f32> { pub fn pow_f_i(x: f32, y: INT) -> RhaiResultOf<f32> {
if cfg!(not(feature = "unchecked")) && y > (i32::MAX as INT) { if cfg!(not(feature = "unchecked")) && y > (i32::MAX as INT) {
Err(make_err(format!( Err(make_err(format!(
"Number raised to too large an index: {} ~ {}", "Number raised to too large an index: {x} ** {y}"
x, y
))) )))
} else { } else {
Ok(x.powi(y as i32)) Ok(x.powi(y as i32))
@ -495,7 +494,7 @@ pub mod decimal_functions {
pub fn add(x: Decimal, y: Decimal) -> RhaiResultOf<Decimal> { pub fn add(x: Decimal, y: Decimal) -> RhaiResultOf<Decimal> {
if cfg!(not(feature = "unchecked")) { if cfg!(not(feature = "unchecked")) {
x.checked_add(y) 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 { } else {
Ok(x + y) Ok(x + y)
} }
@ -504,7 +503,7 @@ pub mod decimal_functions {
pub fn subtract(x: Decimal, y: Decimal) -> RhaiResultOf<Decimal> { pub fn subtract(x: Decimal, y: Decimal) -> RhaiResultOf<Decimal> {
if cfg!(not(feature = "unchecked")) { if cfg!(not(feature = "unchecked")) {
x.checked_sub(y) 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 { } else {
Ok(x - y) Ok(x - y)
} }
@ -513,7 +512,7 @@ pub mod decimal_functions {
pub fn multiply(x: Decimal, y: Decimal) -> RhaiResultOf<Decimal> { pub fn multiply(x: Decimal, y: Decimal) -> RhaiResultOf<Decimal> {
if cfg!(not(feature = "unchecked")) { if cfg!(not(feature = "unchecked")) {
x.checked_mul(y) 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 { } else {
Ok(x * y) Ok(x * y)
} }
@ -523,10 +522,10 @@ pub mod decimal_functions {
if cfg!(not(feature = "unchecked")) { if cfg!(not(feature = "unchecked")) {
// Detect division by zero // Detect division by zero
if y == Decimal::zero() { if y == Decimal::zero() {
Err(make_err(format!("Division by zero: {} / {}", x, y))) Err(make_err(format!("Division by zero: {x} / {y}")))
} else { } else {
x.checked_div(y) 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 { } else {
Ok(x / y) Ok(x / y)
@ -535,12 +534,8 @@ pub mod decimal_functions {
#[rhai_fn(skip, return_raw)] #[rhai_fn(skip, return_raw)]
pub fn modulo(x: Decimal, y: Decimal) -> RhaiResultOf<Decimal> { pub fn modulo(x: Decimal, y: Decimal) -> RhaiResultOf<Decimal> {
if cfg!(not(feature = "unchecked")) { if cfg!(not(feature = "unchecked")) {
x.checked_rem(y).ok_or_else(|| { x.checked_rem(y)
make_err(format!( .ok_or_else(|| make_err(format!("Modulo division by zero or overflow: {x} % {y}")))
"Modulo division by zero or overflow: {} % {}",
x, y
))
})
} else { } else {
Ok(x % y) Ok(x % y)
} }
@ -549,7 +544,7 @@ pub mod decimal_functions {
pub fn power(x: Decimal, y: Decimal) -> RhaiResultOf<Decimal> { pub fn power(x: Decimal, y: Decimal) -> RhaiResultOf<Decimal> {
if cfg!(not(feature = "unchecked")) { if cfg!(not(feature = "unchecked")) {
x.checked_powd(y) 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 { } else {
Ok(x.pow(y)) Ok(x.pow(y))
} }

View File

@ -49,24 +49,21 @@ mod core_functions {
/// ``` /// ```
#[rhai_fn(name = "set_tag", set = "tag", return_raw)] #[rhai_fn(name = "set_tag", set = "tag", return_raw)]
pub fn set_tag(value: &mut Dynamic, tag: INT) -> RhaiResultOf<()> { 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( Err(ERR::ErrorArithmetic(
format!( format!(
"{} is too small to fit into a tag (must be between {} and {})", "{tag} is too small to fit into a tag (must be between {TAG_MIN} and {TAG_MAX})"
tag,
Tag::MIN,
Tag::MAX
), ),
Position::NONE, Position::NONE,
) )
.into()) .into())
} else if tag > Tag::MAX as INT { } else if tag > TAG_MAX as INT {
Err(ERR::ErrorArithmetic( Err(ERR::ErrorArithmetic(
format!( format!(
"{} is too large to fit into a tag (must be between {} and {})", "{tag} is too large to fit into a tag (must be between {TAG_MIN} and {TAG_MAX})"
tag,
Tag::MIN,
Tag::MAX
), ),
Position::NONE, Position::NONE,
) )
@ -281,10 +278,8 @@ fn collect_fn_metadata(
.for_each(|(.., f)| list.push(make_metadata(dict, namespace.into(), f).into())); .for_each(|(.., f)| list.push(make_metadata(dict, namespace.into(), f).into()));
for (ns, m) in module.iter_sub_modules() { for (ns, m) in module.iter_sub_modules() {
let ns = format!( let ns = format!(
"{}{}{}", "{namespace}{}{ns}",
namespace, crate::tokenizer::Token::DoubleColon.literal_syntax()
crate::tokenizer::Token::DoubleColon.literal_syntax(),
ns
); );
scan_module(list, dict, &ns, &**m, filter); scan_module(list, dict, &ns, &**m, filter);
} }

View File

@ -139,16 +139,14 @@ mod int_functions {
#[rhai_fn(name = "parse_int", return_raw)] #[rhai_fn(name = "parse_int", return_raw)]
pub fn parse_int_radix(string: &str, radix: INT) -> RhaiResultOf<INT> { pub fn parse_int_radix(string: &str, radix: INT) -> RhaiResultOf<INT> {
if !(2..=36).contains(&radix) { if !(2..=36).contains(&radix) {
return Err(ERR::ErrorArithmetic( return Err(
format!("Invalid radix: '{}'", radix), ERR::ErrorArithmetic(format!("Invalid radix: '{radix}'"), Position::NONE).into(),
Position::NONE, );
)
.into());
} }
INT::from_str_radix(string.trim(), radix as u32).map_err(|err| { INT::from_str_radix(string.trim(), radix as u32).map_err(|err| {
ERR::ErrorArithmetic( ERR::ErrorArithmetic(
format!("Error parsing integer number '{}': {}", string, err), format!("Error parsing integer number '{string}': {err}"),
Position::NONE, Position::NONE,
) )
.into() .into()
@ -316,7 +314,7 @@ mod float_functions {
pub fn f32_to_int(x: f32) -> RhaiResultOf<INT> { pub fn f32_to_int(x: f32) -> RhaiResultOf<INT> {
if cfg!(not(feature = "unchecked")) && (x > (INT::MAX as f32) || x < (INT::MIN as f32)) { if cfg!(not(feature = "unchecked")) && (x > (INT::MAX as f32) || x < (INT::MIN as f32)) {
Err( Err(
ERR::ErrorArithmetic(format!("Integer overflow: to_int({})", x), Position::NONE) ERR::ErrorArithmetic(format!("Integer overflow: to_int({x})"), Position::NONE)
.into(), .into(),
) )
} else { } else {
@ -328,7 +326,7 @@ mod float_functions {
pub fn f64_to_int(x: f64) -> RhaiResultOf<INT> { pub fn f64_to_int(x: f64) -> RhaiResultOf<INT> {
if cfg!(not(feature = "unchecked")) && (x > (INT::MAX as f64) || x < (INT::MIN as f64)) { if cfg!(not(feature = "unchecked")) && (x > (INT::MAX as f64) || x < (INT::MIN as f64)) {
Err( Err(
ERR::ErrorArithmetic(format!("Integer overflow: to_int({})", x), Position::NONE) ERR::ErrorArithmetic(format!("Integer overflow: to_int({x})"), Position::NONE)
.into(), .into(),
) )
} else { } else {
@ -348,7 +346,7 @@ mod float_functions {
pub fn parse_float(string: &str) -> RhaiResultOf<FLOAT> { pub fn parse_float(string: &str) -> RhaiResultOf<FLOAT> {
string.trim().parse::<FLOAT>().map_err(|err| { string.trim().parse::<FLOAT>().map_err(|err| {
ERR::ErrorArithmetic( ERR::ErrorArithmetic(
format!("Error parsing floating-point number '{}': {}", string, err), format!("Error parsing floating-point number '{string}': {err}"),
Position::NONE, Position::NONE,
) )
.into() .into()
@ -416,14 +414,14 @@ mod decimal_functions {
#[rhai_fn(return_raw)] #[rhai_fn(return_raw)]
pub fn sqrt(x: Decimal) -> RhaiResultOf<Decimal> { pub fn sqrt(x: Decimal) -> RhaiResultOf<Decimal> {
x.sqrt() 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. /// Return the exponential of the decimal number.
#[rhai_fn(return_raw)] #[rhai_fn(return_raw)]
pub fn exp(x: Decimal) -> RhaiResultOf<Decimal> { pub fn exp(x: Decimal) -> RhaiResultOf<Decimal> {
if cfg!(not(feature = "unchecked")) { if cfg!(not(feature = "unchecked")) {
x.checked_exp() x.checked_exp()
.ok_or_else(|| make_err(format!("Exponential overflow: e ** {}", x,))) .ok_or_else(|| make_err(format!("Exponential overflow: e ** {x}")))
} else { } else {
Ok(x.exp()) Ok(x.exp())
} }
@ -433,7 +431,7 @@ mod decimal_functions {
pub fn ln(x: Decimal) -> RhaiResultOf<Decimal> { pub fn ln(x: Decimal) -> RhaiResultOf<Decimal> {
if cfg!(not(feature = "unchecked")) { if cfg!(not(feature = "unchecked")) {
x.checked_ln() 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 { } else {
Ok(x.ln()) Ok(x.ln())
} }
@ -443,7 +441,7 @@ mod decimal_functions {
pub fn log10(x: Decimal) -> RhaiResultOf<Decimal> { pub fn log10(x: Decimal) -> RhaiResultOf<Decimal> {
if cfg!(not(feature = "unchecked")) { if cfg!(not(feature = "unchecked")) {
x.checked_log10() 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 { } else {
Ok(x.log10()) Ok(x.log10())
} }
@ -471,8 +469,7 @@ mod decimal_functions {
if cfg!(not(feature = "unchecked")) { if cfg!(not(feature = "unchecked")) {
if digits < 0 { if digits < 0 {
return Err(make_err(format!( return Err(make_err(format!(
"Invalid number of digits for rounding: {}", "Invalid number of digits for rounding: {digits}"
digits
))); )));
} }
if cfg!(not(feature = "only_i32")) && digits > (u32::MAX as INT) { if cfg!(not(feature = "only_i32")) && digits > (u32::MAX as INT) {
@ -489,8 +486,7 @@ mod decimal_functions {
if cfg!(not(feature = "unchecked")) { if cfg!(not(feature = "unchecked")) {
if digits < 0 { if digits < 0 {
return Err(make_err(format!( return Err(make_err(format!(
"Invalid number of digits for rounding: {}", "Invalid number of digits for rounding: {digits}"
digits
))); )));
} }
if cfg!(not(feature = "only_i32")) && digits > (u32::MAX as INT) { if cfg!(not(feature = "only_i32")) && digits > (u32::MAX as INT) {
@ -507,8 +503,7 @@ mod decimal_functions {
if cfg!(not(feature = "unchecked")) { if cfg!(not(feature = "unchecked")) {
if digits < 0 { if digits < 0 {
return Err(make_err(format!( return Err(make_err(format!(
"Invalid number of digits for rounding: {}", "Invalid number of digits for rounding: {digits}"
digits
))); )));
} }
if cfg!(not(feature = "only_i32")) && digits > (u32::MAX as INT) { if cfg!(not(feature = "only_i32")) && digits > (u32::MAX as INT) {
@ -525,8 +520,7 @@ mod decimal_functions {
if cfg!(not(feature = "unchecked")) { if cfg!(not(feature = "unchecked")) {
if digits < 0 { if digits < 0 {
return Err(make_err(format!( return Err(make_err(format!(
"Invalid number of digits for rounding: {}", "Invalid number of digits for rounding: {digits}"
digits
))); )));
} }
if cfg!(not(feature = "only_i32")) && digits > (u32::MAX as INT) { if cfg!(not(feature = "only_i32")) && digits > (u32::MAX as INT) {
@ -543,8 +537,7 @@ mod decimal_functions {
if cfg!(not(feature = "unchecked")) { if cfg!(not(feature = "unchecked")) {
if digits < 0 { if digits < 0 {
return Err(make_err(format!( return Err(make_err(format!(
"Invalid number of digits for rounding: {}", "Invalid number of digits for rounding: {digits}"
digits
))); )));
} }
if cfg!(not(feature = "only_i32")) && digits > (u32::MAX as INT) { if cfg!(not(feature = "only_i32")) && digits > (u32::MAX as INT) {
@ -572,7 +565,7 @@ mod decimal_functions {
match n { match n {
Some(n) => Ok(n), Some(n) => Ok(n),
_ => Err(ERR::ErrorArithmetic( _ => Err(ERR::ErrorArithmetic(
format!("Integer overflow: to_int({})", x), format!("Integer overflow: to_int({x})"),
Position::NONE, Position::NONE,
) )
.into()), .into()),
@ -603,7 +596,7 @@ mod decimal_functions {
.or_else(|_| Decimal::from_scientific(string)) .or_else(|_| Decimal::from_scientific(string))
.map_err(|err| { .map_err(|err| {
ERR::ErrorArithmetic( ERR::ErrorArithmetic(
format!("Error parsing decimal number '{}': {}", string, err), format!("Error parsing decimal number '{string}': {err}"),
Position::NONE, Position::NONE,
) )
.into() .into()
@ -616,7 +609,7 @@ mod decimal_functions {
pub fn f32_to_decimal(x: f32) -> RhaiResultOf<Decimal> { pub fn f32_to_decimal(x: f32) -> RhaiResultOf<Decimal> {
Decimal::try_from(x).map_err(|_| { Decimal::try_from(x).map_err(|_| {
ERR::ErrorArithmetic( ERR::ErrorArithmetic(
format!("Cannot convert to Decimal: to_decimal({})", x), format!("Cannot convert to Decimal: to_decimal({x})"),
Position::NONE, Position::NONE,
) )
.into() .into()
@ -628,7 +621,7 @@ mod decimal_functions {
pub fn f64_to_decimal(x: f64) -> RhaiResultOf<Decimal> { pub fn f64_to_decimal(x: f64) -> RhaiResultOf<Decimal> {
Decimal::try_from(x).map_err(|_| { Decimal::try_from(x).map_err(|_| {
ERR::ErrorArithmetic( ERR::ErrorArithmetic(
format!("Cannot convert to Decimal: to_decimal({})", x), format!("Cannot convert to Decimal: to_decimal({x})"),
Position::NONE, Position::NONE,
) )
.into() .into()
@ -640,7 +633,7 @@ mod decimal_functions {
pub fn to_float(x: Decimal) -> RhaiResultOf<FLOAT> { pub fn to_float(x: Decimal) -> RhaiResultOf<FLOAT> {
FLOAT::try_from(x).map_err(|_| { FLOAT::try_from(x).map_err(|_| {
ERR::ErrorArithmetic( ERR::ErrorArithmetic(
format!("Cannot convert to floating-point: to_float({})", x), format!("Cannot convert to floating-point: to_float({x})"),
Position::NONE, Position::NONE,
) )
.into() .into()

View File

@ -69,7 +69,7 @@ mod print_debug_functions {
/// Convert the value of the `item` into a string in debug format. /// Convert the value of the `item` into a string in debug format.
#[rhai_fn(name = "to_debug", pure)] #[rhai_fn(name = "to_debug", pure)]
pub fn to_debug_generic(ctx: NativeCallContext, item: &mut Dynamic) -> ImmutableString { 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. /// Return the empty string.
@ -86,7 +86,7 @@ mod print_debug_functions {
/// Convert the string into debug format. /// Convert the string into debug format.
#[rhai_fn(name = "debug", name = "to_debug", pure)] #[rhai_fn(name = "debug", name = "to_debug", pure)]
pub fn debug_string(string: &mut ImmutableString) -> ImmutableString { pub fn debug_string(string: &mut ImmutableString) -> ImmutableString {
format!("{:?}", string).into() format!("{string:?}").into()
} }
/// Return the character into a string. /// Return the character into a string.
@ -97,7 +97,7 @@ mod print_debug_functions {
/// Convert the string into debug format. /// Convert the string into debug format.
#[rhai_fn(name = "debug", name = "to_debug")] #[rhai_fn(name = "debug", name = "to_debug")]
pub fn debug_char(character: char) -> ImmutableString { pub fn debug_char(character: char) -> ImmutableString {
format!("{:?}", character).into() format!("{character:?}").into()
} }
/// Convert the function pointer into a string in debug format. /// 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. /// Return the boolean value into a string.
#[rhai_fn(name = "print", name = "to_string")] #[rhai_fn(name = "print", name = "to_string")]
pub fn print_bool(value: bool) -> ImmutableString { pub fn print_bool(value: bool) -> ImmutableString {
format!("{}", value).into() value.to_string().into()
} }
/// Convert the boolean value into a string in debug format. /// Convert the boolean value into a string in debug format.
#[rhai_fn(name = "debug", name = "to_debug")] #[rhai_fn(name = "debug", name = "to_debug")]
pub fn debug_bool(value: bool) -> ImmutableString { pub fn debug_bool(value: bool) -> ImmutableString {
format!("{:?}", value).into() format!("{value:?}").into()
} }
/// Return the empty string. /// Return the empty string.
@ -146,13 +146,15 @@ mod print_debug_functions {
#[cfg(not(feature = "no_float"))] #[cfg(not(feature = "no_float"))]
#[rhai_fn(name = "debug", name = "to_debug")] #[rhai_fn(name = "debug", name = "to_debug")]
pub fn debug_f64(number: f64) -> ImmutableString { 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. /// Convert the value of `number` into a string.
#[cfg(not(feature = "no_float"))] #[cfg(not(feature = "no_float"))]
#[rhai_fn(name = "debug", name = "to_debug")] #[rhai_fn(name = "debug", name = "to_debug")]
pub fn debug_f32(number: f32) -> ImmutableString { 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. /// Convert the array into a string.
@ -215,13 +217,13 @@ mod print_debug_functions {
#[export_module] #[export_module]
mod number_formatting { mod number_formatting {
fn to_hex<T: LowerHex>(value: T) -> ImmutableString { fn to_hex<T: LowerHex>(value: T) -> ImmutableString {
format!("{:x}", value).into() format!("{value:x}").into()
} }
fn to_octal<T: Octal>(value: T) -> ImmutableString { fn to_octal<T: Octal>(value: T) -> ImmutableString {
format!("{:o}", value).into() format!("{value:o}").into()
} }
fn to_binary<T: Binary>(value: T) -> ImmutableString { fn to_binary<T: Binary>(value: T) -> ImmutableString {
format!("{:b}", value).into() format!("{value:b}").into()
} }
/// Convert the `value` into a string in hex format. /// Convert the `value` into a string in hex format.

View File

@ -30,7 +30,7 @@ mod string_functions {
if s.is_empty() { if s.is_empty() {
string.clone() string.clone()
} else { } else {
format!("{}{}", string, s).into() format!("{string}{s}").into()
} }
} }
#[rhai_fn(name = "+=", name = "append")] #[rhai_fn(name = "+=", name = "append")]
@ -38,7 +38,7 @@ mod string_functions {
let s = print_with_func(FUNC_TO_STRING, &ctx, &mut item); let s = print_with_func(FUNC_TO_STRING, &ctx, &mut item);
if !s.is_empty() { if !s.is_empty() {
*string = format!("{}{}", string, s).into(); *string = format!("{string}{s}").into();
} }
} }
#[rhai_fn(name = "+", pure)] #[rhai_fn(name = "+", pure)]
@ -68,7 +68,7 @@ mod string_functions {
} }
#[rhai_fn(name = "+")] #[rhai_fn(name = "+")]
pub fn add_prepend_char(character: char, string: &str) -> ImmutableString { pub fn add_prepend_char(character: char, string: &str) -> ImmutableString {
format!("{}{}", character, string).into() format!("{character}{string}").into()
} }
#[rhai_fn(name = "+")] #[rhai_fn(name = "+")]

View File

@ -66,8 +66,7 @@ mod time_functions {
if cfg!(not(feature = "unchecked")) && seconds > (INT::MAX as u64) { if cfg!(not(feature = "unchecked")) && seconds > (INT::MAX as u64) {
Err(make_arithmetic_err(format!( Err(make_arithmetic_err(format!(
"Integer overflow for timestamp.elapsed: {}", "Integer overflow for timestamp.elapsed: {seconds}"
seconds
))) )))
} else if timestamp > Instant::now() { } else if timestamp > Instant::now() {
Err(make_arithmetic_err("Time-stamp is later than 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) { if cfg!(not(feature = "unchecked")) && seconds > (INT::MAX as u64) {
Err(make_arithmetic_err(format!( Err(make_arithmetic_err(format!(
"Integer overflow for timestamp duration: -{}", "Integer overflow for timestamp duration: -{seconds}"
seconds
))) )))
} else { } else {
Ok((-(seconds as INT)).into()) Ok((-(seconds as INT)).into())
@ -105,8 +103,7 @@ mod time_functions {
if cfg!(not(feature = "unchecked")) && seconds > (INT::MAX as u64) { if cfg!(not(feature = "unchecked")) && seconds > (INT::MAX as u64) {
Err(make_arithmetic_err(format!( Err(make_arithmetic_err(format!(
"Integer overflow for timestamp duration: {}", "Integer overflow for timestamp duration: {seconds}"
seconds
))) )))
} else { } else {
Ok((seconds as INT).into()) Ok((seconds as INT).into())
@ -122,16 +119,14 @@ mod time_functions {
} else if cfg!(not(feature = "unchecked")) { } else if cfg!(not(feature = "unchecked")) {
if seconds > (INT::MAX as FLOAT) { if seconds > (INT::MAX as FLOAT) {
Err(make_arithmetic_err(format!( Err(make_arithmetic_err(format!(
"Integer overflow for timestamp add: {}", "Integer overflow for timestamp add: {seconds}"
seconds
))) )))
} else { } else {
timestamp timestamp
.checked_add(Duration::from_millis((seconds * 1000.0) as u64)) .checked_add(Duration::from_millis((seconds * 1000.0) as u64))
.ok_or_else(|| { .ok_or_else(|| {
make_arithmetic_err(format!( make_arithmetic_err(format!(
"Timestamp overflow when adding {} second(s)", "Timestamp overflow when adding {seconds} second(s)"
seconds
)) ))
}) })
} }
@ -145,16 +140,14 @@ mod time_functions {
} else if cfg!(not(feature = "unchecked")) { } else if cfg!(not(feature = "unchecked")) {
if seconds > (INT::MAX as FLOAT) { if seconds > (INT::MAX as FLOAT) {
Err(make_arithmetic_err(format!( Err(make_arithmetic_err(format!(
"Integer overflow for timestamp add: {}", "Integer overflow for timestamp add: {seconds}"
seconds
))) )))
} else { } else {
timestamp timestamp
.checked_sub(Duration::from_millis((seconds * 1000.0) as u64)) .checked_sub(Duration::from_millis((seconds * 1000.0) as u64))
.ok_or_else(|| { .ok_or_else(|| {
make_arithmetic_err(format!( make_arithmetic_err(format!(
"Timestamp overflow when adding {} second(s)", "Timestamp overflow when adding {seconds} second(s)"
seconds
)) ))
}) })
} }
@ -195,8 +188,7 @@ mod time_functions {
.checked_add(Duration::from_secs(seconds as u64)) .checked_add(Duration::from_secs(seconds as u64))
.ok_or_else(|| { .ok_or_else(|| {
make_arithmetic_err(format!( make_arithmetic_err(format!(
"Timestamp overflow when adding {} second(s)", "Timestamp overflow when adding {seconds} second(s)"
seconds
)) ))
}) })
} else { } else {
@ -211,8 +203,7 @@ mod time_functions {
.checked_sub(Duration::from_secs(seconds as u64)) .checked_sub(Duration::from_secs(seconds as u64))
.ok_or_else(|| { .ok_or_else(|| {
make_arithmetic_err(format!( make_arithmetic_err(format!(
"Timestamp overflow when adding {} second(s)", "Timestamp overflow when adding {seconds} second(s)"
seconds
)) ))
}) })
} else { } else {

View File

@ -536,7 +536,7 @@ impl Engine {
Token::EOF => { Token::EOF => {
return Err(PERR::MissingToken( return Err(PERR::MissingToken(
Token::RightParen.into(), 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)) .into_err(*token_pos))
} }
@ -677,7 +677,7 @@ impl Engine {
(Token::EOF, pos) => { (Token::EOF, pos) => {
return Err(PERR::MissingToken( return Err(PERR::MissingToken(
Token::RightParen.into(), 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)) .into_err(*pos))
} }
@ -687,7 +687,7 @@ impl Engine {
(.., pos) => { (.., pos) => {
return Err(PERR::MissingToken( return Err(PERR::MissingToken(
Token::Comma.into(), Token::Comma.into(),
format!("to separate the arguments to function call '{}'", id), format!("to separate the arguments to function call '{id}'"),
) )
.into_err(*pos)) .into_err(*pos))
} }
@ -1011,10 +1011,7 @@ impl Engine {
(.., pos) => { (.., pos) => {
return Err(PERR::MissingToken( return Err(PERR::MissingToken(
Token::Colon.into(), Token::Colon.into(),
format!( format!("to follow the property '{name}' in this object map literal"),
"to follow the property '{}' in this object map literal",
name
),
) )
.into_err(pos)) .into_err(pos))
} }
@ -1609,7 +1606,7 @@ impl Engine {
), ),
// Cannot access to `this` as a variable not in a function scope // Cannot access to `this` as a variable not in a function scope
_ if &*s == KEYWORD_THIS => { _ 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( return Err(
LexError::ImproperSymbol(s.to_string(), msg).into_err(settings.pos) LexError::ImproperSymbol(s.to_string(), msg).into_err(settings.pos)
); );
@ -1862,9 +1859,7 @@ impl Engine {
#[cfg(feature = "no_float")] #[cfg(feature = "no_float")]
return None; return None;
}) })
.ok_or_else(|| { .ok_or_else(|| LexError::MalformedNumber(format!("-{num}")).into_err(pos)),
LexError::MalformedNumber(format!("-{}", num)).into_err(pos)
}),
// Negative float // Negative float
#[cfg(not(feature = "no_float"))] #[cfg(not(feature = "no_float"))]
@ -3479,7 +3474,7 @@ impl Engine {
let mut params = StaticVec::new_const(); let mut params = StaticVec::new_const();
if !no_params { 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 { loop {
match input.next().expect(NEVER_ENDS) { match input.next().expect(NEVER_ENDS) {
@ -3497,7 +3492,7 @@ impl Engine {
(.., pos) => { (.., pos) => {
return Err(PERR::MissingToken( return Err(PERR::MissingToken(
Token::RightParen.into(), Token::RightParen.into(),
format!("to close the parameters list of function '{}'", name), format!("to close the parameters list of function '{name}'"),
) )
.into_err(pos)) .into_err(pos))
} }

View File

@ -2406,7 +2406,7 @@ impl<'a> Iterator for TokenIterator<'a> {
(.., true) => unreachable!("no custom operators"), (.., true) => unreachable!("no custom operators"),
// Reserved keyword that is not custom and disabled. // Reserved keyword that is not custom and disabled.
(token, false) if !self.engine.disabled_symbols.is_empty() && self.engine.disabled_symbols.contains(token) => { (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()) Token::LexError(LERR::ImproperSymbol(s.to_string(), msg).into())
}, },
// Reserved keyword/operator that is not custom. // Reserved keyword/operator that is not custom.

View File

@ -341,7 +341,7 @@ impl EvalAltResult {
pub(crate) fn dump_fields(&self, map: &mut crate::Map) { pub(crate) fn dump_fields(&self, map: &mut crate::Map) {
map.insert( map.insert(
"error".into(), "error".into(),
format!("{:?}", self) format!("{self:?}")
.split('(') .split('(')
.next() .next()
.expect("`ErrorXXX(...)`") .expect("`ErrorXXX(...)`")

View File

@ -45,7 +45,7 @@ fn test_custom_syntax() -> Result<(), Box<EvalAltResult>> {
">=" => count < max, ">=" => count < max,
"==" => count != max, "==" => count != max,
"!=" => count == max, "!=" => count == max,
_ => return Err(format!("Unsupported operator: {}", op).into()), _ => return Err(format!("Unsupported operator: {op}").into()),
}; };
if done { if done {
@ -63,7 +63,7 @@ fn test_custom_syntax() -> Result<(), Box<EvalAltResult>> {
context context
.scope_mut() .scope_mut()
.push(format!("{}{}", var_name, count), count); .push(format!("{var_name}{count}"), count);
let stop = !context let stop = !context
.eval_expression_tree(condition)? .eval_expression_tree(condition)?
@ -189,7 +189,7 @@ fn test_custom_syntax() -> Result<(), Box<EvalAltResult>> {
context.scope_mut().set_value(var_name.to_string(), value); context.scope_mut().set_value(var_name.to_string(), value);
Ok(Dynamic::UNIT) Ok(Dynamic::UNIT)
} else { } else {
Err(format!("variable {} is constant", var_name).into()) Err(format!("variable {var_name} is constant").into())
} }
}, },
)?; )?;

View File

@ -68,11 +68,11 @@ fn test_native_overload() -> Result<(), Box<EvalAltResult>> {
.register_fn( .register_fn(
"+", "+",
|s1: ImmutableString, s2: ImmutableString| -> ImmutableString { |s1: ImmutableString, s2: ImmutableString| -> ImmutableString {
format!("{}***{}", s1, s2).into() format!("{s1}***{s2}").into()
}, },
) )
.register_fn("+", |s1: ImmutableString, _: ()| -> ImmutableString { .register_fn("+", |s1: ImmutableString, _: ()| -> ImmutableString {
format!("{} Foo!", s1).into() format!("{s1} Foo!").into()
}); });
assert_eq!( assert_eq!(

View File

@ -81,21 +81,21 @@ fn test_optimizer_parse() -> Result<(), Box<EvalAltResult>> {
let ast = engine.compile("{ const DECISION = false; if DECISION { 42 } else { 123 } }")?; let ast = engine.compile("{ const DECISION = false; if DECISION { 42 } else { 123 } }")?;
assert_eq!( assert_eq!(
format!("{:?}", ast), format!("{ast:?}"),
r#"AST { source: "", doc: "", resolver: None, body: [Expr(123 @ 1:53)] }"# r#"AST { source: "", doc: "", resolver: None, body: [Expr(123 @ 1:53)] }"#
); );
let ast = engine.compile("const DECISION = false; if DECISION { 42 } else { 123 }")?; let ast = engine.compile("const DECISION = false; if DECISION { 42 } else { 123 }")?;
assert_eq!( 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)] }"# 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 }")?; let ast = engine.compile("if 1 == 2 { 42 }")?;
assert_eq!( assert_eq!(
format!("{:?}", ast), format!("{ast:?}"),
r#"AST { source: "", doc: "", resolver: None, body: [] }"# r#"AST { source: "", doc: "", resolver: None, body: [] }"#
); );
@ -104,14 +104,14 @@ fn test_optimizer_parse() -> Result<(), Box<EvalAltResult>> {
let ast = engine.compile("abs(-42)")?; let ast = engine.compile("abs(-42)")?;
assert_eq!( assert_eq!(
format!("{:?}", ast), format!("{ast:?}"),
r#"AST { source: "", doc: "", resolver: None, body: [Expr(42 @ 1:1)] }"# r#"AST { source: "", doc: "", resolver: None, body: [Expr(42 @ 1:1)] }"#
); );
let ast = engine.compile("NUMBER")?; let ast = engine.compile("NUMBER")?;
assert_eq!( assert_eq!(
format!("{:?}", ast), format!("{ast:?}"),
r#"AST { source: "", doc: "", resolver: None, body: [Expr(Variable(NUMBER) @ 1:1)] }"# r#"AST { source: "", doc: "", resolver: None, body: [Expr(Variable(NUMBER) @ 1:1)] }"#
); );
@ -123,7 +123,7 @@ fn test_optimizer_parse() -> Result<(), Box<EvalAltResult>> {
let ast = engine.compile("NUMBER")?; let ast = engine.compile("NUMBER")?;
assert_eq!( assert_eq!(
format!("{:?}", ast), format!("{ast:?}"),
r#"AST { source: "", doc: "", resolver: None, body: [Expr(42 @ 1:1)] }"# r#"AST { source: "", doc: "", resolver: None, body: [Expr(42 @ 1:1)] }"#
); );

View File

@ -70,7 +70,7 @@ macro_rules! reg_functions {
} }
fn make_greeting(n: impl std::fmt::Display) -> String { 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); gen_unary_functions!(greet = make_greeting(INT, bool, char) -> String);

View File

@ -39,14 +39,12 @@ fn test_print_debug() -> Result<(), Box<EvalAltResult>> {
let mut engine = Engine::new(); let mut engine = Engine::new();
engine 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| { .on_debug(move |s, src, pos| {
log2.write().unwrap().push(format!( let src = src.unwrap_or("unknown");
"DEBUG of {} at {:?}: {}", log2.write()
src.unwrap_or("unknown"), .unwrap()
pos, .push(format!("DEBUG of {src} at {pos:?}: {s}"))
s
))
}); });
// Evaluate script // Evaluate script

View File

@ -744,7 +744,7 @@ fn test_serde_json() -> serde_json::Result<()> {
let a = m.remove("b").unwrap().cast::<Array>(); let a = m.remove("b").unwrap().cast::<Array>();
assert_eq!(a.len(), 3); assert_eq!(a.len(), 3);
assert_eq!(format!("{:?}", a), "[1, 2, 3]"); assert_eq!(format!("{a:?}"), "[1, 2, 3]");
Ok(()) Ok(())
} }