Replace the lazy_static crate whth std::sync::LazyLock in components/script (#33004)

* replace in str.rs

Signed-off-by: Hayashi Mikihiro <34ttrweoewiwe28@gmail.com>

* replace navigator.rs

Signed-off-by: Hayashi Mikihiro <34ttrweoewiwe28@gmail.com>

* replace htmlmetaelement.rs

Signed-off-by: Hayashi Mikihiro <34ttrweoewiwe28@gmail.com>

* replace document.rs

Signed-off-by: Hayashi Mikihiro <34ttrweoewiwe28@gmail.com>

* replace cssstyledeclaration.rs

Signed-off-by: Hayashi Mikihiro <34ttrweoewiwe28@gmail.com>

* replace script_runtime.rs

Signed-off-by: Hayashi Mikihiro <34ttrweoewiwe28@gmail.com>

* replace window_named_properties.rs

Signed-off-by: Hayashi Mikihiro <34ttrweoewiwe28@gmail.com>

* reduce dependency lazy_static

Signed-off-by: Hayashi Mikihiro <34ttrweoewiwe28@gmail.com>

* reduce lazy in script_runtime.rs

 `Mutex::new()`  is const contexts. I think that `JS_ENGINE` is need not lazy initialize.

Signed-off-by: Hayashi Mikihiro <34ttrweoewiwe28@gmail.com>

---------

Signed-off-by: Hayashi Mikihiro <34ttrweoewiwe28@gmail.com>
This commit is contained in:
Hayashi Mikihiro 2024-08-12 16:30:35 +09:00 committed by GitHub
parent f38d1574bc
commit a797969efe
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
9 changed files with 98 additions and 104 deletions

1
Cargo.lock generated
View file

@ -5615,7 +5615,6 @@ dependencies = [
"itertools 0.13.0", "itertools 0.13.0",
"jstraceable_derive", "jstraceable_derive",
"keyboard-types", "keyboard-types",
"lazy_static",
"libc", "libc",
"log", "log",
"malloc_size_of", "malloc_size_of",

View file

@ -66,7 +66,6 @@ itertools = { workspace = true }
js = { package = "mozjs", git = "https://github.com/servo/mozjs", features = ["streams"] } js = { package = "mozjs", git = "https://github.com/servo/mozjs", features = ["streams"] }
jstraceable_derive = { path = "../jstraceable_derive" } jstraceable_derive = { path = "../jstraceable_derive" }
keyboard-types = { workspace = true } keyboard-types = { workspace = true }
lazy_static = { workspace = true }
libc = { workspace = true } libc = { workspace = true }
log = { workspace = true } log = { workspace = true }
malloc_size_of = { workspace = true } malloc_size_of = { workspace = true }

View file

@ -9,13 +9,13 @@ use std::hash::{Hash, Hasher};
use std::marker::PhantomData; use std::marker::PhantomData;
use std::ops::{Deref, DerefMut}; use std::ops::{Deref, DerefMut};
use std::str::FromStr; use std::str::FromStr;
use std::sync::LazyLock;
use std::{fmt, ops, str}; use std::{fmt, ops, str};
use chrono::prelude::{Utc, Weekday}; use chrono::prelude::{Utc, Weekday};
use chrono::{Datelike, TimeZone}; use chrono::{Datelike, TimeZone};
use cssparser::CowRcStr; use cssparser::CowRcStr;
use html5ever::{LocalName, Namespace}; use html5ever::{LocalName, Namespace};
use lazy_static::lazy_static;
use num_traits::Zero; use num_traits::Zero;
use regex::Regex; use regex::Regex;
use servo_atoms::Atom; use servo_atoms::Atom;
@ -430,10 +430,10 @@ impl DOMString {
/// <https://html.spec.whatwg.org/multipage/#valid-floating-point-number> /// <https://html.spec.whatwg.org/multipage/#valid-floating-point-number>
pub fn is_valid_floating_point_number_string(&self) -> bool { pub fn is_valid_floating_point_number_string(&self) -> bool {
lazy_static! { static RE: LazyLock<Regex> = LazyLock::new(|| {
static ref RE: Regex = Regex::new(r"^-?(?:\d+\.\d+|\d+|\.\d+)(?:(e|E)(\+|\-)?\d+)?$").unwrap()
Regex::new(r"^-?(?:\d+\.\d+|\d+|\.\d+)(?:(e|E)(\+|\-)?\d+)?$").unwrap(); });
}
RE.is_match(&self.0) && self.parse_floating_point_number().is_some() RE.is_match(&self.0) && self.parse_floating_point_number().is_some()
} }
@ -537,13 +537,14 @@ impl DOMString {
/// <https://html.spec.whatwg.org/multipage/#valid-e-mail-address> /// <https://html.spec.whatwg.org/multipage/#valid-e-mail-address>
pub fn is_valid_email_address_string(&self) -> bool { pub fn is_valid_email_address_string(&self) -> bool {
lazy_static! { static RE: LazyLock<Regex> = LazyLock::new(|| {
static ref RE: Regex = Regex::new(concat!( Regex::new(concat!(
r"^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?", r"^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?",
r"(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$" r"(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$"
)) ))
.unwrap(); .unwrap()
} });
RE.is_match(&self.0) RE.is_match(&self.0)
} }

View file

@ -3,10 +3,10 @@
* file, You can obtain one at https://mozilla.org/MPL/2.0/. */ * file, You can obtain one at https://mozilla.org/MPL/2.0/. */
use std::cmp::Ordering; use std::cmp::Ordering;
use std::sync::LazyLock;
use dom_struct::dom_struct; use dom_struct::dom_struct;
use html5ever::local_name; use html5ever::local_name;
use lazy_static::lazy_static;
use servo_arc::Arc; use servo_arc::Arc;
use servo_url::ServoUrl; use servo_url::ServoUrl;
use style::attr::AttrValue; use style::attr::AttrValue;
@ -344,8 +344,7 @@ impl CSSStyleDeclaration {
} }
} }
lazy_static! { static ENABLED_LONGHAND_PROPERTIES: LazyLock<Vec<LonghandId>> = LazyLock::new(|| {
static ref ENABLED_LONGHAND_PROPERTIES: Vec<LonghandId> = {
// The 'all' shorthand contains all the enabled longhands with 2 exceptions: // The 'all' shorthand contains all the enabled longhands with 2 exceptions:
// 'direction' and 'unicode-bidi', so these must be added afterward. // 'direction' and 'unicode-bidi', so these must be added afterward.
let mut enabled_longhands: Vec<LonghandId> = ShorthandId::All.longhands().collect(); let mut enabled_longhands: Vec<LonghandId> = ShorthandId::All.longhands().collect();
@ -371,8 +370,7 @@ lazy_static! {
} }
}); });
enabled_longhands enabled_longhands
}; });
}
impl CSSStyleDeclarationMethods for CSSStyleDeclaration { impl CSSStyleDeclarationMethods for CSSStyleDeclaration {
// https://dev.w3.org/csswg/cssom/#dom-cssstyledeclaration-length // https://dev.w3.org/csswg/cssom/#dom-cssstyledeclaration-length

View file

@ -11,6 +11,7 @@ use std::default::Default;
use std::mem; use std::mem;
use std::rc::Rc; use std::rc::Rc;
use std::slice::from_ref; use std::slice::from_ref;
use std::sync::LazyLock;
use std::time::{Duration, Instant}; use std::time::{Duration, Instant};
use base::id::BrowsingContextId; use base::id::BrowsingContextId;
@ -28,7 +29,6 @@ use hyper_serde::Serde;
use ipc_channel::ipc::{self, IpcSender}; use ipc_channel::ipc::{self, IpcSender};
use js::rust::{HandleObject, HandleValue}; use js::rust::{HandleObject, HandleValue};
use keyboard_types::{Code, Key, KeyState}; use keyboard_types::{Code, Key, KeyState};
use lazy_static::lazy_static;
use metrics::{ use metrics::{
InteractiveFlag, InteractiveMetrics, InteractiveWindow, ProfilerMetadataFactory, InteractiveFlag, InteractiveMetrics, InteractiveWindow, ProfilerMetadataFactory,
ProgressiveWebMetric, ProgressiveWebMetric,
@ -3219,17 +3219,15 @@ impl Document {
anchors: Default::default(), anchors: Default::default(),
applets: Default::default(), applets: Default::default(),
style_shared_lock: { style_shared_lock: {
lazy_static! {
/// Per-process shared lock for author-origin stylesheets /// Per-process shared lock for author-origin stylesheets
/// ///
/// FIXME: make it per-document or per-pipeline instead: /// FIXME: make it per-document or per-pipeline instead:
/// <https://github.com/servo/servo/issues/16027> /// <https://github.com/servo/servo/issues/16027>
/// (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 ref PER_PROCESS_AUTHOR_SHARED_LOCK: StyleSharedRwLock = { static PER_PROCESS_AUTHOR_SHARED_LOCK: LazyLock<StyleSharedRwLock> =
StyleSharedRwLock::new() LazyLock::new(|| StyleSharedRwLock::new());
};
}
PER_PROCESS_AUTHOR_SHARED_LOCK.clone() PER_PROCESS_AUTHOR_SHARED_LOCK.clone()
//StyleSharedRwLock::new() //StyleSharedRwLock::new()
}, },

View file

@ -3,6 +3,7 @@
* file, You can obtain one at https://mozilla.org/MPL/2.0/. */ * file, You can obtain one at https://mozilla.org/MPL/2.0/. */
use std::str::FromStr; use std::str::FromStr;
use std::sync::LazyLock;
use dom_struct::dom_struct; use dom_struct::dom_struct;
use html5ever::{LocalName, Prefix}; use html5ever::{LocalName, Prefix};
@ -146,8 +147,8 @@ impl HTMLMetaElement {
} }
// 2-11 // 2-11
lazy_static::lazy_static! { static REFRESH_REGEX: LazyLock<Regex> = LazyLock::new(|| {
static ref REFRESH_REGEX: Regex = Regex::new( Regex::new(
r#"(?x) r#"(?x)
^ ^
\s* # 3 \s* # 3
@ -169,8 +170,9 @@ impl HTMLMetaElement {
$ $
"#, "#,
) )
.unwrap(); .unwrap()
} });
let mut url_record = document.url(); let mut url_record = document.url();
let captures = if let Some(captures) = REFRESH_REGEX.captures(content.as_bytes()) { let captures = if let Some(captures) = REFRESH_REGEX.captures(content.as_bytes()) {
captures captures

View file

@ -4,10 +4,10 @@
use std::cell::Cell; use std::cell::Cell;
use std::convert::TryInto; use std::convert::TryInto;
use std::sync::LazyLock;
use dom_struct::dom_struct; use dom_struct::dom_struct;
use js::jsval::JSVal; use js::jsval::JSVal;
use lazy_static::lazy_static;
use crate::dom::bindings::cell::DomRefCell; use crate::dom::bindings::cell::DomRefCell;
use crate::dom::bindings::codegen::Bindings::NavigatorBinding::NavigatorMethods; use crate::dom::bindings::codegen::Bindings::NavigatorBinding::NavigatorMethods;
@ -32,9 +32,8 @@ use crate::dom::xrsystem::XRSystem;
use crate::script_runtime::JSContext; use crate::script_runtime::JSContext;
pub(super) fn hardware_concurrency() -> u64 { pub(super) fn hardware_concurrency() -> u64 {
lazy_static! { static CPUS: LazyLock<u64> = LazyLock::new(|| num_cpus::get().try_into().unwrap_or(1));
static ref CPUS: u64 = num_cpus::get().try_into().unwrap_or(1);
}
*CPUS *CPUS
} }

View file

@ -47,7 +47,6 @@ use js::rust::{
describe_scripted_caller, Handle, HandleObject as RustHandleObject, IntoHandle, JSEngine, describe_scripted_caller, Handle, HandleObject as RustHandleObject, IntoHandle, JSEngine,
JSEngineHandle, ParentRuntime, Runtime as RustRuntime, JSEngineHandle, ParentRuntime, Runtime as RustRuntime,
}; };
use lazy_static::lazy_static;
use malloc_size_of::MallocSizeOfOps; use malloc_size_of::MallocSizeOfOps;
use profile_traits::mem::{Report, ReportKind, ReportsChan}; use profile_traits::mem::{Report, ReportKind, ReportsChan};
use profile_traits::path; use profile_traits::path;
@ -487,9 +486,7 @@ impl Drop for JSEngineSetup {
} }
} }
lazy_static! { static JS_ENGINE: Mutex<Option<JSEngineHandle>> = Mutex::new(None);
static ref JS_ENGINE: Mutex<Option<JSEngineHandle>> = Mutex::new(None);
}
#[allow(unsafe_code)] #[allow(unsafe_code)]
pub unsafe fn new_child_runtime( pub unsafe fn new_child_runtime(

View file

@ -3,6 +3,7 @@
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */ * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
use std::ptr; use std::ptr;
use std::sync::LazyLock;
use js::conversions::jsstr_to_string; use js::conversions::jsstr_to_string;
use js::glue::{AppendToIdVector, CreateProxyHandler, NewProxyObject, ProxyTraps}; use js::glue::{AppendToIdVector, CreateProxyHandler, NewProxyObject, ProxyTraps};
@ -32,9 +33,10 @@ use crate::script_runtime::JSContext as SafeJSContext;
struct SyncWrapper(*const libc::c_void); struct SyncWrapper(*const libc::c_void);
#[allow(unsafe_code)] #[allow(unsafe_code)]
unsafe impl Sync for SyncWrapper {} unsafe impl Sync for SyncWrapper {}
#[allow(unsafe_code)]
unsafe impl Send for SyncWrapper {}
lazy_static::lazy_static! { static HANDLER: LazyLock<SyncWrapper> = LazyLock::new(|| {
static ref HANDLER: SyncWrapper = {
let traps = ProxyTraps { let traps = ProxyTraps {
enter: None, enter: None,
getOwnPropertyDescriptor: Some(get_own_property_descriptor), getOwnPropertyDescriptor: Some(get_own_property_descriptor),
@ -72,8 +74,7 @@ lazy_static::lazy_static! {
unsafe { unsafe {
SyncWrapper(CreateProxyHandler(&traps, ptr::null())) SyncWrapper(CreateProxyHandler(&traps, ptr::null()))
} }
}; });
}
#[allow(unsafe_code)] #[allow(unsafe_code)]
unsafe extern "C" fn get_own_property_descriptor( unsafe extern "C" fn get_own_property_descriptor(