clippy: Fix a variety of warnings in components/script/dom (#31894)

This commit is contained in:
Ekta Siwach 2024-03-29 20:13:10 +05:30 committed by GitHub
parent 4a68243f65
commit b0196ad373
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
10 changed files with 45 additions and 43 deletions

View file

@ -76,8 +76,16 @@ where
} }
} }
/// Represents values that can be rooted through a stable address that will /// `StableTraceObject` represents values that can be rooted through a stable address that will
/// not change for their whole lifetime. /// not change for their whole lifetime.
/// It is an unsafe trait that requires implementors to ensure certain safety guarantees.
///
/// # Safety
///
/// Implementors of this trait must ensure that the `trace` method correctly accounts for all
/// owned and referenced objects, so that the garbage collector can accurately determine which
/// objects are still in use. Failing to adhere to this contract may result in undefined behavior,
/// such as use-after-free errors.
pub unsafe trait StableTraceObject { pub unsafe trait StableTraceObject {
/// Returns a stable trace object which address won't change for the whole /// Returns a stable trace object which address won't change for the whole
/// lifetime of the value. /// lifetime of the value.
@ -267,10 +275,7 @@ impl RootCollection {
unsafe fn unroot(&self, object: *const dyn JSTraceable) { unsafe fn unroot(&self, object: *const dyn JSTraceable) {
assert_in_script(); assert_in_script();
let roots = &mut *self.roots.get(); let roots = &mut *self.roots.get();
match roots match roots.iter().rposition(|r| std::ptr::eq(*r, object)) {
.iter()
.rposition(|r| *r as *const () == object as *const ())
{
Some(idx) => { Some(idx) => {
roots.remove(idx); roots.remove(idx);
}, },
@ -486,7 +491,7 @@ impl<T> Eq for Dom<T> {}
impl<T> PartialEq for LayoutDom<'_, T> { impl<T> PartialEq for LayoutDom<'_, T> {
fn eq(&self, other: &Self) -> bool { fn eq(&self, other: &Self) -> bool {
self.value as *const T == other.value as *const T std::ptr::eq(self.value, other.value)
} }
} }

View file

@ -40,6 +40,11 @@ impl ByteString {
self.0.len() self.0.len()
} }
/// Checks if the ByteString is empty.
pub fn is_empty(&self) -> bool {
self.0.is_empty()
}
/// Returns `self` with AZ replaced by az. /// Returns `self` with AZ replaced by az.
pub fn to_lower(&self) -> ByteString { pub fn to_lower(&self) -> ByteString {
ByteString::new(self.0.to_ascii_lowercase()) ByteString::new(self.0.to_ascii_lowercase())
@ -365,7 +370,7 @@ impl DOMString {
let (year_int, month_int) = parse_month_component(value)?; let (year_int, month_int) = parse_month_component(value)?;
// Step 4 // Step 4
if value.split("-").nth(2).is_some() { if value.split('-').nth(2).is_some() {
return None; return None;
} }
// Step 5 // Step 5
@ -443,7 +448,7 @@ impl DOMString {
if !( if !(
// A valid number is the same as what rust considers to be valid, // A valid number is the same as what rust considers to be valid,
// except for +1., NaN, and Infinity. // except for +1., NaN, and Infinity.
val.is_infinite() || val.is_nan() || input.ends_with(".") || input.starts_with('+') val.is_infinite() || val.is_nan() || input.ends_with('.') || input.starts_with('+')
) { ) {
return Some(val); return Some(val);
} }
@ -677,7 +682,7 @@ fn parse_month_component(value: &str) -> Option<(i32, u32)> {
// Step 4, 5 // Step 4, 5
let month_int = month.parse::<u32>().ok()?; let month_int = month.parse::<u32>().ok()?;
if month.len() != 2 || month_int > 12 || month_int < 1 { if month.len() != 2 || !(1..=12).contains(&month_int) {
return None; return None;
} }

View file

@ -169,12 +169,14 @@ unsafe extern "C" fn read_transfer_callback(
let sc_holder = &mut *(closure as *mut StructuredDataHolder); let sc_holder = &mut *(closure as *mut StructuredDataHolder);
let in_realm_proof = AlreadyInRealm::assert_for_cx(SafeJSContext::from_ptr(cx)); let in_realm_proof = AlreadyInRealm::assert_for_cx(SafeJSContext::from_ptr(cx));
let owner = GlobalScope::from_context(cx, InRealm::Already(&in_realm_proof)); let owner = GlobalScope::from_context(cx, InRealm::Already(&in_realm_proof));
if let Ok(_) = <MessagePort as Transferable>::transfer_receive( if <MessagePort as Transferable>::transfer_receive(
&owner, &owner,
sc_holder, sc_holder,
extra_data, extra_data,
return_object, return_object,
) { )
.is_ok()
{
return true; return true;
} }
} }

View file

@ -197,7 +197,7 @@ pub unsafe fn get_array_index_from_id(_cx: *mut JSContext, id: HandleId) -> Opti
let first_char = char::decode_utf16(chars.iter().cloned()) let first_char = char::decode_utf16(chars.iter().cloned())
.next() .next()
.map_or('\0', |r| r.unwrap_or('\0')); .map_or('\0', |r| r.unwrap_or('\0'));
if first_char < 'a' || first_char > 'z' { if !('a'..='z').contains(&first_char) {
return None; return None;
} }

View file

@ -90,8 +90,7 @@ pub enum XMLName {
/// for details. /// for details.
pub fn xml_name_type(name: &str) -> XMLName { pub fn xml_name_type(name: &str) -> XMLName {
fn is_valid_start(c: char) -> bool { fn is_valid_start(c: char) -> bool {
match c { matches!(c, ':' |
':' |
'A'..='Z' | 'A'..='Z' |
'_' | '_' |
'a'..='z' | 'a'..='z' |
@ -106,9 +105,7 @@ pub fn xml_name_type(name: &str) -> XMLName {
'\u{3001}'..='\u{D7FF}' | '\u{3001}'..='\u{D7FF}' |
'\u{F900}'..='\u{FDCF}' | '\u{F900}'..='\u{FDCF}' |
'\u{FDF0}'..='\u{FFFD}' | '\u{FDF0}'..='\u{FFFD}' |
'\u{10000}'..='\u{EFFFF}' => true, '\u{10000}'..='\u{EFFFF}')
_ => false,
}
} }
fn is_valid_continuation(c: char) -> bool { fn is_valid_continuation(c: char) -> bool {

View file

@ -898,15 +898,15 @@ impl HTMLScriptElement {
warn!("Error creating input and output files for unminify"); warn!("Error creating input and output files for unminify");
} }
let path; let path = match window_from_node(self).unminified_js_dir() {
match window_from_node(self).unminified_js_dir() { Some(unminified_js_dir) => PathBuf::from(unminified_js_dir),
Some(unminified_js_dir) => path = PathBuf::from(unminified_js_dir),
None => { None => {
warn!("Unminified script directory not found"); warn!("Unminified script directory not found");
return; return;
}, },
} };
let (base, has_name) = match script.url.as_str().ends_with("/") {
let (base, has_name) = match script.url.as_str().ends_with('/') {
true => ( true => (
path.join(&script.url[url::Position::BeforeHost..]) path.join(&script.url[url::Position::BeforeHost..])
.as_path() .as_path()

View file

@ -518,11 +518,10 @@ impl Validatable for HTMLSelectElement {
// https://html.spec.whatwg.org/multipage/#the-select-element%3Asuffering-from-being-missing // https://html.spec.whatwg.org/multipage/#the-select-element%3Asuffering-from-being-missing
if validate_flags.contains(ValidationFlags::VALUE_MISSING) && self.Required() { if validate_flags.contains(ValidationFlags::VALUE_MISSING) && self.Required() {
let placeholder = self.get_placeholder_label_option(); let placeholder = self.get_placeholder_label_option();
let selected_option = self let is_value_missing = !self
.list_of_options() .list_of_options()
.filter(|e| e.Selected() && placeholder.as_ref() != Some(e)) .any(|e| e.Selected() && placeholder != Some(e));
.next(); failed_flags.set(ValidationFlags::VALUE_MISSING, is_value_missing);
failed_flags.set(ValidationFlags::VALUE_MISSING, selected_option.is_none());
} }
failed_flags failed_flags

View file

@ -279,12 +279,9 @@ impl VirtualMethods for HTMLVideoElement {
self.super_type().unwrap().attribute_mutated(attr, mutation); self.super_type().unwrap().attribute_mutated(attr, mutation);
if let Some(new_value) = mutation.new_value(attr) { if let Some(new_value) = mutation.new_value(attr) {
match attr.local_name() { if attr.local_name() == &local_name!("poster") {
&local_name!("poster") => { self.fetch_poster_frame(&new_value);
self.fetch_poster_frame(&new_value); }
},
_ => (),
};
} }
} }
} }

View file

@ -82,10 +82,8 @@ impl Navigator {
} }
pub fn gamepads(&self) -> DomRoot<GamepadList> { pub fn gamepads(&self) -> DomRoot<GamepadList> {
let gamepads = self self.gamepads
.gamepads .or_init(|| GamepadList::new(&self.global(), &[]))
.or_init(|| GamepadList::new(&self.global(), &[]));
gamepads
} }
pub fn has_gamepad_gesture(&self) -> bool { pub fn has_gamepad_gesture(&self) -> bool {

View file

@ -10,7 +10,7 @@ use std::default::Default;
use std::ops::Range; use std::ops::Range;
use std::slice::from_ref; use std::slice::from_ref;
use std::sync::Arc as StdArc; use std::sync::Arc as StdArc;
use std::{cmp, iter, mem}; use std::{cmp, iter};
use app_units::Au; use app_units::Au;
use bitflags::bitflags; use bitflags::bitflags;
@ -454,7 +454,7 @@ pub struct QuerySelectorIterator {
iterator: TreeIterator, iterator: TreeIterator,
} }
impl<'a> QuerySelectorIterator { impl QuerySelectorIterator {
fn new(iter: TreeIterator, selectors: SelectorList<SelectorImpl>) -> QuerySelectorIterator { fn new(iter: TreeIterator, selectors: SelectorList<SelectorImpl>) -> QuerySelectorIterator {
QuerySelectorIterator { QuerySelectorIterator {
selectors, selectors,
@ -463,7 +463,7 @@ impl<'a> QuerySelectorIterator {
} }
} }
impl<'a> Iterator for QuerySelectorIterator { impl Iterator for QuerySelectorIterator {
type Item = DomRoot<Node>; type Item = DomRoot<Node>;
fn next(&mut self) -> Option<DomRoot<Node>> { fn next(&mut self) -> Option<DomRoot<Node>> {
@ -1203,8 +1203,7 @@ impl Node {
match last_child.and_then(|node| { match last_child.and_then(|node| {
node.inclusively_preceding_siblings() node.inclusively_preceding_siblings()
.filter_map(DomRoot::downcast::<Element>) .filter_map(DomRoot::downcast::<Element>)
.filter(|elem| is_delete_type(elem)) .find(|elem| is_delete_type(elem))
.next()
}) { }) {
Some(element) => element, Some(element) => element,
None => return Ok(()), None => return Ok(()),
@ -1314,10 +1313,10 @@ where
#[allow(unsafe_code)] #[allow(unsafe_code)]
pub unsafe fn from_untrusted_node_address(candidate: UntrustedNodeAddress) -> DomRoot<Node> { pub unsafe fn from_untrusted_node_address(candidate: UntrustedNodeAddress) -> DomRoot<Node> {
// https://github.com/servo/servo/issues/6383 // https://github.com/servo/servo/issues/6383
let candidate: uintptr_t = mem::transmute(candidate.0); let candidate = candidate.0 as usize;
// let object: *mut JSObject = jsfriendapi::bindgen::JS_GetAddressableObject(runtime, // let object: *mut JSObject = jsfriendapi::bindgen::JS_GetAddressableObject(runtime,
// candidate); // candidate);
let object: *mut JSObject = mem::transmute(candidate); let object = candidate as *mut JSObject;
if object.is_null() { if object.is_null() {
panic!("Attempted to create a `Dom<Node>` from an invalid pointer!") panic!("Attempted to create a `Dom<Node>` from an invalid pointer!")
} }