Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

perf(es/react): Use proper string types for react configuration #9949

Merged
merged 36 commits into from
Jan 26, 2025
Merged
Show file tree
Hide file tree
Changes from 15 commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions Cargo.lock

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

15 changes: 8 additions & 7 deletions crates/swc_ecma_transforms_react/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -18,13 +18,14 @@ default = ["serde-impl"]
serde-impl = ["serde"]

[dependencies]
base64 = { workspace = true }
dashmap = { workspace = true }
indexmap = { workspace = true }
once_cell = { workspace = true }
rayon = { workspace = true, optional = true }
serde = { workspace = true, features = ["derive"], optional = true }
sha1 = { workspace = true }
base64 = { workspace = true }
dashmap = { workspace = true }
indexmap = { workspace = true }
once_cell = { workspace = true }
rayon = { workspace = true, optional = true }
rustc-hash = { workspace = true }
serde = { workspace = true, features = ["derive"], optional = true }
sha1 = { workspace = true }

string_enum = { version = "1.0.0", path = "../string_enum" }
swc_allocator = { version = "2.0.0", path = "../swc_allocator", default-features = false }
Expand Down
74 changes: 52 additions & 22 deletions crates/swc_ecma_transforms_react/src/jsx/mod.rs
Original file line number Diff line number Diff line change
@@ -1,10 +1,16 @@
#![allow(clippy::redundant_allocation)]

use std::{borrow::Cow, iter, iter::once, sync::Arc};
use std::{
borrow::Cow,
iter::{self, once},
sync::{Arc, RwLock},
};

use once_cell::sync::Lazy;
use rustc_hash::FxHashMap;
use serde::{Deserialize, Serialize};
use string_enum::StringEnum;
use swc_atoms::{Atom, JsWord};
use swc_atoms::{atom, Atom, JsWord};
use swc_common::{
comments::{Comment, CommentKind, Comments},
errors::HANDLER,
Expand Down Expand Up @@ -56,12 +62,12 @@ pub struct Options {

/// For automatic runtime
#[serde(default)]
pub import_source: Option<String>,
pub import_source: Option<Atom>,

#[serde(default)]
pub pragma: Option<String>,
pub pragma: Option<Arc<String>>,
#[serde(default)]
pub pragma_frag: Option<String>,
pub pragma_frag: Option<Arc<String>>,

#[serde(default)]
pub throw_if_namespace: Option<bool>,
Expand Down Expand Up @@ -93,16 +99,23 @@ pub struct Options {
pub refresh: Option<RefreshOptions>,
}

pub fn default_import_source() -> String {
"react".into()
macro_rules! static_str {
($s:expr) => {{
static VAL: Lazy<Arc<String>> = Lazy::new(|| Arc::new($s.into()));
VAL.clone()
}};
}

pub fn default_import_source() -> Atom {
atom!("react")
}

pub fn default_pragma() -> String {
"React.createElement".into()
pub fn default_pragma() -> Arc<String> {
static_str!("React.createElement")
}

pub fn default_pragma_frag() -> String {
"React.Fragment".into()
pub fn default_pragma_frag() -> Arc<String> {
static_str!("React.Fragment")
}

fn default_throw_if_namespace() -> bool {
Expand All @@ -113,10 +126,10 @@ fn default_throw_if_namespace() -> bool {
pub fn parse_expr_for_jsx(
cm: &SourceMap,
name: &str,
src: String,
src: Arc<String>,
top_level_mark: Mark,
) -> Arc<Box<Expr>> {
let fm = cm.new_source_file(
let fm = cm.new_source_file_from(
FileName::Internal(format!("jsx-config-{}.js", name)).into(),
src,
);
Expand Down Expand Up @@ -198,10 +211,7 @@ where
top_level_mark,
unresolved_mark,
runtime: options.runtime.unwrap_or_default(),
import_source: options
.import_source
.unwrap_or_else(default_import_source)
.into(),
import_source: options.import_source.unwrap_or_else(default_import_source),
import_jsx: None,
import_jsxs: None,
import_fragment: None,
Expand Down Expand Up @@ -239,7 +249,7 @@ where

runtime: Runtime,
/// For automatic runtime.
import_source: JsWord,
import_source: Atom,
/// For automatic runtime.
import_jsx: Option<Ident>,
/// For automatic runtime.
Expand All @@ -262,7 +272,7 @@ pub struct JsxDirectives {
pub runtime: Option<Runtime>,

/// For automatic runtime.
pub import_source: Option<JsWord>,
pub import_source: Option<Atom>,

/// Parsed from `@jsx`
pub pragma: Option<Arc<Box<Expr>>>,
Expand Down Expand Up @@ -335,7 +345,7 @@ impl JsxDirectives {
Some("@jsxImportSource") => {
if let Some(src) = val {
res.runtime = Some(Runtime::Automatic);
res.import_source = Some(src.into());
res.import_source = Some(Atom::new(src));
}
}
Some("@jsxFrag") => {
Expand All @@ -345,7 +355,7 @@ impl JsxDirectives {
let mut e = (*parse_expr_for_jsx(
cm,
"module-jsx-pragma-frag",
src.to_string(),
cache_source(src),
top_level_mark,
))
.clone();
Expand All @@ -361,7 +371,7 @@ impl JsxDirectives {
let mut e = (*parse_expr_for_jsx(
cm,
"module-jsx-pragma",
src.to_string(),
cache_source(src),
top_level_mark,
))
.clone();
Expand All @@ -380,6 +390,26 @@ impl JsxDirectives {
}
}

fn cache_source(src: &str) -> Arc<String> {
static CACHE: Lazy<RwLock<FxHashMap<String, Arc<String>>>> =
Lazy::new(|| RwLock::new(FxHashMap::default()));

{
let cache = CACHE.write().unwrap();

if let Some(cached) = cache.get(src) {
return cached.clone();
}
}

let cached = Arc::new(src.to_string());
{
let mut cache = CACHE.write().unwrap();
cache.insert(src.to_string(), cached.clone());
}
cached
}

fn is_valid_for_pragma(s: &str) -> bool {
if s.is_empty() {
return false;
Expand Down
4 changes: 2 additions & 2 deletions crates/swc_ecma_transforms_react/src/jsx/tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -337,7 +337,7 @@ test!(
|t| tr(
t,
Options {
pragma: Some("dom".into()),
pragma: Some(Arc::new("dom".into())),
..Default::default()
},
Mark::fresh(Mark::root())
Expand Down Expand Up @@ -808,7 +808,7 @@ test!(
|t| tr(
t,
Options {
pragma: Some("h".into()),
pragma: Some(Arc::new("h".into())),
throw_if_namespace: false.into(),
..Default::default()
},
Expand Down
5 changes: 3 additions & 2 deletions crates/swc_ecma_transforms_typescript/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -13,9 +13,10 @@ version = "7.0.0"
bench = false

[dependencies]
serde = { workspace = true, features = ["derive"] }
once_cell = { workspace = true }
ryu-js = { workspace = true }
serde = { workspace = true, features = ["derive"] }

ryu-js = { workspace = true }
swc_atoms = { version = "3.0.3", path = "../swc_atoms" }
swc_common = { version = "5.0.0", path = "../swc_common" }
swc_ecma_ast = { version = "5.0.1", path = "../swc_ecma_ast" }
Expand Down
6 changes: 4 additions & 2 deletions crates/swc_ecma_transforms_typescript/src/config.rs
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
use std::sync::Arc;

use serde::{Deserialize, Serialize};

#[derive(Debug, Default, Serialize, Deserialize)]
Expand Down Expand Up @@ -39,11 +41,11 @@ pub struct Config {
pub struct TsxConfig {
/// Note: this pass handle jsx directives in comments
#[serde(default)]
pub pragma: Option<String>,
pub pragma: Option<Arc<String>>,

/// Note: this pass handle jsx directives in comments
#[serde(default)]
pub pragma_frag: Option<String>,
pub pragma_frag: Option<Arc<String>>,
}

#[derive(Default, Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
Expand Down
14 changes: 11 additions & 3 deletions crates/swc_ecma_transforms_typescript/src/typescript.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
use std::mem;
use std::{mem, sync::Arc};

use once_cell::sync::Lazy;
use swc_common::{
collections::AHashSet, comments::Comments, sync::Lrc, util::take::Take, Mark, SourceMap, Span,
Spanned,
Expand All @@ -11,6 +12,13 @@ use swc_ecma_visit::{visit_mut_pass, VisitMut, VisitMutWith};
pub use crate::config::*;
use crate::{strip_import_export::StripImportExport, strip_type::StripType, transform::transform};

macro_rules! static_str {
($s:expr) => {{
static VAL: Lazy<Arc<String>> = Lazy::new(|| Arc::new($s.into()));
VAL.clone()
}};
}

pub fn typescript(config: Config, unresolved_mark: Mark, top_level_mark: Mark) -> impl Pass {
debug_assert_ne!(unresolved_mark, top_level_mark);

Expand Down Expand Up @@ -199,7 +207,7 @@ where
self.tsx_config
.pragma
.clone()
.unwrap_or_else(|| "React.createElement".to_string()),
.unwrap_or_else(|| static_str!("React.createElement")),
self.top_level_mark,
);

Expand All @@ -209,7 +217,7 @@ where
self.tsx_config
.pragma_frag
.clone()
.unwrap_or_else(|| "React.Fragment".to_string()),
.unwrap_or_else(|| static_str!("React.Fragment")),
self.top_level_mark,
);

Expand Down
Loading