Skip to content

Commit

Permalink
Using the new formatting arguments from Rust 1.58 (#1834)
Browse files Browse the repository at this point in the history
In [Rust 1.58](https://blog.rust-lang.org/2022/01/13/Rust-1.58.0.html#captured-identifiers-in-format-strings), capturing of bindings were added to format strings. This makes things more clear, so I added this where possible.
  • Loading branch information
Razican committed Feb 13, 2022
1 parent 7b2dc88 commit 53ef07b
Show file tree
Hide file tree
Showing 47 changed files with 300 additions and 339 deletions.
2 changes: 1 addition & 1 deletion boa/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ categories = ["parser-implementations", "wasm"]
license = "Unlicense/MIT"
exclude = ["../.vscode/*", "../Dockerfile", "../Makefile", "../.editorConfig"]
edition = "2021"
rust-version = "1.57"
rust-version = "1.58"

[features]
profiler = ["measureme"]
Expand Down
4 changes: 2 additions & 2 deletions boa/examples/closures.rs
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@ fn main() -> Result<(), JsValue> {
context.register_global_closure("closure", 0, move |_, _, _| {
println!("Called `closure`");
// `variable` is captured from the main function.
println!("variable = {}", variable);
println!("variable = {variable}");
println!();

// We return the moved variable as a `JsValue`.
Expand Down Expand Up @@ -77,7 +77,7 @@ fn main() -> Result<(), JsValue> {
// We can also mutate the moved data inside the closure.
captures.greeting = format!("{} Hello!", captures.greeting).into();

println!("{}", message);
println!("{message}");
println!();

// We convert `message` into `Jsvalue` to be able to return it.
Expand Down
2 changes: 1 addition & 1 deletion boa/src/builtins/array_buffer/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -745,7 +745,7 @@ pub fn create_byte_data_block(size: usize, context: &mut Context) -> JsResult<Ve
// create such a Data Block, throw a RangeError exception.
let mut data_block = Vec::new();
data_block.try_reserve(size).map_err(|e| {
context.construct_range_error(format!("couldn't allocate the data block: {}", e))
context.construct_range_error(format!("couldn't allocate the data block: {e}"))
})?;

// 2. Set all of the bytes of db to 0.
Expand Down
2 changes: 1 addition & 1 deletion boa/src/builtins/bigint/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -104,7 +104,7 @@ impl BigInt {
fn number_to_bigint(number: f64, context: &mut Context) -> JsResult<JsValue> {
// 1. If IsIntegralNumber(number) is false, throw a RangeError exception.
if number.is_nan() || number.is_infinite() || number.fract() != 0.0 {
return context.throw_range_error(format!("Cannot convert {} to BigInt", number));
return context.throw_range_error(format!("Cannot convert {number} to BigInt"));
}

// 2. Return the BigInt value that represents ℝ(number).
Expand Down
33 changes: 15 additions & 18 deletions boa/src/builtins/console/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -41,10 +41,10 @@ pub(crate) fn logger(msg: LogMessage, console_state: &Console) {

match msg {
LogMessage::Error(msg) => {
eprintln!("{:>width$}", msg, width = indent);
eprintln!("{msg:>indent$}");
}
LogMessage::Log(msg) | LogMessage::Info(msg) | LogMessage::Warn(msg) => {
println!("{:>width$}", msg, width = indent);
println!("{msg:>indent$}");
}
}
}
Expand Down Expand Up @@ -75,7 +75,7 @@ pub fn formatter(data: &[JsValue], context: &mut Context) -> JsResult<String> {
.cloned()
.unwrap_or_default()
.to_integer(context)?;
formatted.push_str(&format!("{}", arg));
formatted.push_str(&arg.to_string());
arg_index += 1;
}
/* float */
Expand All @@ -85,13 +85,13 @@ pub fn formatter(data: &[JsValue], context: &mut Context) -> JsResult<String> {
.cloned()
.unwrap_or_default()
.to_number(context)?;
formatted.push_str(&format!("{number:.prec$}", number = arg, prec = 6));
formatted.push_str(&format!("{arg:.6}"));
arg_index += 1;
}
/* object, FIXME: how to render this properly? */
'o' | 'O' => {
let arg = data.get_or_undefined(arg_index);
formatted.push_str(&format!("{}", arg.display()));
formatted.push_str(&arg.display().to_string());
arg_index += 1;
}
/* string */
Expand Down Expand Up @@ -199,7 +199,7 @@ impl Console {
} else if !args[0].is_string() {
args.insert(0, JsValue::new(message));
} else {
let concat = format!("{}: {}", message, args[0].display());
let concat = format!("{message}: {}", args[0].display());
args[0] = JsValue::new(concat);
}

Expand Down Expand Up @@ -375,14 +375,11 @@ impl Console {
None => "default".into(),
};

let msg = format!("count {}:", &label);
let msg = format!("count {label}:");
let c = context.console_mut().count_map.entry(label).or_insert(0);
*c += 1;

logger(
LogMessage::Info(format!("{} {}", msg, c)),
context.console(),
);
logger(LogMessage::Info(format!("{msg} {c}")), context.console());
Ok(JsValue::undefined())
}

Expand All @@ -409,7 +406,7 @@ impl Console {
context.console_mut().count_map.remove(&label);

logger(
LogMessage::Warn(format!("countReset {}", label)),
LogMessage::Warn(format!("countReset {label}")),
context.console(),
);

Expand Down Expand Up @@ -442,7 +439,7 @@ impl Console {

if context.console().timer_map.get(&label).is_some() {
logger(
LogMessage::Warn(format!("Timer '{}' already exist", label)),
LogMessage::Warn(format!("Timer '{label}' already exist")),
context.console(),
);
} else {
Expand Down Expand Up @@ -475,14 +472,14 @@ impl Console {

if let Some(t) = context.console().timer_map.get(&label) {
let time = Self::system_time_in_ms();
let mut concat = format!("{}: {} ms", label, time - t);
let mut concat = format!("{label}: {} ms", time - t);
for msg in args.iter().skip(1) {
concat = concat + " " + &msg.display().to_string();
}
logger(LogMessage::Log(concat), context.console());
} else {
logger(
LogMessage::Warn(format!("Timer '{}' doesn't exist", label)),
LogMessage::Warn(format!("Timer '{label}' doesn't exist")),
context.console(),
);
}
Expand Down Expand Up @@ -513,12 +510,12 @@ impl Console {
if let Some(t) = context.console_mut().timer_map.remove(label.as_str()) {
let time = Self::system_time_in_ms();
logger(
LogMessage::Info(format!("{}: {} ms - timer removed", label, time - t)),
LogMessage::Info(format!("{label}: {} ms - timer removed", time - t)),
context.console(),
);
} else {
logger(
LogMessage::Warn(format!("Timer '{}' doesn't exist", label)),
LogMessage::Warn(format!("Timer '{label}' doesn't exist")),
context.console(),
);
}
Expand All @@ -540,7 +537,7 @@ impl Console {
let group_label = formatter(args, context)?;

logger(
LogMessage::Info(format!("group: {}", &group_label)),
LogMessage::Info(format!("group: {group_label}")),
context.console(),
);
context.console_mut().groups.push(group_label);
Expand Down
4 changes: 2 additions & 2 deletions boa/src/builtins/date/tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -39,15 +39,15 @@ fn forward_dt_local(context: &mut Context, src: &str) -> Option<NaiveDateTime> {
#[test]
fn date_display() {
let dt = super::Date(None);
assert_eq!("[Invalid Date]", format!("[{}]", dt));
assert_eq!("[Invalid Date]", format!("[{dt}]"));

let cd = super::Date::default();
assert_eq!(
format!(
"[{}]",
cd.to_local().unwrap().format("%a %b %d %Y %H:%M:%S GMT%:z")
),
format!("[{}]", cd)
format!("[{cd}]")
);
}

Expand Down
2 changes: 1 addition & 1 deletion boa/src/builtins/error/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -134,7 +134,7 @@ impl Error {
} else if message.is_empty() {
Ok(name.into())
} else {
Ok(format!("{}: {}", name, message).into())
Ok(format!("{name}: {message}").into())
}
}
}
10 changes: 4 additions & 6 deletions boa/src/builtins/function/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -226,7 +226,7 @@ pub(crate) fn make_builtin_fn<N>(
N: Into<String>,
{
let name = name.into();
let _timer = BoaProfiler::global().start_event(&format!("make_builtin_fn: {}", &name), "init");
let _timer = BoaProfiler::global().start_event(&format!("make_builtin_fn: {name}"), "init");

let function = JsObject::from_proto_and_data(
interpreter.standard_objects().function_object().prototype(),
Expand Down Expand Up @@ -453,13 +453,11 @@ impl BuiltInFunctionObject {
constructor: _,
},
Some(name),
) => Ok(format!("function {}() {{\n [native Code]\n}}", &name).into()),
) => Ok(format!("function {name}() {{\n [native Code]\n}}").into()),
(Function::VmOrdinary { .. }, Some(name)) if name.is_empty() => {
Ok("[Function (anonymous)]".into())
}
(Function::VmOrdinary { .. }, Some(name)) => {
Ok(format!("[Function: {}]", &name).into())
}
(Function::VmOrdinary { .. }, Some(name)) => Ok(format!("[Function: {name}]").into()),
(Function::VmOrdinary { .. }, None) => Ok("[Function (anonymous)]".into()),
_ => Ok("TODO".into()),
}
Expand Down Expand Up @@ -552,7 +550,7 @@ fn set_function_name(
}
}
PropertyKey::String(string) => Cow::Borrowed(string),
PropertyKey::Index(index) => Cow::Owned(JsString::new(format!("{}", index))),
PropertyKey::Index(index) => Cow::Owned(JsString::new(index.to_string())),
};

// 3. Else if name is a Private Name, then
Expand Down
16 changes: 5 additions & 11 deletions boa/src/builtins/json/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -498,7 +498,7 @@ impl Json {
{
// i. Let unit be the code unit whose numeric value is that of C.
// ii. Set product to the string-concatenation of product and UnicodeEscape(unit).
product.push_str(&format!("\\\\uAA{:x}", code_point));
product.push_str(&format!("\\\\uAA{code_point:x}"));
}
// c. Else,
code_point => {
Expand Down Expand Up @@ -603,18 +603,15 @@ impl Json {
} else {
// i. Let separator be the string-concatenation of the code unit 0x002C (COMMA),
// the code unit 0x000A (LINE FEED), and state.[[Indent]].
let separator = format!(",{}{}", '\u{A}', state.indent.as_str());
let separator = format!(",\n{}", state.indent.as_str());
// ii. Let properties be the String value formed by concatenating all the element Strings of partial
// with each adjacent pair of Strings separated with separator.
// The separator String is not inserted either before the first String or after the last String.
let properties = partial.join(&separator);
// iii. Let final be the string-concatenation of "{", the code unit 0x000A (LINE FEED), state.[[Indent]], properties, the code unit 0x000A (LINE FEED), stepback, and "}".
format!(
"{{{}{}{}{}{}}}",
'\u{A}',
"{{\n{}{properties}\n{}}}",
state.indent.as_str(),
&properties,
'\u{A}',
stepback.as_str()
)
.into()
Expand Down Expand Up @@ -703,18 +700,15 @@ impl Json {
} else {
// i. Let separator be the string-concatenation of the code unit 0x002C (COMMA),
// the code unit 0x000A (LINE FEED), and state.[[Indent]].
let separator = format!(",{}{}", '\u{A}', state.indent.as_str());
let separator = format!(",\n{}", state.indent.as_str());
// ii. Let properties be the String value formed by concatenating all the element Strings of partial
// with each adjacent pair of Strings separated with separator.
// The separator String is not inserted either before the first String or after the last String.
let properties = partial.join(&separator);
// iii. Let final be the string-concatenation of "[", the code unit 0x000A (LINE FEED), state.[[Indent]], properties, the code unit 0x000A (LINE FEED), stepback, and "]".
format!(
"[{}{}{}{}{}]",
'\u{A}',
"[\n{}{properties}\n{}]",
state.indent.as_str(),
&properties,
'\u{A}',
stepback.as_str()
)
.into()
Expand Down
16 changes: 8 additions & 8 deletions boa/src/builtins/number/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -271,8 +271,8 @@ impl Number {
Ok(JsValue::new(f64_to_exponential(this_num)))
} else {
// Get rid of the '-' sign for -0.0 because of 9. If x < 0, then set s to "-".
let this_num = if this_num == 0. { 0. } else { this_num };
let this_fixed_num = format!("{:.*}", precision, this_num);
let this_num = if this_num == 0_f64 { 0_f64 } else { this_num };
let this_fixed_num = format!("{this_num:.precision$}");
Ok(JsValue::new(this_fixed_num))
}
}
Expand All @@ -297,7 +297,7 @@ impl Number {
context: &mut Context,
) -> JsResult<JsValue> {
let this_num = Self::this_number_value(this, context)?;
let this_str_num = format!("{}", this_num);
let this_str_num = this_num.to_string();
Ok(JsValue::new(this_str_num))
}

Expand Down Expand Up @@ -451,7 +451,7 @@ impl Number {
// Due to f64 limitations, this part differs a bit from the spec,
// but has the same effect. It manipulates the string constructed
// by `format`: digits with an optional dot between two of them.
suffix = format!("{:.100}", this_num);
suffix = format!("{this_num:.100}");

// a: getting an exponent
exponent = Self::flt_str_to_exp(&suffix);
Expand Down Expand Up @@ -686,7 +686,7 @@ impl Number {
// I am not sure if this part is effective as the v8 equivalent https://chromium.googlesource.com/v8/v8/+/refs/heads/master/src/builtins/number.tq#53
// // Fast case where the result is a one character string.
// if x.is_sign_positive() && x.fract() == 0.0 && x < radix_number as f64 {
// return Ok(to_value(format!("{}", std::char::from_digit(x as u32, radix_number as u32).unwrap())))
// return Ok(std::char::from_digit(x as u32, radix_number as u32).unwrap().to_string().into())
// }

// 6. Return the String representation of this Number value using the radix specified by radixNumber.
Expand Down Expand Up @@ -1145,8 +1145,8 @@ impl Number {
/// Helper function that formats a float as a ES6-style exponential number string.
fn f64_to_exponential(n: f64) -> String {
match n.abs() {
x if x >= 1.0 || x == 0.0 => format!("{:e}", n).replace('e', "e+"),
_ => format!("{:e}", n),
x if x >= 1.0 || x == 0.0 => format!("{n:e}").replace('e', "e+"),
_ => format!("{n:e}"),
}
}

Expand All @@ -1155,7 +1155,7 @@ fn f64_to_exponential(n: f64) -> String {
// because in cases like (0.999).toExponential(0) the result will be 1e0.
// Instead we get the index of 'e', and if the next character is not '-' we insert the plus sign
fn f64_to_exponential_with_precision(n: f64, prec: usize) -> String {
let mut res = format!("{:.*e}", prec, n);
let mut res = format!("{n:.prec$e}");
let idx = res.find('e').expect("'e' not found in exponential string");
if res.as_bytes()[idx + 1] != b'-' {
res.insert(idx + 1, '+');
Expand Down
10 changes: 2 additions & 8 deletions boa/src/builtins/number/tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -589,10 +589,7 @@ fn parse_int_varying_radix() {
let expected = i32::from_str_radix(base_str, radix).unwrap();

assert_eq!(
forward(
&mut context,
&format!("parseInt(\"{}\", {} )", base_str, radix)
),
forward(&mut context, &format!("parseInt(\"{base_str}\", {radix} )")),
expected.to_string()
);
}
Expand All @@ -608,10 +605,7 @@ fn parse_int_negative_varying_radix() {
let expected = i32::from_str_radix(base_str, radix).unwrap();

assert_eq!(
forward(
&mut context,
&format!("parseInt(\"{}\", {} )", base_str, radix)
),
forward(&mut context, &format!("parseInt(\"{base_str}\", {radix} )")),
expected.to_string()
);
}
Expand Down
2 changes: 1 addition & 1 deletion boa/src/builtins/object/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -520,7 +520,7 @@ impl Object {
let tag_str = tag.as_string().map_or(builtin_tag, JsString::as_str);

// 17. Return the string-concatenation of "[object ", tag, and "]".
Ok(format!("[object {}]", tag_str).into())
Ok(format!("[object {tag_str}]").into())
}

/// `Object.prototype.hasOwnProperty( property )`
Expand Down
Loading

0 comments on commit 53ef07b

Please sign in to comment.