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

@@ -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));

View File

@@ -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(_) => (),

View File

@@ -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(

View File

@@ -150,7 +150,7 @@ impl Engine {
return if x == r {
name.into()
} 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())?;
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)

View File

@@ -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 {

View File

@@ -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.

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_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!(

View File

@@ -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,
))

View File

@@ -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());

View File

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

View File

@@ -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::<ImmutableString>() {
"&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())

View File

@@ -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)
}

View File

@@ -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<str> = 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,

View File

@@ -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<f32> {
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<Decimal> {
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<Decimal> {
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<Decimal> {
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<Decimal> {
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<Decimal> {
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))
}

View File

@@ -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);
}

View File

@@ -139,16 +139,14 @@ mod int_functions {
#[rhai_fn(name = "parse_int", return_raw)]
pub fn parse_int_radix(string: &str, radix: INT) -> RhaiResultOf<INT> {
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<INT> {
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<INT> {
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<FLOAT> {
string.trim().parse::<FLOAT>().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<Decimal> {
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<Decimal> {
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<Decimal> {
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<Decimal> {
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> {
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> {
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> {
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()

View File

@@ -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<T: LowerHex>(value: T) -> ImmutableString {
format!("{:x}", value).into()
format!("{value:x}").into()
}
fn to_octal<T: Octal>(value: T) -> ImmutableString {
format!("{:o}", value).into()
format!("{value:o}").into()
}
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.

View File

@@ -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 = "+")]

View File

@@ -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 {

View File

@@ -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))
}

View File

@@ -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.

View File

@@ -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(...)`")