Skip to content

Commit

Permalink
refactor: use once_cell instead of lazy_static (denoland#13135)
Browse files Browse the repository at this point in the history
  • Loading branch information
littledivy committed Dec 18, 2021
1 parent 3db18bf commit 6de53b6
Show file tree
Hide file tree
Showing 27 changed files with 447 additions and 326 deletions.
13 changes: 6 additions & 7 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

3 changes: 1 addition & 2 deletions cli/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -62,13 +62,12 @@ fancy-regex = "=0.7.1"
http = "=0.2.4"
import_map = "=0.4.0"
jsonc-parser = { version = "=0.17.0", features = ["serde"] }
lazy_static = "=1.4.0"
libc = "=0.2.106"
log = { version = "=0.4.14", features = ["serde"] }
lspower = "=1.4.0"
notify = "=5.0.0-pre.12"
num_cpus = "=1.13.0"
once_cell = "=1.8.0"
once_cell = "=1.9.0"
percent-encoding = "=2.1.0"
pin-project = "=1.0.8"
rand = { version = "=0.8.4", features = ["small_rng"] }
Expand Down
31 changes: 22 additions & 9 deletions cli/compat/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ use deno_core::error::AnyError;
use deno_core::located_script_name;
use deno_core::url::Url;
use deno_core::JsRuntime;
use once_cell::sync::Lazy;

pub use esm_resolver::check_if_should_use_esm_loader;
pub(crate) use esm_resolver::NodeEsmResolver;
Expand Down Expand Up @@ -62,15 +63,27 @@ static SUPPORTED_MODULES: &[&str] = &[
"zlib",
];

lazy_static::lazy_static! {
static ref NODE_COMPAT_URL: String = std::env::var("DENO_NODE_COMPAT_URL").map(String::into).ok()
.unwrap_or_else(|| STD_URL_STR.to_string());
static ref GLOBAL_URL_STR: String = format!("{}node/global.ts", NODE_COMPAT_URL.as_str());
pub(crate) static ref GLOBAL_URL: Url = Url::parse(&GLOBAL_URL_STR).unwrap();
static ref MODULE_URL_STR: String = format!("{}node/module.ts", NODE_COMPAT_URL.as_str());
pub(crate) static ref MODULE_URL: Url = Url::parse(&MODULE_URL_STR).unwrap();
static ref COMPAT_IMPORT_URL: Url = Url::parse("flags:compat").unwrap();
}
static NODE_COMPAT_URL: Lazy<String> = Lazy::new(|| {
std::env::var("DENO_NODE_COMPAT_URL")
.map(String::into)
.ok()
.unwrap_or_else(|| STD_URL_STR.to_string())
});

static GLOBAL_URL_STR: Lazy<String> =
Lazy::new(|| format!("{}node/global.ts", NODE_COMPAT_URL.as_str()));

pub(crate) static GLOBAL_URL: Lazy<Url> =
Lazy::new(|| Url::parse(&GLOBAL_URL_STR).unwrap());

static MODULE_URL_STR: Lazy<String> =
Lazy::new(|| format!("{}node/module.ts", NODE_COMPAT_URL.as_str()));

pub(crate) static MODULE_URL: Lazy<Url> =
Lazy::new(|| Url::parse(&MODULE_URL_STR).unwrap());

static COMPAT_IMPORT_URL: Lazy<Url> =
Lazy::new(|| Url::parse("flags:compat").unwrap());

/// Provide imports into a module graph when the compat flag is true.
pub(crate) fn get_node_imports() -> Vec<(Url, Vec<String>)> {
Expand Down
15 changes: 8 additions & 7 deletions cli/diagnostics.rs
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ use deno_core::serde::Deserializer;
use deno_core::serde::Serialize;
use deno_core::serde::Serializer;
use deno_graph::ModuleGraphError;
use once_cell::sync::Lazy;
use regex::Regex;
use std::error::Error;
use std::fmt;
Expand Down Expand Up @@ -65,13 +66,13 @@ const UNSTABLE_DENO_PROPS: &[&str] = &[
"utimeSync",
];

lazy_static::lazy_static! {
static ref MSG_MISSING_PROPERTY_DENO: Regex =
Regex::new(r#"Property '([^']+)' does not exist on type 'typeof Deno'"#)
.unwrap();
static ref MSG_SUGGESTION: Regex =
Regex::new(r#" Did you mean '([^']+)'\?"#).unwrap();
}
static MSG_MISSING_PROPERTY_DENO: Lazy<Regex> = Lazy::new(|| {
Regex::new(r#"Property '([^']+)' does not exist on type 'typeof Deno'"#)
.unwrap()
});

static MSG_SUGGESTION: Lazy<Regex> =
Lazy::new(|| Regex::new(r#" Did you mean '([^']+)'\?"#).unwrap());

/// Potentially convert a "raw" diagnostic message from TSC to something that
/// provides a more sensible error message given a Deno runtime context.
Expand Down
9 changes: 5 additions & 4 deletions cli/flags.rs
Original file line number Diff line number Diff line change
Expand Up @@ -12,15 +12,16 @@ use deno_core::url::Url;
use deno_runtime::permissions::PermissionsOptions;
use log::debug;
use log::Level;
use once_cell::sync::Lazy;
use std::net::SocketAddr;
use std::num::NonZeroU32;
use std::num::NonZeroU8;
use std::num::NonZeroUsize;
use std::path::PathBuf;
use std::str::FromStr;

lazy_static::lazy_static! {
static ref LONG_VERSION: String = format!(
static LONG_VERSION: Lazy<String> = Lazy::new(|| {
format!(
"{} ({}, {})\nv8 {}\ntypescript {}",
crate::version::deno(),
if crate::version::is_canary() {
Expand All @@ -31,8 +32,8 @@ lazy_static::lazy_static! {
env!("TARGET"),
deno_core::v8_version(),
crate::version::TYPESCRIPT
);
}
)
});

#[derive(Clone, Debug, PartialEq, Deserialize, Serialize)]
pub struct BundleFlags {
Expand Down
84 changes: 45 additions & 39 deletions cli/lsp/analysis.rs
Original file line number Diff line number Diff line change
Expand Up @@ -18,52 +18,58 @@ use deno_core::ModuleSpecifier;
use lspower::lsp;
use lspower::lsp::Position;
use lspower::lsp::Range;
use once_cell::sync::Lazy;
use regex::Regex;
use std::cmp::Ordering;
use std::collections::HashMap;

lazy_static::lazy_static! {
/// Diagnostic error codes which actually are the same, and so when grouping
/// fixes we treat them the same.
static ref FIX_ALL_ERROR_CODES: HashMap<&'static str, &'static str> =
(&[("2339", "2339"), ("2345", "2339"),])
/// Diagnostic error codes which actually are the same, and so when grouping
/// fixes we treat them the same.
static FIX_ALL_ERROR_CODES: Lazy<HashMap<&'static str, &'static str>> =
Lazy::new(|| {
(&[("2339", "2339"), ("2345", "2339")])
.iter()
.cloned()
.collect();

/// Fixes which help determine if there is a preferred fix when there are
/// multiple fixes available.
static ref PREFERRED_FIXES: HashMap<&'static str, (u32, bool)> = (&[
("annotateWithTypeFromJSDoc", (1, false)),
("constructorForDerivedNeedSuperCall", (1, false)),
("extendsInterfaceBecomesImplements", (1, false)),
("awaitInSyncFunction", (1, false)),
("classIncorrectlyImplementsInterface", (3, false)),
("classDoesntImplementInheritedAbstractMember", (3, false)),
("unreachableCode", (1, false)),
("unusedIdentifier", (1, false)),
("forgottenThisPropertyAccess", (1, false)),
("spelling", (2, false)),
("addMissingAwait", (1, false)),
("fixImport", (0, true)),
])
.iter()
.cloned()
.collect();

static ref IMPORT_SPECIFIER_RE: Regex = Regex::new(r#"\sfrom\s+["']([^"']*)["']"#).unwrap();

static ref DENO_TYPES_RE: Regex =
Regex::new(r#"(?i)^\s*@deno-types\s*=\s*(?:["']([^"']+)["']|(\S+))"#)
.unwrap();
static ref TRIPLE_SLASH_REFERENCE_RE: Regex =
Regex::new(r"(?i)^/\s*<reference\s.*?/>").unwrap();
static ref PATH_REFERENCE_RE: Regex =
Regex::new(r#"(?i)\spath\s*=\s*["']([^"']*)["']"#).unwrap();
static ref TYPES_REFERENCE_RE: Regex =
Regex::new(r#"(?i)\stypes\s*=\s*["']([^"']*)["']"#).unwrap();
.collect()
});

/// Fixes which help determine if there is a preferred fix when there are
/// multiple fixes available.
static PREFERRED_FIXES: Lazy<HashMap<&'static str, (u32, bool)>> =
Lazy::new(|| {
(&[
("annotateWithTypeFromJSDoc", (1, false)),
("constructorForDerivedNeedSuperCall", (1, false)),
("extendsInterfaceBecomesImplements", (1, false)),
("awaitInSyncFunction", (1, false)),
("classIncorrectlyImplementsInterface", (3, false)),
("classDoesntImplementInheritedAbstractMember", (3, false)),
("unreachableCode", (1, false)),
("unusedIdentifier", (1, false)),
("forgottenThisPropertyAccess", (1, false)),
("spelling", (2, false)),
("addMissingAwait", (1, false)),
("fixImport", (0, true)),
])
.iter()
.cloned()
.collect()
});

}
static IMPORT_SPECIFIER_RE: Lazy<Regex> =
Lazy::new(|| Regex::new(r#"\sfrom\s+["']([^"']*)["']"#).unwrap());

static DENO_TYPES_RE: Lazy<Regex> = Lazy::new(|| {
Regex::new(r#"(?i)^\s*@deno-types\s*=\s*(?:["']([^"']+)["']|(\S+))"#).unwrap()
});

static TRIPLE_SLASH_REFERENCE_RE: Lazy<Regex> =
Lazy::new(|| Regex::new(r"(?i)^/\s*<reference\s.*?/>").unwrap());

static PATH_REFERENCE_RE: Lazy<Regex> =
Lazy::new(|| Regex::new(r#"(?i)\spath\s*=\s*["']([^"']*)["']"#).unwrap());
static TYPES_REFERENCE_RE: Lazy<Regex> =
Lazy::new(|| Regex::new(r#"(?i)\stypes\s*=\s*["']([^"']*)["']"#).unwrap());

const SUPPORTED_EXTENSIONS: &[&str] = &[".ts", ".tsx", ".js", ".jsx", ".mjs"];

Expand Down
10 changes: 6 additions & 4 deletions cli/lsp/code_lens.rs
Original file line number Diff line number Diff line change
Expand Up @@ -20,16 +20,18 @@ use deno_core::serde_json;
use deno_core::serde_json::json;
use deno_core::ModuleSpecifier;
use lspower::lsp;
use once_cell::sync::Lazy;
use regex::Regex;
use std::cell::RefCell;
use std::collections::HashSet;
use std::rc::Rc;
use std::sync::Arc;

lazy_static::lazy_static! {
static ref ABSTRACT_MODIFIER: Regex = Regex::new(r"\babstract\b").unwrap();
static ref EXPORT_MODIFIER: Regex = Regex::new(r"\bexport\b").unwrap();
}
static ABSTRACT_MODIFIER: Lazy<Regex> =
Lazy::new(|| Regex::new(r"\babstract\b").unwrap());

static EXPORT_MODIFIER: Lazy<Regex> =
Lazy::new(|| Regex::new(r"\bexport\b").unwrap());

#[derive(Debug, Deserialize, Serialize)]
pub enum CodeLensSource {
Expand Down
48 changes: 34 additions & 14 deletions cli/lsp/documents.rs
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,7 @@ use deno_core::url;
use deno_core::ModuleSpecifier;
use deno_graph::Module;
use lspower::lsp;
use once_cell::sync::Lazy;
use std::collections::BTreeMap;
use std::collections::HashMap;
use std::collections::HashSet;
Expand All @@ -35,20 +36,39 @@ use std::str::FromStr;
use std::sync::Arc;
use std::time::SystemTime;

lazy_static::lazy_static! {
static ref JS_HEADERS: HashMap<String, String> = ([
("content-type".to_string(), "application/javascript".to_string())
]).iter().cloned().collect();
static ref JSX_HEADERS: HashMap<String, String> = ([
("content-type".to_string(), "text/jsx".to_string())
]).iter().cloned().collect();
static ref TS_HEADERS: HashMap<String, String> = ([
("content-type".to_string(), "application/typescript".to_string())
]).iter().cloned().collect();
static ref TSX_HEADERS: HashMap<String, String> = ([
("content-type".to_string(), "text/tsx".to_string())
]).iter().cloned().collect();
}
static JS_HEADERS: Lazy<HashMap<String, String>> = Lazy::new(|| {
([(
"content-type".to_string(),
"application/javascript".to_string(),
)])
.iter()
.cloned()
.collect()
});

static JSX_HEADERS: Lazy<HashMap<String, String>> = Lazy::new(|| {
([("content-type".to_string(), "text/jsx".to_string())])
.iter()
.cloned()
.collect()
});

static TS_HEADERS: Lazy<HashMap<String, String>> = Lazy::new(|| {
([(
"content-type".to_string(),
"application/typescript".to_string(),
)])
.iter()
.cloned()
.collect()
});

static TSX_HEADERS: Lazy<HashMap<String, String>> = Lazy::new(|| {
([("content-type".to_string(), "text/tsx".to_string())])
.iter()
.cloned()
.collect()
});

/// The default parser from `deno_graph` does not include the configuration
/// options we require here, and so implementing an empty struct that provides
Expand Down
7 changes: 3 additions & 4 deletions cli/lsp/path_to_regex.rs
Original file line number Diff line number Diff line change
Expand Up @@ -29,15 +29,14 @@
use deno_core::anyhow::anyhow;
use deno_core::error::AnyError;
use fancy_regex::Regex as FancyRegex;
use once_cell::sync::Lazy;
use regex::Regex;
use std::collections::HashMap;
use std::fmt;
use std::iter::Peekable;

lazy_static::lazy_static! {
static ref ESCAPE_STRING_RE: Regex =
Regex::new(r"([.+*?=^!:${}()\[\]|/\\])").unwrap();
}
static ESCAPE_STRING_RE: Lazy<Regex> =
Lazy::new(|| Regex::new(r"([.+*?=^!:${}()\[\]|/\\])").unwrap());

#[derive(Debug, PartialEq, Eq)]
enum TokenType {
Expand Down
Loading

0 comments on commit 6de53b6

Please sign in to comment.