Browse Source

Fix rust 1.67 lints (#2567)

This Pull Request changes the following:

- Fix rust 1.67 lints
pull/2574/head
raskad 2 years ago
parent
commit
e6a1c3789d
  1. 4
      boa_ast/src/expression/literal/array.rs
  2. 3
      boa_ast/src/lib.rs
  3. 34
      boa_engine/src/builtins/date/mod.rs
  4. 4
      boa_engine/src/builtins/function/mod.rs
  5. 2
      boa_engine/src/builtins/intl/collator/mod.rs
  6. 8
      boa_engine/src/builtins/intl/collator/options.rs
  7. 8
      boa_engine/src/builtins/intl/date_time_format.rs
  8. 10
      boa_engine/src/builtins/intl/list_format/mod.rs
  9. 2
      boa_engine/src/builtins/intl/locale/options.rs
  10. 6
      boa_engine/src/builtins/intl/options.rs
  11. 2
      boa_engine/src/builtins/math/tests.rs
  12. 14
      boa_engine/src/builtins/object/mod.rs
  13. 2
      boa_engine/src/builtins/promise/mod.rs
  14. 4
      boa_engine/src/builtins/regexp/mod.rs
  15. 5
      boa_engine/src/builtins/string/mod.rs
  16. 4
      boa_engine/src/builtins/weak/weak_ref.rs
  17. 2
      boa_engine/src/bytecompiler/jump_control.rs
  18. 2
      boa_engine/src/job.rs
  19. 10
      boa_engine/src/lib.rs
  20. 5
      boa_engine/src/object/internal_methods/array.rs
  21. 5
      boa_engine/src/object/internal_methods/mod.rs
  22. 8
      boa_engine/src/object/operations.rs
  23. 2
      boa_engine/src/string/mod.rs
  24. 26
      boa_engine/src/symbol.rs
  25. 6
      boa_engine/src/tagged.rs
  26. 3
      boa_engine/src/value/integer.rs
  27. 14
      boa_engine/src/vm/flowgraph/color.rs
  28. 6
      boa_engine/src/vm/flowgraph/graph.rs
  29. 2
      boa_examples/src/bin/loadfile.rs
  30. 2
      boa_examples/src/bin/modulehandler.rs
  31. 28
      boa_gc/src/cell.rs
  32. 3
      boa_parser/src/parser/cursor/buffered_lexer/mod.rs
  33. 4
      boa_parser/src/parser/expression/assignment/arrow_function.rs
  34. 4
      boa_parser/src/parser/expression/assignment/async_arrow_function.rs
  35. 2
      boa_parser/src/parser/expression/assignment/exponentiation.rs
  36. 9
      boa_parser/src/parser/expression/primary/object_initializer/mod.rs
  37. 4
      boa_parser/src/parser/statement/declaration/hoistable/mod.rs
  38. 4
      boa_parser/src/parser/statement/mod.rs
  39. 1
      boa_tester/src/main.rs

4
boa_ast/src/expression/literal/array.rs

@ -60,9 +60,7 @@ impl ArrayLiteral {
let mut bindings = Vec::new(); let mut bindings = Vec::new();
for (i, expr) in self.arr.iter().enumerate() { for (i, expr) in self.arr.iter().enumerate() {
let expr = if let Some(expr) = expr { let Some(expr) = expr else {
expr
} else {
bindings.push(ArrayPatternElement::Elision); bindings.push(ArrayPatternElement::Elision);
continue; continue;
}; };

3
boa_ast/src/lib.rs

@ -91,8 +91,7 @@
#![allow( #![allow(
clippy::module_name_repetitions, clippy::module_name_repetitions,
clippy::too_many_lines, clippy::too_many_lines,
clippy::option_if_let_else, clippy::option_if_let_else
clippy::use_self
)] )]
mod position; mod position;

34
boa_engine/src/builtins/date/mod.rs

@ -207,7 +207,7 @@ impl Date {
// 3. If numberOfArgs = 0, then // 3. If numberOfArgs = 0, then
[] => { [] => {
// a. Let dv be the time value (UTC) identifying the current time. // a. Let dv be the time value (UTC) identifying the current time.
Date::default() Self::default()
} }
// 4. Else if numberOfArgs = 1, then // 4. Else if numberOfArgs = 1, then
// a. Let value be values[0]. // a. Let value be values[0].
@ -229,7 +229,7 @@ impl Date {
// 1. Assert: The next step never returns an abrupt completion because v is a String. // 1. Assert: The next step never returns an abrupt completion because v is a String.
// 2. Let tv be the result of parsing v as a date, in exactly the same manner as for the // 2. Let tv be the result of parsing v as a date, in exactly the same manner as for the
// parse method (21.4.3.2). // parse method (21.4.3.2).
Date( Self(
str.to_std_string() str.to_std_string()
.ok() .ok()
.and_then(|s| { .and_then(|s| {
@ -242,7 +242,7 @@ impl Date {
v => { v => {
// Directly convert to integer // Directly convert to integer
// 1. Let tv be ? ToNumber(v). // 1. Let tv be ? ToNumber(v).
Date( Self(
v.to_integer_or_nan(context)? v.to_integer_or_nan(context)?
.as_integer() .as_integer()
// d. Let dv be TimeClip(tv). // d. Let dv be TimeClip(tv).
@ -256,7 +256,7 @@ impl Date {
// 5. Else, // 5. Else,
_ => { _ => {
// Separating this into its own function to simplify the logic. // Separating this into its own function to simplify the logic.
Date( Self(
Self::construct_date(args, context)? Self::construct_date(args, context)?
.and_then(|dt| Local.from_local_datetime(&dt).earliest()) .and_then(|dt| Local.from_local_datetime(&dt).earliest())
.map(|dt| dt.naive_utc()), .map(|dt| dt.naive_utc()),
@ -717,7 +717,7 @@ impl Date {
); );
// 7. Set the [[DateValue]] internal slot of this Date object to u. // 7. Set the [[DateValue]] internal slot of this Date object to u.
*t = Date(datetime); *t = Self(datetime);
// 8. Return u. // 8. Return u.
Ok(t.as_value()) Ok(t.as_value())
@ -748,7 +748,7 @@ impl Date {
.earliest() .earliest()
.as_ref() .as_ref()
.map(DateTime::naive_utc) else { .map(DateTime::naive_utc) else {
*t = Date(None); *t = Self(None);
return Ok(t.as_value()) return Ok(t.as_value())
}; };
datetime datetime
@ -785,7 +785,7 @@ impl Date {
); );
// 8. Set the [[DateValue]] internal slot of this Date object to u. // 8. Set the [[DateValue]] internal slot of this Date object to u.
*t = Date(datetime); *t = Self(datetime);
// 9. Return u. // 9. Return u.
Ok(t.as_value()) Ok(t.as_value())
@ -851,7 +851,7 @@ impl Date {
); );
// 13. Set the [[DateValue]] internal slot of this Date object to u. // 13. Set the [[DateValue]] internal slot of this Date object to u.
*t = Date(datetime); *t = Self(datetime);
// 14. Return u. // 14. Return u.
Ok(t.as_value()) Ok(t.as_value())
@ -892,7 +892,7 @@ impl Date {
); );
// 7. Set the [[DateValue]] internal slot of this Date object to u. // 7. Set the [[DateValue]] internal slot of this Date object to u.
*t = Date(datetime); *t = Self(datetime);
// 8. Return u. // 8. Return u.
Ok(t.as_value()) Ok(t.as_value())
@ -948,7 +948,7 @@ impl Date {
); );
// 11. Set the [[DateValue]] internal slot of this Date object to u. // 11. Set the [[DateValue]] internal slot of this Date object to u.
*t = Date(datetime); *t = Self(datetime);
// 12. Return u. // 12. Return u.
Ok(t.as_value()) Ok(t.as_value())
@ -997,7 +997,7 @@ impl Date {
); );
// 9. Set the [[DateValue]] internal slot of this Date object to u. // 9. Set the [[DateValue]] internal slot of this Date object to u.
*t = Date(datetime); *t = Self(datetime);
// 10. Return u. // 10. Return u.
Ok(t.as_value()) Ok(t.as_value())
@ -1045,7 +1045,7 @@ impl Date {
); );
// 9. Set the [[DateValue]] internal slot of this Date object to u. // 9. Set the [[DateValue]] internal slot of this Date object to u.
*t = Date(datetime); *t = Self(datetime);
// 10. Return u. // 10. Return u.
Ok(t.as_value()) Ok(t.as_value())
@ -1085,14 +1085,14 @@ impl Date {
.as_ref() .as_ref()
.map(DateTime::naive_utc) .map(DateTime::naive_utc)
}) else { }) else {
*t = Date(None); *t = Self(None);
return Ok(t.as_value()); return Ok(t.as_value());
}; };
// 4. If y is NaN, then // 4. If y is NaN, then
let Some(mut year) = year.as_integer() else { let Some(mut year) = year.as_integer() else {
// a. Set the [[DateValue]] internal slot of this Date object to NaN. // a. Set the [[DateValue]] internal slot of this Date object to NaN.
*t = Date(None); *t = Self(None);
// b. Return NaN. // b. Return NaN.
return Ok(t.as_value()); return Ok(t.as_value());
@ -1116,7 +1116,7 @@ impl Date {
); );
// 10. Set the [[DateValue]] internal slot of this Date object to TimeClip(date). // 10. Set the [[DateValue]] internal slot of this Date object to TimeClip(date).
*t = Date(datetime); *t = Self(datetime);
// 11. Return the value of the [[DateValue]] internal slot of this Date object. // 11. Return the value of the [[DateValue]] internal slot of this Date object.
Ok(t.as_value()) Ok(t.as_value())
@ -1150,7 +1150,7 @@ impl Date {
.and_then(NaiveDateTime::from_timestamp_millis); .and_then(NaiveDateTime::from_timestamp_millis);
// 4. Set the [[DateValue]] internal slot of this Date object to v. // 4. Set the [[DateValue]] internal slot of this Date object to v.
*t = Date(timestamp); *t = Self(timestamp);
// 5. Return v. // 5. Return v.
Ok(t.as_value()) Ok(t.as_value())
@ -1410,7 +1410,7 @@ impl Date {
_context: &mut Context<'_>, _context: &mut Context<'_>,
) -> JsResult<JsValue> { ) -> JsResult<JsValue> {
// 1. Return ? thisTimeValue(this value). // 1. Return ? thisTimeValue(this value).
Ok(Date(this_time_value(this)?).as_value()) Ok(Self(this_time_value(this)?).as_value())
} }
/// [`Date.prototype [ @@toPrimitive ] ( hint )`][spec]. /// [`Date.prototype [ @@toPrimitive ] ( hint )`][spec].

4
boa_engine/src/builtins/function/mod.rs

@ -781,7 +781,9 @@ impl BuiltInFunctionObject {
let target_name = target.get("name", context)?; let target_name = target.get("name", context)?;
// 9. If Type(targetName) is not String, set targetName to the empty String. // 9. If Type(targetName) is not String, set targetName to the empty String.
let target_name = target_name.as_string().map_or(js_string!(), Clone::clone); let target_name = target_name
.as_string()
.map_or_else(JsString::default, Clone::clone);
// 10. Perform SetFunctionName(F, targetName, "bound"). // 10. Perform SetFunctionName(F, targetName, "bound").
set_function_name(&f, &target_name.into(), Some(js_string!("bound")), context); set_function_name(&f, &target_name.into(), Some(js_string!("bound")), context);

2
boa_engine/src/builtins/intl/collator/mod.rs

@ -343,7 +343,7 @@ impl Collator {
get_prototype_from_constructor(new_target, StandardConstructors::collator, context)?; get_prototype_from_constructor(new_target, StandardConstructors::collator, context)?;
let collator = JsObject::from_proto_and_data( let collator = JsObject::from_proto_and_data(
prototype, prototype,
ObjectData::collator(Collator { ObjectData::collator(Self {
locale, locale,
collation, collation,
numeric, numeric,

8
boa_engine/src/builtins/intl/collator/options.rs

@ -16,10 +16,10 @@ impl Sensitivity {
/// Converts the sensitivity option to the equivalent ICU4X collator options. /// Converts the sensitivity option to the equivalent ICU4X collator options.
pub(crate) const fn to_collator_options(self) -> (Strength, CaseLevel) { pub(crate) const fn to_collator_options(self) -> (Strength, CaseLevel) {
match self { match self {
Sensitivity::Base => (Strength::Primary, CaseLevel::Off), Self::Base => (Strength::Primary, CaseLevel::Off),
Sensitivity::Accent => (Strength::Secondary, CaseLevel::Off), Self::Accent => (Strength::Secondary, CaseLevel::Off),
Sensitivity::Case => (Strength::Primary, CaseLevel::On), Self::Case => (Strength::Primary, CaseLevel::On),
Sensitivity::Variant => (Strength::Tertiary, CaseLevel::On), Self::Variant => (Strength::Tertiary, CaseLevel::On),
} }
} }
} }

8
boa_engine/src/builtins/intl/date_time_format.rs

@ -27,10 +27,10 @@ use super::options::OptionType;
impl OptionType for HourCycle { impl OptionType for HourCycle {
fn from_value(value: JsValue, context: &mut Context<'_>) -> JsResult<Self> { fn from_value(value: JsValue, context: &mut Context<'_>) -> JsResult<Self> {
match value.to_string(context)?.to_std_string_escaped().as_str() { match value.to_string(context)?.to_std_string_escaped().as_str() {
"h11" => Ok(HourCycle::H11), "h11" => Ok(Self::H11),
"h12" => Ok(HourCycle::H12), "h12" => Ok(Self::H12),
"h23" => Ok(HourCycle::H23), "h23" => Ok(Self::H23),
"h24" => Ok(HourCycle::H24), "h24" => Ok(Self::H24),
_ => Err(JsNativeError::range() _ => Err(JsNativeError::range()
.with_message("provided string was not `h11`, `h12`, `h23` or `h24`") .with_message("provided string was not `h11`, `h12`, `h23` or `h24`")
.into()), .into()),

10
boa_engine/src/builtins/intl/list_format/mod.rs

@ -148,7 +148,7 @@ impl ListFormat {
get_prototype_from_constructor(new_target, StandardConstructors::list_format, context)?; get_prototype_from_constructor(new_target, StandardConstructors::list_format, context)?;
let list_format = JsObject::from_proto_and_data( let list_format = JsObject::from_proto_and_data(
prototype, prototype,
ObjectData::list_format(ListFormat { ObjectData::list_format(Self {
formatter: context formatter: context
.icu() .icu()
.provider() .provider()
@ -249,15 +249,15 @@ impl ListFormat {
impl Part { impl Part {
const fn typ(&self) -> &'static str { const fn typ(&self) -> &'static str {
match self { match self {
Part::Literal(_) => "literal", Self::Literal(_) => "literal",
Part::Element(_) => "element", Self::Element(_) => "element",
} }
} }
#[allow(clippy::missing_const_for_fn)] #[allow(clippy::missing_const_for_fn)]
fn value(self) -> String { fn value(self) -> String {
match self { match self {
Part::Literal(s) | Part::Element(s) => s, Self::Literal(s) | Self::Element(s) => s,
} }
} }
} }
@ -276,7 +276,7 @@ impl ListFormat {
} }
impl PartsWrite for WriteString { impl PartsWrite for WriteString {
type SubPartsWrite = WriteString; type SubPartsWrite = Self;
fn with_part( fn with_part(
&mut self, &mut self,

2
boa_engine/src/builtins/intl/locale/options.rs

@ -7,7 +7,7 @@ impl OptionType for Value {
let val = value let val = value
.to_string(context)? .to_string(context)?
.to_std_string_escaped() .to_std_string_escaped()
.parse::<Value>() .parse::<Self>()
.map_err(|e| JsNativeError::range().with_message(e.to_string()))?; .map_err(|e| JsNativeError::range().with_message(e.to_string()))?;
if val.as_tinystr_slice().is_empty() { if val.as_tinystr_slice().is_empty() {

6
boa_engine/src/builtins/intl/options.rs

@ -94,9 +94,9 @@ impl OptionTypeParsable for LocaleMatcher {}
impl OptionType for CaseFirst { impl OptionType for CaseFirst {
fn from_value(value: JsValue, context: &mut Context<'_>) -> JsResult<Self> { fn from_value(value: JsValue, context: &mut Context<'_>) -> JsResult<Self> {
match value.to_string(context)?.to_std_string_escaped().as_str() { match value.to_string(context)?.to_std_string_escaped().as_str() {
"upper" => Ok(CaseFirst::UpperFirst), "upper" => Ok(Self::UpperFirst),
"lower" => Ok(CaseFirst::LowerFirst), "lower" => Ok(Self::LowerFirst),
"false" => Ok(CaseFirst::Off), "false" => Ok(Self::Off),
_ => Err(JsNativeError::range() _ => Err(JsNativeError::range()
.with_message("provided string was not `upper`, `lower` or `false`") .with_message("provided string was not `upper`, `lower` or `false`")
.into()), .into()),

2
boa_engine/src/builtins/math/tests.rs

@ -93,7 +93,7 @@ fn asinh() {
let a = forward_val(&mut context, "a").unwrap(); let a = forward_val(&mut context, "a").unwrap();
let b = forward_val(&mut context, "b").unwrap(); let b = forward_val(&mut context, "b").unwrap();
assert_eq!(a.to_number(&mut context).unwrap(), 0.881_373_587_019_542_9); assert_eq!(a.to_number(&mut context).unwrap(), 0.881_373_587_019_543);
assert_eq!(b.to_number(&mut context).unwrap(), 0_f64); assert_eq!(b.to_number(&mut context).unwrap(), 0_f64);
} }

14
boa_engine/src/builtins/object/mod.rs

@ -203,9 +203,8 @@ impl Object {
}; };
// 3. If Type(O) is not Object, return undefined. // 3. If Type(O) is not Object, return undefined.
let object = match this { let JsValue::Object(object) = this else {
JsValue::Object(object) => object, return Ok(JsValue::undefined());
_ => return Ok(JsValue::undefined()),
}; };
// 4. Let status be ? O.[[SetPrototypeOf]](proto). // 4. Let status be ? O.[[SetPrototypeOf]](proto).
@ -517,9 +516,7 @@ impl Object {
context: &mut Context<'_>, context: &mut Context<'_>,
) -> JsValue { ) -> JsValue {
// 1. If Desc is undefined, return undefined. // 1. If Desc is undefined, return undefined.
let desc = if let Some(desc) = desc { let Some(desc)= desc else {
desc
} else {
return JsValue::undefined(); return JsValue::undefined();
}; };
@ -892,9 +889,8 @@ impl Object {
args: &[JsValue], args: &[JsValue],
context: &mut Context<'_>, context: &mut Context<'_>,
) -> JsResult<JsValue> { ) -> JsResult<JsValue> {
let key = match args.get(0) { let Some(key) = args.get(0) else {
None => return Ok(JsValue::new(false)), return Ok(JsValue::new(false));
Some(key) => key,
}; };
let key = key.to_property_key(context)?; let key = key.to_property_key(context)?;

2
boa_engine/src/builtins/promise/mod.rs

@ -235,7 +235,7 @@ impl PromiseCapability {
// 9. Set promiseCapability.[[Promise]] to promise. // 9. Set promiseCapability.[[Promise]] to promise.
// 10. Return promiseCapability. // 10. Return promiseCapability.
Ok(PromiseCapability { Ok(Self {
promise, promise,
resolve, resolve,
reject, reject,

4
boa_engine/src/builtins/regexp/mod.rs

@ -609,9 +609,7 @@ impl RegExp {
) -> JsResult<JsValue> { ) -> JsResult<JsValue> {
// 1. Let R be the this value. // 1. Let R be the this value.
// 2. If Type(R) is not Object, throw a TypeError exception. // 2. If Type(R) is not Object, throw a TypeError exception.
let object = if let Some(object) = this.as_object() { let Some(object) = this.as_object() else {
object
} else {
return Err(JsNativeError::typ() return Err(JsNativeError::typ()
.with_message("RegExp.prototype.source method called on incompatible value") .with_message("RegExp.prototype.source method called on incompatible value")
.into()); .into());

5
boa_engine/src/builtins/string/mod.rs

@ -2355,9 +2355,8 @@ pub(crate) fn get_substitution(
/// [spec]: https://tc39.es/ecma262/#sec-isregexp /// [spec]: https://tc39.es/ecma262/#sec-isregexp
fn is_reg_exp(argument: &JsValue, context: &mut Context<'_>) -> JsResult<bool> { fn is_reg_exp(argument: &JsValue, context: &mut Context<'_>) -> JsResult<bool> {
// 1. If Type(argument) is not Object, return false. // 1. If Type(argument) is not Object, return false.
let argument = match argument { let JsValue::Object(argument) = argument else {
JsValue::Object(o) => o, return Ok(false);
_ => return Ok(false),
}; };
is_reg_exp_object(argument, context) is_reg_exp_object(argument, context)

4
boa_engine/src/builtins/weak/weak_ref.rs

@ -35,7 +35,7 @@ impl BuiltIn for WeakRef {
let _timer = Profiler::global().start_event(Self::NAME, "init"); let _timer = Profiler::global().start_event(Self::NAME, "init");
ConstructorBuilder::with_standard_constructor( ConstructorBuilder::with_standard_constructor(
context, context,
WeakRef::constructor, Self::constructor,
context.intrinsics().constructors().weak_ref().clone(), context.intrinsics().constructors().weak_ref().clone(),
) )
.name(Self::NAME) .name(Self::NAME)
@ -45,7 +45,7 @@ impl BuiltIn for WeakRef {
"WeakRef", "WeakRef",
Attribute::CONFIGURABLE, Attribute::CONFIGURABLE,
) )
.method(WeakRef::deref, "deref", 0) .method(Self::deref, "deref", 0)
.build() .build()
.conv::<JsValue>() .conv::<JsValue>()
.pipe(Some) .pipe(Some)

2
boa_engine/src/bytecompiler/jump_control.rs

@ -44,7 +44,7 @@ bitflags! {
impl Default for JumpControlInfoFlags { impl Default for JumpControlInfoFlags {
fn default() -> Self { fn default() -> Self {
JumpControlInfoFlags::empty() Self::empty()
} }
} }

2
boa_engine/src/job.rs

@ -107,7 +107,7 @@ impl Debug for JobCallback {
impl JobCallback { impl JobCallback {
/// Creates a new `JobCallback`. /// Creates a new `JobCallback`.
pub fn new<T: Any + Trace>(callback: JsFunction, host_defined: T) -> Self { pub fn new<T: Any + Trace>(callback: JsFunction, host_defined: T) -> Self {
JobCallback { Self {
callback, callback,
host_defined: Box::new(host_defined), host_defined: Box::new(host_defined),
} }

10
boa_engine/src/lib.rs

@ -95,7 +95,7 @@
clippy::missing_errors_doc, clippy::missing_errors_doc,
clippy::let_unit_value, clippy::let_unit_value,
clippy::option_if_let_else, clippy::option_if_let_else,
// Currently derive macros are linted. Should be fixed in 1.66. See https://github.com/rust-lang/rust-clippy/pull/9454 // Currently lints in places where `Self` would have a type parameter.
clippy::use_self, clippy::use_self,
// It may be worth to look if we can fix the issues highlighted by these lints. // It may be worth to look if we can fix the issues highlighted by these lints.
@ -223,18 +223,14 @@ pub(crate) fn check_output(actions: &[TestAction]) {
assert_eq!( assert_eq!(
&forward(&mut context, case), &forward(&mut context, case),
expected, expected,
"Test case {} ('{}')", "Test case {i} ('{case}')"
i,
case
); );
i += 1; i += 1;
} }
TestAction::TestStartsWith(case, expected) => { TestAction::TestStartsWith(case, expected) => {
assert!( assert!(
&forward(&mut context, case).starts_with(expected), &forward(&mut context, case).starts_with(expected),
"Test case {} ('{}')", "Test case {i} ('{case}')",
i,
case
); );
i += 1; i += 1;
} }

5
boa_engine/src/object/internal_methods/array.rs

@ -111,12 +111,9 @@ fn array_set_length(
context: &mut Context<'_>, context: &mut Context<'_>,
) -> JsResult<bool> { ) -> JsResult<bool> {
// 1. If Desc.[[Value]] is absent, then // 1. If Desc.[[Value]] is absent, then
let new_len_val = match desc.value() { let Some(new_len_val) = desc.value() else {
Some(value) => value,
_ => {
// a. Return OrdinaryDefineOwnProperty(A, "length", Desc). // a. Return OrdinaryDefineOwnProperty(A, "length", Desc).
return super::ordinary_define_own_property(obj, "length".into(), desc, context); return super::ordinary_define_own_property(obj, "length".into(), desc, context);
}
}; };
// 3. Let newLen be ? ToUint32(Desc.[[Value]]). // 3. Let newLen be ? ToUint32(Desc.[[Value]]).

5
boa_engine/src/object/internal_methods/mod.rs

@ -608,10 +608,9 @@ pub(crate) fn ordinary_set(
return Ok(false); return Ok(false);
} }
let receiver = match receiver.as_object() {
Some(obj) => obj,
// b. If Type(Receiver) is not Object, return false. // b. If Type(Receiver) is not Object, return false.
_ => return Ok(false), let Some(receiver) = receiver.as_object() else {
return Ok(false);
}; };
// c. Let existingDescriptor be ? Receiver.[[GetOwnProperty]](P). // c. Let existingDescriptor be ? Receiver.[[GetOwnProperty]](P).

8
boa_engine/src/object/operations.rs

@ -938,7 +938,7 @@ impl JsObject {
/// [spec]: https://tc39.es/ecma262/#sec-initializeinstanceelements /// [spec]: https://tc39.es/ecma262/#sec-initializeinstanceelements
pub(crate) fn initialize_instance_elements( pub(crate) fn initialize_instance_elements(
&self, &self,
constructor: &JsObject, constructor: &Self,
context: &mut Context<'_>, context: &mut Context<'_>,
) -> JsResult<()> { ) -> JsResult<()> {
let constructor_borrow = constructor.borrow(); let constructor_borrow = constructor.borrow();
@ -1110,10 +1110,10 @@ impl JsValue {
#[inline] #[inline]
pub(crate) fn call( pub(crate) fn call(
&self, &self,
this: &JsValue, this: &Self,
args: &[JsValue], args: &[Self],
context: &mut Context<'_>, context: &mut Context<'_>,
) -> JsResult<JsValue> { ) -> JsResult<Self> {
self.as_callable() self.as_callable()
.ok_or_else(|| { .ok_or_else(|| {
JsNativeError::typ().with_message(format!( JsNativeError::typ().with_message(format!(

2
boa_engine/src/string/mod.rs

@ -781,7 +781,7 @@ impl FromStr for JsString {
type Err = Infallible; type Err = Infallible;
fn from_str(s: &str) -> Result<Self, Self::Err> { fn from_str(s: &str) -> Result<Self, Self::Err> {
Ok(JsString::from(s)) Ok(Self::from(s))
} }
} }

26
boa_engine/src/symbol.rs

@ -80,19 +80,19 @@ enum WellKnown {
impl WellKnown { impl WellKnown {
const fn description(self) -> JsString { const fn description(self) -> JsString {
match self { match self {
WellKnown::AsyncIterator => StaticJsStrings::symbol_async_iterator(), Self::AsyncIterator => StaticJsStrings::symbol_async_iterator(),
WellKnown::HasInstance => StaticJsStrings::symbol_has_instance(), Self::HasInstance => StaticJsStrings::symbol_has_instance(),
WellKnown::IsConcatSpreadable => StaticJsStrings::symbol_is_concat_spreadable(), Self::IsConcatSpreadable => StaticJsStrings::symbol_is_concat_spreadable(),
WellKnown::Iterator => StaticJsStrings::symbol_iterator(), Self::Iterator => StaticJsStrings::symbol_iterator(),
WellKnown::Match => StaticJsStrings::symbol_match(), Self::Match => StaticJsStrings::symbol_match(),
WellKnown::MatchAll => StaticJsStrings::symbol_match_all(), Self::MatchAll => StaticJsStrings::symbol_match_all(),
WellKnown::Replace => StaticJsStrings::symbol_replace(), Self::Replace => StaticJsStrings::symbol_replace(),
WellKnown::Search => StaticJsStrings::symbol_search(), Self::Search => StaticJsStrings::symbol_search(),
WellKnown::Species => StaticJsStrings::symbol_species(), Self::Species => StaticJsStrings::symbol_species(),
WellKnown::Split => StaticJsStrings::symbol_split(), Self::Split => StaticJsStrings::symbol_split(),
WellKnown::ToPrimitive => StaticJsStrings::symbol_to_primitive(), Self::ToPrimitive => StaticJsStrings::symbol_to_primitive(),
WellKnown::ToStringTag => StaticJsStrings::symbol_to_string_tag(), Self::ToStringTag => StaticJsStrings::symbol_to_string_tag(),
WellKnown::Unscopables => StaticJsStrings::symbol_unscopables(), Self::Unscopables => StaticJsStrings::symbol_unscopables(),
} }
} }

6
boa_engine/src/tagged.rs

@ -50,7 +50,7 @@ impl<T> Tagged<T> {
debug_assert!(std::mem::align_of::<T>() >= 2); debug_assert!(std::mem::align_of::<T>() >= 2);
let addr = (tag << 1) | 1; let addr = (tag << 1) | 1;
// SAFETY: `addr` is never zero, since we always set its LSB to 1 // SAFETY: `addr` is never zero, since we always set its LSB to 1
unsafe { Tagged(NonNull::new_unchecked(sptr::invalid_mut(addr))) } unsafe { Self(NonNull::new_unchecked(sptr::invalid_mut(addr))) }
} }
/// Creates a new `Tagged` pointer from a raw pointer. /// Creates a new `Tagged` pointer from a raw pointer.
@ -65,7 +65,7 @@ impl<T> Tagged<T> {
pub(crate) const unsafe fn from_ptr(ptr: *mut T) -> Tagged<T> { pub(crate) const unsafe fn from_ptr(ptr: *mut T) -> Tagged<T> {
debug_assert!(std::mem::align_of::<T>() >= 2); debug_assert!(std::mem::align_of::<T>() >= 2);
// SAFETY: the caller must ensure the invariants hold. // SAFETY: the caller must ensure the invariants hold.
unsafe { Tagged(NonNull::new_unchecked(ptr)) } unsafe { Self(NonNull::new_unchecked(ptr)) }
} }
/// Creates a new `Tagged` pointer from a `NonNull` pointer. /// Creates a new `Tagged` pointer from a `NonNull` pointer.
@ -75,7 +75,7 @@ impl<T> Tagged<T> {
/// - `T` must have an alignment of at least 2. /// - `T` must have an alignment of at least 2.
pub(crate) const fn from_non_null(ptr: NonNull<T>) -> Tagged<T> { pub(crate) const fn from_non_null(ptr: NonNull<T>) -> Tagged<T> {
debug_assert!(std::mem::align_of::<T>() >= 2); debug_assert!(std::mem::align_of::<T>() >= 2);
Tagged(ptr) Self(ptr)
} }
/// Unwraps the `Tagged` pointer. /// Unwraps the `Tagged` pointer.

3
boa_engine/src/value/integer.rs

@ -121,7 +121,6 @@ impl IntegerOrNan {
impl From<IntegerOrInfinity> for IntegerOrNan { impl From<IntegerOrInfinity> for IntegerOrNan {
fn from(ior: IntegerOrInfinity) -> Self { fn from(ior: IntegerOrInfinity) -> Self {
ior.as_integer() ior.as_integer().map_or(Self::Nan, IntegerOrNan::Integer)
.map_or(IntegerOrNan::Nan, IntegerOrNan::Integer)
} }
} }

14
boa_engine/src/vm/flowgraph/color.rs

@ -77,13 +77,13 @@ impl Color {
impl Display for Color { impl Display for Color {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self { match self {
Color::None => f.write_str(""), Self::None => f.write_str(""),
Color::Red => f.write_str("red"), Self::Red => f.write_str("red"),
Color::Green => f.write_str("green"), Self::Green => f.write_str("green"),
Color::Blue => f.write_str("blue"), Self::Blue => f.write_str("blue"),
Color::Yellow => f.write_str("yellow"), Self::Yellow => f.write_str("yellow"),
Color::Purple => f.write_str("purple"), Self::Purple => f.write_str("purple"),
Color::Rgb { r, g, b } => write!(f, "#{r:02X}{b:02X}{g:02X}"), Self::Rgb { r, g, b } => write!(f, "#{r:02X}{b:02X}{g:02X}"),
} }
} }
} }

6
boa_engine/src/vm/flowgraph/graph.rs

@ -83,8 +83,8 @@ impl SubGraph {
/// Create a subgraph in this subgraph. /// Create a subgraph in this subgraph.
#[inline] #[inline]
pub fn subgraph(&mut self, label: String) -> &mut SubGraph { pub fn subgraph(&mut self, label: String) -> &mut Self {
self.subgraphs.push(SubGraph::new(label)); self.subgraphs.push(Self::new(label));
let result = self let result = self
.subgraphs .subgraphs
.last_mut() .last_mut()
@ -248,7 +248,7 @@ impl Graph {
#[inline] #[inline]
#[must_use] #[must_use]
pub fn new(direction: Direction) -> Self { pub fn new(direction: Direction) -> Self {
Graph { Self {
subgraphs: Vec::default(), subgraphs: Vec::default(),
direction, direction,
} }

2
boa_examples/src/bin/loadfile.rs

@ -26,6 +26,6 @@ fn main() {
} }
}; };
} }
Err(msg) => eprintln!("Error: {}", msg), Err(msg) => eprintln!("Error: {msg}"),
} }
} }

2
boa_examples/src/bin/modulehandler.rs

@ -45,7 +45,7 @@ fn require(_: &JsValue, args: &[JsValue], ctx: &mut Context<'_>) -> JsResult<JsV
.to_std_string_escaped(); .to_std_string_escaped();
// Read the module source file // Read the module source file
println!("Loading: {}", libfile); println!("Loading: {libfile}");
let buffer = read_to_string(libfile); let buffer = read_to_string(libfile);
if let Err(..) = buffer { if let Err(..) = buffer {
println!("Error: {}", buffer.unwrap_err()); println!("Error: {}", buffer.unwrap_err());

28
boa_gc/src/cell.rs

@ -12,7 +12,7 @@ use std::{
/// `BorrowFlag` represent the internal state of a `GcCell` and /// `BorrowFlag` represent the internal state of a `GcCell` and
/// keeps track of the amount of current borrows. /// keeps track of the amount of current borrows.
#[derive(Copy, Clone)] #[derive(Copy, Clone)]
pub(crate) struct BorrowFlag(usize); struct BorrowFlag(usize);
/// `BorrowState` represents the various states of a `BorrowFlag` /// `BorrowState` represents the various states of a `BorrowFlag`
/// ///
@ -20,7 +20,7 @@ pub(crate) struct BorrowFlag(usize);
/// - Writing: the value is currently being written/borrowed mutably. /// - Writing: the value is currently being written/borrowed mutably.
/// - Unused: the value is currently unrooted. /// - Unused: the value is currently unrooted.
#[derive(Copy, Clone, Debug, Eq, PartialEq)] #[derive(Copy, Clone, Debug, Eq, PartialEq)]
pub(crate) enum BorrowState { enum BorrowState {
Reading, Reading,
Writing, Writing,
Unused, Unused,
@ -31,11 +31,11 @@ const WRITING: usize = !1;
const UNUSED: usize = 0; const UNUSED: usize = 0;
/// The base borrowflag init is rooted, and has no outstanding borrows. /// The base borrowflag init is rooted, and has no outstanding borrows.
pub(crate) const BORROWFLAG_INIT: BorrowFlag = BorrowFlag(ROOT); const BORROWFLAG_INIT: BorrowFlag = BorrowFlag(ROOT);
impl BorrowFlag { impl BorrowFlag {
/// Check the current `BorrowState` of `BorrowFlag`. /// Check the current `BorrowState` of `BorrowFlag`.
pub(crate) const fn borrowed(self) -> BorrowState { const fn borrowed(self) -> BorrowState {
match self.0 & !ROOT { match self.0 & !ROOT {
UNUSED => BorrowState::Unused, UNUSED => BorrowState::Unused,
WRITING => BorrowState::Writing, WRITING => BorrowState::Writing,
@ -44,18 +44,18 @@ impl BorrowFlag {
} }
/// Check whether the borrow bit is flagged. /// Check whether the borrow bit is flagged.
pub(crate) const fn rooted(self) -> bool { const fn rooted(self) -> bool {
self.0 & ROOT > 0 self.0 & ROOT > 0
} }
/// Set the `BorrowFlag`'s state to writing. /// Set the `BorrowFlag`'s state to writing.
pub(crate) const fn set_writing(self) -> Self { const fn set_writing(self) -> Self {
// Set every bit other than the root bit, which is preserved // Set every bit other than the root bit, which is preserved
Self(self.0 | WRITING) Self(self.0 | WRITING)
} }
/// Remove the root flag on `BorrowFlag` /// Remove the root flag on `BorrowFlag`
pub(crate) const fn set_unused(self) -> Self { const fn set_unused(self) -> Self {
// Clear every bit other than the root bit, which is preserved // Clear every bit other than the root bit, which is preserved
Self(self.0 & ROOT) Self(self.0 & ROOT)
} }
@ -65,7 +65,7 @@ impl BorrowFlag {
/// # Panic /// # Panic
/// - This method will panic if the current `BorrowState` is writing. /// - This method will panic if the current `BorrowState` is writing.
/// - This method will panic after incrementing if the borrow count overflows. /// - This method will panic after incrementing if the borrow count overflows.
pub(crate) fn add_reading(self) -> Self { fn add_reading(self) -> Self {
assert!(self.borrowed() != BorrowState::Writing); assert!(self.borrowed() != BorrowState::Writing);
// Add 1 to the integer starting at the second binary digit. As our // Add 1 to the integer starting at the second binary digit. As our
// borrowstate is not writing, we know that overflow cannot happen, so // borrowstate is not writing, we know that overflow cannot happen, so
@ -86,7 +86,7 @@ impl BorrowFlag {
/// ///
/// # Panic /// # Panic
/// - This method will panic if the current `BorrowState` is not reading. /// - This method will panic if the current `BorrowState` is not reading.
pub(crate) fn sub_reading(self) -> Self { fn sub_reading(self) -> Self {
assert!(self.borrowed() == BorrowState::Reading); assert!(self.borrowed() == BorrowState::Reading);
// Subtract 1 from the integer starting at the second binary digit. As // Subtract 1 from the integer starting at the second binary digit. As
// our borrowstate is not writing or unused, we know that overflow or // our borrowstate is not writing or unused, we know that overflow or
@ -98,7 +98,7 @@ impl BorrowFlag {
} }
/// Set the root flag on the `BorrowFlag`. /// Set the root flag on the `BorrowFlag`.
pub(crate) fn set_rooted(self, rooted: bool) -> Self { fn set_rooted(self, rooted: bool) -> Self {
// Preserve the non-root bits // Preserve the non-root bits
Self((self.0 & !ROOT) | (usize::from(rooted))) Self((self.0 & !ROOT) | (usize::from(rooted)))
} }
@ -118,8 +118,8 @@ impl Debug for BorrowFlag {
/// ///
/// This object is a `RefCell` that can be used inside of a `Gc<T>`. /// This object is a `RefCell` that can be used inside of a `Gc<T>`.
pub struct GcRefCell<T: ?Sized + 'static> { pub struct GcRefCell<T: ?Sized + 'static> {
pub(crate) flags: Cell<BorrowFlag>, flags: Cell<BorrowFlag>,
pub(crate) cell: UnsafeCell<T>, cell: UnsafeCell<T>,
} }
impl<T: Trace> GcRefCell<T> { impl<T: Trace> GcRefCell<T> {
@ -296,8 +296,8 @@ unsafe impl<T: Trace + ?Sized> Trace for GcRefCell<T> {
/// A wrapper type for an immutably borrowed value from a `GcCell<T>`. /// A wrapper type for an immutably borrowed value from a `GcCell<T>`.
pub struct GcRef<'a, T: ?Sized + 'static> { pub struct GcRef<'a, T: ?Sized + 'static> {
pub(crate) flags: &'a Cell<BorrowFlag>, flags: &'a Cell<BorrowFlag>,
pub(crate) value: &'a T, value: &'a T,
} }
impl<'a, T: ?Sized> GcRef<'a, T> { impl<'a, T: ?Sized> GcRef<'a, T> {

3
boa_parser/src/parser/cursor/buffered_lexer/mod.rs

@ -215,8 +215,7 @@ where
) -> ParseResult<Option<&Token>> { ) -> ParseResult<Option<&Token>> {
assert!( assert!(
skip_n <= MAX_PEEK_SKIP, skip_n <= MAX_PEEK_SKIP,
"you cannot skip more than {} elements", "you cannot skip more than {MAX_PEEK_SKIP} elements",
MAX_PEEK_SKIP
); );
let mut read_index = self.read_index; let mut read_index = self.read_index;

4
boa_parser/src/parser/expression/assignment/arrow_function.rs

@ -81,8 +81,8 @@ where
let _timer = Profiler::global().start_event("ArrowFunction", "Parsing"); let _timer = Profiler::global().start_event("ArrowFunction", "Parsing");
let next_token = cursor.peek(0, interner).or_abrupt()?; let next_token = cursor.peek(0, interner).or_abrupt()?;
let (params, params_start_position) = if let TokenKind::Punctuator(Punctuator::OpenParen) = let (params, params_start_position) = if next_token.kind()
&next_token.kind() == &TokenKind::Punctuator(Punctuator::OpenParen)
{ {
// CoverParenthesizedExpressionAndArrowParameterList // CoverParenthesizedExpressionAndArrowParameterList
let params_start_position = cursor let params_start_position = cursor

4
boa_parser/src/parser/expression/assignment/async_arrow_function.rs

@ -77,8 +77,8 @@ where
cursor.peek_expect_no_lineterminator(0, "async arrow function", interner)?; cursor.peek_expect_no_lineterminator(0, "async arrow function", interner)?;
let next_token = cursor.peek(0, interner).or_abrupt()?; let next_token = cursor.peek(0, interner).or_abrupt()?;
let (params, params_start_position) = if let TokenKind::Punctuator(Punctuator::OpenParen) = let (params, params_start_position) = if next_token.kind()
&next_token.kind() == &TokenKind::Punctuator(Punctuator::OpenParen)
{ {
let params_start_position = cursor let params_start_position = cursor
.expect(Punctuator::OpenParen, "async arrow function", interner)? .expect(Punctuator::OpenParen, "async arrow function", interner)?

2
boa_parser/src/parser/expression/assignment/exponentiation.rs

@ -88,7 +88,7 @@ where
let lhs = UpdateExpression::new(self.name, self.allow_yield, self.allow_await) let lhs = UpdateExpression::new(self.name, self.allow_yield, self.allow_await)
.parse(cursor, interner)?; .parse(cursor, interner)?;
if let Some(tok) = cursor.peek(0, interner)? { if let Some(tok) = cursor.peek(0, interner)? {
if let TokenKind::Punctuator(Punctuator::Exp) = tok.kind() { if tok.kind() == &TokenKind::Punctuator(Punctuator::Exp) {
cursor.advance(interner); cursor.advance(interner);
return Ok(Binary::new( return Ok(Binary::new(
ArithmeticOp::Exp.into(), ArithmeticOp::Exp.into(),

9
boa_parser/src/parser/expression/primary/object_initializer/mod.rs

@ -213,7 +213,7 @@ where
let token = cursor.peek(0, interner).or_abrupt()?; let token = cursor.peek(0, interner).or_abrupt()?;
let position = token.span().start(); let position = token.span().start();
if let TokenKind::Punctuator(Punctuator::Mul) = token.kind() { if token.kind() == &TokenKind::Punctuator(Punctuator::Mul) {
let (class_element_name, method) = let (class_element_name, method) =
AsyncGeneratorMethod::new(self.allow_yield, self.allow_await) AsyncGeneratorMethod::new(self.allow_yield, self.allow_await)
.parse(cursor, interner)?; .parse(cursor, interner)?;
@ -223,12 +223,7 @@ where
return Err(Error::general("invalid super usage", position)); return Err(Error::general("invalid super usage", position));
} }
let property_name = let property::ClassElementName::PropertyName(property_name) = class_element_name else {
if let property::ClassElementName::PropertyName(property_name) =
class_element_name
{
property_name
} else {
return Err(Error::general( return Err(Error::general(
"private identifiers not allowed in object literal", "private identifiers not allowed in object literal",
position, position,

4
boa_parser/src/parser/statement/declaration/hoistable/mod.rs

@ -90,7 +90,7 @@ where
} }
TokenKind::Keyword((Keyword::Function, false)) => { TokenKind::Keyword((Keyword::Function, false)) => {
let next_token = cursor.peek(1, interner).or_abrupt()?; let next_token = cursor.peek(1, interner).or_abrupt()?;
if let TokenKind::Punctuator(Punctuator::Mul) = next_token.kind() { if next_token.kind() == &TokenKind::Punctuator(Punctuator::Mul) {
GeneratorDeclaration::new(self.allow_yield, self.allow_await, self.is_default) GeneratorDeclaration::new(self.allow_yield, self.allow_await, self.is_default)
.parse(cursor, interner) .parse(cursor, interner)
.map(Declaration::from) .map(Declaration::from)
@ -102,7 +102,7 @@ where
} }
TokenKind::Keyword((Keyword::Async, false)) => { TokenKind::Keyword((Keyword::Async, false)) => {
let next_token = cursor.peek(2, interner).or_abrupt()?; let next_token = cursor.peek(2, interner).or_abrupt()?;
if let TokenKind::Punctuator(Punctuator::Mul) = next_token.kind() { if next_token.kind() == &TokenKind::Punctuator(Punctuator::Mul) {
AsyncGeneratorDeclaration::new( AsyncGeneratorDeclaration::new(
self.allow_yield, self.allow_yield,
self.allow_await, self.allow_await,

4
boa_parser/src/parser/statement/mod.rs

@ -632,7 +632,7 @@ where
} }
if let Some(peek_token) = cursor.peek(0, interner)? { if let Some(peek_token) = cursor.peek(0, interner)? {
if let TokenKind::Punctuator(Punctuator::Comma) = peek_token.kind() { if peek_token.kind() == &TokenKind::Punctuator(Punctuator::Comma) {
cursor.expect( cursor.expect(
TokenKind::Punctuator(Punctuator::Comma), TokenKind::Punctuator(Punctuator::Comma),
"object binding pattern", "object binding pattern",
@ -830,7 +830,7 @@ where
} }
if let Some(peek_token) = cursor.peek(0, interner)? { if let Some(peek_token) = cursor.peek(0, interner)? {
if let TokenKind::Punctuator(Punctuator::Comma) = peek_token.kind() { if peek_token.kind() == &TokenKind::Punctuator(Punctuator::Comma) {
cursor.expect( cursor.expect(
TokenKind::Punctuator(Punctuator::Comma), TokenKind::Punctuator(Punctuator::Comma),
"array binding pattern", "array binding pattern",

1
boa_tester/src/main.rs

@ -60,7 +60,6 @@
clippy::nursery, clippy::nursery,
)] )]
#![allow( #![allow(
clippy::use_self,
clippy::too_many_lines, clippy::too_many_lines,
clippy::redundant_pub_crate, clippy::redundant_pub_crate,
clippy::cast_precision_loss, clippy::cast_precision_loss,

Loading…
Cancel
Save