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

@ -881,7 +881,7 @@ where
.event_loops .event_loops
.get(host) .get(host)
.ok_or("Trying to get an event-loop from an unknown browsing context group") .ok_or("Trying to get an event-loop from an unknown browsing context group")
.map(|event_loop| event_loop.clone()) .cloned()
} }
fn set_event_loop( fn set_event_loop(

View file

@ -73,7 +73,7 @@ pub fn build_html_directory_listing(
if let Ok(mut path_segments) = parent_url.path_segments_mut() { if let Ok(mut path_segments) = parent_url.path_segments_mut() {
path_segments.pop(); path_segments.pop();
} }
parent_url_string = parent_url.as_str().to_owned(); parent_url.as_str().clone_into(&mut parent_url_string);
} }
page_html.push_str(&read_string(Resource::DirectoryListingHTML)); page_html.push_str(&read_string(Resource::DirectoryListingHTML));
@ -126,7 +126,7 @@ fn write_directory_entry(entry: DirEntry, metadata: Metadata, url: &Url, output:
let file_size = metadata_to_file_size_string(&metadata); let file_size = metadata_to_file_size_string(&metadata);
let last_modified = metadata let last_modified = metadata
.modified() .modified()
.map(|time| DateTime::<Local>::from(time)) .map(DateTime::<Local>::from)
.map(|time| time.format("%F %r").to_string()) .map(|time| time.format("%F %r").to_string())
.unwrap_or_default(); .unwrap_or_default();
@ -154,5 +154,5 @@ pub fn metadata_to_file_size_string(metadata: &Metadata) -> String {
_ => "GB", _ => "GB",
}; };
return format!("{:.2} {prefix}", float_size); format!("{:.2} {prefix}", float_size)
} }

View file

@ -565,14 +565,14 @@ impl MIMEChecker for GroupedClassifier {
} }
enum Match { enum Match {
None,
Start, Start,
DidNotMatch,
StartAndEnd, StartAndEnd,
} }
impl Match { impl Match {
fn chain<F: FnOnce() -> Match>(self, f: F) -> Match { fn chain<F: FnOnce() -> Match>(self, f: F) -> Match {
if let Match::DidNotMatch = self { if let Match::None = self {
return f(); return f();
} }
self self
@ -584,7 +584,7 @@ where
T: Iterator<Item = &'a u8> + Clone, T: Iterator<Item = &'a u8> + Clone,
{ {
if !matcher.matches(start) { if !matcher.matches(start) {
Match::DidNotMatch Match::None
} else if end.len() == 1 { } else if end.len() == 1 {
if matcher.any(|&x| x == end[0]) { if matcher.any(|&x| x == end[0]) {
Match::StartAndEnd Match::StartAndEnd
@ -630,7 +630,7 @@ impl FeedsClassifier {
.chain(|| eats_until(&mut matcher, b"!", b">")) .chain(|| eats_until(&mut matcher, b"!", b">"))
{ {
Match::StartAndEnd => continue, Match::StartAndEnd => continue,
Match::DidNotMatch => {}, Match::None => {},
Match::Start => return None, Match::Start => return None,
} }
@ -658,7 +658,7 @@ impl FeedsClassifier {
) )
}) { }) {
Match::StartAndEnd => return Some("application/rss+xml".parse().unwrap()), Match::StartAndEnd => return Some("application/rss+xml".parse().unwrap()),
Match::DidNotMatch => {}, Match::None => {},
Match::Start => return None, Match::Start => return None,
} }
} }

View file

@ -241,7 +241,7 @@ impl Attr {
pub trait AttrHelpersForLayout<'dom> { pub trait AttrHelpersForLayout<'dom> {
fn value(self) -> &'dom AttrValue; fn value(self) -> &'dom AttrValue;
fn as_str(&self) -> &'dom str; fn as_str(&self) -> &'dom str;
fn as_tokens(self) -> Option<&'dom [Atom]>; fn to_tokens(self) -> Option<&'dom [Atom]>;
fn local_name(self) -> &'dom LocalName; fn local_name(self) -> &'dom LocalName;
fn namespace(self) -> &'dom Namespace; fn namespace(self) -> &'dom Namespace;
} }
@ -259,7 +259,7 @@ impl<'dom> AttrHelpersForLayout<'dom> for LayoutDom<'dom, Attr> {
} }
#[inline] #[inline]
fn as_tokens(self) -> Option<&'dom [Atom]> { fn to_tokens(self) -> Option<&'dom [Atom]> {
match *self.value() { match *self.value() {
AttrValue::TokenList(_, ref tokens) => Some(tokens), AttrValue::TokenList(_, ref tokens) => Some(tokens),
_ => None, _ => None,

View file

@ -79,6 +79,8 @@ struct DecodeResolver {
pub error_callback: Option<Rc<DecodeErrorCallback>>, pub error_callback: Option<Rc<DecodeErrorCallback>>,
} }
type BoxedSliceOfPromises = Box<[Rc<Promise>]>;
#[dom_struct] #[dom_struct]
pub struct BaseAudioContext { pub struct BaseAudioContext {
eventtarget: EventTarget, eventtarget: EventTarget,
@ -90,7 +92,7 @@ pub struct BaseAudioContext {
listener: MutNullableDom<AudioListener>, listener: MutNullableDom<AudioListener>,
/// Resume promises which are soon to be fulfilled by a queued task. /// Resume promises which are soon to be fulfilled by a queued task.
#[ignore_malloc_size_of = "promises are hard"] #[ignore_malloc_size_of = "promises are hard"]
in_flight_resume_promises_queue: DomRefCell<VecDeque<(Box<[Rc<Promise>]>, ErrorResult)>>, in_flight_resume_promises_queue: DomRefCell<VecDeque<(BoxedSliceOfPromises, ErrorResult)>>,
/// <https://webaudio.github.io/web-audio-api/#pendingresumepromises> /// <https://webaudio.github.io/web-audio-api/#pendingresumepromises>
#[ignore_malloc_size_of = "promises are hard"] #[ignore_malloc_size_of = "promises are hard"]
pending_resume_promises: DomRefCell<Vec<Rc<Promise>>>, pending_resume_promises: DomRefCell<Vec<Rc<Promise>>>,

View file

@ -418,6 +418,10 @@ where
/// without causing conflicts , unexpected behavior. /// without causing conflicts , unexpected behavior.
/// <https://github.com/servo/mozjs/blob/main/mozjs-sys/mozjs/js/public/ArrayBuffer.h#L89> /// <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) { 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 _); let _ = Arc::from_raw(free_user_data as *const _);
} }

View file

@ -61,15 +61,10 @@ pub struct CallbackObject {
incumbent: Option<Dom<GlobalScope>>, incumbent: Option<Dom<GlobalScope>>,
} }
impl Default for CallbackObject {
#[allow(crown::unrooted_must_root)]
fn default() -> CallbackObject {
CallbackObject::new()
}
}
impl CallbackObject { impl CallbackObject {
#[allow(crown::unrooted_must_root)] #[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 { fn new() -> CallbackObject {
CallbackObject { CallbackObject {
callback: Heap::default(), callback: Heap::default(),
@ -140,6 +135,8 @@ pub struct CallbackFunction {
impl CallbackFunction { impl CallbackFunction {
/// Create a new `CallbackFunction` for this object. /// Create a new `CallbackFunction` for this object.
#[allow(crown::unrooted_must_root)] #[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 { pub fn new() -> CallbackFunction {
CallbackFunction { CallbackFunction {
object: CallbackObject::new(), object: CallbackObject::new(),
@ -167,6 +164,8 @@ pub struct CallbackInterface {
impl CallbackInterface { impl CallbackInterface {
/// Create a new CallbackInterface object for the given `JSObject`. /// 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 { pub fn new() -> CallbackInterface {
CallbackInterface { CallbackInterface {
object: CallbackObject::new(), object: CallbackObject::new(),

View file

@ -28,9 +28,13 @@ pub struct DomRefCell<T> {
// =================================================== // ===================================================
impl<T> 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)] #[allow(unsafe_code)]
pub unsafe fn borrow_for_layout(&self) -> &T { pub unsafe fn borrow_for_layout(&self) -> &T {
assert_in_layout(); assert_in_layout();
@ -41,6 +45,11 @@ impl<T> DomRefCell<T> {
/// Borrow the contents for the purpose of script deallocation. /// 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)] #[allow(unsafe_code, clippy::mut_from_ref)]
pub unsafe fn borrow_for_script_deallocation(&self) -> &mut T { pub unsafe fn borrow_for_script_deallocation(&self) -> &mut T {
assert_in_script(); assert_in_script();
@ -49,6 +58,12 @@ impl<T> DomRefCell<T> {
/// Mutably borrow a cell for layout. Ideally this would use /// Mutably borrow a cell for layout. Ideally this would use
/// `RefCell::try_borrow_mut_unguarded` but that doesn't exist yet. /// `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)] #[allow(unsafe_code, clippy::mut_from_ref)]
pub unsafe fn borrow_mut_for_layout(&self) -> &mut T { pub unsafe fn borrow_mut_for_layout(&self) -> &mut T {
assert_in_layout(); assert_in_layout();

View file

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

View file

@ -25,26 +25,26 @@ pub struct ConstantSpec {
#[allow(dead_code)] #[allow(dead_code)]
pub enum ConstantVal { pub enum ConstantVal {
/// `long` constant. /// `long` constant.
IntVal(i32), Int(i32),
/// `unsigned long` constant. /// `unsigned long` constant.
UintVal(u32), Uint(u32),
/// `double` constant. /// `double` constant.
DoubleVal(f64), Double(f64),
/// `boolean` constant. /// `boolean` constant.
BoolVal(bool), Bool(bool),
/// `null` constant. /// `null` constant.
NullVal, Null,
} }
impl ConstantSpec { impl ConstantSpec {
/// Returns a `JSVal` that represents the value of this `ConstantSpec`. /// Returns a `JSVal` that represents the value of this `ConstantSpec`.
pub fn get_value(&self) -> JSVal { pub fn get_value(&self) -> JSVal {
match self.value { match self.value {
ConstantVal::NullVal => NullValue(), ConstantVal::Null => NullValue(),
ConstantVal::IntVal(i) => Int32Value(i), ConstantVal::Int(i) => Int32Value(i),
ConstantVal::UintVal(u) => UInt32Value(u), ConstantVal::Uint(u) => UInt32Value(u),
ConstantVal::DoubleVal(d) => DoubleValue(d), ConstantVal::Double(d) => DoubleValue(d),
ConstantVal::BoolVal(b) => BooleanValue(b), 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 { impl Error {
/// Convert this error value to a JS value, consuming it in the process. /// Convert this error value to a JS value, consuming it in the process.
#[allow(clippy::wrong_self_convention)]
pub unsafe fn to_jsval( pub unsafe fn to_jsval(
self, self,
cx: *mut JSContext, cx: *mut JSContext,

View file

@ -81,6 +81,8 @@ impl Reflector {
} }
/// Create an uninitialized `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 { pub fn new() -> Reflector {
Reflector { Reflector {
object: Heap::default(), object: Heap::default(),

View file

@ -238,7 +238,7 @@ pub struct RootCollection {
roots: UnsafeCell<Vec<*const dyn JSTraceable>>, 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>); pub struct ThreadLocalStackRoots<'a>(PhantomData<&'a u32>);
@ -339,6 +339,10 @@ impl<T> MallocSizeOf for Dom<T> {
impl<T> Dom<T> { impl<T> Dom<T> {
/// Returns `LayoutDom<T>` containing the same pointer. /// 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> { pub unsafe fn to_layout(&self) -> LayoutDom<T> {
assert_in_layout(); assert_in_layout();
LayoutDom { LayoutDom {

View file

@ -12,7 +12,7 @@ use crate::dom::bindings::root::{Dom, DomRoot};
use crate::dom::bindings::trace::JSTraceable; use crate::dom::bindings::trace::JSTraceable;
use crate::dom::globalscope::GlobalScope; 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)] #[derive(Debug, Eq, JSTraceable, PartialEq)]
enum StackEntryKind { 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 /// 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> /// <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<()> { pub fn convert_valid_normalized_local_date_and_time_string(&mut self) -> Option<()> {
let ((year, month, day), (hour, minute, second)) = let date = self.parse_local_date_and_time_string()?;
self.parse_local_date_and_time_string()?; if date.seconds == 0.0 {
if second == 0.0 {
self.0 = format!( self.0 = format!(
"{:04}-{:02}-{:02}T{:02}:{:02}", "{: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, // we need exactly one leading zero on the seconds,
// whatever their total string length might be // whatever their total string length might be
self.0 = format!( self.0 = format!(
"{:04}-{:02}-{:02}T{:02}:{:02}:0{}", "{: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 { } else {
// we need no leading zeroes on the seconds // we need no leading zeroes on the seconds
self.0 = format!( self.0 = format!(
"{:04}-{:02}-{:02}T{:02}:{:02}:{}", "{: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(()) Some(())
} }
/// <https://html.spec.whatwg.org/multipage/#parse-a-local-date-and-time-string> /// <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; let value = &self;
// Step 1, 2, 4 // Step 1, 2, 4
let mut iterator = if value.contains('T') { let mut iterator = if value.contains('T') {
@ -514,11 +513,11 @@ impl DOMString {
// Step 3 // Step 3
let date = iterator.next()?; let date = iterator.next()?;
let date_tuple = parse_date_component(date)?; let (year, month, day) = parse_date_component(date)?;
// Step 5 // Step 5
let time = iterator.next()?; let time = iterator.next()?;
let time_tuple = parse_time_component(time)?; let (hour, minute, seconds) = parse_time_component(time)?;
// Step 6 // Step 6
if iterator.next().is_some() { if iterator.next().is_some() {
@ -526,7 +525,14 @@ impl DOMString {
} }
// Step 7, 8, 9 // 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> /// <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 { fn is_leap_year(year: i32) -> bool {
year % 400 == 0 || (year % 4 == 0 && year % 100 != 0) 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] #[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 where
K: std::borrow::Borrow<Q>, K: std::borrow::Borrow<Q>,
Q: Hash + Eq,
{ {
self.0.get_mut(k) self.0.get_mut(k)
} }
#[inline] #[inline]
pub fn contains_key<Q: ?Sized>(&self, k: &Q) -> bool pub fn contains_key<Q: Hash + Eq + ?Sized>(&self, k: &Q) -> bool
where where
K: std::borrow::Borrow<Q>, K: std::borrow::Borrow<Q>,
Q: Hash + Eq,
{ {
self.0.contains_key(k) self.0.contains_key(k)
} }
#[inline] #[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 where
K: std::borrow::Borrow<Q>, K: std::borrow::Borrow<Q>,
Q: Hash + Eq,
{ {
self.0.remove(k) 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 { pub fn validate_qualified_name(qualified_name: &str) -> ErrorResult {
// Step 2. // Step 2.
match xml_name_type(qualified_name) { 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::Name => Err(Error::InvalidCharacter), // see whatwg/dom#671
XMLName::QName => Ok(()), XMLName::QName => Ok(()),
} }
@ -83,7 +83,7 @@ pub fn validate_and_extract(
pub enum XMLName { pub enum XMLName {
QName, QName,
Name, Name,
InvalidXMLName, Invalid,
} }
/// Check if an element name is valid. See <http://www.w3.org/TR/xml/#NT-Name> /// 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 non_qname_colons = false;
let mut seen_colon = false; let mut seen_colon = false;
let mut last = match iter.next() { let mut last = match iter.next() {
None => return XMLName::InvalidXMLName, None => return XMLName::Invalid,
Some(c) => { Some(c) => {
if !is_valid_start(c) { if !is_valid_start(c) {
return XMLName::InvalidXMLName; return XMLName::Invalid;
} }
if c == ':' { if c == ':' {
non_qname_colons = true; non_qname_colons = true;
@ -137,7 +137,7 @@ pub fn xml_name_type(name: &str) -> XMLName {
for c in iter { for c in iter {
if !is_valid_continuation(c) { if !is_valid_continuation(c) {
return XMLName::InvalidXMLName; return XMLName::Invalid;
} }
if c == ':' { if c == ':' {
if seen_colon { if seen_colon {

View file

@ -100,7 +100,7 @@ use crate::dom::bindings::refcounted::{Trusted, TrustedPromise};
use crate::dom::bindings::reflector::{reflect_dom_object_with_proto, DomObject}; use crate::dom::bindings::reflector::{reflect_dom_object_with_proto, DomObject};
use crate::dom::bindings::root::{Dom, DomRoot, DomSlice, LayoutDom, MutNullableDom}; use crate::dom::bindings::root::{Dom, DomRoot, DomSlice, LayoutDom, MutNullableDom};
use crate::dom::bindings::str::{DOMString, USVString}; use crate::dom::bindings::str::{DOMString, USVString};
use crate::dom::bindings::xmlname::XMLName::InvalidXMLName; use crate::dom::bindings::xmlname::XMLName::Invalid;
use crate::dom::bindings::xmlname::{ use crate::dom::bindings::xmlname::{
namespace_from_domstring, validate_and_extract, xml_name_type, namespace_from_domstring, validate_and_extract, xml_name_type,
}; };
@ -3006,7 +3006,7 @@ pub enum DocumentSource {
#[allow(unsafe_code)] #[allow(unsafe_code)]
pub trait LayoutDocumentHelpers<'dom> { pub trait LayoutDocumentHelpers<'dom> {
fn is_html_document_for_layout(self) -> bool; fn is_html_document_for_layout(&self) -> bool;
fn needs_paint_from_layout(self); fn needs_paint_from_layout(self);
fn will_paint(self); fn will_paint(self);
fn quirks_mode(self) -> QuirksMode; fn quirks_mode(self) -> QuirksMode;
@ -3019,7 +3019,7 @@ pub trait LayoutDocumentHelpers<'dom> {
#[allow(unsafe_code)] #[allow(unsafe_code)]
impl<'dom> LayoutDocumentHelpers<'dom> for LayoutDom<'dom, Document> { impl<'dom> LayoutDocumentHelpers<'dom> for LayoutDom<'dom, Document> {
#[inline] #[inline]
fn is_html_document_for_layout(self) -> bool { fn is_html_document_for_layout(&self) -> bool {
self.unsafe_get().is_html_document self.unsafe_get().is_html_document
} }
@ -4297,7 +4297,7 @@ impl DocumentMethods for Document {
mut local_name: DOMString, mut local_name: DOMString,
options: StringOrElementCreationOptions, options: StringOrElementCreationOptions,
) -> Fallible<DomRoot<Element>> { ) -> Fallible<DomRoot<Element>> {
if xml_name_type(&local_name) == InvalidXMLName { if xml_name_type(&local_name) == Invalid {
debug!("Not a valid element name"); debug!("Not a valid element name");
return Err(Error::InvalidCharacter); return Err(Error::InvalidCharacter);
} }
@ -4359,7 +4359,7 @@ impl DocumentMethods for Document {
// https://dom.spec.whatwg.org/#dom-document-createattribute // https://dom.spec.whatwg.org/#dom-document-createattribute
fn CreateAttribute(&self, mut local_name: DOMString) -> Fallible<DomRoot<Attr>> { fn CreateAttribute(&self, mut local_name: DOMString) -> Fallible<DomRoot<Attr>> {
if xml_name_type(&local_name) == InvalidXMLName { if xml_name_type(&local_name) == Invalid {
debug!("Not a valid element name"); debug!("Not a valid element name");
return Err(Error::InvalidCharacter); return Err(Error::InvalidCharacter);
} }
@ -4438,7 +4438,7 @@ impl DocumentMethods for Document {
data: DOMString, data: DOMString,
) -> Fallible<DomRoot<ProcessingInstruction>> { ) -> Fallible<DomRoot<ProcessingInstruction>> {
// Step 1. // Step 1.
if xml_name_type(&target) == InvalidXMLName { if xml_name_type(&target) == Invalid {
return Err(Error::InvalidCharacter); return Err(Error::InvalidCharacter);
} }
@ -5373,7 +5373,7 @@ impl DocumentMethods for Document {
// https://drafts.csswg.org/css-font-loading/#font-face-source // https://drafts.csswg.org/css-font-loading/#font-face-source
fn Fonts(&self) -> DomRoot<FontFaceSet> { fn Fonts(&self) -> DomRoot<FontFaceSet> {
self.fonts self.fonts
.or_init(|| FontFaceSet::new(&*self.global(), None)) .or_init(|| FontFaceSet::new(&self.global(), None))
} }
} }

View file

@ -87,7 +87,7 @@ use crate::dom::bindings::refcounted::{Trusted, TrustedPromise};
use crate::dom::bindings::reflector::DomObject; use crate::dom::bindings::reflector::DomObject;
use crate::dom::bindings::root::{Dom, DomRoot, LayoutDom, MutNullableDom}; use crate::dom::bindings::root::{Dom, DomRoot, LayoutDom, MutNullableDom};
use crate::dom::bindings::str::{DOMString, USVString}; use crate::dom::bindings::str::{DOMString, USVString};
use crate::dom::bindings::xmlname::XMLName::InvalidXMLName; use crate::dom::bindings::xmlname::XMLName::Invalid;
use crate::dom::bindings::xmlname::{ use crate::dom::bindings::xmlname::{
namespace_from_domstring, validate_and_extract, xml_name_type, namespace_from_domstring, validate_and_extract, xml_name_type,
}; };
@ -622,7 +622,7 @@ pub trait LayoutElementHelpers<'dom> {
fn get_span(self) -> Option<u32>; fn get_span(self) -> Option<u32>;
fn get_colspan(self) -> Option<u32>; fn get_colspan(self) -> Option<u32>;
fn get_rowspan(self) -> Option<u32>; fn get_rowspan(self) -> Option<u32>;
fn is_html_element(self) -> bool; fn is_html_element(&self) -> bool;
fn id_attribute(self) -> *const Option<Atom>; fn id_attribute(self) -> *const Option<Atom>;
fn style_attribute(self) -> *const Option<Arc<Locked<PropertyDeclarationBlock>>>; fn style_attribute(self) -> *const Option<Arc<Locked<PropertyDeclarationBlock>>>;
fn local_name(self) -> &'dom LocalName; fn local_name(self) -> &'dom LocalName;
@ -658,7 +658,7 @@ impl<'dom> LayoutElementHelpers<'dom> for LayoutDom<'dom, Element> {
#[inline] #[inline]
fn has_class_for_layout(self, name: &AtomIdent, case_sensitivity: CaseSensitivity) -> bool { fn has_class_for_layout(self, name: &AtomIdent, case_sensitivity: CaseSensitivity) -> bool {
get_attr_for_layout(self, &ns!(), &local_name!("class")).map_or(false, |attr| { get_attr_for_layout(self, &ns!(), &local_name!("class")).map_or(false, |attr| {
attr.as_tokens() attr.to_tokens()
.unwrap() .unwrap()
.iter() .iter()
.any(|atom| case_sensitivity.eq_atom(atom, name)) .any(|atom| case_sensitivity.eq_atom(atom, name))
@ -668,7 +668,7 @@ impl<'dom> LayoutElementHelpers<'dom> for LayoutDom<'dom, Element> {
#[inline] #[inline]
fn get_classes_for_layout(self) -> Option<&'dom [Atom]> { fn get_classes_for_layout(self) -> Option<&'dom [Atom]> {
get_attr_for_layout(self, &ns!(), &local_name!("class")) get_attr_for_layout(self, &ns!(), &local_name!("class"))
.map(|attr| attr.as_tokens().unwrap()) .map(|attr| attr.to_tokens().unwrap())
} }
fn synthesize_presentational_hints_for_legacy_attributes<V>(self, hints: &mut V) fn synthesize_presentational_hints_for_legacy_attributes<V>(self, hints: &mut V)
@ -1036,7 +1036,7 @@ impl<'dom> LayoutElementHelpers<'dom> for LayoutDom<'dom, Element> {
} }
#[inline] #[inline]
fn is_html_element(self) -> bool { fn is_html_element(&self) -> bool {
*self.namespace() == ns!(html) *self.namespace() == ns!(html)
} }
@ -1543,7 +1543,7 @@ impl Element {
// https://html.spec.whatwg.org/multipage/#attr-data-* // https://html.spec.whatwg.org/multipage/#attr-data-*
pub fn set_custom_attribute(&self, name: DOMString, value: DOMString) -> ErrorResult { pub fn set_custom_attribute(&self, name: DOMString, value: DOMString) -> ErrorResult {
// Step 1. // Step 1.
if let InvalidXMLName = xml_name_type(&name) { if let Invalid = xml_name_type(&name) {
return Err(Error::InvalidCharacter); return Err(Error::InvalidCharacter);
} }
@ -2130,7 +2130,7 @@ impl ElementMethods for Element {
// https://dom.spec.whatwg.org/#dom-element-toggleattribute // https://dom.spec.whatwg.org/#dom-element-toggleattribute
fn ToggleAttribute(&self, name: DOMString, force: Option<bool>) -> Fallible<bool> { fn ToggleAttribute(&self, name: DOMString, force: Option<bool>) -> Fallible<bool> {
// Step 1. // Step 1.
if xml_name_type(&name) == InvalidXMLName { if xml_name_type(&name) == Invalid {
return Err(Error::InvalidCharacter); return Err(Error::InvalidCharacter);
} }
@ -2172,7 +2172,7 @@ impl ElementMethods for Element {
// https://dom.spec.whatwg.org/#dom-element-setattribute // https://dom.spec.whatwg.org/#dom-element-setattribute
fn SetAttribute(&self, name: DOMString, value: DOMString) -> ErrorResult { fn SetAttribute(&self, name: DOMString, value: DOMString) -> ErrorResult {
// Step 1. // Step 1.
if xml_name_type(&name) == InvalidXMLName { if xml_name_type(&name) == Invalid {
return Err(Error::InvalidCharacter); return Err(Error::InvalidCharacter);
} }

View file

@ -591,10 +591,11 @@ impl EventTarget {
} }
#[allow(unsafe_code)] #[allow(unsafe_code)]
pub fn set_event_handler_common<T: CallbackContainer>(&self, ty: &str, listener: Option<Rc<T>>) pub fn set_event_handler_common<T: CallbackContainer>(
where &self,
T: CallbackContainer, ty: &str,
{ listener: Option<Rc<T>>,
) {
let cx = GlobalScope::get_cx(); let cx = GlobalScope::get_cx();
let event_listener = listener.map(|listener| { let event_listener = listener.map(|listener| {
@ -606,10 +607,7 @@ impl EventTarget {
} }
#[allow(unsafe_code)] #[allow(unsafe_code)]
pub fn set_error_event_handler<T: CallbackContainer>(&self, ty: &str, listener: Option<Rc<T>>) pub fn set_error_event_handler<T: CallbackContainer>(&self, ty: &str, listener: Option<Rc<T>>) {
where
T: CallbackContainer,
{
let cx = GlobalScope::get_cx(); let cx = GlobalScope::get_cx();
let event_listener = listener.map(|listener| { let event_listener = listener.map(|listener| {
@ -625,9 +623,7 @@ impl EventTarget {
&self, &self,
ty: &str, ty: &str,
listener: Option<Rc<T>>, listener: Option<Rc<T>>,
) where ) {
T: CallbackContainer,
{
let cx = GlobalScope::get_cx(); let cx = GlobalScope::get_cx();
let event_listener = listener.map(|listener| { let event_listener = listener.map(|listener| {

View file

@ -69,10 +69,10 @@ impl GPUCompilationMessage {
global, global,
info.message.into(), info.message.into(),
GPUCompilationMessageType::Error, GPUCompilationMessageType::Error,
info.line_number as u64, info.line_number,
info.line_pos as u64, info.line_pos,
info.offset as u64, info.offset,
info.length as u64, info.length,
) )
} }
} }

View file

@ -216,7 +216,7 @@ impl GPUDevice {
/// <https://gpuweb.github.io/gpuweb/#lose-the-device> /// <https://gpuweb.github.io/gpuweb/#lose-the-device>
pub fn lose(&self, reason: GPUDeviceLostReason, msg: String) { pub fn lose(&self, reason: GPUDeviceLostReason, msg: String) {
let ref lost_promise = *self.lost_promise.borrow(); let lost_promise = &(*self.lost_promise.borrow());
let global = &self.global(); let global = &self.global();
let lost = GPUDeviceLostInfo::new(global, msg.into(), reason); let lost = GPUDeviceLostInfo::new(global, msg.into(), reason);
lost_promise.resolve_native(&*lost); lost_promise.resolve_native(&*lost);
@ -964,7 +964,7 @@ impl GPUDeviceMethods for GPUDevice {
.0 .0
.send(WebGPURequest::PushErrorScope { .send(WebGPURequest::PushErrorScope {
device_id: self.device.0, device_id: self.device.0,
filter: filter.to_webgpu(), filter: filter.as_webgpu(),
}) })
.is_err() .is_err()
{ {

View file

@ -80,7 +80,7 @@ impl From<ErrorFilter> for GPUErrorFilter {
} }
impl GPUErrorFilter { impl GPUErrorFilter {
pub fn to_webgpu(&self) -> ErrorFilter { pub fn as_webgpu(&self) -> ErrorFilter {
match self { match self {
GPUErrorFilter::Validation => ErrorFilter::Validation, GPUErrorFilter::Validation => ErrorFilter::Validation,
GPUErrorFilter::Out_of_memory => ErrorFilter::OutOfMemory, GPUErrorFilter::Out_of_memory => ErrorFilter::OutOfMemory,

View file

@ -535,7 +535,7 @@ pub fn extract_mime_type(headers: &HyperHeaders) -> Option<Vec<u8>> {
// Step 6.4 // Step 6.4
if temp_essence != essence { if temp_essence != essence {
charset = temp_charset.map(|c| c.to_string()); charset = temp_charset.map(|c| c.to_string());
essence = temp_essence.to_owned(); temp_essence.clone_into(&mut essence);
} else { } else {
// Step 6.5 // Step 6.5
if temp_charset.is_none() && charset.is_some() { if temp_charset.is_none() && charset.is_some() {

View file

@ -57,8 +57,7 @@ impl HTMLFontElement {
pub(crate) fn parse_face_attribute(face_value: Atom) -> Vec<SingleFontFamily> { pub(crate) fn parse_face_attribute(face_value: Atom) -> Vec<SingleFontFamily> {
face_value face_value
.to_string() .split(',')
.split(",")
.map(|string| Self::parse_single_face_value_from_string(string.trim())) .map(|string| Self::parse_single_face_value_from_string(string.trim()))
.collect() .collect()
} }

View file

@ -917,14 +917,14 @@ impl HTMLFormElement {
url.query().unwrap_or("").to_string().into_bytes() url.query().unwrap_or("").to_string().into_bytes()
}, },
FormEncType::FormDataEncoded => { FormEncType::MultipartFormData => {
let mime: Mime = format!("multipart/form-data; boundary={}", boundary) let mime: Mime = format!("multipart/form-data; boundary={}", boundary)
.parse() .parse()
.unwrap(); .unwrap();
load_data.headers.typed_insert(ContentType::from(mime)); load_data.headers.typed_insert(ContentType::from(mime));
encode_multipart_form_data(form_data, boundary, encoding) encode_multipart_form_data(form_data, boundary, encoding)
}, },
FormEncType::TextPlainEncoded => { FormEncType::TextPlain => {
load_data load_data
.headers .headers
.typed_insert(ContentType::from(mime::TEXT_PLAIN)); .typed_insert(ContentType::from(mime::TEXT_PLAIN));
@ -1366,9 +1366,9 @@ impl FormDatum {
#[derive(Clone, Copy, MallocSizeOf)] #[derive(Clone, Copy, MallocSizeOf)]
pub enum FormEncType { pub enum FormEncType {
TextPlainEncoded, TextPlain,
UrlEncoded, UrlEncoded,
FormDataEncoded, MultipartFormData,
} }
#[derive(Clone, Copy, MallocSizeOf)] #[derive(Clone, Copy, MallocSizeOf)]
@ -1420,8 +1420,8 @@ impl<'a> FormSubmitter<'a> {
), ),
}; };
match &*attr { match &*attr {
"multipart/form-data" => FormEncType::FormDataEncoded, "multipart/form-data" => FormEncType::MultipartFormData,
"text/plain" => FormEncType::TextPlainEncoded, "text/plain" => FormEncType::TextPlain,
// https://html.spec.whatwg.org/multipage/#attr-fs-enctype // https://html.spec.whatwg.org/multipage/#attr-fs-enctype
// urlencoded is the default // urlencoded is the default
_ => FormEncType::UrlEncoded, _ => FormEncType::UrlEncoded,

View file

@ -2141,15 +2141,16 @@ impl HTMLInputElement {
}, },
InputType::DatetimeLocal => { InputType::DatetimeLocal => {
// Is this supposed to know the locale's daylight-savings-time rules? // Is this supposed to know the locale's daylight-savings-time rules?
value.parse_local_date_and_time_string().and_then( value.parse_local_date_and_time_string().and_then(|date| {
|((year, month, day), (hours, minutes, seconds))| { let seconds = date.seconds as u32;
let hms_millis = let milliseconds = ((date.seconds - seconds as f64) * 1000.) as u32;
(seconds + 60.0 * minutes as f64 + 3600.0 * hours as f64) * 1000.0; Some(
NaiveDate::from_ymd_opt(year, month, day) NaiveDate::from_ymd_opt(date.year, date.month, date.day)?
.and_then(|date| date.and_hms_opt(0, 0, 0)) .and_hms_milli_opt(date.hour, date.minute, seconds, milliseconds)?
.map(|time| time.and_utc().timestamp_millis() as f64 + hms_millis) .and_utc()
}, .timestamp_millis() as f64,
) )
})
}, },
InputType::Number | InputType::Range => value.parse_floating_point_number(), InputType::Number | InputType::Range => value.parse_floating_point_number(),
// min/max/valueAsNumber/stepDown/stepUp do not apply to // min/max/valueAsNumber/stepDown/stepUp do not apply to