clippy: Fix suggestions in script, libservo, and servoshell (#33453)

* fix clone on copy warning in servoshell

Signed-off-by: Ali Zein Yousuf <azy5030@gmail.com>

* Remove unecessary borrow in libservo

Signed-off-by: Ali Zein Yousuf <azy5030@gmail.com>

* Ignore too many arguments warning on create_constellation()

Signed-off-by: Ali Zein Yousuf <azy5030@gmail.com>

* fix explicit auto-deref warning

Signed-off-by: Ali Zein Yousuf <azy5030@gmail.com>

* Autofix multiple clippy warnings in components/script

Signed-off-by: Ali Zein Yousuf <azy5030@gmail.com>

---------

Signed-off-by: Ali Zein Yousuf <azy5030@gmail.com>
This commit is contained in:
Ali 2024-09-14 03:41:13 -05:00 committed by GitHub
parent 6a3cdc47ec
commit ed6b1b5e6a
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
22 changed files with 44 additions and 42 deletions

View file

@ -236,7 +236,7 @@ pub fn handle_get_stylesheet_style(
}; };
Some(style.Style()) Some(style.Style())
}) })
.map(|style| { .flat_map(|style| {
(0..style.Length()).map(move |i| { (0..style.Length()).map(move |i| {
let name = style.Item(i); let name = style.Item(i);
NodeStyle { NodeStyle {
@ -246,7 +246,6 @@ pub fn handle_get_stylesheet_style(
} }
}) })
}) })
.flatten()
.collect(); .collect();
Some(styles) Some(styles)
@ -279,7 +278,7 @@ pub fn handle_get_selectors(
let rule = list.Item(j)?; let rule = list.Item(j)?;
let style = rule.downcast::<CSSStyleRule>()?; let style = rule.downcast::<CSSStyleRule>()?;
let selector = style.SelectorText(); let selector = style.SelectorText();
let _ = elem.Matches(selector.clone()).ok()?.then_some(())?; elem.Matches(selector.clone()).ok()?.then_some(())?;
Some((selector.into(), i)) Some((selector.into(), i))
})) }))
}) })

View file

@ -259,7 +259,7 @@ unsafe fn id_to_source(cx: SafeJSContext, id: RawHandleId) -> Option<DOMString>
jsstr.set(jsapi::JS_ValueToSource(*cx, value.handle().into())); jsstr.set(jsapi::JS_ValueToSource(*cx, value.handle().into()));
jsstr.get() jsstr.get()
}) })
.and_then(|jsstr| ptr::NonNull::new(jsstr)) .and_then(ptr::NonNull::new)
.map(|jsstr| jsstring_to_str(*cx, jsstr)) .map(|jsstr| jsstring_to_str(*cx, jsstr))
} }

View file

@ -905,6 +905,6 @@ impl FromInputValueString for &str {
)) ))
.unwrap() .unwrap()
}); });
RE.is_match(&self) RE.is_match(self)
} }
} }

View file

@ -3242,7 +3242,7 @@ impl Document {
/// (Need to figure out what to do with the style attribute /// (Need to figure out what to do with the style attribute
/// of elements adopted into another document.) /// of elements adopted into another document.)
static PER_PROCESS_AUTHOR_SHARED_LOCK: LazyLock<StyleSharedRwLock> = static PER_PROCESS_AUTHOR_SHARED_LOCK: LazyLock<StyleSharedRwLock> =
LazyLock::new(|| StyleSharedRwLock::new()); LazyLock::new(StyleSharedRwLock::new);
PER_PROCESS_AUTHOR_SHARED_LOCK.clone() PER_PROCESS_AUTHOR_SHARED_LOCK.clone()
//StyleSharedRwLock::new() //StyleSharedRwLock::new()

View file

@ -37,7 +37,7 @@ impl File {
blob: Blob::new_inherited(blob_impl), blob: Blob::new_inherited(blob_impl),
name, name,
// https://w3c.github.io/FileAPI/#dfn-lastModified // https://w3c.github.io/FileAPI/#dfn-lastModified
modified: modified.unwrap_or_else(SystemTime::now).into(), modified: modified.unwrap_or_else(SystemTime::now),
} }
} }
@ -87,7 +87,7 @@ impl File {
normalize_type_string(&selected.type_string.to_string()), normalize_type_string(&selected.type_string.to_string()),
), ),
name, name,
Some(selected.modified.into()), Some(selected.modified),
) )
} }

View file

@ -317,7 +317,7 @@ impl Gamepad {
} }
pub fn vibration_actuator(&self) -> &GamepadHapticActuator { pub fn vibration_actuator(&self) -> &GamepadHapticActuator {
&*self.vibration_actuator &self.vibration_actuator
} }
} }

View file

@ -96,7 +96,7 @@ impl GamepadHapticActuator {
} }
Self { Self {
reflector_: Reflector::new(), reflector_: Reflector::new(),
gamepad_index: gamepad_index.into(), gamepad_index: gamepad_index,
effects, effects,
playing_effect_promise: DomRefCell::new(None), playing_effect_promise: DomRefCell::new(None),
sequence_id: Cell::new(0), sequence_id: Cell::new(0),
@ -118,7 +118,7 @@ impl GamepadHapticActuator {
gamepad_index: u32, gamepad_index: u32,
supported_haptic_effects: GamepadSupportedHapticEffects, supported_haptic_effects: GamepadSupportedHapticEffects,
) -> DomRoot<GamepadHapticActuator> { ) -> DomRoot<GamepadHapticActuator> {
let haptic_actuator = reflect_dom_object_with_proto( reflect_dom_object_with_proto(
Box::new(GamepadHapticActuator::new_inherited( Box::new(GamepadHapticActuator::new_inherited(
gamepad_index, gamepad_index,
supported_haptic_effects, supported_haptic_effects,
@ -126,8 +126,7 @@ impl GamepadHapticActuator {
global, global,
None, None,
CanGc::note(), CanGc::note(),
); )
haptic_actuator
} }
} }
@ -367,7 +366,7 @@ impl GamepadHapticActuator {
return; return;
} }
let this = Trusted::new(&*self); let this = Trusted::new(self);
let _ = self.global().gamepad_task_source().queue( let _ = self.global().gamepad_task_source().queue(
task!(stop_playing_effect: move || { task!(stop_playing_effect: move || {
let actuator = this.root(); let actuator = this.root();

View file

@ -296,7 +296,7 @@ impl GPUBufferMethods for GPUBuffer {
let range_size = if let Some(s) = size { let range_size = if let Some(s) = size {
s s
} else { } else {
self.size.checked_sub(offset).unwrap_or(0) self.size.saturating_sub(offset)
}; };
// Step 2: validation // Step 2: validation
let mut mapping = self.mapping.borrow_mut(); let mut mapping = self.mapping.borrow_mut();

View file

@ -224,7 +224,7 @@ impl TryFrom<&GPUExtent3D> for wgt::Extent3d {
}), }),
GPUExtent3D::RangeEnforcedUnsignedLongSequence(ref v) => { GPUExtent3D::RangeEnforcedUnsignedLongSequence(ref v) => {
// https://gpuweb.github.io/gpuweb/#abstract-opdef-validate-gpuextent3d-shape // https://gpuweb.github.io/gpuweb/#abstract-opdef-validate-gpuextent3d-shape
if v.len() < 1 || v.len() > 3 { if v.is_empty() || v.len() > 3 {
Err(Error::Type( Err(Error::Type(
"GPUExtent3D size must be between 1 and 3 (inclusive)".to_string(), "GPUExtent3D size must be between 1 and 3 (inclusive)".to_string(),
)) ))
@ -460,7 +460,7 @@ impl TryFrom<&GPUOrigin3D> for wgt::Origin3d {
)) ))
} else { } else {
Ok(wgt::Origin3d { Ok(wgt::Origin3d {
x: v.get(0).copied().unwrap_or(0), x: v.first().copied().unwrap_or(0),
y: v.get(1).copied().unwrap_or(0), y: v.get(1).copied().unwrap_or(0),
z: v.get(2).copied().unwrap_or(0), z: v.get(2).copied().unwrap_or(0),
}) })
@ -485,7 +485,7 @@ impl TryFrom<&GPUImageCopyTexture> for wgpu_com::ImageCopyTexture {
origin: ic_texture origin: ic_texture
.origin .origin
.as_ref() .as_ref()
.map(|origin| wgt::Origin3d::try_from(origin)) .map(wgt::Origin3d::try_from)
.transpose()? .transpose()?
.unwrap_or_default(), .unwrap_or_default(),
aspect: match ic_texture.aspect { aspect: match ic_texture.aspect {
@ -497,12 +497,12 @@ impl TryFrom<&GPUImageCopyTexture> for wgpu_com::ImageCopyTexture {
} }
} }
impl<'a> Into<Option<Cow<'a, str>>> for &GPUObjectDescriptorBase { impl<'a> From<&GPUObjectDescriptorBase> for Option<Cow<'a, str>> {
fn into(self) -> Option<Cow<'a, str>> { fn from(val: &GPUObjectDescriptorBase) -> Self {
if self.label.is_empty() { if val.label.is_empty() {
None None
} else { } else {
Some(Cow::Owned(self.label.to_string())) Some(Cow::Owned(val.label.to_string()))
} }
} }
} }

View file

@ -478,7 +478,7 @@ impl GPUDeviceMethods for GPUDevice {
&self, &self,
descriptor: &GPURenderPipelineDescriptor, descriptor: &GPURenderPipelineDescriptor,
) -> Fallible<DomRoot<GPURenderPipeline>> { ) -> Fallible<DomRoot<GPURenderPipeline>> {
let (implicit_ids, desc) = self.parse_render_pipeline(&descriptor)?; let (implicit_ids, desc) = self.parse_render_pipeline(descriptor)?;
let render_pipeline = GPURenderPipeline::create(self, implicit_ids, desc, None)?; let render_pipeline = GPURenderPipeline::create(self, implicit_ids, desc, None)?;
Ok(GPURenderPipeline::new( Ok(GPURenderPipeline::new(
&self.global(), &self.global(),
@ -494,7 +494,7 @@ impl GPUDeviceMethods for GPUDevice {
descriptor: &GPURenderPipelineDescriptor, descriptor: &GPURenderPipelineDescriptor,
comp: InRealm, comp: InRealm,
) -> Fallible<Rc<Promise>> { ) -> Fallible<Rc<Promise>> {
let (implicit_ids, desc) = self.parse_render_pipeline(&descriptor)?; let (implicit_ids, desc) = self.parse_render_pipeline(descriptor)?;
let promise = Promise::new_in_current_realm(comp); let promise = Promise::new_in_current_realm(comp);
let sender = response_async(&promise, self); let sender = response_async(&promise, self);
GPURenderPipeline::create(self, implicit_ids, desc, Some(sender))?; GPURenderPipeline::create(self, implicit_ids, desc, Some(sender))?;

View file

@ -90,7 +90,7 @@ impl GPURenderBundleEncoder {
.map(|format| { .map(|format| {
device device
.validate_texture_format_required_features(format) .validate_texture_format_required_features(format)
.map(|f| Some(f)) .map(Some)
}) })
.collect::<Fallible<Vec<_>>>()?, .collect::<Fallible<Vec<_>>>()?,
), ),

View file

@ -99,7 +99,7 @@ impl HTMLHeadElement {
.filter(|elem| { .filter(|elem| {
elem.get_string_attribute(&local_name!("http-equiv")) elem.get_string_attribute(&local_name!("http-equiv"))
.to_ascii_lowercase() == .to_ascii_lowercase() ==
"content-security-policy".to_owned() *"content-security-policy"
}) })
.filter(|elem| { .filter(|elem| {
elem.get_attribute(&ns!(), &local_name!("content")) elem.get_attribute(&ns!(), &local_name!("content"))

View file

@ -310,7 +310,7 @@ impl HTMLLinkElement {
// Step 2. Let options be a new link processing options // Step 2. Let options be a new link processing options
let destination = element let destination = element
.get_attribute(&ns!(), &local_name!("as")) .get_attribute(&ns!(), &local_name!("as"))
.map(|attr| translate_a_preload_destination(&*attr.value())) .map(|attr| translate_a_preload_destination(&attr.value()))
.unwrap_or(Destination::None); .unwrap_or(Destination::None);
let mut options = LinkProcessingOptions { let mut options = LinkProcessingOptions {
@ -383,7 +383,7 @@ impl HTMLLinkElement {
.networking_task_source_with_canceller(); .networking_task_source_with_canceller();
let fetch_context = sync::Arc::new(sync::Mutex::new(PrefetchContext { let fetch_context = sync::Arc::new(sync::Mutex::new(PrefetchContext {
url: url, url,
link: Trusted::new(self), link: Trusted::new(self),
resource_timing: ResourceFetchTiming::new(ResourceTimingType::Resource), resource_timing: ResourceFetchTiming::new(ResourceTimingType::Resource),
})); }));

View file

@ -607,7 +607,7 @@ impl Node {
pub fn is_empty(&self) -> bool { pub fn is_empty(&self) -> bool {
// A node is considered empty if its length is 0. // A node is considered empty if its length is 0.
return self.len() == 0; self.len() == 0
} }
/// <https://dom.spec.whatwg.org/#concept-tree-index> /// <https://dom.spec.whatwg.org/#concept-tree-index>

View file

@ -49,7 +49,7 @@ impl SecurityPolicyViolationEvent {
original_policy: init.originalPolicy.clone(), original_policy: init.originalPolicy.clone(),
source_file: init.sourceFile.clone(), source_file: init.sourceFile.clone(),
sample: init.sample.clone(), sample: init.sample.clone(),
disposition: init.disposition.clone(), disposition: init.disposition,
status_code: init.statusCode, status_code: init.statusCode,
line_number: init.lineNumber, line_number: init.lineNumber,
column_number: init.columnNumber, column_number: init.columnNumber,
@ -169,7 +169,7 @@ impl SecurityPolicyViolationEventMethods for SecurityPolicyViolationEvent {
/// <https://w3c.github.io/webappsec-csp/#dom-securitypolicyviolationevent-disposition> /// <https://w3c.github.io/webappsec-csp/#dom-securitypolicyviolationevent-disposition>
fn Disposition(&self) -> SecurityPolicyViolationEventDisposition { fn Disposition(&self) -> SecurityPolicyViolationEventDisposition {
self.disposition.clone() self.disposition
} }
/// <https://w3c.github.io/webappsec-csp/#dom-securitypolicyviolationevent-statuscode> /// <https://w3c.github.io/webappsec-csp/#dom-securitypolicyviolationevent-statuscode>

View file

@ -1664,7 +1664,7 @@ impl ScriptThread {
.iter() .iter()
.filter(|(_, document)| document.window().is_top_level()) .filter(|(_, document)| document.window().is_top_level())
.flat_map(|(id, document)| { .flat_map(|(id, document)| {
std::iter::once(id.clone()).chain( std::iter::once(id).chain(
document document
.iter_iframes() .iter_iframes()
.filter_map(|iframe| iframe.pipeline_id()), .filter_map(|iframe| iframe.pipeline_id()),
@ -2556,8 +2556,8 @@ impl ScriptThread {
DevtoolScriptControlMsg::EvaluateJS(id, s, reply) => match documents.find_window(id) { DevtoolScriptControlMsg::EvaluateJS(id, s, reply) => match documents.find_window(id) {
Some(window) => { Some(window) => {
let global = window.upcast::<GlobalScope>(); let global = window.upcast::<GlobalScope>();
let _aes = AutoEntryScript::new(&global); let _aes = AutoEntryScript::new(global);
devtools::handle_evaluate_js(&global, s, reply) devtools::handle_evaluate_js(global, s, reply)
}, },
None => warn!("Message sent to closed pipeline {}.", id), None => warn!("Message sent to closed pipeline {}.", id),
}, },

View file

@ -161,7 +161,7 @@ impl From<SecurityPolicyViolationReport> for SecurityPolicyViolationEventInit {
lineNumber: value.line_number, lineNumber: value.line_number,
columnNumber: value.column_number, columnNumber: value.column_number,
originalPolicy: value.original_policy.into(), originalPolicy: value.original_policy.into(),
disposition: value.disposition.into(), disposition: value.disposition,
parent: EventInit::empty(), parent: EventInit::empty(),
} }
} }

View file

@ -170,10 +170,13 @@ impl<T: QueuedTaskConversion> TaskQueue<T> {
), ),
}; };
let mut throttled_tasks = self.throttled.borrow_mut(); let mut throttled_tasks = self.throttled.borrow_mut();
throttled_tasks throttled_tasks.entry(task_source).or_default().push_back((
.entry(task_source.clone()) worker,
.or_default() category,
.push_back((worker, category, boxed, pipeline_id, task_source)); boxed,
pipeline_id,
task_source,
));
} }
} }

View file

@ -49,7 +49,7 @@ fn find_python() -> PathBuf {
for name in &candidates { for name in &candidates {
// Command::new() allows us to omit the `.exe` suffix on windows // Command::new() allows us to omit the `.exe` suffix on windows
if Command::new(&name) if Command::new(name)
.arg("--version") .arg("--version")
.output() .output()
.is_ok_and(|out| out.status.success()) .is_ok_and(|out| out.status.success())

View file

@ -1001,6 +1001,7 @@ fn get_layout_factory(legacy_layout: bool) -> Arc<dyn LayoutFactory> {
Arc::new(layout_thread_2020::LayoutFactoryImpl()) Arc::new(layout_thread_2020::LayoutFactoryImpl())
} }
#[allow(clippy::too_many_arguments)]
fn create_constellation( fn create_constellation(
user_agent: Cow<'static, str>, user_agent: Cow<'static, str>,
config_dir: Option<PathBuf>, config_dir: Option<PathBuf>,

View file

@ -100,7 +100,7 @@ mod platform {
unsafe { mach_timebase_info(&mut timebase_info) }; unsafe { mach_timebase_info(&mut timebase_info) };
timebase_info timebase_info
}); });
&*TIMEBASE_INFO &TIMEBASE_INFO
} }
#[allow(unsafe_code)] #[allow(unsafe_code)]

View file

@ -152,7 +152,7 @@ where
// Returns the existing preload data for the given WebView, or a new one. // Returns the existing preload data for the given WebView, or a new one.
fn ensure_preload_data_mut(&mut self, webview_id: &WebViewId) -> &mut WebViewPreloadData { fn ensure_preload_data_mut(&mut self, webview_id: &WebViewId) -> &mut WebViewPreloadData {
if let Entry::Vacant(entry) = self.webview_preload_data.entry(webview_id.clone()) { if let Entry::Vacant(entry) = self.webview_preload_data.entry(*webview_id) {
entry.insert(WebViewPreloadData::default()); entry.insert(WebViewPreloadData::default());
} }
self.webview_preload_data.get_mut(webview_id).unwrap() self.webview_preload_data.get_mut(webview_id).unwrap()