clippy: Fix a bunch of warnings in script (#32680)

This is just a portion of the errors that are remaining to be fixed.
This commit is contained in:
Martin Robinson 2024-07-04 13:40:23 +02:00 committed by GitHub
parent 93fdb8263d
commit 26624a109f
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
27 changed files with 150 additions and 113 deletions

View file

@ -418,6 +418,10 @@ where
/// without causing conflicts , unexpected behavior.
/// <https://github.com/servo/mozjs/blob/main/mozjs-sys/mozjs/js/public/ArrayBuffer.h#L89>
unsafe extern "C" fn free_func(_contents: *mut c_void, free_user_data: *mut c_void) {
// Clippy warns about "creating a `Arc` from a void raw pointer" here, but suggests
// the exact same line to fix it. Doing the cast is tricky because of the use of
// a generic type in this parameter.
#[allow(clippy::from_raw_with_void_ptr)]
let _ = Arc::from_raw(free_user_data as *const _);
}

View file

@ -61,15 +61,10 @@ pub struct CallbackObject {
incumbent: Option<Dom<GlobalScope>>,
}
impl Default for CallbackObject {
#[allow(crown::unrooted_must_root)]
fn default() -> CallbackObject {
CallbackObject::new()
}
}
impl CallbackObject {
#[allow(crown::unrooted_must_root)]
// These are used by the bindings and do not need `default()` functions.
#[allow(clippy::new_without_default)]
fn new() -> CallbackObject {
CallbackObject {
callback: Heap::default(),
@ -140,6 +135,8 @@ pub struct CallbackFunction {
impl CallbackFunction {
/// Create a new `CallbackFunction` for this object.
#[allow(crown::unrooted_must_root)]
// These are used by the bindings and do not need `default()` functions.
#[allow(clippy::new_without_default)]
pub fn new() -> CallbackFunction {
CallbackFunction {
object: CallbackObject::new(),
@ -167,6 +164,8 @@ pub struct CallbackInterface {
impl CallbackInterface {
/// Create a new CallbackInterface object for the given `JSObject`.
// These are used by the bindings and do not need `default()` functions.
#[allow(clippy::new_without_default)]
pub fn new() -> CallbackInterface {
CallbackInterface {
object: CallbackObject::new(),

View file

@ -28,9 +28,13 @@ pub struct DomRefCell<T> {
// ===================================================
impl<T> DomRefCell<T> {
/// Return a reference to the contents.
/// Return a reference to the contents. For use in layout only.
///
/// For use in layout only.
/// # Safety
///
/// Unlike RefCell::borrow, this method is unsafe because it does not return a Ref, thus leaving
/// the borrow flag untouched. Mutably borrowing the RefCell while the reference returned by
/// this method is alive is undefined behaviour.
#[allow(unsafe_code)]
pub unsafe fn borrow_for_layout(&self) -> &T {
assert_in_layout();
@ -41,6 +45,11 @@ impl<T> DomRefCell<T> {
/// Borrow the contents for the purpose of script deallocation.
///
/// # Safety
///
/// Unlike RefCell::borrow, this method is unsafe because it does not return a Ref, thus leaving
/// the borrow flag untouched. Mutably borrowing the RefCell while the reference returned by
/// this method is alive is undefined behaviour.
#[allow(unsafe_code, clippy::mut_from_ref)]
pub unsafe fn borrow_for_script_deallocation(&self) -> &mut T {
assert_in_script();
@ -49,6 +58,12 @@ impl<T> DomRefCell<T> {
/// Mutably borrow a cell for layout. Ideally this would use
/// `RefCell::try_borrow_mut_unguarded` but that doesn't exist yet.
///
/// # Safety
///
/// Unlike RefCell::borrow, this method is unsafe because it does not return a Ref, thus leaving
/// the borrow flag untouched. Mutably borrowing the RefCell while the reference returned by
/// this method is alive is undefined behaviour.
#[allow(unsafe_code, clippy::mut_from_ref)]
pub unsafe fn borrow_mut_for_layout(&self) -> &mut T {
assert_in_layout();

View file

@ -42,8 +42,9 @@ from Configuration import (
AUTOGENERATED_WARNING_COMMENT = "/* THIS FILE IS AUTOGENERATED - DO NOT EDIT */\n\n"
ALLOWED_WARNING_LIST = ['non_camel_case_types', 'non_upper_case_globals', 'unused_imports',
'unused_variables', 'unused_assignments', 'unused_mut',
'clippy::approx_constant', 'clippy::let_unit_value', 'clippy::needless_return',
'clippy::too_many_arguments', 'clippy::unnecessary_cast', 'clippy::upper_case_acronyms']
'clippy::approx_constant', 'clippy::enum_variant_name', 'clippy::let_unit_value',
'clippy::needless_return', 'clippy::too_many_arguments', 'clippy::unnecessary_cast',
'clippy::upper_case_acronyms']
ALLOWED_WARNINGS = f"#![allow({','.join(ALLOWED_WARNING_LIST)})]\n\n"
FINALIZE_HOOK_NAME = '_finalize'
@ -1316,16 +1317,16 @@ def convertConstIDLValueToJSVal(value):
tag = value.type.tag()
if tag in [IDLType.Tags.int8, IDLType.Tags.uint8, IDLType.Tags.int16,
IDLType.Tags.uint16, IDLType.Tags.int32]:
return "ConstantVal::IntVal(%s)" % (value.value)
return "ConstantVal::Int(%s)" % (value.value)
if tag == IDLType.Tags.uint32:
return "ConstantVal::UintVal(%s)" % (value.value)
return "ConstantVal::Uint(%s)" % (value.value)
if tag in [IDLType.Tags.int64, IDLType.Tags.uint64]:
return "ConstantVal::DoubleVal(%s as f64)" % (value.value)
return "ConstantVal::Double(%s as f64)" % (value.value)
if tag == IDLType.Tags.bool:
return "ConstantVal::BoolVal(true)" if value.value else "ConstantVal::BoolVal(false)"
return "ConstantVal::Bool(true)" if value.value else "ConstantVal::BoolVal(false)"
if tag in [IDLType.Tags.unrestricted_float, IDLType.Tags.float,
IDLType.Tags.unrestricted_double, IDLType.Tags.double]:
return "ConstantVal::DoubleVal(%s as f64)" % (value.value)
return "ConstantVal::Double(%s as f64)" % (value.value)
raise TypeError("Const value of unhandled type: " + value.type)

View file

@ -25,26 +25,26 @@ pub struct ConstantSpec {
#[allow(dead_code)]
pub enum ConstantVal {
/// `long` constant.
IntVal(i32),
Int(i32),
/// `unsigned long` constant.
UintVal(u32),
Uint(u32),
/// `double` constant.
DoubleVal(f64),
Double(f64),
/// `boolean` constant.
BoolVal(bool),
Bool(bool),
/// `null` constant.
NullVal,
Null,
}
impl ConstantSpec {
/// Returns a `JSVal` that represents the value of this `ConstantSpec`.
pub fn get_value(&self) -> JSVal {
match self.value {
ConstantVal::NullVal => NullValue(),
ConstantVal::IntVal(i) => Int32Value(i),
ConstantVal::UintVal(u) => UInt32Value(u),
ConstantVal::DoubleVal(d) => DoubleValue(d),
ConstantVal::BoolVal(b) => BooleanValue(b),
ConstantVal::Null => NullValue(),
ConstantVal::Int(i) => Int32Value(i),
ConstantVal::Uint(u) => UInt32Value(u),
ConstantVal::Double(d) => DoubleValue(d),
ConstantVal::Bool(b) => BooleanValue(b),
}
}
}

View file

@ -319,6 +319,7 @@ pub unsafe fn throw_constructor_without_new(cx: *mut JSContext, name: &str) {
impl Error {
/// Convert this error value to a JS value, consuming it in the process.
#[allow(clippy::wrong_self_convention)]
pub unsafe fn to_jsval(
self,
cx: *mut JSContext,

View file

@ -81,6 +81,8 @@ impl Reflector {
}
/// Create an uninitialized `Reflector`.
// These are used by the bindings and do not need `default()` functions.
#[allow(clippy::new_without_default)]
pub fn new() -> Reflector {
Reflector {
object: Heap::default(),

View file

@ -238,7 +238,7 @@ pub struct RootCollection {
roots: UnsafeCell<Vec<*const dyn JSTraceable>>,
}
thread_local!(static STACK_ROOTS: Cell<Option<*const RootCollection>> = Cell::new(None));
thread_local!(static STACK_ROOTS: Cell<Option<*const RootCollection>> = const { Cell::new(None) });
pub struct ThreadLocalStackRoots<'a>(PhantomData<&'a u32>);
@ -339,6 +339,10 @@ impl<T> MallocSizeOf for Dom<T> {
impl<T> Dom<T> {
/// Returns `LayoutDom<T>` containing the same pointer.
///
/// # Safety
///
/// The `self` parameter to this method must meet all the requirements of [`ptr::NonNull::as_ref`].
pub unsafe fn to_layout(&self) -> LayoutDom<T> {
assert_in_layout();
LayoutDom {

View file

@ -12,7 +12,7 @@ use crate::dom::bindings::root::{Dom, DomRoot};
use crate::dom::bindings::trace::JSTraceable;
use crate::dom::globalscope::GlobalScope;
thread_local!(static STACK: RefCell<Vec<StackEntry>> = RefCell::new(Vec::new()));
thread_local!(static STACK: RefCell<Vec<StackEntry>> = const { RefCell::new(Vec::new()) });
#[derive(Debug, Eq, JSTraceable, PartialEq)]
enum StackEntryKind {

View file

@ -478,32 +478,31 @@ impl DOMString {
/// where date and time are both valid, and the time string must be as short as possible
/// <https://html.spec.whatwg.org/multipage/#valid-normalised-local-date-and-time-string>
pub fn convert_valid_normalized_local_date_and_time_string(&mut self) -> Option<()> {
let ((year, month, day), (hour, minute, second)) =
self.parse_local_date_and_time_string()?;
if second == 0.0 {
let date = self.parse_local_date_and_time_string()?;
if date.seconds == 0.0 {
self.0 = format!(
"{:04}-{:02}-{:02}T{:02}:{:02}",
year, month, day, hour, minute
date.year, date.month, date.day, date.hour, date.minute
);
} else if second < 10.0 {
} else if date.seconds < 10.0 {
// we need exactly one leading zero on the seconds,
// whatever their total string length might be
self.0 = format!(
"{:04}-{:02}-{:02}T{:02}:{:02}:0{}",
year, month, day, hour, minute, second
date.year, date.month, date.day, date.hour, date.minute, date.seconds
);
} else {
// we need no leading zeroes on the seconds
self.0 = format!(
"{:04}-{:02}-{:02}T{:02}:{:02}:{}",
year, month, day, hour, minute, second
date.year, date.month, date.day, date.hour, date.minute, date.seconds
);
}
Some(())
}
/// <https://html.spec.whatwg.org/multipage/#parse-a-local-date-and-time-string>
pub fn parse_local_date_and_time_string(&self) -> Option<((i32, u32, u32), (u32, u32, f64))> {
pub(crate) fn parse_local_date_and_time_string(&self) -> Option<ParsedDate> {
let value = &self;
// Step 1, 2, 4
let mut iterator = if value.contains('T') {
@ -514,11 +513,11 @@ impl DOMString {
// Step 3
let date = iterator.next()?;
let date_tuple = parse_date_component(date)?;
let (year, month, day) = parse_date_component(date)?;
// Step 5
let time = iterator.next()?;
let time_tuple = parse_time_component(time)?;
let (hour, minute, seconds) = parse_time_component(time)?;
// Step 6
if iterator.next().is_some() {
@ -526,7 +525,14 @@ impl DOMString {
}
// Step 7, 8, 9
Some((date_tuple, time_tuple))
Some(ParsedDate {
year,
month,
day,
hour,
minute,
seconds,
})
}
/// <https://html.spec.whatwg.org/multipage/#valid-e-mail-address>
@ -803,3 +809,13 @@ fn max_week_in_year(year: i32) -> u32 {
fn is_leap_year(year: i32) -> bool {
year % 400 == 0 || (year % 4 == 0 && year % 100 != 0)
}
#[derive(Clone, Debug, Default, MallocSizeOf, PartialEq)]
pub(crate) struct ParsedDate {
pub year: i32,
pub month: u32,
pub day: u32,
pub hour: u32,
pub minute: u32,
pub seconds: f64,
}

View file

@ -187,28 +187,25 @@ where
}
#[inline]
pub fn get_mut<Q: ?Sized>(&mut self, k: &Q) -> Option<&mut V>
pub fn get_mut<Q: Hash + Eq + ?Sized>(&mut self, k: &Q) -> Option<&mut V>
where
K: std::borrow::Borrow<Q>,
Q: Hash + Eq,
{
self.0.get_mut(k)
}
#[inline]
pub fn contains_key<Q: ?Sized>(&self, k: &Q) -> bool
pub fn contains_key<Q: Hash + Eq + ?Sized>(&self, k: &Q) -> bool
where
K: std::borrow::Borrow<Q>,
Q: Hash + Eq,
{
self.0.contains_key(k)
}
#[inline]
pub fn remove<Q: ?Sized>(&mut self, k: &Q) -> Option<V>
pub fn remove<Q: Hash + Eq + ?Sized>(&mut self, k: &Q) -> Option<V>
where
K: std::borrow::Borrow<Q>,
Q: Hash + Eq,
{
self.0.remove(k)
}

View file

@ -13,7 +13,7 @@ use crate::dom::bindings::str::DOMString;
pub fn validate_qualified_name(qualified_name: &str) -> ErrorResult {
// Step 2.
match xml_name_type(qualified_name) {
XMLName::InvalidXMLName => Err(Error::InvalidCharacter),
XMLName::Invalid => Err(Error::InvalidCharacter),
XMLName::Name => Err(Error::InvalidCharacter), // see whatwg/dom#671
XMLName::QName => Ok(()),
}
@ -83,7 +83,7 @@ pub fn validate_and_extract(
pub enum XMLName {
QName,
Name,
InvalidXMLName,
Invalid,
}
/// Check if an element name is valid. See <http://www.w3.org/TR/xml/#NT-Name>
@ -123,10 +123,10 @@ pub fn xml_name_type(name: &str) -> XMLName {
let mut non_qname_colons = false;
let mut seen_colon = false;
let mut last = match iter.next() {
None => return XMLName::InvalidXMLName,
None => return XMLName::Invalid,
Some(c) => {
if !is_valid_start(c) {
return XMLName::InvalidXMLName;
return XMLName::Invalid;
}
if c == ':' {
non_qname_colons = true;
@ -137,7 +137,7 @@ pub fn xml_name_type(name: &str) -> XMLName {
for c in iter {
if !is_valid_continuation(c) {
return XMLName::InvalidXMLName;
return XMLName::Invalid;
}
if c == ':' {
if seen_colon {